Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 5a8648eb

History | View | Annotate | Download (50.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=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
_TSetParamsResultItemItems = [
157
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
158
  ht.TAny,
159
  ]
160

    
161
_TSetParamsResult = \
162
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
163
                     ht.TItems(_TSetParamsResultItemItems)))
164

    
165
_SUMMARY_PREFIX = {
166
  "CLUSTER_": "C_",
167
  "GROUP_": "G_",
168
  "NODE_": "N_",
169
  "INSTANCE_": "I_",
170
  }
171

    
172
#: Attribute name for dependencies
173
DEPEND_ATTR = "depends"
174

    
175
#: Attribute name for comment
176
COMMENT_ATTR = "comment"
177

    
178

    
179
def _NameToId(name):
180
  """Convert an opcode class name to an OP_ID.
181

182
  @type name: string
183
  @param name: the class name, as OpXxxYyy
184
  @rtype: string
185
  @return: the name in the OP_XXXX_YYYY format
186

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

    
199

    
200
def RequireFileStorage():
201
  """Checks that file storage is enabled.
202

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

206
  @raise errors.OpPrereqError: when file storage is disabled
207

208
  """
209
  if not constants.ENABLE_FILE_STORAGE:
210
    raise errors.OpPrereqError("File storage disabled at configure time",
211
                               errors.ECODE_INVAL)
212

    
213

    
214
def RequireSharedFileStorage():
215
  """Checks that shared file storage is enabled.
216

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

220
  @raise errors.OpPrereqError: when shared file storage is disabled
221

222
  """
223
  if not constants.ENABLE_SHARED_FILE_STORAGE:
224
    raise errors.OpPrereqError("Shared file storage disabled at"
225
                               " configure time", errors.ECODE_INVAL)
226

    
227

    
228
@ht.WithDesc("CheckFileStorage")
229
def _CheckFileStorage(value):
230
  """Ensures file storage is enabled if used.
231

232
  """
233
  if value == constants.DT_FILE:
234
    RequireFileStorage()
235
  elif value == constants.DT_SHARED_FILE:
236
    RequireSharedFileStorage()
237
  return True
238

    
239

    
240
def _BuildDiskTemplateCheck(accept_none):
241
  """Builds check for disk template.
242

243
  @type accept_none: bool
244
  @param accept_none: whether to accept None as a correct value
245
  @rtype: callable
246

247
  """
248
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
249

    
250
  if accept_none:
251
    template_check = ht.TOr(template_check, ht.TNone)
252

    
253
  return ht.TAnd(template_check, _CheckFileStorage)
254

    
255

    
256
def _CheckStorageType(storage_type):
257
  """Ensure a given storage type is valid.
258

259
  """
260
  if storage_type not in constants.VALID_STORAGE_TYPES:
261
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
262
                               errors.ECODE_INVAL)
263
  if storage_type == constants.ST_FILE:
264
    RequireFileStorage()
265
  return True
266

    
267

    
268
#: Storage type parameter
269
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
270
                 "Storage type")
271

    
272

    
273
class _AutoOpParamSlots(type):
274
  """Meta class for opcode definitions.
275

276
  """
277
  def __new__(mcs, name, bases, attrs):
278
    """Called when a class should be created.
279

280
    @param mcs: The meta class
281
    @param name: Name of created class
282
    @param bases: Base classes
283
    @type attrs: dict
284
    @param attrs: Class attributes
285

286
    """
287
    assert "__slots__" not in attrs, \
288
      "Class '%s' defines __slots__ when it should use OP_PARAMS" % name
289
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
290

    
291
    attrs["OP_ID"] = _NameToId(name)
292

    
293
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
294
    params = attrs.setdefault("OP_PARAMS", [])
295

    
296
    # Use parameter names as slots
297
    slots = [pname for (pname, _, _, _) in params]
298

    
299
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
300
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
301

    
302
    attrs["__slots__"] = slots
303

    
304
    return type.__new__(mcs, name, bases, attrs)
305

    
306

    
307
class BaseOpCode(object):
308
  """A simple serializable object.
309

310
  This object serves as a parent class for OpCode without any custom
311
  field handling.
312

313
  """
314
  # pylint: disable=E1101
315
  # as OP_ID is dynamically defined
316
  __metaclass__ = _AutoOpParamSlots
317

    
318
  def __init__(self, **kwargs):
319
    """Constructor for BaseOpCode.
320

321
    The constructor takes only keyword arguments and will set
322
    attributes on this object based on the passed arguments. As such,
323
    it means that you should not pass arguments which are not in the
324
    __slots__ attribute for this class.
325

326
    """
327
    slots = self._all_slots()
328
    for key in kwargs:
329
      if key not in slots:
330
        raise TypeError("Object %s doesn't support the parameter '%s'" %
331
                        (self.__class__.__name__, key))
332
      setattr(self, key, kwargs[key])
333

    
334
  def __getstate__(self):
335
    """Generic serializer.
336

337
    This method just returns the contents of the instance as a
338
    dictionary.
339

340
    @rtype:  C{dict}
341
    @return: the instance attributes and their values
342

343
    """
344
    state = {}
345
    for name in self._all_slots():
346
      if hasattr(self, name):
347
        state[name] = getattr(self, name)
348
    return state
349

    
350
  def __setstate__(self, state):
351
    """Generic unserializer.
352

353
    This method just restores from the serialized state the attributes
354
    of the current instance.
355

356
    @param state: the serialized opcode data
357
    @type state:  C{dict}
358

359
    """
360
    if not isinstance(state, dict):
361
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
362
                       type(state))
363

    
364
    for name in self._all_slots():
365
      if name not in state and hasattr(self, name):
366
        delattr(self, name)
367

    
368
    for name in state:
369
      setattr(self, name, state[name])
370

    
371
  @classmethod
372
  def _all_slots(cls):
373
    """Compute the list of all declared slots for a class.
374

375
    """
376
    slots = []
377
    for parent in cls.__mro__:
378
      slots.extend(getattr(parent, "__slots__", []))
379
    return slots
380

    
381
  @classmethod
382
  def GetAllParams(cls):
383
    """Compute list of all parameters for an opcode.
