Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ b95479a5

History | View | Annotate | Download (46.9 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
_PEarlyRelease = ("early_release", False, ht.TBool,
116
                  "Whether to release locks as soon as possible")
117

    
118
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
119

    
120
#: Do not remember instance state changes
121
_PNoRemember = ("no_remember", False, ht.TBool,
122
                "Do not remember the state change")
123

    
124
#: Target node for instance migration/failover
125
_PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
126
                         "Target node for shared-storage instances")
127

    
128
_PStartupPaused = ("startup_paused", False, ht.TBool,
129
                   "Pause instance at startup")
130

    
131

    
132
#: OP_ID conversion regular expression
133
_OPID_RE = re.compile("([a-z])([A-Z])")
134

    
135
#: Utility function for L{OpClusterSetParams}
136
_TestClusterOsList = ht.TOr(ht.TNone,
137
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
138
    ht.TMap(ht.WithDesc("GetFirstItem")(operator.itemgetter(0)),
139
            ht.TElemOf(constants.DDMS_VALUES)))))
140

    
141

    
142
# TODO: Generate check from constants.INIC_PARAMS_TYPES
143
#: Utility function for testing NIC definitions
144
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
145
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
146

    
147
_SUMMARY_PREFIX = {
148
  "CLUSTER_": "C_",
149
  "GROUP_": "G_",
150
  "NODE_": "N_",
151
  "INSTANCE_": "I_",
152
  }
153

    
154
#: Attribute name for dependencies
155
DEPEND_ATTR = "depends"
156

    
157

    
158
def _NameToId(name):
159
  """Convert an opcode class name to an OP_ID.
160

161
  @type name: string
162
  @param name: the class name, as OpXxxYyy
163
  @rtype: string
164
  @return: the name in the OP_XXXX_YYYY format
165

166
  """
167
  if not name.startswith("Op"):
168
    return None
169
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
170
  # consume any input, and hence we would just have all the elements
171
  # in the list, one by one; but it seems that split doesn't work on
172
  # non-consuming input, hence we have to process the input string a
173
  # bit
174
  name = _OPID_RE.sub(r"\1,\2", name)
175
  elems = name.split(",")
176
  return "_".join(n.upper() for n in elems)
177

    
178

    
179
def RequireFileStorage():
180
  """Checks that file storage is enabled.
181

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

185
  @raise errors.OpPrereqError: when file storage is disabled
186

187
  """
188
  if not constants.ENABLE_FILE_STORAGE:
189
    raise errors.OpPrereqError("File storage disabled at configure time",
190
                               errors.ECODE_INVAL)
191

    
192

    
193
def RequireSharedFileStorage():
194
  """Checks that shared file storage is enabled.
195

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

199
  @raise errors.OpPrereqError: when shared file storage is disabled
200

201
  """
202
  if not constants.ENABLE_SHARED_FILE_STORAGE:
203
    raise errors.OpPrereqError("Shared file storage disabled at"
204
                               " configure time", errors.ECODE_INVAL)
205

    
206

    
207
@ht.WithDesc("CheckFileStorage")
208
def _CheckFileStorage(value):
209
  """Ensures file storage is enabled if used.
210

211
  """
212
  if value == constants.DT_FILE:
213
    RequireFileStorage()
214
  elif value == constants.DT_SHARED_FILE:
215
    RequireSharedFileStorage()
216
  return True
217

    
218

    
219
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
220
                             _CheckFileStorage)
221

    
222

    
223
def _CheckStorageType(storage_type):
224
  """Ensure a given storage type is valid.
225

226
  """
227
  if storage_type not in constants.VALID_STORAGE_TYPES:
228
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
229
                               errors.ECODE_INVAL)
230
  if storage_type == constants.ST_FILE:
231
    RequireFileStorage()
232
  return True
233

    
234

    
235
#: Storage type parameter
236
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
237
                 "Storage type")
238

    
239

    
240
class _AutoOpParamSlots(type):
241
  """Meta class for opcode definitions.
242

243
  """
244
  def __new__(mcs, name, bases, attrs):
245
    """Called when a class should be created.
246

247
    @param mcs: The meta class
248
    @param name: Name of created class
249
    @param bases: Base classes
250
    @type attrs: dict
251
    @param attrs: Class attributes
252

253
    """
254
    assert "__slots__" not in attrs, \
255
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
256
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
257

    
258
    attrs["OP_ID"] = _NameToId(name)
259

    
260
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
261
    params = attrs.setdefault("OP_PARAMS", [])
262

    
263
    # Use parameter names as slots
264
    slots = [pname for (pname, _, _, _) in params]
265

    
266
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
267
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
268

    
269
    attrs["__slots__"] = slots
270

    
271
    return type.__new__(mcs, name, bases, attrs)
272

    
273

    
274
class BaseOpCode(object):
275
  """A simple serializable object.
276

277
  This object serves as a parent class for OpCode without any custom
278
  field handling.
279

280
  """
281
  # pylint: disable-msg=E1101
282
  # as OP_ID is dynamically defined
283
  __metaclass__ = _AutoOpParamSlots
284

    
285
  def __init__(self, **kwargs):
286
    """Constructor for BaseOpCode.
287

288
    The constructor takes only keyword arguments and will set
289
    attributes on this object based on the passed arguments. As such,
290
    it means that you should not pass arguments which are not in the
291
    __slots__ attribute for this class.
292

293
    """
294
    slots = self._all_slots()
295
    for key in kwargs:
296
      if key not in slots:
297
        raise TypeError("Object %s doesn't support the parameter '%s'" %
298
                        (self.__class__.__name__, key))
