Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ f7686867

History | View | Annotate | Download (49.4 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

    
39
from ganeti import compat
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
_PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
132

    
133
# Parameters for cluster verification
134
_PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
135
                         "Whether to simulate errors (useful for debugging)")
136
_PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
137
_PSkipChecks = ("skip_checks", ht.EmptyList,
138
                ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
139
                "Which checks to skip")
140

    
141
#: OP_ID conversion regular expression
142
_OPID_RE = re.compile("([a-z])([A-Z])")
143

    
144
#: Utility function for L{OpClusterSetParams}
145
_TestClusterOsList = ht.TOr(ht.TNone,
146
  ht.TListOf(ht.TAnd(ht.TList, ht.TIsLength(2),
147
    ht.TMap(ht.WithDesc("GetFirstItem")(compat.fst),
148
            ht.TElemOf(constants.DDMS_VALUES)))))
149

    
150

    
151
# TODO: Generate check from constants.INIC_PARAMS_TYPES
152
#: Utility function for testing NIC definitions
153
_TestNicDef = ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
154
                         ht.TOr(ht.TNone, ht.TNonEmptyString))
155

    
156
_SUMMARY_PREFIX = {
157
  "CLUSTER_": "C_",
158
  "GROUP_": "G_",
159
  "NODE_": "N_",
160
  "INSTANCE_": "I_",
161
  }
162

    
163
#: Attribute name for dependencies
164
DEPEND_ATTR = "depends"
165

    
166
#: Attribute name for comment
167
COMMENT_ATTR = "comment"
168

    
169

    
170
def _NameToId(name):
171
  """Convert an opcode class name to an OP_ID.
172

173
  @type name: string
174
  @param name: the class name, as OpXxxYyy
175
  @rtype: string
176
  @return: the name in the OP_XXXX_YYYY format
177

178
  """
179
  if not name.startswith("Op"):
180
    return None
181
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
182
  # consume any input, and hence we would just have all the elements
183
  # in the list, one by one; but it seems that split doesn't work on
184
  # non-consuming input, hence we have to process the input string a
185
  # bit
186
  name = _OPID_RE.sub(r"\1,\2", name)
187
  elems = name.split(",")
188
  return "_".join(n.upper() for n in elems)
189

    
190

    
191
def RequireFileStorage():
192
  """Checks that file storage is enabled.
193

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

197
  @raise errors.OpPrereqError: when file storage is disabled
198

199
  """
200
  if not constants.ENABLE_FILE_STORAGE:
201
    raise errors.OpPrereqError("File storage disabled at configure time",
202
                               errors.ECODE_INVAL)
203

    
204

    
205
def RequireSharedFileStorage():
206
  """Checks that shared file storage is enabled.
207

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

211
  @raise errors.OpPrereqError: when shared file storage is disabled
212

213
  """
214
  if not constants.ENABLE_SHARED_FILE_STORAGE:
215
    raise errors.OpPrereqError("Shared file storage disabled at"
216
                               " configure time", errors.ECODE_INVAL)
217

    
218

    
219
@ht.WithDesc("CheckFileStorage")
220
def _CheckFileStorage(value):
221
  """Ensures file storage is enabled if used.
222

223
  """
224
  if value == constants.DT_FILE:
225
    RequireFileStorage()
226
  elif value == constants.DT_SHARED_FILE:
227
    RequireSharedFileStorage()
228
  return True
229

    
230

    
231
_CheckDiskTemplate = ht.TAnd(ht.TElemOf(constants.DISK_TEMPLATES),
232
                             _CheckFileStorage)
233

    
234

    
235
def _CheckStorageType(storage_type):
236
  """Ensure a given storage type is valid.
237

238
  """
239
  if storage_type not in constants.VALID_STORAGE_TYPES:
240
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
241
                               errors.ECODE_INVAL)
242
  if storage_type == constants.ST_FILE:
243
    RequireFileStorage()
244
  return True
245

    
246

    
247
#: Storage type parameter
248
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
249
                 "Storage type")
250

    
251

    
252
class _AutoOpParamSlots(type):
253
  """Meta class for opcode definitions.
254

255
  """
256
  def __new__(mcs, name, bases, attrs):
257
    """Called when a class should be created.
258

259
    @param mcs: The meta class
260
    @param name: Name of created class
261
    @param bases: Base classes
262
    @type attrs: dict
263
    @param attrs: Class attributes
264

265
    """
266
    assert "__slots__" not in attrs, \
267
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
268
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
269

    
270
    attrs["OP_ID"] = _NameToId(name)
271

    
272
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
273
    params = attrs.setdefault("OP_PARAMS", [])
274

    
275
    # Use parameter names as slots
276
    slots = [pname for (pname, _, _, _) in params]
277

    
278
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
279
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
280

    
281
    attrs["__slots__"] = slots
282

    
283
    return type.__new__(mcs, name, bases, attrs)
284

    
285

    
286
class BaseOpCode(object):
287
  """A simple serializable object.
288

289
  This object serves as a parent class for OpCode without any custom
290
  field handling.
291

292
  """
293
  # pylint: disable-msg=E1101
294
  # as OP_ID is dynamically defined
295
  __metaclass__ = _AutoOpParamSlots
296

    
297
  def __init__(self, **kwargs):
298
    """Constructor for BaseOpCode.
299

300
    The constructor takes only keyword arguments and will set
301
    attributes on this object based on the passed arguments. As such,
302
    it means that you should not pass arguments which are not in the
303
    __slots__ attribute for this class.
304

305
    """
306
    slots = self._all_slots()
307
    for key in kwargs:
308
      if key not in slots:
309
        raise TypeError("Object %s doesn't support the parameter '%s'" %
310
                        (self.__class__.__name__, key))
311
      setattr(self, key, kwargs[key])
312

    
313
  def __getstate__(self):
314
    """Generic serializer.
315

316
    This method just returns the contents of the instance as a
317
    dictionary.
318

319
    @rtype:  C{dict}
320
    @return: the instance attributes and their values
321

322
    """