384

385
    """
386
    slots = []
387
    for parent in cls.__mro__:
388
      slots.extend(getattr(parent, "OP_PARAMS", []))
389
    return slots
390

    
391
  def Validate(self, set_defaults):
392
    """Validate opcode parameters, optionally setting default values.
393

394
    @type set_defaults: bool
395
    @param set_defaults: Whether to set default values
396
    @raise errors.OpPrereqError: When a parameter value doesn't match
397
                                 requirements
398

399
    """
400
    for (attr_name, default, test, _) in self.GetAllParams():
401
      assert test == ht.NoType or callable(test)
402

    
403
      if not hasattr(self, attr_name):
404
        if default == ht.NoDefault:
405
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
406
                                     (self.OP_ID, attr_name),
407
                                     errors.ECODE_INVAL)
408
        elif set_defaults:
409
          if callable(default):
410
            dval = default()
411
          else:
412
            dval = default
413
          setattr(self, attr_name, dval)
414

    
415
      if test == ht.NoType:
416
        # no tests here
417
        continue
418

    
419
      if set_defaults or hasattr(self, attr_name):
420
        attr_val = getattr(self, attr_name)
421
        if not test(attr_val):
422
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
423
                        self.OP_ID, attr_name, type(attr_val), attr_val)
424
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
425
                                     (self.OP_ID, attr_name),
426
                                     errors.ECODE_INVAL)
427

    
428

    
429
def _BuildJobDepCheck(relative):
430
  """Builds check for job dependencies (L{DEPEND_ATTR}).
431

432
  @type relative: bool
433
  @param relative: Whether to accept relative job IDs (negative)
434
  @rtype: callable
435

436
  """
437
  if relative:
438
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
439
  else:
440
    job_id = ht.TJobId
441

    
442
  job_dep = \
443
    ht.TAnd(ht.TIsLength(2),
444
            ht.TItems([job_id,
445
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
446

    
447
  return ht.TOr(ht.TNone, ht.TListOf(job_dep))
448

    
449

    
450
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
451

    
452
#: List of submission status and job ID as returned by C{SubmitManyJobs}
453
_TJobIdListItem = \
454
  ht.TAnd(ht.TIsLength(2),
455
          ht.TItems([ht.Comment("success")(ht.TBool),
456
                     ht.Comment("Job ID if successful, error message"
457
                                " otherwise")(ht.TOr(ht.TString,
458
                                                     ht.TJobId))]))
459
TJobIdList = ht.TListOf(_TJobIdListItem)
460

    
461
#: Result containing only list of submitted jobs
462
TJobIdListOnly = ht.TStrictDict(True, True, {
463
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
464
  })
465

    
466

    
467
class OpCode(BaseOpCode):
468
  """Abstract OpCode.
469

470
  This is the root of the actual OpCode hierarchy. All clases derived
471
  from this class should override OP_ID.
472

473
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
474
               children of this class.
475
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
476
                      string returned by Summary(); see the docstring of that
477
                      method for details).
478
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
479
                   get if not already defined, and types they must match.
480
  @cvar OP_RESULT: Callable to verify opcode result
481
  @cvar WITH_LU: Boolean that specifies whether this should be included in
482
      mcpu's dispatch table
483
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
484
                 the check steps
485
  @ivar priority: Opcode priority for queue
486

487
  """
488
  # pylint: disable=E1101
489
  # as OP_ID is dynamically defined
490
  WITH_LU = True
491
  OP_PARAMS = [
492
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
493
    ("debug_level", None, ht.TOr(ht.TNone, ht.TPositiveInt), "Debug level"),
494
    ("priority", constants.OP_PRIO_DEFAULT,
495
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
496
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
497
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
498
     " job IDs can be used"),
499
    (COMMENT_ATTR, None, ht.TMaybeString,
500
     "Comment describing the purpose of the opcode"),
501
    ]
502
  OP_RESULT = None
503

    
504
  def __getstate__(self):
505
    """Specialized getstate for opcodes.
506

507
    This method adds to the state dictionary the OP_ID of the class,
508
    so that on unload we can identify the correct class for
509
    instantiating the opcode.
510

511
    @rtype:   C{dict}
512
    @return:  the state as a dictionary
513

514
    """
515
    data = BaseOpCode.__getstate__(self)
516
    data["OP_ID"] = self.OP_ID
517
    return data
518

    
519
  @classmethod
520
  def LoadOpCode(cls, data):
521
    """Generic load opcode method.
522

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

527
    @type data:  C{dict}
528
    @param data: the serialized opcode
529

530
    """
531
    if not isinstance(data, dict):
532
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
533
    if "OP_ID" not in data:
534
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
535
    op_id = data["OP_ID"]
536
    op_class = None
537
    if op_id in OP_MAPPING:
538
      op_class = OP_MAPPING[op_id]
539
    else:
540
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
541
                       op_id)
542
    op = op_class()
543
    new_data = data.copy()
544
    del new_data["OP_ID"]
545
    op.__setstate__(new_data)
546
    return op
547

    
548
  def Summary(self):
549
    """Generates a summary description of this opcode.
550