299
      setattr(self, key, kwargs[key])
300

    
301
  def __getstate__(self):
302
    """Generic serializer.
303

304
    This method just returns the contents of the instance as a
305
    dictionary.
306

307
    @rtype:  C{dict}
308
    @return: the instance attributes and their values
309

310
    """
311
    state = {}
312
    for name in self._all_slots():
313
      if hasattr(self, name):
314
        state[name] = getattr(self, name)
315
    return state
316

    
317
  def __setstate__(self, state):
318
    """Generic unserializer.
319

320
    This method just restores from the serialized state the attributes
321
    of the current instance.
322

323
    @param state: the serialized opcode data
324
    @type state:  C{dict}
325

326
    """
327
    if not isinstance(state, dict):
328
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
329
                       type(state))
330

    
331
    for name in self._all_slots():
332
      if name not in state and hasattr(self, name):
333
        delattr(self, name)
334

    
335
    for name in state:
336
      setattr(self, name, state[name])
337

    
338
  @classmethod
339
  def _all_slots(cls):
340
    """Compute the list of all declared slots for a class.
341

342
    """
343
    slots = []
344
    for parent in cls.__mro__:
345
      slots.extend(getattr(parent, "__slots__", []))
346
    return slots
347

    
348
  @classmethod
349
  def GetAllParams(cls):
350
    """Compute list of all parameters for an opcode.
351

352
    """
353
    slots = []
354
    for parent in cls.__mro__:
355
      slots.extend(getattr(parent, "OP_PARAMS", []))
356
    return slots
357

    
358
  def Validate(self, set_defaults):
359
    """Validate opcode parameters, optionally setting default values.
360

361
    @type set_defaults: bool
362
    @param set_defaults: Whether to set default values
363
    @raise errors.OpPrereqError: When a parameter value doesn't match
364
                                 requirements
365

366
    """
367
    for (attr_name, default, test, _) in self.GetAllParams():
368
      assert test == ht.NoType or callable(test)
369

    
370
      if not hasattr(self, attr_name):
371
        if default == ht.NoDefault:
372
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
373
                                     (self.OP_ID, attr_name),
374
                                     errors.ECODE_INVAL)
375
        elif set_defaults:
376
          if callable(default):
377
            dval = default()
378
          else:
379
            dval = default
380
          setattr(self, attr_name, dval)
381

    
382
      if test == ht.NoType:
383
        # no tests here
384
        continue
385

    
386
      if set_defaults or hasattr(self, attr_name):
387
        attr_val = getattr(self, attr_name)
388
        if not test(attr_val):
389
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
390
                        self.OP_ID, attr_name, type(attr_val), attr_val)
391
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
392
                                     (self.OP_ID, attr_name),
393
                                     errors.ECODE_INVAL)
394

    
395

    
396
class OpCode(BaseOpCode):
397
  """Abstract OpCode.
398

399
  This is the root of the actual OpCode hierarchy. All clases derived
400
  from this class should override OP_ID.
401

402
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
403
               children of this class.
404
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
405
                      string returned by Summary(); see the docstring of that
406
                      method for details).
407
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
408
                   get if not already defined, and types they must match.
409
  @cvar WITH_LU: Boolean that specifies whether this should be included in
410
      mcpu's dispatch table
411
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
412
                 the check steps
413
  @ivar priority: Opcode priority for queue
414

415
  """
416
  # pylint: disable-msg=E1101
417
  # as OP_ID is dynamically defined
418
  WITH_LU = True
419
  _T_JOB_DEP = \