323
    state = {}
324
    for name in self._all_slots():
325
      if hasattr(self, name):
326
        state[name] = getattr(self, name)
327
    return state
328

    
329
  def __setstate__(self, state):
330
    """Generic unserializer.
331

332
    This method just restores from the serialized state the attributes
333
    of the current instance.
334

335
    @param state: the serialized opcode data
336
    @type state:  C{dict}
337

338
    """
339
    if not isinstance(state, dict):
340
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
341
                       type(state))
342

    
343
    for name in self._all_slots():
344
      if name not in state and hasattr(self, name):
345
        delattr(self, name)
346

    
347
    for name in state:
348
      setattr(self, name, state[name])
349

    
350
  @classmethod
351
  def _all_slots(cls):
352
    """Compute the list of all declared slots for a class.
353

354
    """
355
    slots = []
356
    for parent in cls.__mro__:
357
      slots.extend(getattr(parent, "__slots__", []))
358
    return slots
359

    
360
  @classmethod
361
  def GetAllParams(cls):
362
    """Compute list of all parameters for an opcode.
363

364
    """
365
    slots = []
366
    for parent in cls.__mro__:
367
      slots.extend(getattr(parent, "OP_PARAMS", []))
368
    return slots
369

    
370
  def Validate(self, set_defaults):
371
    """Validate opcode parameters, optionally setting default values.
372

373
    @type set_defaults: bool
374
    @param set_defaults: Whether to set default values
375
    @raise errors.OpPrereqError: When a parameter value doesn't match
376
                                 requirements
377

378
    """
379
    for (attr_name, default, test, _) in self.GetAllParams():
380
      assert test == ht.NoType or callable(test)
381

    
382
      if not hasattr(self, attr_name):
383
        if default == ht.NoDefault:
384
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
385
                                     (self.OP_ID, attr_name),
386
                                     errors.ECODE_INVAL)
387
        elif set_defaults:
388
          if callable(default):
389
            dval = default()
390
          else:
391
            dval = default
392
          setattr(self, attr_name, dval)
393

    
394
      if test == ht.NoType:
395
        # no tests here
396
        continue
397

    
398
      if set_defaults or hasattr(self, attr_name):
399
        attr_val = getattr(self, attr_name)
400
        if not test(attr_val):
401
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
402
                        self.OP_ID, attr_name, type(attr_val), attr_val)
403
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
404
                                     (self.OP_ID, attr_name),
405
                                     errors.ECODE_INVAL)
406

    
407

    
408
def _BuildJobDepCheck(relative):
409
  """Builds check for job dependencies (L{DEPEND_ATTR}).
410

411
  @type relative: bool
412
  @param relative: Whether to accept relative job IDs (negative)
413
  @rtype: callable
414

415
  """
416
  if relative:
417
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
418
  else:
419
    job_id = ht.TJobId
420

    
421
  job_dep = \