551
    The summary is the value of the OP_ID attribute (without the "OP_"
552
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
553
    defined; this field should allow to easily identify the operation
554
    (for an instance creation job, e.g., it would be the instance
555
    name).
556

557
    """
558
    assert self.OP_ID is not None and len(self.OP_ID) > 3
559
    # all OP_ID start with OP_, we remove that
560
    txt = self.OP_ID[3:]
561
    field_name = getattr(self, "OP_DSC_FIELD", None)
562
    if field_name:
563
      field_value = getattr(self, field_name, None)
564
      if isinstance(field_value, (list, tuple)):
565
        field_value = ",".join(str(i) for i in field_value)
566
      txt = "%s(%s)" % (txt, field_value)
567
    return txt
568

    
569
  def TinySummary(self):
570
    """Generates a compact summary description of the opcode.
571

572
    """
573
    assert self.OP_ID.startswith("OP_")
574

    
575
    text = self.OP_ID[3:]
576

    
577
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
578
      if text.startswith(prefix):
579
        return supplement + text[len(prefix):]
580

    
581
    return text
582

    
583

    
584
# cluster opcodes
585

    
586
class OpClusterPostInit(OpCode):
587
  """Post cluster initialization.
588

589
  This opcode does not touch the cluster at all. Its purpose is to run hooks
590
  after the cluster has been initialized.
591

592
  """
593

    
594

    
595
class OpClusterDestroy(OpCode):
596
  """Destroy the cluster.
597

598
  This opcode has no other parameters. All the state is irreversibly
599
  lost after the execution of this opcode.
600

601
  """
602

    
603

    
604
class OpClusterQuery(OpCode):
605
  """Query cluster information."""
606

    
607

    
608
class OpClusterVerify(OpCode):
609
  """Submits all jobs necessary to verify the cluster.
610

611
  """
612
  OP_PARAMS = [
613
    _PDebugSimulateErrors,
614
    _PErrorCodes,
615
    _PSkipChecks,
616
    _PVerbose,
617
    ("group_name", None, ht.TMaybeString, "Group to verify")
618
    ]
619
  OP_RESULT = TJobIdListOnly
620

    
621

    
622
class OpClusterVerifyConfig(OpCode):
623
  """Verify the cluster config.
624

625
  """
626
  OP_PARAMS = [
627
    _PDebugSimulateErrors,
628
    _PErrorCodes,
629
    _PVerbose,
630
    ]
631
  OP_RESULT = ht.TBool
632

    
633

    
634
class OpClusterVerifyGroup(OpCode):
635
  """Run verify on a node group from the cluster.
636

637
  @type skip_checks: C{list}
638
  @ivar skip_checks: steps to be skipped from the verify process; this
639
                     needs to be a subset of
640
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
641
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
642

643
  """
644
  OP_DSC_FIELD = "group_name"
645
  OP_PARAMS = [
646
    _PGroupName,
647
    _PDebugSimulateErrors,
648
    _PErrorCodes,
649
    _PSkipChecks,
650
    _PVerbose,
651
    ]
652
  OP_RESULT = ht.TBool
653

    
654

    
655
class OpClusterVerifyDisks(OpCode):
656
  """Verify the cluster disks.
657

658
  """
659
  OP_RESULT = TJobIdListOnly
660

    
661

    
662
class OpGroupVerifyDisks(OpCode):
663
  """Verifies the status of all disks in a node group.
664

665
  Result: a tuple of three elements:
666
    - dict of node names with issues (values: error msg)
667
    - list of instances with degraded disks (that should be activated)
668
    - dict of instances with missing logical volumes (values: (node, vol)
669
      pairs with details about the missing volumes)
670

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

676
  Note that only instances that are drbd-based are taken into
677
  consideration. This might need to be revisited in the future.
678

679
  """
680
  OP_DSC_FIELD = "group_name"
681
  OP_PARAMS = [
682
    _PGroupName,
683
    ]
684
  OP_RESULT = \
685
    ht.TAnd(ht.TIsLength(3),
686
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
687
                       ht.TListOf(ht.TString),
688
                       ht.TDictOf(ht.TString, ht.TListOf(ht.TString))]))
689

    
690

    
691
class OpClusterRepairDiskSizes(OpCode):
692
  """Verify the disk sizes of the instances and fixes configuration
693
  mimatches.
694

695
  Parameters: optional instances list, in case we want to restrict the
696
  checks to only a subset of the instances.
697

698
  Result: a list of tuples, (instance, disk, new-size) for changed
699
  configurations.
700

701
  In normal operation, the list should be empty.
702

703
  @type instances: list
704
  @ivar instances: the list of instances to check, or empty for all instances
705

706
  """
707
  OP_PARAMS = [
708
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
709
    ]
710

    
711

    
712
class OpClusterConfigQuery(OpCode):
713
  """Query cluster configuration values."""
714
  OP_PARAMS = [
715
    _POutputFields
716
    ]
717

    
718

    
719
class OpClusterRename(OpCode):
720
  """Rename the cluster.
721

722
  @type name: C{str}
723
  @ivar name: The new name of the cluster. The name and/or the master IP
724
              address will be changed to match the new name and its IP
725
              address.
726

727
  """
728
  OP_DSC_FIELD = "name"
729
  OP_PARAMS = [
730
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
731
    ]
732

    
733

    
734
class OpClusterSetParams(OpCode):
735
  """Change the parameters of the cluster.
736

737
  @type vg_name: C{str} or C{None}
738
  @ivar vg_name: The new volume group name or None to disable LVM usage.
739

740
  """
741
  OP_PARAMS = [
742
    ("vg_name", None, ht.TMaybeString, "Volume group name"),
743
    ("enabled_hypervisors", None,
744
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
745
            ht.TNone),
746
     "List of enabled hypervisors"),
747
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
748
                              ht.TNone),
749
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
750
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
751
     "Cluster-wide backend parameter defaults"),
752
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
753
                            ht.TNone),
754
     "Cluster-wide per-OS hypervisor parameter defaults"),
755
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
756
                              ht.TNone),
757
     "Cluster-wide OS parameter defaults"),
758
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone),
759
     "Master candidate pool size"),
760
    ("uid_pool", None, ht.NoType,
761
     "Set UID pool, must be list of lists describing UID ranges (two items,"
762
     " start and end inclusive)"),
763
    ("add_uids", None, ht.NoType,
764
     "Extend UID pool, must be list of lists describing UID ranges (two"
765
     " items, start and end inclusive) to be added"),
766
    ("remove_uids", None, ht.NoType,
767
     "Shrink UID pool, must be list of lists describing UID ranges (two"
768
     " items, start and end inclusive) to be removed"),
769
    ("maintain_node_health", None, ht.TMaybeBool,
770
     "Whether to automatically maintain node health"),
771
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
772
     "Whether to wipe disks before allocating them to instances"),
773
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
774
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
775
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
776
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
777
     "Default iallocator for cluster"),
778
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
779
     "Master network device"),
780
    ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
781
     "Netmask of the master IP"),
782
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone),
783
     "List of reserved LVs"),
784
    ("hidden_os", None, _TestClusterOsList,
785
     "Modify list of hidden operating systems. Each modification must have"
786
     " two items, the operation and the OS name. The operation can be"
787
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
788
    ("blacklisted_os", None, _TestClusterOsList,
789
     "Modify list of blacklisted operating systems. Each modification must have"
790
     " two items, the operation and the OS name. The operation can be"
791
     " ``%s`` or ``%s``." % (constants.DDM_ADD, constants.DDM_REMOVE)),
792
    ]
793

    
794

    
795
class OpClusterRedistConf(OpCode):
796
  """Force a full push of the cluster configuration.
797

798
  """
799

    
800

    
801
class OpClusterActivateMasterIp(OpCode):
802
  """Activate the master IP on the master node.
803

804
  """
805

    
806

    
807
class OpClusterDeactivateMasterIp(OpCode):
808
  """Deactivate the master IP on the master node.
809

810
  """
811

    
812

    
813
class OpQuery(OpCode):
814
  """Query for resources/items.
815

816
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
817
  @ivar fields: List of fields to retrieve
818
  @ivar filter: Query filter
819

820
  """
821
  OP_DSC_FIELD = "what"
822
  OP_PARAMS = [
823
    _PQueryWhat,
824
    _PUseLocking,
825
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
826
     "Requested fields"),
827
    ("filter", None, ht.TOr(ht.TNone, ht.TListOf),
828
     "Query filter"),
829
    ]
830

    
831

    
832
class OpQueryFields(OpCode):
833
  """Query for available resource/item fields.
834

835
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
836
  @ivar fields: List of fields to retrieve
837

838
  """
839
  OP_DSC_FIELD = "what"
840
  OP_PARAMS = [
841
    _PQueryWhat,
842
    ("fields", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
843
     "Requested fields; if not given, all are returned"),
844
    ]
845

    
846

    
847
class OpOobCommand(OpCode):
848
  """Interact with OOB."""
849
  OP_PARAMS = [
850
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
851
     "List of nodes to run the OOB command against"),
852
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
853
     "OOB command to be run"),
854
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
855
     "Timeout before the OOB helper will be terminated"),
856
    ("ignore_status", False, ht.TBool,
857
     "Ignores the node offline status for power off"),
858
    ("power_delay", constants.OOB_POWER_DELAY, ht.TPositiveFloat,
859
     "Time in seconds to wait between powering on nodes"),
860
    ]
861

    
862

    
863
# node opcodes
864

    
865
class OpNodeRemove(OpCode):
866
  """Remove a node.
867

868
  @type node_name: C{str}
869
  @ivar node_name: The name of the node to remove. If the node still has
870
                   instances on it, the operation will fail.
871

872
  """
873
  OP_DSC_FIELD = "node_name"
874
  OP_PARAMS = [
875
    _PNodeName,
876
    ]
877

    
878

    
879
class OpNodeAdd(OpCode):
880
  """Add a node to the cluster.
881

882
  @type node_name: C{str}
883
  @ivar node_name: The name of the node to add. This can be a short name,
884
                   but it will be expanded to the FQDN.
885
  @type primary_ip: IP address
886
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
887
                    opcode is submitted, but will be filled during the node
888
                    add (so it will be visible in the job query).
889
  @type secondary_ip: IP address
890
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
891
                      if the cluster has been initialized in 'dual-network'
892
                      mode, otherwise it must not be given.
893
  @type readd: C{bool}
894
  @ivar readd: Whether to re-add an existing node to the cluster. If
895
               this is not passed, then the operation will abort if the node
896
               name is already in the cluster; use this parameter to 'repair'
897
               a node that had its configuration broken, or was reinstalled
898
               without removal from the cluster.
899
  @type group: C{str}
900
  @ivar group: The node group to which this node will belong.
901
  @type vm_capable: C{bool}
902
  @ivar vm_capable: The vm_capable node attribute
903
  @type master_capable: C{bool}
904
  @ivar master_capable: The master_capable node attribute
905

906
  """
907
  OP_DSC_FIELD = "node_name"
908
  OP_PARAMS = [
909
    _PNodeName,
910
    ("primary_ip", None, ht.NoType, "Primary IP address"),
911
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
912
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
913
    ("group", None, ht.TMaybeString, "Initial node group"),
914
    ("master_capable", None, ht.TMaybeBool,
915
     "Whether node can become master or master candidate"),
916
    ("vm_capable", None, ht.TMaybeBool,
917
     "Whether node can host instances"),
918
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
919
    ]
920

    
921

    
922
class OpNodeQuery(OpCode):
923
  """Compute the list of nodes."""
924
  OP_PARAMS = [
925
    _POutputFields,
926
    _PUseLocking,
927
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
928
     "Empty list to query all nodes, node names otherwise"),
929
    ]
930

    
931

    
932
class OpNodeQueryvols(OpCode):
933
  """Get list of volumes on node."""
934
  OP_PARAMS = [
935
    _POutputFields,
936
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
937
     "Empty list to query all nodes, node names otherwise"),
938
    ]
939

    
940

    
941
class OpNodeQueryStorage(OpCode):
942
  """Get information on storage for node(s)."""
943
  OP_PARAMS = [
944
    _POutputFields,
945
    _PStorageType,
946
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
947
    ("name", None, ht.TMaybeString, "Storage name"),
948
    ]
949

    
950

    
951
class OpNodeModifyStorage(OpCode):
952
  """Modifies the properies of a storage unit"""
953
  OP_PARAMS = [
954
    _PNodeName,
955
    _PStorageType,
956
    _PStorageName,
957
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
958
    ]
959

    
960

    
961
class OpRepairNodeStorage(OpCode):
962
  """Repairs the volume group on a node."""
963
  OP_DSC_FIELD = "node_name"
964
  OP_PARAMS = [
965
    _PNodeName,
966
    _PStorageType,
967
    _PStorageName,
968
    _PIgnoreConsistency,
969
    ]
970

    
971

    
972
class OpNodeSetParams(OpCode):
973
  """Change the parameters of a node."""
974
  OP_DSC_FIELD = "node_name"
975
  OP_PARAMS = [
976
    _PNodeName,
977
    _PForce,
978
    ("master_candidate", None, ht.TMaybeBool,
979
     "Whether the node should become a master candidate"),
980
    ("offline", None, ht.TMaybeBool,
981
     "Whether the node should be marked as offline"),
982
    ("drained", None, ht.TMaybeBool,
983
     "Whether the node should be marked as drained"),
984
    ("auto_promote", False, ht.TBool,
985
     "Whether node(s) should be promoted to master candidate if necessary"),
986
    ("master_capable", None, ht.TMaybeBool,
987
     "Denote whether node can become master or master candidate"),
988
    ("vm_capable", None, ht.TMaybeBool,
989
     "Denote whether node can host instances"),
990
    ("secondary_ip", None, ht.TMaybeString,
991
     "Change node's secondary IP address"),
992
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
993
    ("powered", None, ht.TMaybeBool,
994
     "Whether the node should be marked as powered"),
995
    ]
996
  OP_RESULT = _TSetParamsResult
997

    
998

    
999
class OpNodePowercycle(OpCode):
1000
  """Tries to powercycle a node."""
1001
  OP_DSC_FIELD = "node_name"
1002
  OP_PARAMS = [
1003
    _PNodeName,
1004
    _PForce,
1005
    ]
1006

    
1007

    
1008
class OpNodeMigrate(OpCode):
1009
  """Migrate all instances from a node."""
1010
  OP_DSC_FIELD = "node_name"
1011
  OP_PARAMS = [
1012
    _PNodeName,
1013
    _PMigrationMode,
1014
    _PMigrationLive,
1015
    _PMigrationTargetNode,
1016
    ("iallocator", None, ht.TMaybeString,
1017
     "Iallocator for deciding the target node for shared-storage instances"),
1018
    ]
1019

    
1020

    
1021
class OpNodeEvacuate(OpCode):
1022
  """Evacuate instances off a number of nodes."""
1023
  OP_DSC_FIELD = "node_name"
1024
  OP_PARAMS = [
1025
    _PEarlyRelease,
1026
    _PNodeName,
1027
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1028
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1029
    ("mode", ht.NoDefault, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES),
1030
     "Node evacuation mode"),
1031
    ]
1032
  OP_RESULT = TJobIdListOnly
1033

    
1034

    
1035
# instance opcodes
1036

    
1037
class OpInstanceCreate(OpCode):
1038
  """Create an instance.
1039

1040
  @ivar instance_name: Instance name
1041
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1042
  @ivar source_handshake: Signed handshake from source (remote import only)
1043
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1044
  @ivar source_instance_name: Previous name of instance (remote import only)
1045
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1046
    (remote import only)
1047

1048
  """
1049
  OP_DSC_FIELD = "instance_name"
1050
  OP_PARAMS = [
1051
    _PInstanceName,
1052
    _PForceVariant,
1053
    _PWaitForSync,
1054
    _PNameCheck,
1055
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1056
    ("disks", ht.NoDefault,
1057
     # TODO: Generate check from constants.IDISK_PARAMS_TYPES
1058
     ht.TListOf(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
1059
                           ht.TOr(ht.TNonEmptyString, ht.TInt))),
1060
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1061
     " each disk definition must contain a ``%s`` value and"
1062
     " can contain an optional ``%s`` value denoting the disk access mode"
1063
     " (%s)" %
1064
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1065
      constants.IDISK_MODE,
1066
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1067
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1068
     "Disk template"),
1069
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1070
     "Driver for file-backed disks"),
1071
    ("file_storage_dir", None, ht.TMaybeString,
1072
     "Directory for storing file-backed disks"),
1073
    ("hvparams", ht.EmptyDict, ht.TDict,
1074
     "Hypervisor parameters for instance, hypervisor-dependent"),
1075
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1076
    ("iallocator", None, ht.TMaybeString,
1077
     "Iallocator for deciding which node(s) to use"),
1078
    ("identify_defaults", False, ht.TBool,
1079
     "Reset instance parameters to default if equal"),
1080
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1081
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1082
     "Instance creation mode"),
1083
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1084
     "List of NIC (network interface) definitions, for example"
1085
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1086
     " contain the optional values %s" %
1087
     (constants.INIC_IP,
1088
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1089
    ("no_install", None, ht.TMaybeBool,
1090
     "Do not install the OS (will disable automatic start)"),
1091
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1092
    ("os_type", None, ht.TMaybeString, "Operating system"),
1093
    ("pnode", None, ht.TMaybeString, "Primary node"),
1094
    ("snode", None, ht.TMaybeString, "Secondary node"),
1095
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1096
     "Signed handshake from source (remote import only)"),
1097
    ("source_instance_name", None, ht.TMaybeString,
1098
     "Source instance name (remote import only)"),
1099
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1100
     ht.TPositiveInt,
1101
     "How long source instance was given to shut down (remote import only)"),
1102
    ("source_x509_ca", None, ht.TMaybeString,
1103
     "Source X509 CA in PEM format (remote import only)"),
1104
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1105
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1106
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1107
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1108
    ]
1109
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1110

    
1111

    
1112
class OpInstanceReinstall(OpCode):
1113
  """Reinstall an instance's OS."""
1114
  OP_DSC_FIELD = "instance_name"
1115
  OP_PARAMS = [
1116
    _PInstanceName,
1117
    _PForceVariant,
1118
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1119
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1120
    ]
1121

    
1122

    
1123
class OpInstanceRemove(OpCode):
1124
  """Remove an instance."""
1125
  OP_DSC_FIELD = "instance_name"
1126
  OP_PARAMS = [
1127
    _PInstanceName,
1128
    _PShutdownTimeout,
1129
    ("ignore_failures", False, ht.TBool,
1130
     "Whether to ignore failures during removal"),
1131
    ]
1132

    
1133

    
1134
class OpInstanceRename(OpCode):
1135
  """Rename an instance."""
1136
  OP_PARAMS = [
1137
    _PInstanceName,
1138
    _PNameCheck,
1139
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1140
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1141
    ]
1142
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1143

    
1144

    
1145
class OpInstanceStartup(OpCode):
1146
  """Startup an instance."""
1147
  OP_DSC_FIELD = "instance_name"
1148
  OP_PARAMS = [
1149
    _PInstanceName,
1150
    _PForce,
1151
    _PIgnoreOfflineNodes,
1152
    ("hvparams", ht.EmptyDict, ht.TDict,
1153
     "Temporary hypervisor parameters, hypervisor-dependent"),
1154
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1155
    _PNoRemember,
1156
    _PStartupPaused,
1157
    ]
1158

    
1159

    
1160
class OpInstanceShutdown(OpCode):
1161
  """Shutdown an instance."""
1162
  OP_DSC_FIELD = "instance_name"
1163
  OP_PARAMS = [
1164
    _PInstanceName,
1165
    _PIgnoreOfflineNodes,
1166
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TPositiveInt,
1167
     "How long to wait for instance to shut down"),
1168
    _PNoRemember,
1169
    ]