420
    ht.TAnd(ht.TIsLength(2),
421
            ht.TItems([ht.TJobId,
422
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
423
  OP_PARAMS = [
424
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
425
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
426
    ("priority", constants.OP_PRIO_DEFAULT,
427
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
428
    (DEPEND_ATTR, None, ht.TOr(ht.TNone, ht.TListOf(_T_JOB_DEP)),
429
     "Job dependencies"),
430
    ]
431

    
432
  def __getstate__(self):
433
    """Specialized getstate for opcodes.
434

435
    This method adds to the state dictionary the OP_ID of the class,
436
    so that on unload we can identify the correct class for
437
    instantiating the opcode.
438

439
    @rtype:   C{dict}
440
    @return:  the state as a dictionary
441

442
    """
443
    data = BaseOpCode.__getstate__(self)
444
    data["OP_ID"] = self.OP_ID
445
    return data
446

    
447
  @classmethod
448
  def LoadOpCode(cls, data):
449
    """Generic load opcode method.
450

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

455
    @type data:  C{dict}
456
    @param data: the serialized opcode
457

458
    """
459
    if not isinstance(data, dict):
460
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
461
    if "OP_ID" not in data:
462
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
463
    op_id = data["OP_ID"]
464
    op_class = None
465
    if op_id in OP_MAPPING:
466
      op_class = OP_MAPPING[op_id]
467
    else:
468
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
469
                       op_id)
470
    op = op_class()
471
    new_data = data.copy()
472
    del new_data["OP_ID"]
473
    op.__setstate__(new_data)
474
    return op
475

    
476
  def Summary(self):
477
    """Generates a summary description of this opcode.
478

479
    The summary is the value of the OP_ID attribute (without the "OP_"
480
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
481
    defined; this field should allow to easily identify the operation
482
    (for an instance creation job, e.g., it would be the instance
483
    name).
484

485
    """
486
    assert self.OP_ID is not None and len(self.OP_ID) > 3
487
    # all OP_ID start with OP_, we remove that
488
    txt = self.OP_ID[3:]
489
    field_name = getattr(self, "OP_DSC_FIELD", None)
490
    if field_name:
491
      field_value = getattr(self, field_name, None)
492
      if isinstance(field_value, (list, tuple)):
493
        field_value = ",".join(str(i) for i in field_value)
494
      txt = "%s(%s)" % (txt, field_value)
495
    return txt
496

    
497
  def TinySummary(self):
498
    """Generates a compact summary description of the opcode.
499

500
    """
501
    assert self.OP_ID.startswith("OP_")
502

    
503
    text = self.OP_ID[3:]
504

    
505
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
506
      if text.startswith(prefix):
507
        return supplement + text[len(prefix):]
508

    
509
    return text
510

    
511

    
512
# cluster opcodes
513

    
514
class OpClusterPostInit(OpCode):
515
  """Post cluster initialization.
516

517
  This opcode does not touch the cluster at all. Its purpose is to run hooks
518
  after the cluster has been initialized.
519

520
  """
521

    
522

    
523
class OpClusterDestroy(OpCode):
524
  """Destroy the cluster.
525

526
  This opcode has no other parameters. All the state is irreversibly
527
  lost after the execution of this opcode.
528

529
  """
530

    
531

    
532
class OpClusterQuery(OpCode):
533
  """Query cluster information."""
534

    
535

    
536
class OpClusterVerifyConfig(OpCode):
537
  """Verify the cluster config.
538

539
  """
540
  OP_PARAMS = [
541
    ("verbose", False, ht.TBool, None),
542
    ("error_codes", False, ht.TBool, None),
543
    ("debug_simulate_errors", False, ht.TBool, None),
544
    ]
545

    
546

    
547
class OpClusterVerifyGroup(OpCode):
548
  """Run verify on a node group from the cluster.
549

550
  @type skip_checks: C{list}
551
  @ivar skip_checks: steps to be skipped from the verify process; this
552
                     needs to be a subset of
553
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
554
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
555

556
  """
557
  OP_DSC_FIELD = "group_name"
558
  OP_PARAMS = [
559
    ("group_name", ht.NoDefault, ht.TNonEmptyString, None),
560
    ("skip_checks", ht.EmptyList,
561
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)), None),
562
    ("verbose", False, ht.TBool, None),
563
    ("error_codes", False, ht.TBool, None),
564
    ("debug_simulate_errors", False, ht.TBool, None),
565
    ]
566

    
567

    
568
class OpClusterVerifyDisks(OpCode):
569
  """Verify the cluster disks.
570

571
  Parameters: none
572

573
  Result: a tuple of four elements:
574
    - list of node names with bad data returned (unreachable, etc.)
575
    - dict of node names with broken volume groups (values: error msg)
576
    - list of instances with degraded disks (that should be activated)
577
    - dict of instances with missing logical volumes (values: (node, vol)
578
      pairs with details about the missing volumes)
579

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

585
  Note that only instances that are drbd-based are taken into
586
  consideration. This might need to be revisited in the future.
587

588
  """
589

    
590

    
591
class OpClusterRepairDiskSizes(OpCode):
592
  """Verify the disk sizes of the instances and fixes configuration
593
  mimatches.
594

595
  Parameters: optional instances list, in case we want to restrict the
596
  checks to only a subset of the instances.
597

598
  Result: a list of tuples, (instance, disk, new-size) for changed
599
  configurations.
600

601
  In normal operation, the list should be empty.
602

603
  @type instances: list
604
  @ivar instances: the list of instances to check, or empty for all instances
605

606
  """
607
  OP_PARAMS = [
608
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
609
    ]
610

    
611

    
612
class OpClusterConfigQuery(OpCode):
613
  """Query cluster configuration values."""
614
  OP_PARAMS = [
615
    _POutputFields
616
    ]
617

    
618

    
619
class OpClusterRename(OpCode):
620
  """Rename the cluster.
621

622
  @type name: C{str}
623
  @ivar name: The new name of the cluster. The name and/or the master IP
624
              address will be changed to match the new name and its IP
625
              address.
626

627
  """
628
  OP_DSC_FIELD = "name"
629
  OP_PARAMS = [
630
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
631
    ]
632

    
633

    
634
class OpClusterSetParams(OpCode):
635
  """Change the parameters of the cluster.
636

637
  @type vg_name: C{str} or C{None}
638
  @ivar vg_name: The new volume group name or None to disable LVM usage.
639

640
  """
641
  OP_PARAMS = [
642
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
643
    ("enabled_hypervisors", None,
644
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
645
            ht.TNone),
646
     "List of enabled hypervisors"),
647
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
648
                              ht.TNone),
649
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
650
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
651
     "Cluster-wide backend parameter defaults"),
652
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
653
                            ht.TNone),
654
     "Cluster-wide per-OS hypervisor parameter defaults"),
655
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
656
                              ht.TNone),
657
     "Cluster-wide OS parameter defaults"),
658
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
659
     "Master candidate pool size"),
660
    ("uid_pool", None, ht.NoType,
661
     "Set UID pool, must be list of lists describing UID ranges (two items,"
662
     " start and end inclusive)"),
663
    ("add_uids", None, ht.NoType,
664
     "Extend UID pool, must be list of lists describing UID ranges (two"
665
     " items, start and end inclusive) to be added"),
666
    ("remove_uids", None, ht.NoType,
667
     "Shrink UID pool, must be list of lists describing UID ranges (two"
668
     " items, start and end inclusive) to be removed"),
669
    ("maintain_node_health", None, ht.TMaybeBool,
670
     "Whether to automatically maintain node health"),
671
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
672
     "Whether to wipe disks before allocating them to instances"),