422
    ht.TAnd(ht.TIsLength(2),
423
            ht.TItems([job_id,
424
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
425

    
426
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
427

    
428

    
429
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
430

    
431
#: List of submission status and job ID as returned by C{SubmitManyJobs}
432
TJobIdList = ht.TListOf(ht.TItems([ht.TBool, ht.TOr(ht.TString, ht.TJobId)]))
433

    
434
#: Result containing only list of submitted jobs
435
TJobIdListOnly = ht.TStrictDict(True, True, {
436
  constants.JOB_IDS_KEY: TJobIdList,
437
  })
438

    
439

    
440
class OpCode(BaseOpCode):
441
  """Abstract OpCode.
442

443
  This is the root of the actual OpCode hierarchy. All clases derived
444
  from this class should override OP_ID.
445

446
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
447
               children of this class.
448
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
449
                      string returned by Summary(); see the docstring of that
450
                      method for details).
451
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
452
                   get if not already defined, and types they must match.
453
  @cvar OP_RESULT: Callable to verify opcode result
454
  @cvar WITH_LU: Boolean that specifies whether this should be included in
455
      mcpu's dispatch table
456
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
457
                 the check steps
458
  @ivar priority: Opcode priority for queue
459

460
  """
461
  # pylint: disable-msg=E1101
462
  # as OP_ID is dynamically defined
463
  WITH_LU = True
464
  OP_PARAMS = [
465
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
466
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
467
    ("priority", constants.OP_PRIO_DEFAULT,
468
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
469
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
470
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
471
     " job IDs can be used"),
472
    (COMMENT_ATTR, None, ht.TMaybeString,
473
     "Comment describing the purpose of the opcode"),
474
    ]
475
  OP_RESULT = None
476

    
477
  def __getstate__(self):
478
    """Specialized getstate for opcodes.
479

480
    This method adds to the state dictionary the OP_ID of the class,
481
    so that on unload we can identify the correct class for
482
    instantiating the opcode.
483

484
    @rtype:   C{dict}
485
    @return:  the state as a dictionary
486

487
    """
488
    data = BaseOpCode.__getstate__(self)
489
    data["OP_ID"] = self.OP_ID
490
    return data
491

    
492
  @classmethod
493
  def LoadOpCode(cls, data):
494
    """Generic load opcode method.
495

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

500
    @type data:  C{dict}
501
    @param data: the serialized opcode
502

503
    """
504
    if not isinstance(data, dict):
505
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
506
    if "OP_ID" not in data:
507
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
508
    op_id = data["OP_ID"]
509
    op_class = None
510
    if op_id in OP_MAPPING:
511
      op_class = OP_MAPPING[op_id]
512
    else:
513
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
514
                       op_id)
515
    op = op_class()
516
    new_data = data.copy()
517
    del new_data["OP_ID"]
518
    op.__setstate__(new_data)
519
    return op
520

    
521
  def Summary(self):
522
    """Generates a summary description of this opcode.
523

524
    The summary is the value of the OP_ID attribute (without the "OP_"
525
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
526
    defined; this field should allow to easily identify the operation
527
    (for an instance creation job, e.g., it would be the instance
528
    name).
529

530
    """
531
    assert self.OP_ID is not None and len(self.OP_ID) > 3
532
    # all OP_ID start with OP_, we remove that
533
    txt = self.OP_ID[3:]
534
    field_name = getattr(self, "OP_DSC_FIELD", None)
535
    if field_name:
536
      field_value = getattr(self, field_name, None)
537
      if isinstance(field_value, (list, tuple)):
538
        field_value = ",".join(str(i) for i in field_value)
539
      txt = "%s(%s)" % (txt, field_value)
540
    return txt
541

    
542
  def TinySummary(self):
543
    """Generates a compact summary description of the opcode.
544

545
    """
546
    assert self.OP_ID.startswith("OP_")
547

    
548
    text = self.OP_ID[3:]
549

    
550
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
551
      if text.startswith(prefix):
552
        return supplement + text[len(prefix):]
553

    
554
    return text
555

    
556

    
557
# cluster opcodes
558

    
559
class OpClusterPostInit(OpCode):
560
  """Post cluster initialization.
561

562
  This opcode does not touch the cluster at all. Its purpose is to run hooks
563
  after the cluster has been initialized.
564

565
  """
566

    
567

    
568
class OpClusterDestroy(OpCode):
569
  """Destroy the cluster.
570

571
  This opcode has no other parameters. All the state is irreversibly
572
  lost after the execution of this opcode.
573

574
  """
575

    
576

    
577
class OpClusterQuery(OpCode):
578
  """Query cluster information."""
579

    
580

    
581
class OpClusterVerify(OpCode):
582
  """Submits all jobs necessary to verify the cluster.
583

584
  """
585
  OP_PARAMS = [
586
    _PDebugSimulateErrors,
587
    _PErrorCodes,
588
    _PSkipChecks,
589
    _PVerbose,
590
    ("group_name", None, ht.TMaybeString, "Group to verify")
591
    ]
592
  OP_RESULT = TJobIdListOnly
593

    
594

    
595
class OpClusterVerifyConfig(OpCode):
596
  """Verify the cluster config.
597

598
  """
599
  OP_PARAMS = [
600
    _PDebugSimulateErrors,
601
    _PErrorCodes,
602
    _PVerbose,
603
    ]
604
  OP_RESULT = ht.TBool
605

    
606

    
607
class OpClusterVerifyGroup(OpCode):
608
  """Run verify on a node group from the cluster.
609

610
  @type skip_checks: C{list}
611
  @ivar skip_checks: steps to be skipped from the verify process; this
612
                     needs to be a subset of
613
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
614
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
615

616
  """
617
  OP_DSC_FIELD = "group_name"
618
  OP_PARAMS = [
619
    _PGroupName,
620
    _PDebugSimulateErrors,
621
    _PErrorCodes,
622
    _PSkipChecks,
623
    _PVerbose,
624
    ]
625
  OP_RESULT = ht.TBool
626

    
627

    
628
class OpClusterVerifyDisks(OpCode):
629
  """Verify the cluster disks.
630

631
  """
632
  OP_RESULT = TJobIdListOnly
633

    
634

    
635
class OpGroupVerifyDisks(OpCode):
636
  """Verifies the status of all disks in a node group.
637

638
  Result: a tuple of three elements:
639
    - dict of node names with issues (values: error msg)
640
    - list of instances with degraded disks (that should be activated)
641
    - dict of instances with missing logical volumes (values: (node, vol)
642
      pairs with details about the missing volumes)
643

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

649
  Note that only instances that are drbd-based are taken into
650
  consideration. This might need to be revisited in the future.
651

652
  """
653
  OP_DSC_FIELD = "group_name"
654
  OP_PARAMS = [
655
    _PGroupName,
656
    ]
657
  OP_RESULT = \
658
    ht.TAnd(ht.TIsLength(3),
659
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
660
                       ht.TListOf(ht.TString),
661
                       ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
662

    
663

    
664
class OpClusterRepairDiskSizes(OpCode):
665
  """Verify the disk sizes of the instances and fixes configuration
666
  mimatches.
667

668
  Parameters: optional instances list, in case we want to restrict the
669
  checks to only a subset of the instances.
670

671
  Result: a list of tuples, (instance, disk, new-size) for changed
672
  configurations.
673

674
  In normal operation, the list should be empty.
675

676
  @type instances: list
677
  @ivar instances: the list of instances to check, or empty for all instances
678

679
  """
680
  OP_PARAMS = [
681
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
682
    ]
683

    
684

    
685
class OpClusterConfigQuery(OpCode):
686
  """Query cluster configuration values."""
687
  OP_PARAMS = [
688
    _POutputFields
689
    ]
690

    
691

    
692
class OpClusterRename(OpCode):
693
  """Rename the cluster.
694

695
  @type name: C{str}
696
  @ivar name: The new name of the cluster. The name and/or the master IP
697
              address will be changed to match the new name and its IP
698
              address.
699

700
  """
701
  OP_DSC_FIELD = "name"
702
  OP_PARAMS = [
703
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
704
    ]
705

    
706

    
707
class OpClusterSetParams(OpCode):
708
  """Change the parameters of the cluster.
709

710
  @type vg_name: C{str} or C{None}
711
  @ivar vg_name: The new volume group name or None to disable LVM usage.
712

713
  """
714
  OP_PARAMS = [
715
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
716
    ("enabled_hypervisors", None,
717
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
718
            ht.TNone),
719
     "List of enabled hypervisors"),
720
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
721
                              ht.TNone),
722
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
723
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
724
     "Cluster-wide backend parameter defaults"),
725
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
726
                            ht.TNone),
727
     "Cluster-wide per-OS hypervisor parameter defaults"),
728
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
729
                              ht.TNone),
730
     "Cluster-wide OS parameter defaults"),