1170

    
1171

    
1172
class OpInstanceReboot(OpCode):
1173
  """Reboot an instance."""
1174
  OP_DSC_FIELD = "instance_name"
1175
  OP_PARAMS = [
1176
    _PInstanceName,
1177
    _PShutdownTimeout,
1178
    ("ignore_secondaries", False, ht.TBool,
1179
     "Whether to start the instance even if secondary disks are failing"),
1180
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1181
     "How to reboot instance"),
1182
    ]
1183

    
1184

    
1185
class OpInstanceReplaceDisks(OpCode):
1186
  """Replace the disks of an instance."""
1187
  OP_DSC_FIELD = "instance_name"
1188
  OP_PARAMS = [
1189
    _PInstanceName,
1190
    _PEarlyRelease,
1191
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1192
     "Replacement mode"),
1193
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1194
     "Disk indexes"),
1195
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1196
    ("iallocator", None, ht.TMaybeString,
1197
     "Iallocator for deciding new secondary node"),
1198
    ]
1199

    
1200

    
1201
class OpInstanceFailover(OpCode):
1202
  """Failover an instance."""
1203
  OP_DSC_FIELD = "instance_name"
1204
  OP_PARAMS = [
1205
    _PInstanceName,
1206
    _PShutdownTimeout,
1207
    _PIgnoreConsistency,
1208
    _PMigrationTargetNode,
1209
    ("iallocator", None, ht.TMaybeString,
1210
     "Iallocator for deciding the target node for shared-storage instances"),
1211
    ]