673
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
674
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
675
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
676
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
677
     "Default iallocator for cluster"),
678
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
679
     "Master network device"),
680
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
681
     "List of reserved LVs"),
682
    ("hidden_os", None, _TestClusterOsList,
683
     "Modify list of hidden operating systems. Each modification must have"
684
     " two items, the operation and the OS name. The operation can be"
685
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
686
    ("blacklisted_os", None, _TestClusterOsList,
687
     "Modify list of blacklisted operating systems. Each modification must have"
688
     " two items, the operation and the OS name. The operation can be"
689
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
690
    ]
691

    
692

    
693
class OpClusterRedistConf(OpCode):
694
  """Force a full push of the cluster configuration.
695

696
  """
697

    
698

    
699
class OpQuery(OpCode):
700
  """Query for resources/items.
701

702
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
703
  @ivar fields: List of fields to retrieve
704
  @ivar filter: Query filter
705

706
  """
707
  OP_PARAMS = [
708
    _PQueryWhat,
709
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
710
     "Requested fields"),
711
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
712
     "Query filter"),
713
    ]
714

    
715

    
716
class OpQueryFields(OpCode):
717
  """Query for available resource/item fields.
718

719
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
720
  @ivar fields: List of fields to retrieve
721

722
  """
723
  OP_PARAMS = [
724
    _PQueryWhat,
725
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
726
     "Requested fields; if not given, all are returned"),
727
    ]
728

    
729

    
730
class OpOobCommand(OpCode):
731
  """Interact with OOB."""
732
  OP_PARAMS = [
733
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
734
     "List of nodes to run the OOB command against"),
735
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
736
     "OOB command to be run"),
737
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
738
     "Timeout before the OOB helper will be terminated"),
739
    ("ignore_status", False, ht.TBool,
740
     "Ignores the node offline status for power off"),
741
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
742
     "Time in seconds to wait between powering on nodes"),
743
    ]
744

    
745

    
746
# node opcodes
747

    
748
class OpNodeRemove(OpCode):
749
  """Remove a node.
750

751
  @type node_name: C{str}
752
  @ivar node_name: The name of the node to remove. If the node still has
753
                   instances on it, the operation will fail.
754

755
  """
756
  OP_DSC_FIELD = "node_name"
757
  OP_PARAMS = [
758
    _PNodeName,
759
    ]
760

    
761

    
762
class OpNodeAdd(OpCode):
763
  """Add a node to the cluster.
764

765
  @type node_name: C{str}
766
  @ivar node_name: The name of the node to add. This can be a short name,
767
                   but it will be expanded to the FQDN.
768
  @type primary_ip: IP address
769
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
770
                    opcode is submitted, but will be filled during the node
771
                    add (so it will be visible in the job query).
772
  @type secondary_ip: IP address
773
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
774
                      if the cluster has been initialized in 'dual-network'
775
                      mode, otherwise it must not be given.
776
  @type readd: C{bool}
777
  @ivar readd: Whether to re-add an existing node to the cluster. If
778
               this is not passed, then the operation will abort if the node
779
               name is already in the cluster; use this parameter to 'repair'
780
               a node that had its configuration broken, or was reinstalled
781
               without removal from the cluster.
782
  @type group: C{str}
783
  @ivar group: The node group to which this node will belong.
784
  @type vm_capable: C{bool}
785
  @ivar vm_capable: The vm_capable node attribute
786
  @type master_capable: C{bool}
787
  @ivar master_capable: The master_capable node attribute
788

789
  """
790
  OP_DSC_FIELD = "node_name"
791
  OP_PARAMS = [
792
    _PNodeName,
793
    ("primary_ip", None, ht.NoType, "Primary IP address"),
794
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
795
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
796
    ("group", None, ht.TMaybeString, "Initial node group"),
797
    ("master_capable", None, ht.TMaybeBool,
798
     "Whether node can become master or master candidate"),
799
    ("vm_capable", None, ht.TMaybeBool,
800
     "Whether node can host instances"),
801
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
802
    ]
803

    
804

    
805
class OpNodeQuery(OpCode):
806
  """Compute the list of nodes."""
807
  OP_PARAMS = [
808
    _POutputFields,
809
    _PUseLocking,
810
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
811
     "Empty list to query all nodes, node names otherwise"),
812
    ]
813

    
814

    
815
class OpNodeQueryvols(OpCode):
816
  """Get list of volumes on node."""
817
  OP_PARAMS = [
818
    _POutputFields,
819
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
820
     "Empty list to query all nodes, node names otherwise"),
821
    ]
822

    
823

    
824
class OpNodeQueryStorage(OpCode):
825
  """Get information on storage for node(s)."""
826
  OP_PARAMS = [
827
    _POutputFields,
828
    _PStorageType,
829
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
830
    ("name", None, ht.TMaybeString, "Storage name"),
831
    ]
832

    
833

    
834
class OpNodeModifyStorage(OpCode):
835
  """Modifies the properies of a storage unit"""
836
  OP_PARAMS = [
837
    _PNodeName,
838
    _PStorageType,
839
    _PStorageName,
840
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
841
    ]
842

    
843

    
844
class OpRepairNodeStorage(OpCode):
845
  """Repairs the volume group on a node."""
846
  OP_DSC_FIELD = "node_name"
847
  OP_PARAMS = [
848
    _PNodeName,
849
    _PStorageType,
850
    _PStorageName,
851
    _PIgnoreConsistency,
852
    ]
853

    
854

    
855
class OpNodeSetParams(OpCode):
856
  """Change the parameters of a node."""
857
  OP_DSC_FIELD = "node_name"