731
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
732
     "Master candidate pool size"),
733
    ("uid_pool", None, ht.NoType,
734
     "Set UID pool, must be list of lists describing UID ranges (two items,"
735
     " start and end inclusive)"),
736
    ("add_uids", None, ht.NoType,
737
     "Extend UID pool, must be list of lists describing UID ranges (two"
738
     " items, start and end inclusive) to be added"),
739
    ("remove_uids", None, ht.NoType,
740
     "Shrink UID pool, must be list of lists describing UID ranges (two"
741
     " items, start and end inclusive) to be removed"),
742
    ("maintain_node_health", None, ht.TMaybeBool,
743
     "Whether to automatically maintain node health"),
744
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
745
     "Whether to wipe disks before allocating them to instances"),
746
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
747
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
748
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
749
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
750
     "Default iallocator for cluster"),
751
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
752
     "Master network device"),
753
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
754
     "List of reserved LVs"),
755
    ("hidden_os", None, _TestClusterOsList,
756
     "Modify list of hidden operating systems. Each modification must have"
757
     " two items, the operation and the OS name. The operation can be"
758
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
759
    ("blacklisted_os", None, _TestClusterOsList,
760
     "Modify list of blacklisted operating systems. Each modification must have"
761
     " two items, the operation and the OS name. The operation can be"
762
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
763
    ]
764

    
765

    
766
class OpClusterRedistConf(OpCode):
767
  """Force a full push of the cluster configuration.
768

769
  """
770

    
771

    
772
class OpQuery(OpCode):
773
  """Query for resources/items.
774

775
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
776
  @ivar fields: List of fields to retrieve
777
  @ivar filter: Query filter
778

779
  """
780
  OP_DSC_FIELD = "what"
781
  OP_PARAMS = [
782
    _PQueryWhat,
783
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
784
     "Requested fields"),
785
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
786
     "Query filter"),
787
    ]
788

    
789

    
790
class OpQueryFields(OpCode):
791
  """Query for available resource/item fields.
792

793
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
794
  @ivar fields: List of fields to retrieve
795

796
  """
797
  OP_DSC_FIELD = "what"
798
  OP_PARAMS = [
799
    _PQueryWhat,
800
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
801
     "Requested fields; if not given, all are returned"),
802
    ]
803

    
804

    
805
class OpOobCommand(OpCode):
806
  """Interact with OOB."""
807
  OP_PARAMS = [
808
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
809
     "List of nodes to run the OOB command against"),
810
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
811
     "OOB command to be run"),
812
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
813
     "Timeout before the OOB helper will be terminated"),
814
    ("ignore_status", False, ht.TBool,
815
     "Ignores the node offline status for power off"),
816
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
817
     "Time in seconds to wait between powering on nodes"),
818
    ]
819

    
820

    
821
# node opcodes
822

    
823
class OpNodeRemove(OpCode):
824
  """Remove a node.
825

826
  @type node_name: C{str}
827
  @ivar node_name: The name of the node to remove. If the node still has
828
                   instances on it, the operation will fail.
829

830
  """
831
  OP_DSC_FIELD = "node_name"
832
  OP_PARAMS = [
833
    _PNodeName,
834
    ]
835

    
836

    
837
class OpNodeAdd(OpCode):
838
  """Add a node to the cluster.
839

840
  @type node_name: C{str}
841
  @ivar node_name: The name of the node to add. This can be a short name,
842
                   but it will be expanded to the FQDN.
843
  @type primary_ip: IP address
844
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
845
                    opcode is submitted, but will be filled during the node
846
                    add (so it will be visible in the job query).
847
  @type secondary_ip: IP address
848
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
849
                      if the cluster has been initialized in 'dual-network'
850
                      mode, otherwise it must not be given.
851
  @type readd: C{bool}
852
  @ivar readd: Whether to re-add an existing node to the cluster. If
853
               this is not passed, then the operation will abort if the node
854
               name is already in the cluster; use this parameter to 'repair'
855
               a node that had its configuration broken, or was reinstalled
856
               without removal from the cluster.
857
  @type group: C{str}
858
  @ivar group: The node group to which this node will belong.
859
  @type vm_capable: C{bool}
860
  @ivar vm_capable: The vm_capable node attribute
861
  @type master_capable: C{bool}
862
  @ivar master_capable: The master_capable node attribute
863

864
  """
865
  OP_DSC_FIELD = "node_name"
866
  OP_PARAMS = [
867
    _PNodeName,
868
    ("primary_ip", None, ht.NoType, "Primary IP address"),
869
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
870
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
871
    ("group", None, ht.TMaybeString, "Initial node group"),
872
    ("master_capable", None, ht.TMaybeBool,
873
     "Whether node can become master or master candidate"),
874
    ("vm_capable", None, ht.TMaybeBool,
875
     "Whether node can host instances"),
876
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
877
    ]
878

    
879

    
880
class OpNodeQuery(OpCode):
881
  """Compute the list of nodes."""
882
  OP_PARAMS = [
883
    _POutputFields,
884
    _PUseLocking,
885
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
886
     "Empty list to query all nodes, node names otherwise"),
887
    ]
888

    
889

    
890
class OpNodeQueryvols(OpCode):
891
  """Get list of volumes on node."""
892
  OP_PARAMS = [
893
    _POutputFields,
894
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
895
     "Empty list to query all nodes, node names otherwise"),
896
    ]
897

    
898

    
899
class OpNodeQueryStorage(OpCode):
900
  """Get information on storage for node(s)."""
901
  OP_PARAMS = [
902
    _POutputFields,
903
    _PStorageType,
904
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
905
    ("name", None, ht.TMaybeString, "Storage name"),
906
    ]
907

    
908

    
909
class OpNodeModifyStorage(OpCode):
910
  """Modifies the properies of a storage unit"""
911
  OP_PARAMS = [
912
    _PNodeName,
913
    _PStorageType,
914
    _PStorageName,
915
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
916
    ]