1212

    
1213

    
1214
class OpInstanceMigrate(OpCode):
1215
  """Migrate an instance.
1216

1217
  This migrates (without shutting down an instance) to its secondary
1218
  node.
1219

1220
  @ivar instance_name: the name of the instance
1221
  @ivar mode: the migration mode (live, non-live or None for auto)
1222

1223
  """
1224
  OP_DSC_FIELD = "instance_name"
1225
  OP_PARAMS = [
1226
    _PInstanceName,
1227
    _PMigrationMode,
1228
    _PMigrationLive,
1229
    _PMigrationTargetNode,
1230
    ("cleanup", False, ht.TBool,
1231
     "Whether a previously failed migration should be cleaned up"),
1232
    ("iallocator", None, ht.TMaybeString,
1233
     "Iallocator for deciding the target node for shared-storage instances"),
1234
    ("allow_failover", False, ht.TBool,
1235
     "Whether we can fallback to failover if migration is not possible"),
1236
    ]
1237

    
1238

    
1239
class OpInstanceMove(OpCode):
1240
  """Move an instance.
1241

1242
  This move (with shutting down an instance and data copying) to an
1243
  arbitrary node.
1244

1245
  @ivar instance_name: the name of the instance
1246
  @ivar target_node: the destination node
1247

1248
  """