858
  OP_PARAMS = [
859
    _PNodeName,
860
    _PForce,
861
    ("master_candidate", None, ht.TMaybeBool,
862
     "Whether the node should become a master candidate"),
863
    ("offline", None, ht.TMaybeBool,
864
     "Whether the node should be marked as offline"),
865
    ("drained", None, ht.TMaybeBool,
866
     "Whether the node should be marked as drained"),
867
    ("auto_promote", False, ht.TBool,
868
     "Whether node(s) should be promoted to master candidate if necessary"),
869
    ("master_capable", None, ht.TMaybeBool,
870
     "Denote whether node can become master or master candidate"),
871
    ("vm_capable", None, ht.TMaybeBool,
872
     "Denote whether node can host instances"),
873
    ("secondary_ip", None, ht.TMaybeString,
874
     "Change node's secondary IP address"),
875
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
876
    ("powered", None, ht.TMaybeBool,
877
     "Whether the node should be marked as powered"),
878
    ]
879

    
880

    
881
class OpNodePowercycle(OpCode):
882
  """Tries to powercycle a node."""
883
  OP_DSC_FIELD = "node_name"
884
  OP_PARAMS = [
885
    _PNodeName,
886
    _PForce,
887
    ]
888

    
889

    
890
class OpNodeMigrate(OpCode):
891
  """Migrate all instances from a node."""
892
  OP_DSC_FIELD = "node_name"
893
  OP_PARAMS = [
894
    _PNodeName,
895
    _PMigrationMode,
896
    _PMigrationLive,
897
    _PMigrationTargetNode,
898
    ("iallocator", None, ht.TMaybeString,
899
     "Iallocator for deciding the target node for shared-storage instances"),
900
    ]
901

    
902

    
903
class OpNodeEvacuate(OpCode):
904
  """Evacuate instances off a number of nodes."""
905
  OP_DSC_FIELD = "node_name"
906
  OP_PARAMS = [
907
    _PEarlyRelease,
908
    _PNodeName,
909
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
910
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
911
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
912
     "Node evacuation mode"),
913
    ]
914

    
915

    
916
# instance opcodes
917

    
918
class OpInstanceCreate(OpCode):
919
  """Create an instance.
920

921
  @ivar instance_name: Instance name
922
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
923
  @ivar source_handshake: Signed handshake from source (remote import only)
924
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
925
  @ivar source_instance_name: Previous name of instance (remote import only)
926
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
927
    (remote import only)
928

929
  """
930
  OP_DSC_FIELD = "instance_name"
931
  OP_PARAMS = [
932
    _PInstanceName,
933
    _PForceVariant,
934
    _PWaitForSync,
935
    _PNameCheck,
936
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
937
    ("disks", ht.NoDefault,
938
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
939
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
940
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
941
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
942
     " each disk definition must contain a ``%s`` value and"
943
     " can contain an optional ``%s`` value denoting the disk access mode"
944
     " (%s)" %
945
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
946
      constants.IDISK_MODE,
947
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
948
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
949
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
950
     "Driver for file-backed disks"),
951
    ("file_storage_dir", None, ht.TMaybeString,
952
     "Directory for storing file-backed disks"),
953
    ("hvparams", ht.EmptyDict, ht.TDict,
954
     "Hypervisor parameters for instance, hypervisor-dependent"),
955
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
956
    ("iallocator", None, ht.TMaybeString,
957
     "Iallocator for deciding which node(s) to use"),
958
    ("identify_defaults", False, ht.TBool,
959
     "Reset instance parameters to default if equal"),
960
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
961
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
962
     "Instance creation mode"),
963
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
964
     "List of NIC (network interface) definitions, for example"
965
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
966
     " contain the optional values %s" %
967
     (constants.INIC_IP,
968
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
969
    ("no_install", None, ht.TMaybeBool,
970
     "Do not install the OS (will disable automatic start)"),
971
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
972
    ("os_type", None, ht.TMaybeString, "Operating system"),
973
    ("pnode", None, ht.TMaybeString, "Primary node"),
974
    ("snode", None, ht.TMaybeString, "Secondary node"),
975
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
976
     "Signed handshake from source (remote import only)"),
977
    ("source_instance_name", None, ht.TMaybeString,
978
     "Source instance name (remote import only)"),
979
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
980
     ht.TPositiveInt,
981
     "How long source instance was given to shut down (remote import only)"),
982
    ("source_x509_ca", None, ht.TMaybeString,
983
     "Source X509 CA in PEM format (remote import only)"),
984
    ("src_node", None, ht.TMaybeString, "Source node for import"),
985
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
986
    ("start", True, ht.TBool, "Whether to start instance after creation"),
987
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
988
    ]
989

    
990

    
991
class OpInstanceReinstall(OpCode):
992
  """Reinstall an instance's OS."""
993
  OP_DSC_FIELD = "instance_name"
994
  OP_PARAMS = [
995
    _PInstanceName,
996
    _PForceVariant,
997
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
998
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
999
    ]
1000

    
1001

    
1002
class OpInstanceRemove(OpCode):
1003
  """Remove an instance."""
1004
  OP_DSC_FIELD = "instance_name"
1005
  OP_PARAMS = [
1006
    _PInstanceName,
1007
    _PShutdownTimeout,
1008
    ("ignore_failures", False, ht.TBool,
1009
     "Whether to ignore failures during removal"),
1010
    ]
1011

    
1012

    
1013
class OpInstanceRename(OpCode):
1014
  """Rename an instance."""
1015
  OP_PARAMS = [
1016
    _PInstanceName,
1017
    _PNameCheck,
1018
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1019
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1020
    ]