917

    
918

    
919
class OpRepairNodeStorage(OpCode):
920
  """Repairs the volume group on a node."""
921
  OP_DSC_FIELD = "node_name"
922
  OP_PARAMS = [
923
    _PNodeName,
924
    _PStorageType,
925
    _PStorageName,
926
    _PIgnoreConsistency,
927
    ]
928

    
929

    
930
class OpNodeSetParams(OpCode):
931
  """Change the parameters of a node."""
932
  OP_DSC_FIELD = "node_name"
933
  OP_PARAMS = [
934
    _PNodeName,
935
    _PForce,
936
    ("master_candidate", None, ht.TMaybeBool,
937
     "Whether the node should become a master candidate"),
938
    ("offline", None, ht.TMaybeBool,
939
     "Whether the node should be marked as offline"),
940
    ("drained", None, ht.TMaybeBool,
941
     "Whether the node should be marked as drained"),
942
    ("auto_promote", False, ht.TBool,
943
     "Whether node(s) should be promoted to master candidate if necessary"),
944
    ("master_capable", None, ht.TMaybeBool,
945
     "Denote whether node can become master or master candidate"),
946
    ("vm_capable", None, ht.TMaybeBool,
947
     "Denote whether node can host instances"),
948
    ("secondary_ip", None, ht.TMaybeString,
949
     "Change node's secondary IP address"),
950
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
951
    ("powered", None, ht.TMaybeBool,
952
     "Whether the node should be marked as powered"),
953
    ]
954

    
955

    
956
class OpNodePowercycle(OpCode):
957
  """Tries to powercycle a node."""
958
  OP_DSC_FIELD = "node_name"
959
  OP_PARAMS = [
960
    _PNodeName,
961
    _PForce,
962
    ]
963

    
964

    
965
class OpNodeMigrate(OpCode):
966
  """Migrate all instances from a node."""
967
  OP_DSC_FIELD = "node_name"
968
  OP_PARAMS = [
969
    _PNodeName,
970
    _PMigrationMode,
971
    _PMigrationLive,
972
    _PMigrationTargetNode,
973
    ("iallocator", None, ht.TMaybeString,
974
     "Iallocator for deciding the target node for shared-storage instances"),
975
    ]
976

    
977

    
978
class OpNodeEvacuate(OpCode):
979
  """Evacuate instances off a number of nodes."""
980
  OP_DSC_FIELD = "node_name"
981
  OP_PARAMS = [
982
    _PEarlyRelease,
983
    _PNodeName,
984
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
985
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
986
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
987
     "Node evacuation mode"),
988
    ]
989

    
990

    
991
# instance opcodes
992

    
993
class OpInstanceCreate(OpCode):
994
  """Create an instance.
995

996
  @ivar instance_name: Instance name
997
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
998
  @ivar source_handshake: Signed handshake from source (remote import only)
999
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1000
  @ivar source_instance_name: Previous name of instance (remote import only)
1001
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1002
    (remote import only)
1003

1004
  """
1005
  OP_DSC_FIELD = "instance_name"
1006
  OP_PARAMS = [
1007
    _PInstanceName,
1008
    _PForceVariant,
1009
    _PWaitForSync,
1010
    _PNameCheck,
1011
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1012
    ("disks", ht.NoDefault,
1013
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1014
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1015
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
1016
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1017
     " each disk definition must contain a ``%s`` value and"
1018
     " can contain an optional ``%s`` value denoting the disk access mode"
1019
     " (%s)" %
1020
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1021
      constants.IDISK_MODE,
1022
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1023
    ("disk_template", ht.NoDefault, _CheckDiskTemplate, "Disk template"),
1024
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1025
     "Driver for file-backed disks"),
1026
    ("file_storage_dir", None, ht.TMaybeString,
1027
     "Directory for storing file-backed disks"),
1028
    ("hvparams", ht.EmptyDict, ht.TDict,
1029
     "Hypervisor parameters for instance, hypervisor-dependent"),
1030
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1031
    ("iallocator", None, ht.TMaybeString,
1032
     "Iallocator for deciding which node(s) to use"),
1033
    ("identify_defaults", False, ht.TBool,
1034
     "Reset instance parameters to default if equal"),
1035
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1036
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1037
     "Instance creation mode"),
1038
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1039
     "List of NIC (network interface) definitions, for example"
1040
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1041
     " contain the optional values %s" %
1042
     (constants.INIC_IP,
1043
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1044
    ("no_install", None, ht.TMaybeBool,
1045
     "Do not install the OS (will disable automatic start)"),
1046
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1047
    ("os_type", None, ht.TMaybeString, "Operating system"),
1048
    ("pnode", None, ht.TMaybeString, "Primary node"),
1049
    ("snode", None, ht.TMaybeString, "Secondary node"),
1050
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1051
     "Signed handshake from source (remote import only)"),
1052
    ("source_instance_name", None, ht.TMaybeString,
1053
     "Source instance name (remote import only)"),
1054
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1055
     ht.TPositiveInt,
1056
     "How long source instance was given to shut down (remote import only)"),
1057
    ("source_x509_ca", None, ht.TMaybeString,
1058
     "Source X509 CA in PEM format (remote import only)"),
1059
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1060
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1061
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1062
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1063
    ]
1064

    
1065

    
1066
class OpInstanceReinstall(OpCode):
1067
  """Reinstall an instance's OS."""
1068
  OP_DSC_FIELD = "instance_name"
1069
  OP_PARAMS = [
1070
    _PInstanceName,
1071
    _PForceVariant,
1072
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1073
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1074
    ]
1075

    
1076

    
1077
class OpInstanceRemove(OpCode):
1078
  """Remove an instance."""
1079
  OP_DSC_FIELD = "instance_name"
1080
  OP_PARAMS = [
1081
    _PInstanceName,
1082
    _PShutdownTimeout,
1083
    ("ignore_failures", False, ht.TBool,
1084
     "Whether to ignore failures during removal"),
1085
    ]