1249
  OP_DSC_FIELD = "instance_name"
1250
  OP_PARAMS = [
1251
    _PInstanceName,
1252
    _PShutdownTimeout,
1253
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1254
    _PIgnoreConsistency,
1255
    ]
1256

    
1257

    
1258
class OpInstanceConsole(OpCode):
1259
  """Connect to an instance's console."""
1260
  OP_DSC_FIELD = "instance_name"
1261
  OP_PARAMS = [
1262
    _PInstanceName
1263
    ]
1264

    
1265

    
1266
class OpInstanceActivateDisks(OpCode):
1267
  """Activate an instance's disks."""
1268
  OP_DSC_FIELD = "instance_name"
1269
  OP_PARAMS = [
1270
    _PInstanceName,
1271
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1272
    ]
1273

    
1274

    
1275
class OpInstanceDeactivateDisks(OpCode):
1276
  """Deactivate an instance's disks."""
1277
  OP_DSC_FIELD = "instance_name"
1278
  OP_PARAMS = [
1279
    _PInstanceName,
1280
    _PForce,
1281
    ]
1282

    
1283

    
1284
class OpInstanceRecreateDisks(OpCode):
1285
  """Recreate an instance's disks."""
1286
  OP_DSC_FIELD = "instance_name"
1287
  OP_PARAMS = [
1288
    _PInstanceName,
1289
    ("disks", ht.EmptyList, ht.TListOf(ht.TPositiveInt),
1290
     "List of disk indexes"),
1291
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1292
     "New instance nodes, if relocation is desired"),
1293
    ]
1294

    
1295

    
1296
class OpInstanceQuery(OpCode):
1297
  """Compute the list of instances."""
1298
  OP_PARAMS = [
1299
    _POutputFields,
1300
    _PUseLocking,
1301
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1302
     "Empty list to query all instances, instance names otherwise"),
1303
    ]
1304

    
1305

    
1306
class OpInstanceQueryData(OpCode):
1307
  """Compute the run-time status of instances."""
1308
  OP_PARAMS = [
1309
    _PUseLocking,
1310
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1311
     "Instance names"),
1312
    ("static", False, ht.TBool,
1313
     "Whether to only return configuration data without querying"
1314
     " nodes"),
1315
    ]
1316

    
1317

    
1318
class OpInstanceSetParams(OpCode):
1319
  """Change the parameters of an instance."""
1320
  OP_DSC_FIELD = "instance_name"