1021

    
1022

    
1023
class OpInstanceStartup(OpCode):
1024
  """Startup an instance."""
1025
  OP_DSC_FIELD = "instance_name"
1026
  OP_PARAMS = [
1027
    _PInstanceName,
1028
    _PForce,
1029
    _PIgnoreOfflineNodes,
1030
    ("hvparams", ht.EmptyDict, ht.TDict,
1031
     "Temporary hypervisor parameters, hypervisor-dependent"),
1032
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1033
    _PNoRemember,
1034
    _PStartupPaused,
1035
    ]
1036

    
1037

    
1038
class OpInstanceShutdown(OpCode):
1039
  """Shutdown an instance."""
1040
  OP_DSC_FIELD = "instance_name"
1041
  OP_PARAMS = [
1042
    _PInstanceName,
1043
    _PIgnoreOfflineNodes,
1044
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1045
     "How long to wait for instance to shut down"),
1046
    _PNoRemember,
1047
    ]
1048

    
1049

    
1050
class OpInstanceReboot(OpCode):
1051
  """Reboot an instance."""
1052
  OP_DSC_FIELD = "instance_name"
1053
  OP_PARAMS = [
1054
    _PInstanceName,
1055
    _PShutdownTimeout,
1056
    ("ignore_secondaries", False, ht.TBool,
1057
     "Whether to start the instance even if secondary disks are failing"),
1058
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1059
     "How to reboot instance"),
1060
    ]
1061

    
1062

    
1063
class OpInstanceReplaceDisks(OpCode):
1064
  """Replace the disks of an instance."""
1065
  OP_DSC_FIELD = "instance_name"
1066
  OP_PARAMS = [
1067
    _PInstanceName,
1068
    _PEarlyRelease,
1069
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1070
     "Replacement mode"),
1071
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1072
     "Disk indexes"),
1073
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1074
    ("iallocator", None, ht.TMaybeString,
1075
     "Iallocator for deciding new secondary node"),
1076
    ]
1077

    
1078

    
1079
class OpInstanceFailover(OpCode):
1080
  """Failover an instance."""
1081
  OP_DSC_FIELD = "instance_name"
1082
  OP_PARAMS = [
1083
    _PInstanceName,
1084
    _PShutdownTimeout,
1085
    _PIgnoreConsistency,
1086
    _PMigrationTargetNode,
1087
    ("iallocator", None, ht.TMaybeString,
1088
     "Iallocator for deciding the target node for shared-storage instances"),
1089
    ]
1090

    
1091

    
1092
class OpInstanceMigrate(OpCode):
1093
  """Migrate an instance.
1094

1095
  This migrates (without shutting down an instance) to its secondary
1096
  node.
1097

1098
  @ivar instance_name: the name of the instance
1099
  @ivar mode: the migration mode (live, non-live or None for auto)
1100

1101
  """
1102
  OP_DSC_FIELD = "instance_name"
1103
  OP_PARAMS = [
1104
    _PInstanceName,
1105
    _PMigrationMode,
1106
    _PMigrationLive,
1107
    _PMigrationTargetNode,
1108
    ("cleanup", False, ht.TBool,
1109
     "Whether a previously failed migration should be cleaned up"),
1110
    ("iallocator", None, ht.TMaybeString,
1111
     "Iallocator for deciding the target node for shared-storage instances"),
1112
    ("allow_failover", False, ht.TBool,
1113
     "Whether we can fallback to failover if migration is not possible"),
1114
    ]
1115

    
1116

    
1117
class OpInstanceMove(OpCode):
1118
  """Move an instance.
1119

1120
  This move (with shutting down an instance and data copying) to an
1121
  arbitrary node.
1122

1123
  @ivar instance_name: the name of the instance
1124
  @ivar target_node: the destination node
1125

1126
  """
1127
  OP_DSC_FIELD = "instance_name"
1128
  OP_PARAMS = [
1129
    _PInstanceName,
1130
    _PShutdownTimeout,
1131
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1132
    _PIgnoreConsistency,
1133
    ]
1134

    
1135

    
1136
class OpInstanceConsole(OpCode):
1137
  """Connect to an instance's console."""
1138
  OP_DSC_FIELD = "instance_name"
1139
  OP_PARAMS = [
1140
    _PInstanceName
1141
    ]
1142

    
1143

    
1144
class OpInstanceActivateDisks(OpCode):
1145
  """Activate an instance's disks."""
1146
  OP_DSC_FIELD = "instance_name"
1147
  OP_PARAMS = [
1148
    _PInstanceName,
1149
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1150
    ]
1151

    
1152

    
1153
class OpInstanceDeactivateDisks(OpCode):
1154
  """Deactivate an instance's disks."""
1155
  OP_DSC_FIELD = "instance_name"
1156
  OP_PARAMS = [
1157
    _PInstanceName,
1158
    _PForce,
1159
    ]
1160

    
1161

    
1162
class OpInstanceRecreateDisks(OpCode):
1163
  """Deactivate an instance's disks."""
1164
  OP_DSC_FIELD = "instance_name"
1165
  OP_PARAMS = [
1166
    _PInstanceName,
1167
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1168
     "List of disk indexes"),
1169
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1170
     "New instance nodes, if relocation is desired"),
1171
    ]
1172

    
1173

    
1174
class OpInstanceQuery(OpCode):
1175
  """Compute the list of instances."""
1176
  OP_PARAMS = [
1177
    _POutputFields,
1178
    _PUseLocking,
1179
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1180
     "Empty list to query all instances, instance names otherwise"),
1181
    ]