1086

    
1087

    
1088
class OpInstanceRename(OpCode):
1089
  """Rename an instance."""
1090
  OP_PARAMS = [
1091
    _PInstanceName,
1092
    _PNameCheck,
1093
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1094
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1095
    ]
1096

    
1097

    
1098
class OpInstanceStartup(OpCode):
1099
  """Startup an instance."""
1100
  OP_DSC_FIELD = "instance_name"
1101
  OP_PARAMS = [
1102
    _PInstanceName,
1103
    _PForce,
1104
    _PIgnoreOfflineNodes,
1105
    ("hvparams", ht.EmptyDict, ht.TDict,
1106
     "Temporary hypervisor parameters, hypervisor-dependent"),
1107
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1108
    _PNoRemember,
1109
    _PStartupPaused,
1110
    ]
1111

    
1112

    
1113
class OpInstanceShutdown(OpCode):
1114
  """Shutdown an instance."""
1115
  OP_DSC_FIELD = "instance_name"
1116
  OP_PARAMS = [
1117
    _PInstanceName,
1118
    _PIgnoreOfflineNodes,
1119
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1120
     "How long to wait for instance to shut down"),
1121
    _PNoRemember,
1122
    ]
1123

    
1124

    
1125
class OpInstanceReboot(OpCode):
1126
  """Reboot an instance."""
1127
  OP_DSC_FIELD = "instance_name"
1128
  OP_PARAMS = [
1129
    _PInstanceName,
1130
    _PShutdownTimeout,
1131
    ("ignore_secondaries", False, ht.TBool,
1132
     "Whether to start the instance even if secondary disks are failing"),
1133
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1134
     "How to reboot instance"),
1135
    ]
1136

    
1137

    
1138
class OpInstanceReplaceDisks(OpCode):
1139
  """Replace the disks of an instance."""
1140
  OP_DSC_FIELD = "instance_name"
1141
  OP_PARAMS = [
1142
    _PInstanceName,
1143
    _PEarlyRelease,
1144
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1145
     "Replacement mode"),
1146
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1147
     "Disk indexes"),
1148
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1149
    ("iallocator", None, ht.TMaybeString,
1150
     "Iallocator for deciding new secondary node"),
1151
    ]
1152

    
1153

    
1154
class OpInstanceFailover(OpCode):
1155
  """Failover an instance."""
1156
  OP_DSC_FIELD = "instance_name"
1157
  OP_PARAMS = [
1158
    _PInstanceName,
1159
    _PShutdownTimeout,
1160
    _PIgnoreConsistency,
1161
    _PMigrationTargetNode,
1162
    ("iallocator", None, ht.TMaybeString,
1163
     "Iallocator for deciding the target node for shared-storage instances"),
1164
    ]
1165

    
1166

    
1167
class OpInstanceMigrate(OpCode):
1168
  """Migrate an instance.
1169

1170
  This migrates (without shutting down an instance) to its secondary
1171
  node.
1172

1173
  @ivar instance_name: the name of the instance
1174
  @ivar mode: the migration mode (live, non-live or None for auto)
1175

1176
  """
1177
  OP_DSC_FIELD = "instance_name"
1178
  OP_PARAMS = [
1179
    _PInstanceName,
1180
    _PMigrationMode,
1181
    _PMigrationLive,
1182
    _PMigrationTargetNode,
1183
    ("cleanup", False, ht.TBool,
1184
     "Whether a previously failed migration should be cleaned up"),
1185
    ("iallocator", None, ht.TMaybeString,
1186
     "Iallocator for deciding the target node for shared-storage instances"),
1187
    ("allow_failover", False, ht.TBool,
1188
     "Whether we can fallback to failover if migration is not possible"),
1189
    ]
1190

    
1191

    
1192
class OpInstanceMove(OpCode):
1193
  """Move an instance.
1194

1195
  This move (with shutting down an instance and data copying) to an
1196
  arbitrary node.
1197

1198
  @ivar instance_name: the name of the instance
1199
  @ivar target_node: the destination node
1200

1201
  """
1202
  OP_DSC_FIELD = "instance_name"
1203
  OP_PARAMS = [
1204
    _PInstanceName,
1205
    _PShutdownTimeout,
1206
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1207
    _PIgnoreConsistency,
1208
    ]
1209

    
1210

    
1211
class OpInstanceConsole(OpCode):
1212
  """Connect to an instance's console."""
1213
  OP_DSC_FIELD = "instance_name"
1214
  OP_PARAMS = [
1215
    _PInstanceName
1216
    ]
1217

    
1218

    
1219
class OpInstanceActivateDisks(OpCode):
1220
  """Activate an instance's disks."""
1221
  OP_DSC_FIELD = "instance_name"
1222
  OP_PARAMS = [
1223
    _PInstanceName,
1224
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1225
    ]
1226

    
1227

    
1228
class OpInstanceDeactivateDisks(OpCode):
1229
  """Deactivate an instance's disks."""
1230
  OP_DSC_FIELD = "instance_name"
1231
  OP_PARAMS = [
1232
    _PInstanceName,
1233
    _PForce,
1234
    ]
1235

    
1236

    
1237
class OpInstanceRecreateDisks(OpCode):
1238
  """Deactivate an instance's disks."""
1239
  OP_DSC_FIELD = "instance_name"
1240
  OP_PARAMS = [
1241
    _PInstanceName,
1242
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1243
     "List of disk indexes"),
1244
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1245
     "New instance nodes, if relocation is desired"),
1246
    ]
1247

    
1248

    
1249
class OpInstanceQuery(OpCode):
1250
  """Compute the list of instances."""
1251
  OP_PARAMS = [
1252
    _POutputFields,
1253
    _PUseLocking,
1254
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1255
     "Empty list to query all instances, instance names otherwise"),
1256
    ]
1257

    
1258

    
1259
class OpInstanceQueryData(OpCode):
1260
  """Compute the run-time status of instances."""