1321
  OP_PARAMS = [
1322
    _PInstanceName,
1323
    _PForce,
1324
    _PForceVariant,
1325
    # TODO: Use _TestNicDef
1326
    ("nics", ht.EmptyList, ht.TList,
1327
     "List of NIC changes. Each item is of the form ``(op, settings)``."
1328
     " ``op`` can be ``%s`` to add a new NIC with the specified settings,"
1329
     " ``%s`` to remove the last NIC or a number to modify the settings"
1330
     " of the NIC with that index." %
1331
     (constants.DDM_ADD, constants.DDM_REMOVE)),
1332
    ("disks", ht.EmptyList, ht.TList, "List of disk changes. See ``nics``."),
1333
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1334
    ("hvparams", ht.EmptyDict, ht.TDict,
1335
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1336
    ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1337
     "Disk template for instance"),
1338
    ("remote_node", None, ht.TMaybeString,
1339
     "Secondary node (used when changing disk template)"),
1340
    ("os_name", None, ht.TMaybeString,
1341
     "Change instance's OS name. Does not reinstall the instance."),
1342
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1343
    ("wait_for_sync", True, ht.TBool,
1344
     "Whether to wait for the disk to synchronize, when changing template"),
1345
    ]
1346
  OP_RESULT = _TSetParamsResult
1347

    
1348

    
1349
class OpInstanceGrowDisk(OpCode):
1350
  """Grow a disk of an instance."""
1351
  OP_DSC_FIELD = "instance_name"
1352
  OP_PARAMS = [
1353
    _PInstanceName,
1354
    _PWaitForSync,
1355
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1356
    ("amount", ht.NoDefault, ht.TInt,
1357
     "Amount of disk space to add (megabytes)"),
1358
    ]
1359

    
1360

    
1361
class OpInstanceChangeGroup(OpCode):
1362
  """Moves an instance to another node group."""
1363
  OP_DSC_FIELD = "instance_name"
1364
  OP_PARAMS = [
1365
    _PInstanceName,
1366
    _PEarlyRelease,
1367
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1368
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1369
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1370
    ]
1371
  OP_RESULT = TJobIdListOnly
1372

    
1373

    
1374
# Node group opcodes
1375

    
1376
class OpGroupAdd(OpCode):
1377
  """Add a node group to the cluster."""
1378
  OP_DSC_FIELD = "group_name"
1379
  OP_PARAMS = [
1380
    _PGroupName,
1381
    _PNodeGroupAllocPolicy,
1382
    _PGroupNodeParams,
1383
    ]
1384

    
1385

    
1386
class OpGroupAssignNodes(OpCode):
1387
  """Assign nodes to a node group."""
1388
  OP_DSC_FIELD = "group_name"
1389
  OP_PARAMS = [
1390
    _PGroupName,
1391
    _PForce,
1392
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1393
     "List of nodes to assign"),
1394
    ]
1395

    
1396

    
1397
class OpGroupQuery(OpCode):
1398
  """Compute the list of node groups."""
1399
  OP_PARAMS = [
1400
    _POutputFields,
1401
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1402
     "Empty list to query all groups, group names otherwise"),
1403
    ]
1404

    
1405

    
1406
class OpGroupSetParams(OpCode):
1407
  """Change the parameters of a node group."""
1408
  OP_DSC_FIELD = "group_name"
1409
  OP_PARAMS = [
1410
    _PGroupName,
1411
    _PNodeGroupAllocPolicy,
1412
    _PGroupNodeParams,
1413
    ]
1414
  OP_RESULT = _TSetParamsResult
1415

    
1416

    
1417
class OpGroupRemove(OpCode):
1418
  """Remove a node group from the cluster."""
1419
  OP_DSC_FIELD = "group_name"
1420
  OP_PARAMS = [
1421
    _PGroupName,
1422
    ]
1423

    
1424

    
1425
class OpGroupRename(OpCode):
1426
  """Rename a node group in the cluster."""
1427
  OP_PARAMS = [
1428
    _PGroupName,
1429
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1430
    ]
1431
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1432

    
1433

    
1434
class OpGroupEvacuate(OpCode):
1435
  """Evacuate a node group in the cluster."""
1436
  OP_DSC_FIELD = "group_name"
1437
  OP_PARAMS = [
1438
    _PGroupName,
1439
    _PEarlyRelease,
1440
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1441
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1442
     "Destination group names or UUIDs"),
1443
    ]
1444
  OP_RESULT = TJobIdListOnly
1445

    
1446

    
1447
# OS opcodes
1448
class OpOsDiagnose(OpCode):
1449
  """Compute the list of guest operating systems."""
1450
  OP_PARAMS = [
1451
    _POutputFields,
1452
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1453
     "Which operating systems to diagnose"),
1454
    ]
1455

    
1456

    
1457
# Exports opcodes
1458
class OpBackupQuery(OpCode):
1459
  """Compute the list of exported images."""
1460
  OP_PARAMS = [
1461
    _PUseLocking,
1462
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1463
     "Empty list to query all nodes, node names otherwise"),
1464
    ]
1465

    
1466

    
1467
class OpBackupPrepare(OpCode):
1468
  """Prepares an instance export.
1469

1470
  @ivar instance_name: Instance name
1471
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1472

1473
  """
1474
  OP_DSC_FIELD = "instance_name"
1475
  OP_PARAMS = [
1476
    _PInstanceName,
1477
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1478
     "Export mode"),
1479
    ]
1480

    
1481

    
1482
class OpBackupExport(OpCode):
1483
  """Export an instance.
1484

1485
  For local exports, the export destination is the node name. For remote
1486
  exports, the export destination is a list of tuples, each consisting of
1487
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1488
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1489
  destination X509 CA must be a signed certificate.
1490

1491
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1492
  @ivar target_node: Export destination
1493
  @ivar x509_key_name: X509 key to use (remote export only)
1494
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1495
                             only)
1496

1497
  """
1498
  OP_DSC_FIELD = "instance_name"
1499
  OP_PARAMS = [
1500
    _PInstanceName,
1501
    _PShutdownTimeout,
1502
    # TODO: Rename target_node as it changes meaning for different export modes
1503
    # (e.g. "destination")
1504
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1505
     "Destination information, depends on export mode"),