1182

    
1183

    
1184
class OpInstanceQueryData(OpCode):
1185
  """Compute the run-time status of instances."""
1186
  OP_PARAMS = [
1187
    _PUseLocking,
1188
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1189
     "Instance names"),
1190
    ("static", False, ht.TBool,
1191
     "Whether to only return configuration data without querying"
1192
     " nodes"),
1193
    ]
1194

    
1195

    
1196
class OpInstanceSetParams(OpCode):
1197
  """Change the parameters of an instance."""
1198
  OP_DSC_FIELD = "instance_name"
1199
  OP_PARAMS = [
1200
    _PInstanceName,
1201
    _PForce,
1202
    _PForceVariant,
1203
    # TODO: Use _TestNicDef
1204
    ("nics", ht.EmptyList, ht.TList,
1205
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1206
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1207
     " ``%s`` to remove the last NIC or a number to modify the settings"
1208
     " of the NIC with that index." %
1209
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1210
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1211
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1212
    ("hvparams", ht.EmptyDict, ht.TDict,
1213
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1214
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1215
     "Disk template for instance"),
1216
    ("remote_node", None, ht.TMaybeString,
1217
     "Secondary node (used when changing disk template)"),
1218
    ("os_name", None, ht.TMaybeString,
1219
     "Change instance's OS name. Does not reinstall the instance."),
1220
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1221
    ("wait_for_sync", True, ht.TBool,
1222
     "Whether to wait for the disk to synchronize, when changing template"),
1223
    ]
1224

    
1225

    
1226
class OpInstanceGrowDisk(OpCode):
1227
  """Grow a disk of an instance."""
1228
  OP_DSC_FIELD = "instance_name"
1229
  OP_PARAMS = [
1230
    _PInstanceName,
1231
    _PWaitForSync,
1232
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1233
    ("amount", ht.NoDefault, ht.TInt,
1234
     "Amount of disk space to add (megabytes)"),
1235
    ]
1236

    
1237

    
1238
# Node group opcodes
1239

    
1240
class OpGroupAdd(OpCode):
1241
  """Add a node group to the cluster."""
1242
  OP_DSC_FIELD = "group_name"
1243
  OP_PARAMS = [
1244
    _PGroupName,
1245
    _PNodeGroupAllocPolicy,
1246
    _PGroupNodeParams,
1247
    ]
1248

    
1249

    
1250
class OpGroupAssignNodes(OpCode):
1251
  """Assign nodes to a node group."""
1252
  OP_DSC_FIELD = "group_name"
1253
  OP_PARAMS = [
1254
    _PGroupName,
1255
    _PForce,
1256
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1257
     "List of nodes to assign"),
1258
    ]
1259

    
1260

    
1261
class OpGroupQuery(OpCode):
1262
  """Compute the list of node groups."""
1263
  OP_PARAMS = [
1264
    _POutputFields,
1265
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1266
     "Empty list to query all groups, group names otherwise"),
1267
    ]
1268

    
1269

    
1270
class OpGroupSetParams(OpCode):
1271
  """Change the parameters of a node group."""
1272
  OP_DSC_FIELD = "group_name"
1273
  OP_PARAMS = [
1274
    _PGroupName,
1275
    _PNodeGroupAllocPolicy,
1276
    _PGroupNodeParams,
1277
    ]
1278

    
1279

    
1280
class OpGroupRemove(OpCode):
1281
  """Remove a node group from the cluster."""
1282
  OP_DSC_FIELD = "group_name"
1283
  OP_PARAMS = [
1284
    _PGroupName,
1285
    ]
1286

    
1287

    
1288
class OpGroupRename(OpCode):
1289
  """Rename a node group in the cluster."""
1290
  OP_PARAMS = [
1291
    _PGroupName,
1292
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1293
    ]
1294

    
1295

    
1296
# OS opcodes
1297
class OpOsDiagnose(OpCode):
1298
  """Compute the list of guest operating systems."""
1299
  OP_PARAMS = [
1300
    _POutputFields,
1301
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1302
     "Which operating systems to diagnose"),
1303
    ]
1304

    
1305

    
1306
# Exports opcodes
1307
class OpBackupQuery(OpCode):
1308
  """Compute the list of exported images."""
1309
  OP_PARAMS = [
1310
    _PUseLocking,
1311
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1312
     "Empty list to query all nodes, node names otherwise"),
1313
    ]
1314

    
1315

    
1316
class OpBackupPrepare(OpCode):
1317
  """Prepares an instance export.
1318

1319
  @ivar instance_name: Instance name
1320
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1321

1322
  """
1323
  OP_DSC_FIELD = "instance_name"
1324
  OP_PARAMS = [
1325
    _PInstanceName,
1326
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1327
     "Export mode"),
1328
    ]
1329

    
1330

    
1331
class OpBackupExport(OpCode):
1332
  """Export an instance.
1333

1334
  For local exports, the export destination is the node name. For remote
1335
  exports, the export destination is a list of tuples, each consisting of
1336
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1337
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1338
  destination X509 CA must be a signed certificate.
1339

1340
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1341
  @ivar target_node: Export destination
1342
  @ivar x509_key_name: X509 key to use (remote export only)
1343
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1344
                             only)
1345

1346
  """
1347
  OP_DSC_FIELD = "instance_name"
1348
  OP_PARAMS = [
1349
    _PInstanceName,
1350
    _PShutdownTimeout,
1351
    # TODO: Rename target_node as it changes meaning for different export modes
1352
    # (e.g. "destination")
1353
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1354
     "Destination information, depends on export mode"),