1261
  OP_PARAMS = [
1262
    _PUseLocking,
1263
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1264
     "Instance names"),
1265
    ("static", False, ht.TBool,
1266
     "Whether to only return configuration data without querying"
1267
     " nodes"),
1268
    ]
1269

    
1270

    
1271
class OpInstanceSetParams(OpCode):
1272
  """Change the parameters of an instance."""
1273
  OP_DSC_FIELD = "instance_name"
1274
  OP_PARAMS = [
1275
    _PInstanceName,
1276
    _PForce,
1277
    _PForceVariant,
1278
    # TODO: Use _TestNicDef
1279
    ("nics", ht.EmptyList, ht.TList,
1280
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1281
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1282
     " ``%s`` to remove the last NIC or a number to modify the settings"
1283
     " of the NIC with that index." %
1284
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1285
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1286
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1287
    ("hvparams", ht.EmptyDict, ht.TDict,
1288
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1289
    ("disk_template", None, ht.TOr(ht.TNone, _CheckDiskTemplate),
1290
     "Disk template for instance"),
1291
    ("remote_node", None, ht.TMaybeString,
1292
     "Secondary node (used when changing disk template)"),
1293
    ("os_name", None, ht.TMaybeString,
1294
     "Change instance's OS name. Does not reinstall the instance."),
1295
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1296
    ("wait_for_sync", True, ht.TBool,
1297
     "Whether to wait for the disk to synchronize, when changing template"),
1298
    ]
1299

    
1300

    
1301
class OpInstanceGrowDisk(OpCode):
1302
  """Grow a disk of an instance."""
1303
  OP_DSC_FIELD = "instance_name"
1304
  OP_PARAMS = [
1305
    _PInstanceName,
1306
    _PWaitForSync,
1307
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1308
    ("amount", ht.NoDefault, ht.TInt,
1309
     "Amount of disk space to add (megabytes)"),
1310
    ]
1311

    
1312

    
1313
class OpInstanceChangeGroup(OpCode):
1314
  """Moves an instance to another node group."""
1315
  OP_DSC_FIELD = "instance_name"
1316
  OP_PARAMS = [
1317
    _PInstanceName,
1318
    _PEarlyRelease,
1319
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1320
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1321
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1322
    ]
1323

    
1324

    
1325
# Node group opcodes
1326

    
1327
class OpGroupAdd(OpCode):
1328
  """Add a node group to the cluster."""
1329
  OP_DSC_FIELD = "group_name"
1330
  OP_PARAMS = [
1331
    _PGroupName,
1332
    _PNodeGroupAllocPolicy,
1333
    _PGroupNodeParams,
1334
    ]
1335

    
1336

    
1337
class OpGroupAssignNodes(OpCode):
1338
  """Assign nodes to a node group."""
1339
  OP_DSC_FIELD = "group_name"
1340
  OP_PARAMS = [
1341
    _PGroupName,
1342
    _PForce,
1343
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1344
     "List of nodes to assign"),
1345
    ]
1346

    
1347

    
1348
class OpGroupQuery(OpCode):
1349
  """Compute the list of node groups."""
1350
  OP_PARAMS = [
1351
    _POutputFields,
1352
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1353
     "Empty list to query all groups, group names otherwise"),
1354
    ]
1355

    
1356

    
1357
class OpGroupSetParams(OpCode):
1358
  """Change the parameters of a node group."""
1359
  OP_DSC_FIELD = "group_name"
1360
  OP_PARAMS = [
1361
    _PGroupName,
1362
    _PNodeGroupAllocPolicy,
1363
    _PGroupNodeParams,
1364
    ]
1365

    
1366

    
1367
class OpGroupRemove(OpCode):
1368
  """Remove a node group from the cluster."""
1369
  OP_DSC_FIELD = "group_name"
1370
  OP_PARAMS = [
1371
    _PGroupName,
1372
    ]
1373

    
1374

    
1375
class OpGroupRename(OpCode):
1376
  """Rename a node group in the cluster."""
1377
  OP_PARAMS = [
1378
    _PGroupName,
1379
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1380
    ]
1381

    
1382

    
1383
class OpGroupEvacuate(OpCode):
1384
  """Evacuate a node group in the cluster."""
1385
  OP_DSC_FIELD = "group_name"
1386
  OP_PARAMS = [
1387
    _PGroupName,
1388
    _PEarlyRelease,
1389
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1390
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1391
     "Destination group names or UUIDs"),
1392
    ]
1393

    
1394

    
1395
# OS opcodes
1396
class OpOsDiagnose(OpCode):
1397
  """Compute the list of guest operating systems."""
1398
  OP_PARAMS = [
1399
    _POutputFields,
1400
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1401
     "Which operating systems to diagnose"),
1402
    ]
1403

    
1404

    
1405
# Exports opcodes
1406
class OpBackupQuery(OpCode):
1407
  """Compute the list of exported images."""
1408
  OP_PARAMS = [
1409
    _PUseLocking,
1410
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1411
     "Empty list to query all nodes, node names otherwise"),
1412
    ]
1413

    
1414

    
1415
class OpBackupPrepare(OpCode):
1416
  """Prepares an instance export.
1417

1418
  @ivar instance_name: Instance name
1419
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1420

1421
  """
1422
  OP_DSC_FIELD = "instance_name"
1423
  OP_PARAMS = [
1424
    _PInstanceName,
1425
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1426
     "Export mode"),
1427
    ]
1428

    
1429

    
1430
class OpBackupExport(OpCode):
1431
  """Export an instance.
1432

1433
  For local exports, the export destination is the node name. For remote
1434
  exports, the export destination is a list of tuples, each consisting of
1435
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1436
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1437
  destination X509 CA must be a signed certificate.
1438

1439
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1440
  @ivar target_node: Export destination
1441
  @ivar x509_key_name: X509 key to use (remote export only)
1442
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1443
                             only)
1444

1445
  """