1506
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1507
    ("remove_instance", False, ht.TBool,
1508
     "Whether to remove instance after export"),
1509
    ("ignore_remove_failures", False, ht.TBool,
1510
     "Whether to ignore failures while removing instances"),
1511
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1512
     "Export mode"),
1513
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1514
     "Name of X509 key (remote export only)"),
1515
    ("destination_x509_ca", None, ht.TMaybeString,
1516
     "Destination X509 CA (remote export only)"),
1517
    ]
1518

    
1519

    
1520
class OpBackupRemove(OpCode):
1521
  """Remove an instance's export."""
1522
  OP_DSC_FIELD = "instance_name"
1523
  OP_PARAMS = [
1524
    _PInstanceName,
1525
    ]
1526

    
1527

    
1528
# Tags opcodes
1529
class OpTagsGet(OpCode):
1530
  """Returns the tags of the given object."""
1531
  OP_DSC_FIELD = "name"
1532
  OP_PARAMS = [
1533
    _PTagKind,
1534
    # Name is only meaningful for nodes and instances
1535
    ("name", ht.NoDefault, ht.TMaybeString, None),
1536
    ]
1537

    
1538

    
1539
class OpTagsSearch(OpCode):
1540
  """Searches the tags in the cluster for a given pattern."""
1541
  OP_DSC_FIELD = "pattern"
1542
  OP_PARAMS = [
1543
    ("pattern", ht.NoDefault, ht.TNonEmptyString, None),
1544
    ]
1545

    
1546

    
1547
class OpTagsSet(OpCode):
1548
  """Add a list of tags on a given object."""
1549
  OP_PARAMS = [
1550
    _PTagKind,
1551
    _PTags,
1552
    # Name is only meaningful for nodes and instances
1553
    ("name", ht.NoDefault, ht.TMaybeString, None),
1554
    ]
1555

    
1556

    
1557
class OpTagsDel(OpCode):
1558
  """Remove a list of tags from a given object."""
1559
  OP_PARAMS = [
1560
    _PTagKind,
1561
    _PTags,
1562
    # Name is only meaningful for nodes and instances
1563
    ("name", ht.NoDefault, ht.TMaybeString, None),
1564
    ]
1565

    
1566

    
1567
# Test opcodes
1568
class OpTestDelay(OpCode):
1569
  """Sleeps for a configured amount of time.
1570

1571
  This is used just for debugging and testing.
1572

1573
  Parameters:
1574
    - duration: the time to sleep
1575
    - on_master: if true, sleep on the master
1576
    - on_nodes: list of nodes in which to sleep
1577

1578
  If the on_master parameter is true, it will execute a sleep on the
1579
  master (before any node sleep).
1580

1581
  If the on_nodes list is not empty, it will sleep on those nodes
1582
  (after the sleep on the master, if that is enabled).
1583

1584
  As an additional feature, the case of duration < 0 will be reported
1585
  as an execution error, so this opcode can be used as a failure
1586
  generator. The case of duration == 0 will not be treated specially.
1587

1588
  """
1589
  OP_DSC_FIELD = "duration"
1590
  OP_PARAMS = [
1591
    ("duration", ht.NoDefault, ht.TNumber, None),
1592
    ("on_master", True, ht.TBool, None),
1593
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1594
    ("repeat", 0, ht.TPositiveInt, None),
1595
    ]
1596

    
1597

    
1598
class OpTestAllocator(OpCode):
1599
  """Allocator framework testing.
1600

1601
  This opcode has two modes:
1602
    - gather and return allocator input for a given mode (allocate new
1603
      or replace secondary) and a given instance definition (direction
1604
      'in')
1605
    - run a selected allocator for a given operation (as above) and
1606
      return the allocator output (direction 'out')
1607

1608
  """
1609
  OP_DSC_FIELD = "allocator"
1610
  OP_PARAMS = [
1611
    ("direction", ht.NoDefault,
1612
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1613
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1614
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1615
    ("nics", ht.NoDefault, ht.TOr(ht.TNone, ht.TListOf(
1616
     ht.TDictOf(ht.TElemOf([constants.INIC_MAC, constants.INIC_IP, "bridge"]),
1617
                ht.TOr(ht.TNone, ht.TNonEmptyString)))), None),
1618
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1619
    ("hypervisor", None, ht.TMaybeString, None),
1620
    ("allocator", None, ht.TMaybeString, None),
1621
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1622
    ("memory", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1623
    ("vcpus", None, ht.TOr(ht.TNone, ht.TPositiveInt), None),
1624
    ("os", None, ht.TMaybeString, None),
1625
    ("disk_template", None, ht.TMaybeString, None),
1626
    ("instances", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1627
     None),
1628
    ("evac_mode", None,
1629
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1630
    ("target_groups", None, ht.TOr(ht.TNone, ht.TListOf(ht.TNonEmptyString)),
1631
     None),
1632
    ]
1633

    
1634

    
1635
class OpTestJqueue(OpCode):
1636
  """Utility opcode to test some aspects of the job queue.
1637

1638
  """
1639
  OP_PARAMS = [
1640
    ("notify_waitlock", False, ht.TBool, None),
1641
    ("notify_exec", False, ht.TBool, None),
1642
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1643
    ("fail", False, ht.TBool, None),
1644
    ]
1645

    
1646

    
1647
class OpTestDummy(OpCode):
1648
  """Utility opcode used by unittests.
1649

1650
  """
1651
  OP_PARAMS = [
1652
    ("result", ht.NoDefault, ht.NoType, None),
1653
    ("messages", ht.NoDefault, ht.NoType, None),
1654
    ("fail", ht.NoDefault, ht.NoType, None),
1655
    ("submit_jobs", None, ht.NoType, None),
1656
    ]
1657
  WITH_LU = False
1658

    
1659

    
1660
def _GetOpList():
1661
  """Returns list of all defined opcodes.
1662

1663
  Does not eliminate duplicates by C{OP_ID}.
1664

1665
  """
1666
  return [v for v in globals().values()
1667
          if (isinstance(v, type) and issubclass(v, OpCode) and
1668
              hasattr(v, "OP_ID") and v is not OpCode)]
1669

    
1670

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