1355
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1356
    ("remove_instance", False, ht.TBool,
1357
     "Whether to remove instance after export"),
1358
    ("ignore_remove_failures", False, ht.TBool,
1359
     "Whether to ignore failures while removing instances"),
1360
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1361
     "Export mode"),
1362
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1363
     "Name of X509 key (remote export only)"),
1364
    ("destination_x509_ca", None, ht.TMaybeString,
1365
     "Destination X509 CA (remote export only)"),
1366
    ]
1367

    
1368

    
1369
class OpBackupRemove(OpCode):
1370
  """Remove an instance's export."""
1371
  OP_DSC_FIELD = "instance_name"
1372
  OP_PARAMS = [
1373
    _PInstanceName,
1374
    ]
1375

    
1376

    
1377
# Tags opcodes
1378
class OpTagsGet(OpCode):
1379
  """Returns the tags of the given object."""
1380
  OP_DSC_FIELD = "name"
1381
  OP_PARAMS = [
1382
    _PTagKind,
1383
    # Name is only meaningful for nodes and instances
1384
    ("name", ht.NoDefault, ht.TMaybeString, None),
1385
    ]
1386

    
1387

    
1388
class OpTagsSearch(OpCode):
1389
  """Searches the tags in the cluster for a given pattern."""
1390
  OP_DSC_FIELD = "pattern"
1391
  OP_PARAMS = [
1392
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1393
    ]
1394

    
1395

    
1396
class OpTagsSet(OpCode):
1397
  """Add a list of tags on a given object."""
1398
  OP_PARAMS = [
1399
    _PTagKind,
1400
    _PTags,
1401
    # Name is only meaningful for nodes and instances
1402
    ("name", ht.NoDefault, ht.TMaybeString, None),
1403
    ]
1404

    
1405

    
1406
class OpTagsDel(OpCode):
1407
  """Remove a list of tags from a given object."""
1408
  OP_PARAMS = [
1409
    _PTagKind,
1410
    _PTags,
1411
    # Name is only meaningful for nodes and instances
1412
    ("name", ht.NoDefault, ht.TMaybeString, None),
1413
    ]
1414

    
1415
# Test opcodes
1416
class OpTestDelay(OpCode):
1417
  """Sleeps for a configured amount of time.
1418

1419
  This is used just for debugging and testing.
1420

1421
  Parameters:
1422
    - duration: the time to sleep
1423
    - on_master: if true, sleep on the master
1424
    - on_nodes: list of nodes in which to sleep
1425

1426
  If the on_master parameter is true, it will execute a sleep on the
1427
  master (before any node sleep).
1428

1429
  If the on_nodes list is not empty, it will sleep on those nodes
1430
  (after the sleep on the master, if that is enabled).
1431

1432
  As an additional feature, the case of duration < 0 will be reported
1433
  as an execution error, so this opcode can be used as a failure
1434
  generator. The case of duration == 0 will not be treated specially.
1435

1436
  """
1437
  OP_DSC_FIELD = "duration"
1438
  OP_PARAMS = [
1439
    ("duration", ht.NoDefault, ht.TNumber, None),
1440
    ("on_master", True, ht.TBool, None),
1441
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1442
    ("repeat", 0, ht.TPositiveInt, None),
1443
    ]
1444

    
1445

    
1446
class OpTestAllocator(OpCode):
1447
  """Allocator framework testing.
1448

1449
  This opcode has two modes:
1450
    - gather and return allocator input for a given mode (allocate new
1451
      or replace secondary) and a given instance definition (direction
1452
      'in')
1453
    - run a selected allocator for a given operation (as above) and
1454
      return the allocator output (direction 'out')
1455

1456
  """
1457
  OP_DSC_FIELD = "allocator"
1458
  OP_PARAMS = [
1459
    ("direction", ht.NoDefault,
1460
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1461
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1462
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1463
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1464
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1465
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1466
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1467
    ("hypervisor", None, ht.TMaybeString, None),
1468
    ("allocator", None, ht.TMaybeString, None),
1469
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1470
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1471
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1472
    ("os", None, ht.TMaybeString, None),
1473
    ("disk_template", None, ht.TMaybeString, None),
1474
    ("evac_nodes", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1475
     None),
1476
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1477
     None),
1478
    ("evac_mode", None,
1479
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1480
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1481
     None),
1482
    ]
1483

    
1484

    
1485
class OpTestJqueue(OpCode):
1486
  """Utility opcode to test some aspects of the job queue.
1487

1488
  """
1489
  OP_PARAMS = [
1490
    ("notify_waitlock", False, ht.TBool, None),
1491
    ("notify_exec", False, ht.TBool, None),
1492
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1493
    ("fail", False, ht.TBool, None),
1494
    ]
1495

    
1496

    
1497
class OpTestDummy(OpCode):
1498
  """Utility opcode used by unittests.
1499

1500
  """
1501
  OP_PARAMS = [
1502
    ("result", ht.NoDefault, ht.NoType, None),
1503
    ("messages", ht.NoDefault, ht.NoType, None),
1504
    ("fail", ht.NoDefault, ht.NoType, None),
1505
    ("submit_jobs", None, ht.NoType, None),
1506
    ]
1507
  WITH_LU = False
1508

    
1509

    
1510
def _GetOpList():
1511
  """Returns list of all defined opcodes.
1512

1513
  Does not eliminate duplicates by C{OP_ID}.
1514

1515
  """
1516
  return [v for v in globals().values()
1517
          if (isinstance(v, type) and issubclass(v, OpCode) and
1518
              hasattr(v, "OP_ID") and v is not OpCode)]
1519

    
1520

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