1446
  OP_DSC_FIELD = "instance_name"
1447
  OP_PARAMS = [
1448
    _PInstanceName,
1449
    _PShutdownTimeout,
1450
    # TODO: Rename target_node as it changes meaning for different export modes
1451
    # (e.g. "destination")
1452
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1453
     "Destination information, depends on export mode"),
1454
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1455
    ("remove_instance", False, ht.TBool,
1456
     "Whether to remove instance after export"),
1457
    ("ignore_remove_failures", False, ht.TBool,
1458
     "Whether to ignore failures while removing instances"),
1459
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1460
     "Export mode"),
1461
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1462
     "Name of X509 key (remote export only)"),
1463
    ("destination_x509_ca", None, ht.TMaybeString,
1464
     "Destination X509 CA (remote export only)"),
1465
    ]
1466

    
1467

    
1468
class OpBackupRemove(OpCode):
1469
  """Remove an instance's export."""
1470
  OP_DSC_FIELD = "instance_name"
1471
  OP_PARAMS = [
1472
    _PInstanceName,
1473
    ]
1474

    
1475

    
1476
# Tags opcodes
1477
class OpTagsGet(OpCode):
1478
  """Returns the tags of the given object."""
1479
  OP_DSC_FIELD = "name"
1480
  OP_PARAMS = [
1481
    _PTagKind,
1482
    # Name is only meaningful for nodes and instances
1483
    ("name", ht.NoDefault, ht.TMaybeString, None),
1484
    ]
1485

    
1486

    
1487
class OpTagsSearch(OpCode):
1488
  """Searches the tags in the cluster for a given pattern."""
1489
  OP_DSC_FIELD = "pattern"
1490
  OP_PARAMS = [
1491
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1492
    ]
1493

    
1494

    
1495
class OpTagsSet(OpCode):
1496
  """Add a list of tags on a given object."""
1497
  OP_PARAMS = [
1498
    _PTagKind,
1499
    _PTags,
1500
    # Name is only meaningful for nodes and instances
1501
    ("name", ht.NoDefault, ht.TMaybeString, None),
1502
    ]
1503

    
1504

    
1505
class OpTagsDel(OpCode):
1506
  """Remove a list of tags from a given object."""
1507
  OP_PARAMS = [
1508
    _PTagKind,
1509
    _PTags,
1510
    # Name is only meaningful for nodes and instances
1511
    ("name", ht.NoDefault, ht.TMaybeString, None),
1512
    ]
1513

    
1514
# Test opcodes
1515
class OpTestDelay(OpCode):
1516
  """Sleeps for a configured amount of time.
1517

1518
  This is used just for debugging and testing.
1519

1520
  Parameters:
1521
    - duration: the time to sleep
1522
    - on_master: if true, sleep on the master
1523
    - on_nodes: list of nodes in which to sleep
1524

1525
  If the on_master parameter is true, it will execute a sleep on the
1526
  master (before any node sleep).
1527

1528
  If the on_nodes list is not empty, it will sleep on those nodes
1529
  (after the sleep on the master, if that is enabled).
1530

1531
  As an additional feature, the case of duration < 0 will be reported
1532
  as an execution error, so this opcode can be used as a failure
1533
  generator. The case of duration == 0 will not be treated specially.
1534

1535
  """
1536
  OP_DSC_FIELD = "duration"
1537
  OP_PARAMS = [
1538
    ("duration", ht.NoDefault, ht.TNumber, None),
1539
    ("on_master", True, ht.TBool, None),
1540
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1541
    ("repeat", 0, ht.TPositiveInt, None),
1542
    ]
1543

    
1544

    
1545
class OpTestAllocator(OpCode):
1546
  """Allocator framework testing.
1547

1548
  This opcode has two modes:
1549
    - gather and return allocator input for a given mode (allocate new
1550
      or replace secondary) and a given instance definition (direction
1551
      'in')
1552
    - run a selected allocator for a given operation (as above) and
1553
      return the allocator output (direction 'out')
1554

1555
  """
1556
  OP_DSC_FIELD = "allocator"
1557
  OP_PARAMS = [
1558
    ("direction", ht.NoDefault,
1559
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1560
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1561
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1562
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1563
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1564
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1565
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1566
    ("hypervisor", None, ht.TMaybeString, None),
1567
    ("allocator", None, ht.TMaybeString, None),
1568
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1569
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1570
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1571
    ("os", None, ht.TMaybeString, None),
1572
    ("disk_template", None, ht.TMaybeString, None),
1573
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1574
     None),
1575
    ("evac_mode", None,
1576
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1577
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1578
     None),
1579
    ]
1580

    
1581

    
1582
class OpTestJqueue(OpCode):
1583
  """Utility opcode to test some aspects of the job queue.
1584

1585
  """
1586
  OP_PARAMS = [
1587
    ("notify_waitlock", False, ht.TBool, None),
1588
    ("notify_exec", False, ht.TBool, None),
1589
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1590
    ("fail", False, ht.TBool, None),
1591
    ]
1592

    
1593

    
1594
class OpTestDummy(OpCode):
1595
  """Utility opcode used by unittests.
1596

1597
  """
1598
  OP_PARAMS = [
1599
    ("result", ht.NoDefault, ht.NoType, None),
1600
    ("messages", ht.NoDefault, ht.NoType, None),
1601
    ("fail", ht.NoDefault, ht.NoType, None),
1602
    ("submit_jobs", None, ht.NoType, None),
1603
    ]
1604
  WITH_LU = False
1605

    
1606

    
1607
def _GetOpList():
1608
  """Returns list of all defined opcodes.
1609

1610
  Does not eliminate duplicates by C{OP_ID}.
1611

1612
  """
1613
  return [v for v in globals().values()
1614
          if (isinstance(v, type) and issubclass(v, OpCode) and
1615
              hasattr(v, "OP_ID") and v is not OpCode)]
1616

    
1617

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