Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ 2c9fa1ff

History | View | Annotate | Download (60.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012 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 constants
40
from ganeti import errors
41
from ganeti import ht
42
from ganeti import objects
43
from ganeti import objectutils
44

    
45

    
46
# Common opcode attributes
47

    
48
#: output fields for a query operation
49
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
50
                  "Selected output fields")
51

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

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

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

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

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

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

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

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

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

    
87
#: List of tag strings
88
_PTags = ("tags", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
89
          "List of tag names")
90

    
91
_PForceVariant = ("force_variant", False, ht.TBool,
92
                  "Whether to force an unknown OS variant")
93

    
94
_PWaitForSync = ("wait_for_sync", True, ht.TBool,
95
                 "Whether to wait for the disk to synchronize")
96

    
97
_PWaitForSyncFalse = ("wait_for_sync", False, ht.TBool,
98
                      "Whether to wait for the disk to synchronize"
99
                      " (defaults to false)")
100

    
101
_PIgnoreConsistency = ("ignore_consistency", False, ht.TBool,
102
                       "Whether to ignore disk consistency")
103

    
104
_PStorageName = ("name", ht.NoDefault, ht.TMaybeString, "Storage name")
105

    
106
_PUseLocking = ("use_locking", False, ht.TBool,
107
                "Whether to use synchronization")
108

    
109
_PNameCheck = ("name_check", True, ht.TBool, "Whether to check name")
110

    
111
_PNodeGroupAllocPolicy = \
112
  ("alloc_policy", None,
113
   ht.TOr(ht.TNone, ht.TElemOf(constants.VALID_ALLOC_POLICIES)),
114
   "Instance allocation policy")
115

    
116
_PGroupNodeParams = ("ndparams", None, ht.TMaybeDict,
117
                     "Default node parameters for group")
118

    
119
_PQueryWhat = ("what", ht.NoDefault, ht.TElemOf(constants.QR_VIA_OP),
120
               "Resource(s) to query for")
121

    
122
_PEarlyRelease = ("early_release", False, ht.TBool,
123
                  "Whether to release locks as soon as possible")
124

    
125
_PIpCheckDoc = "Whether to ensure instance's IP address is inactive"
126

    
127
#: Do not remember instance state changes
128
_PNoRemember = ("no_remember", False, ht.TBool,
129
                "Do not remember the state change")
130

    
131
#: Target node for instance migration/failover
132
_PMigrationTargetNode = ("target_node", None, ht.TMaybeString,
133
                         "Target node for shared-storage instances")
134

    
135
_PStartupPaused = ("startup_paused", False, ht.TBool,
136
                   "Pause instance at startup")
137

    
138
_PVerbose = ("verbose", False, ht.TBool, "Verbose mode")
139

    
140
# Parameters for cluster verification
141
_PDebugSimulateErrors = ("debug_simulate_errors", False, ht.TBool,
142
                         "Whether to simulate errors (useful for debugging)")
143
_PErrorCodes = ("error_codes", False, ht.TBool, "Error codes")
144
_PSkipChecks = ("skip_checks", ht.EmptyList,
145
                ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS)),
146
                "Which checks to skip")
147
_PIgnoreErrors = ("ignore_errors", ht.EmptyList,
148
                  ht.TListOf(ht.TElemOf(constants.CV_ALL_ECODES_STRINGS)),
149
                  "List of error codes that should be treated as warnings")
150

    
151
# Disk parameters
152
_PDiskParams = ("diskparams", None,
153
                ht.TOr(
154
                  ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict),
155
                  ht.TNone),
156
                "Disk templates' parameter defaults")
157

    
158
# Parameters for node resource model
159
_PHvState = ("hv_state", None, ht.TMaybeDict, "Set hypervisor states")
160
_PDiskState = ("disk_state", None, ht.TMaybeDict, "Set disk states")
161

    
162

    
163
_PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
164
                   "Whether to ignore ipolicy violations")
165

    
166
# Allow runtime changes while migrating
167
_PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
168
                      "Allow runtime changes (eg. memory ballooning)")
169

    
170

    
171
#: OP_ID conversion regular expression
172
_OPID_RE = re.compile("([a-z])([A-Z])")
173

    
174
#: Utility function for L{OpClusterSetParams}
175
_TestClusterOsListItem = \
176
  ht.TAnd(ht.TIsLength(2), ht.TItems([
177
    ht.TElemOf(constants.DDMS_VALUES),
178
    ht.TNonEmptyString,
179
    ]))
180

    
181
_TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
182

    
183
# TODO: Generate check from constants.INIC_PARAMS_TYPES
184
#: Utility function for testing NIC definitions
185
_TestNicDef = \
186
  ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
187
                                          ht.TOr(ht.TNone, ht.TNonEmptyString)))
188

    
189
_TSetParamsResultItemItems = [
190
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
191
  ht.Comment("new value")(ht.TAny),
192
  ]
193

    
194
_TSetParamsResult = \
195
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
196
                     ht.TItems(_TSetParamsResultItemItems)))
197

    
198
# TODO: Generate check from constants.IDISK_PARAMS_TYPES (however, not all users
199
# of this check support all parameters)
200
_TDiskParams = \
201
  ht.Comment("Disk parameters")(ht.TDictOf(ht.TElemOf(constants.IDISK_PARAMS),
202
                                           ht.TOr(ht.TNonEmptyString, ht.TInt)))
203

    
204
_TQueryRow = \
205
  ht.TListOf(ht.TAnd(ht.TIsLength(2),
206
                     ht.TItems([ht.TElemOf(constants.RS_ALL),
207
                                ht.TAny])))
208

    
209
_TQueryResult = ht.TListOf(_TQueryRow)
210

    
211
_TOldQueryRow = ht.TListOf(ht.TAny)
212

    
213
_TOldQueryResult = ht.TListOf(_TOldQueryRow)
214

    
215

    
216
_SUMMARY_PREFIX = {
217
  "CLUSTER_": "C_",
218
  "GROUP_": "G_",
219
  "NODE_": "N_",
220
  "INSTANCE_": "I_",
221
  }
222

    
223
#: Attribute name for dependencies
224
DEPEND_ATTR = "depends"
225

    
226
#: Attribute name for comment
227
COMMENT_ATTR = "comment"
228

    
229

    
230
def _NameToId(name):
231
  """Convert an opcode class name to an OP_ID.
232

233
  @type name: string
234
  @param name: the class name, as OpXxxYyy
235
  @rtype: string
236
  @return: the name in the OP_XXXX_YYYY format
237

238
  """
239
  if not name.startswith("Op"):
240
    return None
241
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
242
  # consume any input, and hence we would just have all the elements
243
  # in the list, one by one; but it seems that split doesn't work on
244
  # non-consuming input, hence we have to process the input string a
245
  # bit
246
  name = _OPID_RE.sub(r"\1,\2", name)
247
  elems = name.split(",")
248
  return "_".join(n.upper() for n in elems)
249

    
250

    
251
def _GenerateObjectTypeCheck(obj, fields_types):
252
  """Helper to generate type checks for objects.
253

254
  @param obj: The object to generate type checks
255
  @param fields_types: The fields and their types as a dict
256
  @return: A ht type check function
257

258
  """
259
  assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
260
    "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
261
  return ht.TStrictDict(True, True, fields_types)
262

    
263

    
264
_TQueryFieldDef = \
265
  _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
266
    "name": ht.TNonEmptyString,
267
    "title": ht.TNonEmptyString,
268
    "kind": ht.TElemOf(constants.QFT_ALL),
269
    "doc": ht.TNonEmptyString,
270
    })
271

    
272

    
273
def RequireFileStorage():
274
  """Checks that file storage is enabled.
275

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

279
  @raise errors.OpPrereqError: when file storage is disabled
280

281
  """
282
  if not constants.ENABLE_FILE_STORAGE:
283
    raise errors.OpPrereqError("File storage disabled at configure time",
284
                               errors.ECODE_INVAL)
285

    
286

    
287
def RequireSharedFileStorage():
288
  """Checks that shared file storage is enabled.
289

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

293
  @raise errors.OpPrereqError: when shared file storage is disabled
294

295
  """
296
  if not constants.ENABLE_SHARED_FILE_STORAGE:
297
    raise errors.OpPrereqError("Shared file storage disabled at"
298
                               " configure time", errors.ECODE_INVAL)
299

    
300

    
301
@ht.WithDesc("CheckFileStorage")
302
def _CheckFileStorage(value):
303
  """Ensures file storage is enabled if used.
304

305
  """
306
  if value == constants.DT_FILE:
307
    RequireFileStorage()
308
  elif value == constants.DT_SHARED_FILE:
309
    RequireSharedFileStorage()
310
  return True
311

    
312

    
313
def _BuildDiskTemplateCheck(accept_none):
314
  """Builds check for disk template.
315

316
  @type accept_none: bool
317
  @param accept_none: whether to accept None as a correct value
318
  @rtype: callable
319

320
  """
321
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
322

    
323
  if accept_none:
324
    template_check = ht.TOr(template_check, ht.TNone)
325

    
326
  return ht.TAnd(template_check, _CheckFileStorage)
327

    
328

    
329
def _CheckStorageType(storage_type):
330
  """Ensure a given storage type is valid.
331

332
  """
333
  if storage_type not in constants.VALID_STORAGE_TYPES:
334
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
335
                               errors.ECODE_INVAL)
336
  if storage_type == constants.ST_FILE:
337
    # TODO: What about shared file storage?
338
    RequireFileStorage()
339
  return True
340

    
341

    
342
#: Storage type parameter
343
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
344
                 "Storage type")
345

    
346

    
347
class _AutoOpParamSlots(objectutils.AutoSlots):
348
  """Meta class for opcode definitions.
349

350
  """
351
  def __new__(mcs, name, bases, attrs):
352
    """Called when a class should be created.
353

354
    @param mcs: The meta class
355
    @param name: Name of created class
356
    @param bases: Base classes
357
    @type attrs: dict
358
    @param attrs: Class attributes
359

360
    """
361
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
362

    
363
    slots = mcs._GetSlots(attrs)
364
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
365
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
366

    
367
    attrs["OP_ID"] = _NameToId(name)
368

    
369
    return objectutils.AutoSlots.__new__(mcs, name, bases, attrs)
370

    
371
  @classmethod
372
  def _GetSlots(mcs, attrs):
373
    """Build the slots out of OP_PARAMS.
374

375
    """
376
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
377
    params = attrs.setdefault("OP_PARAMS", [])
378

    
379
    # Use parameter names as slots
380
    return [pname for (pname, _, _, _) in params]
381

    
382

    
383
class BaseOpCode(objectutils.ValidatedSlots):
384
  """A simple serializable object.
385

386
  This object serves as a parent class for OpCode without any custom
387
  field handling.
388

389
  """
390
  # pylint: disable=E1101
391
  # as OP_ID is dynamically defined
392
  __metaclass__ = _AutoOpParamSlots
393

    
394
  def __getstate__(self):
395
    """Generic serializer.
396

397
    This method just returns the contents of the instance as a
398
    dictionary.
399

400
    @rtype:  C{dict}
401
    @return: the instance attributes and their values
402

403
    """
404
    state = {}
405
    for name in self.GetAllSlots():
406
      if hasattr(self, name):
407
        state[name] = getattr(self, name)
408
    return state
409

    
410
  def __setstate__(self, state):
411
    """Generic unserializer.
412

413
    This method just restores from the serialized state the attributes
414
    of the current instance.
415

416
    @param state: the serialized opcode data
417
    @type state:  C{dict}
418

419
    """
420
    if not isinstance(state, dict):
421
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
422
                       type(state))
423

    
424
    for name in self.GetAllSlots():
425
      if name not in state and hasattr(self, name):
426
        delattr(self, name)
427

    
428
    for name in state:
429
      setattr(self, name, state[name])
430

    
431
  @classmethod
432
  def GetAllParams(cls):
433
    """Compute list of all parameters for an opcode.
434

435
    """
436
    slots = []
437
    for parent in cls.__mro__:
438
      slots.extend(getattr(parent, "OP_PARAMS", []))
439
    return slots
440

    
441
  def Validate(self, set_defaults): # pylint: disable=W0221
442
    """Validate opcode parameters, optionally setting default values.
443

444
    @type set_defaults: bool
445
    @param set_defaults: Whether to set default values
446
    @raise errors.OpPrereqError: When a parameter value doesn't match
447
                                 requirements
448

449
    """
450
    for (attr_name, default, test, _) in self.GetAllParams():
451
      assert test == ht.NoType or callable(test)
452

    
453
      if not hasattr(self, attr_name):
454
        if default == ht.NoDefault:
455
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
456
                                     (self.OP_ID, attr_name),
457
                                     errors.ECODE_INVAL)
458
        elif set_defaults:
459
          if callable(default):
460
            dval = default()
461
          else:
462
            dval = default
463
          setattr(self, attr_name, dval)
464

    
465
      if test == ht.NoType:
466
        # no tests here
467
        continue
468

    
469
      if set_defaults or hasattr(self, attr_name):
470
        attr_val = getattr(self, attr_name)
471
        if not test(attr_val):
472
          logging.error("OpCode %s, parameter %s, has invalid type %s/value %s"
473
                        " expecting type %s",
474
                        self.OP_ID, attr_name, type(attr_val), attr_val, test)
475
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
476
                                     (self.OP_ID, attr_name),
477
                                     errors.ECODE_INVAL)
478

    
479

    
480
def _BuildJobDepCheck(relative):
481
  """Builds check for job dependencies (L{DEPEND_ATTR}).
482

483
  @type relative: bool
484
  @param relative: Whether to accept relative job IDs (negative)
485
  @rtype: callable
486

487
  """
488
  if relative:
489
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
490
  else:
491
    job_id = ht.TJobId
492

    
493
  job_dep = \
494
    ht.TAnd(ht.TIsLength(2),
495
            ht.TItems([job_id,
496
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
497

    
498
  return ht.TMaybeListOf(job_dep)
499

    
500

    
501
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
502

    
503
#: List of submission status and job ID as returned by C{SubmitManyJobs}
504
_TJobIdListItem = \
505
  ht.TAnd(ht.TIsLength(2),
506
          ht.TItems([ht.Comment("success")(ht.TBool),
507
                     ht.Comment("Job ID if successful, error message"
508
                                " otherwise")(ht.TOr(ht.TString,
509
                                                     ht.TJobId))]))
510
TJobIdList = ht.TListOf(_TJobIdListItem)
511

    
512
#: Result containing only list of submitted jobs
513
TJobIdListOnly = ht.TStrictDict(True, True, {
514
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
515
  })
516

    
517

    
518
class OpCode(BaseOpCode):
519
  """Abstract OpCode.
520

521
  This is the root of the actual OpCode hierarchy. All clases derived
522
  from this class should override OP_ID.
523

524
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
525
               children of this class.
526
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
527
                      string returned by Summary(); see the docstring of that
528
                      method for details).
529
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
530
                   get if not already defined, and types they must match.
531
  @cvar OP_RESULT: Callable to verify opcode result
532
  @cvar WITH_LU: Boolean that specifies whether this should be included in
533
      mcpu's dispatch table
534
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
535
                 the check steps
536
  @ivar priority: Opcode priority for queue
537

538
  """
539
  # pylint: disable=E1101
540
  # as OP_ID is dynamically defined
541
  WITH_LU = True
542
  OP_PARAMS = [
543
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
544
    ("debug_level", None, ht.TOr(ht.TNone, ht.TNonNegativeInt), "Debug level"),
545
    ("priority", constants.OP_PRIO_DEFAULT,
546
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
547
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
548
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
549
     " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
550
     " for details"),
551
    (COMMENT_ATTR, None, ht.TMaybeString,
552
     "Comment describing the purpose of the opcode"),
553
    ]
554
  OP_RESULT = None
555

    
556
  def __getstate__(self):
557
    """Specialized getstate for opcodes.
558

559
    This method adds to the state dictionary the OP_ID of the class,
560
    so that on unload we can identify the correct class for
561
    instantiating the opcode.
562

563
    @rtype:   C{dict}
564
    @return:  the state as a dictionary
565

566
    """
567
    data = BaseOpCode.__getstate__(self)
568
    data["OP_ID"] = self.OP_ID
569
    return data
570

    
571
  @classmethod
572
  def LoadOpCode(cls, data):
573
    """Generic load opcode method.
574

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

579
    @type data:  C{dict}
580
    @param data: the serialized opcode
581

582
    """
583
    if not isinstance(data, dict):
584
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
585
    if "OP_ID" not in data:
586
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
587
    op_id = data["OP_ID"]
588
    op_class = None
589
    if op_id in OP_MAPPING:
590
      op_class = OP_MAPPING[op_id]
591
    else:
592
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
593
                       op_id)
594
    op = op_class()
595
    new_data = data.copy()
596
    del new_data["OP_ID"]
597
    op.__setstate__(new_data)
598
    return op
599

    
600
  def Summary(self):
601
    """Generates a summary description of this opcode.
602

603
    The summary is the value of the OP_ID attribute (without the "OP_"
604
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
605
    defined; this field should allow to easily identify the operation
606
    (for an instance creation job, e.g., it would be the instance
607
    name).
608

609
    """
610
    assert self.OP_ID is not None and len(self.OP_ID) > 3
611
    # all OP_ID start with OP_, we remove that
612
    txt = self.OP_ID[3:]
613
    field_name = getattr(self, "OP_DSC_FIELD", None)
614
    if field_name:
615
      field_value = getattr(self, field_name, None)
616
      if isinstance(field_value, (list, tuple)):
617
        field_value = ",".join(str(i) for i in field_value)
618
      txt = "%s(%s)" % (txt, field_value)
619
    return txt
620

    
621
  def TinySummary(self):
622
    """Generates a compact summary description of the opcode.
623

624
    """
625
    assert self.OP_ID.startswith("OP_")
626

    
627
    text = self.OP_ID[3:]
628

    
629
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
630
      if text.startswith(prefix):
631
        return supplement + text[len(prefix):]
632

    
633
    return text
634

    
635

    
636
# cluster opcodes
637

    
638
class OpClusterPostInit(OpCode):
639
  """Post cluster initialization.
640

641
  This opcode does not touch the cluster at all. Its purpose is to run hooks
642
  after the cluster has been initialized.
643

644
  """
645
  OP_RESULT = ht.TBool
646

    
647

    
648
class OpClusterDestroy(OpCode):
649
  """Destroy the cluster.
650

651
  This opcode has no other parameters. All the state is irreversibly
652
  lost after the execution of this opcode.
653

654
  """
655
  OP_RESULT = ht.TNonEmptyString
656

    
657

    
658
class OpClusterQuery(OpCode):
659
  """Query cluster information."""
660
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
661

    
662

    
663
class OpClusterVerify(OpCode):
664
  """Submits all jobs necessary to verify the cluster.
665

666
  """
667
  OP_PARAMS = [
668
    _PDebugSimulateErrors,
669
    _PErrorCodes,
670
    _PSkipChecks,
671
    _PIgnoreErrors,
672
    _PVerbose,
673
    ("group_name", None, ht.TMaybeString, "Group to verify")
674
    ]
675
  OP_RESULT = TJobIdListOnly
676

    
677

    
678
class OpClusterVerifyConfig(OpCode):
679
  """Verify the cluster config.
680

681
  """
682
  OP_PARAMS = [
683
    _PDebugSimulateErrors,
684
    _PErrorCodes,
685
    _PIgnoreErrors,
686
    _PVerbose,
687
    ]
688
  OP_RESULT = ht.TBool
689

    
690

    
691
class OpClusterVerifyGroup(OpCode):
692
  """Run verify on a node group from the cluster.
693

694
  @type skip_checks: C{list}
695
  @ivar skip_checks: steps to be skipped from the verify process; this
696
                     needs to be a subset of
697
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
698
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
699

700
  """
701
  OP_DSC_FIELD = "group_name"
702
  OP_PARAMS = [
703
    _PGroupName,
704
    _PDebugSimulateErrors,
705
    _PErrorCodes,
706
    _PSkipChecks,
707
    _PIgnoreErrors,
708
    _PVerbose,
709
    ]
710
  OP_RESULT = ht.TBool
711

    
712

    
713
class OpClusterVerifyDisks(OpCode):
714
  """Verify the cluster disks.
715

716
  """
717
  OP_RESULT = TJobIdListOnly
718

    
719

    
720
class OpGroupVerifyDisks(OpCode):
721
  """Verifies the status of all disks in a node group.
722

723
  Result: a tuple of three elements:
724
    - dict of node names with issues (values: error msg)
725
    - list of instances with degraded disks (that should be activated)
726
    - dict of instances with missing logical volumes (values: (node, vol)
727
      pairs with details about the missing volumes)
728

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

734
  Note that only instances that are drbd-based are taken into
735
  consideration. This might need to be revisited in the future.
736

737
  """
738
  OP_DSC_FIELD = "group_name"
739
  OP_PARAMS = [
740
    _PGroupName,
741
    ]
742
  OP_RESULT = \
743
    ht.TAnd(ht.TIsLength(3),
744
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
745
                       ht.TListOf(ht.TString),
746
                       ht.TDictOf(ht.TString,
747
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
748

    
749

    
750
class OpClusterRepairDiskSizes(OpCode):
751
  """Verify the disk sizes of the instances and fixes configuration
752
  mimatches.
753

754
  Parameters: optional instances list, in case we want to restrict the
755
  checks to only a subset of the instances.
756

757
  Result: a list of tuples, (instance, disk, new-size) for changed
758
  configurations.
759

760
  In normal operation, the list should be empty.
761

762
  @type instances: list
763
  @ivar instances: the list of instances to check, or empty for all instances
764

765
  """
766
  OP_PARAMS = [
767
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
768
    ]
769
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
770
                                 ht.TItems([ht.TNonEmptyString,
771
                                            ht.TNonNegativeInt,
772
                                            ht.TNonNegativeInt])))
773

    
774

    
775
class OpClusterConfigQuery(OpCode):
776
  """Query cluster configuration values."""
777
  OP_PARAMS = [
778
    _POutputFields
779
    ]
780
  OP_RESULT = ht.TListOf(ht.TAny)
781

    
782

    
783
class OpClusterRename(OpCode):
784
  """Rename the cluster.
785

786
  @type name: C{str}
787
  @ivar name: The new name of the cluster. The name and/or the master IP
788
              address will be changed to match the new name and its IP
789
              address.
790

791
  """
792
  OP_DSC_FIELD = "name"
793
  OP_PARAMS = [
794
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
795
    ]
796
  OP_RESULT = ht.TNonEmptyString
797

    
798

    
799
class OpClusterSetParams(OpCode):
800
  """Change the parameters of the cluster.
801

802
  @type vg_name: C{str} or C{None}
803
  @ivar vg_name: The new volume group name or None to disable LVM usage.
804

805
  """
806
  OP_PARAMS = [
807
    _PHvState,
808
    _PDiskState,
809
    ("vg_name", None, ht.TOr(ht.TString, ht.TNone), "Volume group name"),
810
    ("enabled_hypervisors", None,
811
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
812
            ht.TNone),
813
     "List of enabled hypervisors"),
814
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
815
                              ht.TNone),
816
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
817
    ("beparams", None, ht.TOr(ht.TDict, ht.TNone),
818
     "Cluster-wide backend parameter defaults"),
819
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
820
                            ht.TNone),
821
     "Cluster-wide per-OS hypervisor parameter defaults"),
822
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
823
                              ht.TNone),
824
     "Cluster-wide OS parameter defaults"),
825
    _PDiskParams,
826
    ("candidate_pool_size", None, ht.TOr(ht.TPositiveInt, ht.TNone),
827
     "Master candidate pool size"),
828
    ("uid_pool", None, ht.NoType,
829
     "Set UID pool, must be list of lists describing UID ranges (two items,"
830
     " start and end inclusive)"),
831
    ("add_uids", None, ht.NoType,
832
     "Extend UID pool, must be list of lists describing UID ranges (two"
833
     " items, start and end inclusive) to be added"),
834
    ("remove_uids", None, ht.NoType,
835
     "Shrink UID pool, must be list of lists describing UID ranges (two"
836
     " items, start and end inclusive) to be removed"),
837
    ("maintain_node_health", None, ht.TMaybeBool,
838
     "Whether to automatically maintain node health"),
839
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
840
     "Whether to wipe disks before allocating them to instances"),
841
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
842
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
843
    ("ipolicy", None, ht.TMaybeDict,
844
     "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
845
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone), "DRBD helper program"),
846
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone),
847
     "Default iallocator for cluster"),
848
    ("master_netdev", None, ht.TOr(ht.TString, ht.TNone),
849
     "Master network device"),
850
    ("master_netmask", None, ht.TOr(ht.TInt, ht.TNone),
851
     "Netmask of the master IP"),
852
    ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
853
     "List of reserved LVs"),
854
    ("hidden_os", None, _TestClusterOsList,
855
     "Modify list of hidden operating systems: each modification must have"
856
     " two items, the operation and the OS name; the operation can be"
857
     " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
858
    ("blacklisted_os", None, _TestClusterOsList,
859
     "Modify list of blacklisted operating systems: each modification must"
860
     " have two items, the operation and the OS name; the operation can be"
861
     " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
862
    ("use_external_mip_script", None, ht.TMaybeBool,
863
     "Whether to use an external master IP address setup script"),
864
    ]
865
  OP_RESULT = ht.TNone
866

    
867

    
868
class OpClusterRedistConf(OpCode):
869
  """Force a full push of the cluster configuration.
870

871
  """
872
  OP_RESULT = ht.TNone
873

    
874

    
875
class OpClusterActivateMasterIp(OpCode):
876
  """Activate the master IP on the master node.
877

878
  """
879
  OP_RESULT = ht.TNone
880

    
881

    
882
class OpClusterDeactivateMasterIp(OpCode):
883
  """Deactivate the master IP on the master node.
884

885
  """
886
  OP_RESULT = ht.TNone
887

    
888

    
889
class OpQuery(OpCode):
890
  """Query for resources/items.
891

892
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
893
  @ivar fields: List of fields to retrieve
894
  @ivar qfilter: Query filter
895

896
  """
897
  OP_DSC_FIELD = "what"
898
  OP_PARAMS = [
899
    _PQueryWhat,
900
    _PUseLocking,
901
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
902
     "Requested fields"),
903
    ("qfilter", None, ht.TOr(ht.TNone, ht.TList),
904
     "Query filter"),
905
    ]
906
  OP_RESULT = \
907
    _GenerateObjectTypeCheck(objects.QueryResponse, {
908
      "fields": ht.TListOf(_TQueryFieldDef),
909
      "data": _TQueryResult,
910
      })
911

    
912

    
913
class OpQueryFields(OpCode):
914
  """Query for available resource/item fields.
915

916
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
917
  @ivar fields: List of fields to retrieve
918

919
  """
920
  OP_DSC_FIELD = "what"
921
  OP_PARAMS = [
922
    _PQueryWhat,
923
    ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
924
     "Requested fields; if not given, all are returned"),
925
    ]
926
  OP_RESULT = \
927
    _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
928
      "fields": ht.TListOf(_TQueryFieldDef),
929
      })
930

    
931

    
932
class OpOobCommand(OpCode):
933
  """Interact with OOB."""
934
  OP_PARAMS = [
935
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
936
     "List of nodes to run the OOB command against"),
937
    ("command", None, ht.TElemOf(constants.OOB_COMMANDS),
938
     "OOB command to be run"),
939
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
940
     "Timeout before the OOB helper will be terminated"),
941
    ("ignore_status", False, ht.TBool,
942
     "Ignores the node offline status for power off"),
943
    ("power_delay", constants.OOB_POWER_DELAY, ht.TNonNegativeFloat,
944
     "Time in seconds to wait between powering on nodes"),
945
    ]
946
  # Fixme: Make it more specific with all the special cases in LUOobCommand
947
  OP_RESULT = _TQueryResult
948

    
949

    
950
class OpRestrictedCommand(OpCode):
951
  """Runs a restricted command on node(s).
952

953
  """
954
  OP_PARAMS = [
955
    _PUseLocking,
956
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
957
     "Nodes on which the command should be run (at least one)"),
958
    ("command", ht.NoDefault, ht.TNonEmptyString,
959
     "Command name (no parameters)"),
960
    ]
961

    
962
  _RESULT_ITEMS = [
963
    ht.Comment("success")(ht.TBool),
964
    ht.Comment("output or error message")(ht.TString),
965
    ]
966

    
967
  OP_RESULT = \
968
    ht.TListOf(ht.TAnd(ht.TIsLength(len(_RESULT_ITEMS)),
969
                       ht.TItems(_RESULT_ITEMS)))
970

    
971

    
972
# node opcodes
973

    
974
class OpNodeRemove(OpCode):
975
  """Remove a node.
976

977
  @type node_name: C{str}
978
  @ivar node_name: The name of the node to remove. If the node still has
979
                   instances on it, the operation will fail.
980

981
  """
982
  OP_DSC_FIELD = "node_name"
983
  OP_PARAMS = [
984
    _PNodeName,
985
    ]
986
  OP_RESULT = ht.TNone
987

    
988

    
989
class OpNodeAdd(OpCode):
990
  """Add a node to the cluster.
991

992
  @type node_name: C{str}
993
  @ivar node_name: The name of the node to add. This can be a short name,
994
                   but it will be expanded to the FQDN.
995
  @type primary_ip: IP address
996
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
997
                    opcode is submitted, but will be filled during the node
998
                    add (so it will be visible in the job query).
999
  @type secondary_ip: IP address
1000
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
1001
                      if the cluster has been initialized in 'dual-network'
1002
                      mode, otherwise it must not be given.
1003
  @type readd: C{bool}
1004
  @ivar readd: Whether to re-add an existing node to the cluster. If
1005
               this is not passed, then the operation will abort if the node
1006
               name is already in the cluster; use this parameter to 'repair'
1007
               a node that had its configuration broken, or was reinstalled
1008
               without removal from the cluster.
1009
  @type group: C{str}
1010
  @ivar group: The node group to which this node will belong.
1011
  @type vm_capable: C{bool}
1012
  @ivar vm_capable: The vm_capable node attribute
1013
  @type master_capable: C{bool}
1014
  @ivar master_capable: The master_capable node attribute
1015

1016
  """
1017
  OP_DSC_FIELD = "node_name"
1018
  OP_PARAMS = [
1019
    _PNodeName,
1020
    _PHvState,
1021
    _PDiskState,
1022
    ("primary_ip", None, ht.NoType, "Primary IP address"),
1023
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1024
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1025
    ("group", None, ht.TMaybeString, "Initial node group"),
1026
    ("master_capable", None, ht.TMaybeBool,
1027
     "Whether node can become master or master candidate"),
1028
    ("vm_capable", None, ht.TMaybeBool,
1029
     "Whether node can host instances"),
1030
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1031
    ]
1032
  OP_RESULT = ht.TNone
1033

    
1034

    
1035
class OpNodeQuery(OpCode):
1036
  """Compute the list of nodes."""
1037
  OP_PARAMS = [
1038
    _POutputFields,
1039
    _PUseLocking,
1040
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1041
     "Empty list to query all nodes, node names otherwise"),
1042
    ]
1043
  OP_RESULT = _TOldQueryResult
1044

    
1045

    
1046
class OpNodeQueryvols(OpCode):
1047
  """Get list of volumes on node."""
1048
  OP_PARAMS = [
1049
    _POutputFields,
1050
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1051
     "Empty list to query all nodes, node names otherwise"),
1052
    ]
1053
  OP_RESULT = ht.TListOf(ht.TAny)
1054

    
1055

    
1056
class OpNodeQueryStorage(OpCode):
1057
  """Get information on storage for node(s)."""
1058
  OP_PARAMS = [
1059
    _POutputFields,
1060
    _PStorageType,
1061
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1062
    ("name", None, ht.TMaybeString, "Storage name"),
1063
    ]
1064
  OP_RESULT = _TOldQueryResult
1065

    
1066

    
1067
class OpNodeModifyStorage(OpCode):
1068
  """Modifies the properies of a storage unit"""
1069
  OP_DSC_FIELD = "node_name"
1070
  OP_PARAMS = [
1071
    _PNodeName,
1072
    _PStorageType,
1073
    _PStorageName,
1074
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1075
    ]
1076
  OP_RESULT = ht.TNone
1077

    
1078

    
1079
class OpRepairNodeStorage(OpCode):
1080
  """Repairs the volume group on a node."""
1081
  OP_DSC_FIELD = "node_name"
1082
  OP_PARAMS = [
1083
    _PNodeName,
1084
    _PStorageType,
1085
    _PStorageName,
1086
    _PIgnoreConsistency,
1087
    ]
1088
  OP_RESULT = ht.TNone
1089

    
1090

    
1091
class OpNodeSetParams(OpCode):
1092
  """Change the parameters of a node."""
1093
  OP_DSC_FIELD = "node_name"
1094
  OP_PARAMS = [
1095
    _PNodeName,
1096
    _PForce,
1097
    _PHvState,
1098
    _PDiskState,
1099
    ("master_candidate", None, ht.TMaybeBool,
1100
     "Whether the node should become a master candidate"),
1101
    ("offline", None, ht.TMaybeBool,
1102
     "Whether the node should be marked as offline"),
1103
    ("drained", None, ht.TMaybeBool,
1104
     "Whether the node should be marked as drained"),
1105
    ("auto_promote", False, ht.TBool,
1106
     "Whether node(s) should be promoted to master candidate if necessary"),
1107
    ("master_capable", None, ht.TMaybeBool,
1108
     "Denote whether node can become master or master candidate"),
1109
    ("vm_capable", None, ht.TMaybeBool,
1110
     "Denote whether node can host instances"),
1111
    ("secondary_ip", None, ht.TMaybeString,
1112
     "Change node's secondary IP address"),
1113
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1114
    ("powered", None, ht.TMaybeBool,
1115
     "Whether the node should be marked as powered"),
1116
    ]
1117
  OP_RESULT = _TSetParamsResult
1118

    
1119

    
1120
class OpNodePowercycle(OpCode):
1121
  """Tries to powercycle a node."""
1122
  OP_DSC_FIELD = "node_name"
1123
  OP_PARAMS = [
1124
    _PNodeName,
1125
    _PForce,
1126
    ]
1127
  OP_RESULT = ht.TMaybeString
1128

    
1129

    
1130
class OpNodeMigrate(OpCode):
1131
  """Migrate all instances from a node."""
1132
  OP_DSC_FIELD = "node_name"
1133
  OP_PARAMS = [
1134
    _PNodeName,
1135
    _PMigrationMode,
1136
    _PMigrationLive,
1137
    _PMigrationTargetNode,
1138
    _PAllowRuntimeChgs,
1139
    _PIgnoreIpolicy,
1140
    ("iallocator", None, ht.TMaybeString,
1141
     "Iallocator for deciding the target node for shared-storage instances"),
1142
    ]
1143
  OP_RESULT = TJobIdListOnly
1144

    
1145

    
1146
class OpNodeEvacuate(OpCode):
1147
  """Evacuate instances off a number of nodes."""
1148
  OP_DSC_FIELD = "node_name"
1149
  OP_PARAMS = [
1150
    _PEarlyRelease,
1151
    _PNodeName,
1152
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1153
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1154
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1155
     "Node evacuation mode"),
1156
    ]
1157
  OP_RESULT = TJobIdListOnly
1158

    
1159

    
1160
# instance opcodes
1161

    
1162
class OpInstanceCreate(OpCode):
1163
  """Create an instance.
1164

1165
  @ivar instance_name: Instance name
1166
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1167
  @ivar source_handshake: Signed handshake from source (remote import only)
1168
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1169
  @ivar source_instance_name: Previous name of instance (remote import only)
1170
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1171
    (remote import only)
1172

1173
  """
1174
  OP_DSC_FIELD = "instance_name"
1175
  OP_PARAMS = [
1176
    _PInstanceName,
1177
    _PForceVariant,
1178
    _PWaitForSync,
1179
    _PNameCheck,
1180
    _PIgnoreIpolicy,
1181
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1182
    ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1183
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1184
     " each disk definition must contain a ``%s`` value and"
1185
     " can contain an optional ``%s`` value denoting the disk access mode"
1186
     " (%s)" %
1187
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1188
      constants.IDISK_MODE,
1189
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1190
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1191
     "Disk template"),
1192
    ("file_driver", None, ht.TOr(ht.TNone, ht.TElemOf(constants.FILE_DRIVER)),
1193
     "Driver for file-backed disks"),
1194
    ("file_storage_dir", None, ht.TMaybeString,
1195
     "Directory for storing file-backed disks"),
1196
    ("hvparams", ht.EmptyDict, ht.TDict,
1197
     "Hypervisor parameters for instance, hypervisor-dependent"),
1198
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1199
    ("iallocator", None, ht.TMaybeString,
1200
     "Iallocator for deciding which node(s) to use"),
1201
    ("identify_defaults", False, ht.TBool,
1202
     "Reset instance parameters to default if equal"),
1203
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1204
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1205
     "Instance creation mode"),
1206
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1207
     "List of NIC (network interface) definitions, for example"
1208
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1209
     " contain the optional values %s" %
1210
     (constants.INIC_IP,
1211
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1212
    ("no_install", None, ht.TMaybeBool,
1213
     "Do not install the OS (will disable automatic start)"),
1214
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1215
    ("os_type", None, ht.TMaybeString, "Operating system"),
1216
    ("pnode", None, ht.TMaybeString, "Primary node"),
1217
    ("snode", None, ht.TMaybeString, "Secondary node"),
1218
    ("source_handshake", None, ht.TOr(ht.TList, ht.TNone),
1219
     "Signed handshake from source (remote import only)"),
1220
    ("source_instance_name", None, ht.TMaybeString,
1221
     "Source instance name (remote import only)"),
1222
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1223
     ht.TNonNegativeInt,
1224
     "How long source instance was given to shut down (remote import only)"),
1225
    ("source_x509_ca", None, ht.TMaybeString,
1226
     "Source X509 CA in PEM format (remote import only)"),
1227
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1228
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1229
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1230
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1231
    ]
1232
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1233

    
1234

    
1235
class OpInstanceMultiAlloc(OpCode):
1236
  """Allocates multiple instances.
1237

1238
  """
1239
  OP_PARAMS = [
1240
    ("iallocator", None, ht.TMaybeString,
1241
     "Iallocator used to allocate all the instances"),
1242
    ("instances", [], ht.TListOf(ht.TInstanceOf(OpInstanceCreate)),
1243
     "List of instance create opcodes describing the instances to allocate"),
1244
    ]
1245
  _JOB_LIST = ht.Comment("List of submitted jobs")(TJobIdList)
1246
  ALLOCATABLE_KEY = "allocatable"
1247
  FAILED_KEY = "allocatable"
1248
  OP_RESULT = ht.TStrictDict(True, True, {
1249
    constants.JOB_IDS_KEY: _JOB_LIST,
1250
    ALLOCATABLE_KEY: ht.TListOf(ht.TNonEmptyString),
1251
    FAILED_KEY: ht.TListOf(ht.TNonEmptyString)
1252
    })
1253

    
1254
  def __getstate__(self):
1255
    """Generic serializer.
1256

1257
    """
1258
    state = OpCode.__getstate__(self)
1259
    if hasattr(self, "instances"):
1260
      # pylint: disable=E1101
1261
      state["instances"] = [inst.__getstate__() for inst in self.instances]
1262
    return state
1263

    
1264
  def __setstate__(self, state):
1265
    """Generic unserializer.
1266

1267
    This method just restores from the serialized state the attributes
1268
    of the current instance.
1269

1270
    @param state: the serialized opcode data
1271
    @type state: C{dict}
1272

1273
    """
1274
    if not isinstance(state, dict):
1275
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
1276
                       type(state))
1277

    
1278
    if "instances" in state:
1279
      insts = [OpCode.LoadOpCode(inst) for inst in state["instances"]]
1280
      state["instances"] = insts
1281
    return OpCode.__setstate__(self, state)
1282

    
1283
  def Validate(self, set_defaults):
1284
    """Validates this opcode.
1285

1286
    We do this recursively.
1287

1288
    """
1289
    OpCode.Validate(self, set_defaults)
1290

    
1291
    for inst in self.instances: # pylint: disable=E1101
1292
      inst.Validate(set_defaults)
1293

    
1294

    
1295
class OpInstanceReinstall(OpCode):
1296
  """Reinstall an instance's OS."""
1297
  OP_DSC_FIELD = "instance_name"
1298
  OP_PARAMS = [
1299
    _PInstanceName,
1300
    _PForceVariant,
1301
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1302
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1303
    ]
1304
  OP_RESULT = ht.TNone
1305

    
1306

    
1307
class OpInstanceRemove(OpCode):
1308
  """Remove an instance."""
1309
  OP_DSC_FIELD = "instance_name"
1310
  OP_PARAMS = [
1311
    _PInstanceName,
1312
    _PShutdownTimeout,
1313
    ("ignore_failures", False, ht.TBool,
1314
     "Whether to ignore failures during removal"),
1315
    ]
1316
  OP_RESULT = ht.TNone
1317

    
1318

    
1319
class OpInstanceRename(OpCode):
1320
  """Rename an instance."""
1321
  OP_PARAMS = [
1322
    _PInstanceName,
1323
    _PNameCheck,
1324
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1325
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1326
    ]
1327
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1328

    
1329

    
1330
class OpInstanceStartup(OpCode):
1331
  """Startup an instance."""
1332
  OP_DSC_FIELD = "instance_name"
1333
  OP_PARAMS = [
1334
    _PInstanceName,
1335
    _PForce,
1336
    _PIgnoreOfflineNodes,
1337
    ("hvparams", ht.EmptyDict, ht.TDict,
1338
     "Temporary hypervisor parameters, hypervisor-dependent"),
1339
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1340
    _PNoRemember,
1341
    _PStartupPaused,
1342
    ]
1343
  OP_RESULT = ht.TNone
1344

    
1345

    
1346
class OpInstanceShutdown(OpCode):
1347
  """Shutdown an instance."""
1348
  OP_DSC_FIELD = "instance_name"
1349
  OP_PARAMS = [
1350
    _PInstanceName,
1351
    _PIgnoreOfflineNodes,
1352
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TNonNegativeInt,
1353
     "How long to wait for instance to shut down"),
1354
    _PNoRemember,
1355
    ]
1356
  OP_RESULT = ht.TNone
1357

    
1358

    
1359
class OpInstanceReboot(OpCode):
1360
  """Reboot an instance."""
1361
  OP_DSC_FIELD = "instance_name"
1362
  OP_PARAMS = [
1363
    _PInstanceName,
1364
    _PShutdownTimeout,
1365
    ("ignore_secondaries", False, ht.TBool,
1366
     "Whether to start the instance even if secondary disks are failing"),
1367
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1368
     "How to reboot instance"),
1369
    ]
1370
  OP_RESULT = ht.TNone
1371

    
1372

    
1373
class OpInstanceReplaceDisks(OpCode):
1374
  """Replace the disks of an instance."""
1375
  OP_DSC_FIELD = "instance_name"
1376
  OP_PARAMS = [
1377
    _PInstanceName,
1378
    _PEarlyRelease,
1379
    _PIgnoreIpolicy,
1380
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1381
     "Replacement mode"),
1382
    ("disks", ht.EmptyList, ht.TListOf(ht.TNonNegativeInt),
1383
     "Disk indexes"),
1384
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1385
    ("iallocator", None, ht.TMaybeString,
1386
     "Iallocator for deciding new secondary node"),
1387
    ]
1388
  OP_RESULT = ht.TNone
1389

    
1390

    
1391
class OpInstanceFailover(OpCode):
1392
  """Failover an instance."""
1393
  OP_DSC_FIELD = "instance_name"
1394
  OP_PARAMS = [
1395
    _PInstanceName,
1396
    _PShutdownTimeout,
1397
    _PIgnoreConsistency,
1398
    _PMigrationTargetNode,
1399
    _PIgnoreIpolicy,
1400
    ("iallocator", None, ht.TMaybeString,
1401
     "Iallocator for deciding the target node for shared-storage instances"),
1402
    ]
1403
  OP_RESULT = ht.TNone
1404

    
1405

    
1406
class OpInstanceMigrate(OpCode):
1407
  """Migrate an instance.
1408

1409
  This migrates (without shutting down an instance) to its secondary
1410
  node.
1411

1412
  @ivar instance_name: the name of the instance
1413
  @ivar mode: the migration mode (live, non-live or None for auto)
1414

1415
  """
1416
  OP_DSC_FIELD = "instance_name"
1417
  OP_PARAMS = [
1418
    _PInstanceName,
1419
    _PMigrationMode,
1420
    _PMigrationLive,
1421
    _PMigrationTargetNode,
1422
    _PAllowRuntimeChgs,
1423
    _PIgnoreIpolicy,
1424
    ("cleanup", False, ht.TBool,
1425
     "Whether a previously failed migration should be cleaned up"),
1426
    ("iallocator", None, ht.TMaybeString,
1427
     "Iallocator for deciding the target node for shared-storage instances"),
1428
    ("allow_failover", False, ht.TBool,
1429
     "Whether we can fallback to failover if migration is not possible"),
1430
    ]
1431
  OP_RESULT = ht.TNone
1432

    
1433

    
1434
class OpInstanceMove(OpCode):
1435
  """Move an instance.
1436

1437
  This move (with shutting down an instance and data copying) to an
1438
  arbitrary node.
1439

1440
  @ivar instance_name: the name of the instance
1441
  @ivar target_node: the destination node
1442

1443
  """
1444
  OP_DSC_FIELD = "instance_name"
1445
  OP_PARAMS = [
1446
    _PInstanceName,
1447
    _PShutdownTimeout,
1448
    _PIgnoreIpolicy,
1449
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1450
    _PIgnoreConsistency,
1451
    ]
1452
  OP_RESULT = ht.TNone
1453

    
1454

    
1455
class OpInstanceConsole(OpCode):
1456
  """Connect to an instance's console."""
1457
  OP_DSC_FIELD = "instance_name"
1458
  OP_PARAMS = [
1459
    _PInstanceName
1460
    ]
1461
  OP_RESULT = ht.TDict
1462

    
1463

    
1464
class OpInstanceActivateDisks(OpCode):
1465
  """Activate an instance's disks."""
1466
  OP_DSC_FIELD = "instance_name"
1467
  OP_PARAMS = [
1468
    _PInstanceName,
1469
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1470
    _PWaitForSyncFalse,
1471
    ]
1472
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1473
                                 ht.TItems([ht.TNonEmptyString,
1474
                                            ht.TNonEmptyString,
1475
                                            ht.TNonEmptyString])))
1476

    
1477

    
1478
class OpInstanceDeactivateDisks(OpCode):
1479
  """Deactivate an instance's disks."""
1480
  OP_DSC_FIELD = "instance_name"
1481
  OP_PARAMS = [
1482
    _PInstanceName,
1483
    _PForce,
1484
    ]
1485
  OP_RESULT = ht.TNone
1486

    
1487

    
1488
class OpInstanceRecreateDisks(OpCode):
1489
  """Recreate an instance's disks."""
1490
  _TDiskChanges = \
1491
    ht.TAnd(ht.TIsLength(2),
1492
            ht.TItems([ht.Comment("Disk index")(ht.TNonNegativeInt),
1493
                       ht.Comment("Parameters")(_TDiskParams)]))
1494

    
1495
  OP_DSC_FIELD = "instance_name"
1496
  OP_PARAMS = [
1497
    _PInstanceName,
1498
    ("disks", ht.EmptyList,
1499
     ht.TOr(ht.TListOf(ht.TNonNegativeInt), ht.TListOf(_TDiskChanges)),
1500
     "List of disk indexes (deprecated) or a list of tuples containing a disk"
1501
     " index and a possibly empty dictionary with disk parameter changes"),
1502
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1503
     "New instance nodes, if relocation is desired"),
1504
    ("iallocator", None, ht.TMaybeString,
1505
     "Iallocator for deciding new nodes"),
1506
    ]
1507
  OP_RESULT = ht.TNone
1508

    
1509

    
1510
class OpInstanceQuery(OpCode):
1511
  """Compute the list of instances."""
1512
  OP_PARAMS = [
1513
    _POutputFields,
1514
    _PUseLocking,
1515
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1516
     "Empty list to query all instances, instance names otherwise"),
1517
    ]
1518
  OP_RESULT = _TOldQueryResult
1519

    
1520

    
1521
class OpInstanceQueryData(OpCode):
1522
  """Compute the run-time status of instances."""
1523
  OP_PARAMS = [
1524
    _PUseLocking,
1525
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1526
     "Instance names"),
1527
    ("static", False, ht.TBool,
1528
     "Whether to only return configuration data without querying"
1529
     " nodes"),
1530
    ]
1531
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1532

    
1533

    
1534
def _TestInstSetParamsModList(fn):
1535
  """Generates a check for modification lists.
1536

1537
  """
1538
  # Old format
1539
  # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1540
  old_mod_item_fn = \
1541
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1542
      ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TNonNegativeInt),
1543
      fn,
1544
      ]))
1545

    
1546
  # New format, supporting adding/removing disks/NICs at arbitrary indices
1547
  mod_item_fn = \
1548
    ht.TAnd(ht.TIsLength(3), ht.TItems([
1549
      ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1550
      ht.Comment("Disk index, can be negative, e.g. -1 for last disk")(ht.TInt),
1551
      fn,
1552
      ]))
1553

    
1554
  return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1555
                ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1556

    
1557

    
1558
class OpInstanceSetParams(OpCode):
1559
  """Change the parameters of an instance.
1560

1561
  """
1562
  TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1563
  TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1564

    
1565
  OP_DSC_FIELD = "instance_name"
1566
  OP_PARAMS = [
1567
    _PInstanceName,
1568
    _PForce,
1569
    _PForceVariant,
1570
    _PIgnoreIpolicy,
1571
    ("nics", ht.EmptyList, TestNicModifications,
1572
     "List of NIC changes: each item is of the form ``(op, index, settings)``,"
1573
     " ``op`` is one of ``%s``, ``%s`` or ``%s``, ``index`` can be either -1"
1574
     " to refer to the last position, or a zero-based index number; a"
1575
     " deprecated version of this parameter used the form ``(op, settings)``,"
1576
     " where ``op`` can be ``%s`` to add a new NIC with the specified"
1577
     " settings, ``%s`` to remove the last NIC or a number to modify the"
1578
     " settings of the NIC with that index" %
1579
     (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1580
      constants.DDM_ADD, constants.DDM_REMOVE)),
1581
    ("disks", ht.EmptyList, TestDiskModifications,
1582
     "List of disk changes; see ``nics``"),
1583
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1584
    ("runtime_mem", None, ht.TMaybePositiveInt, "New runtime memory"),
1585
    ("hvparams", ht.EmptyDict, ht.TDict,
1586
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1587
    ("disk_template", None, ht.TOr(ht.TNone, _BuildDiskTemplateCheck(False)),
1588
     "Disk template for instance"),
1589
    ("remote_node", None, ht.TMaybeString,
1590
     "Secondary node (used when changing disk template)"),
1591
    ("os_name", None, ht.TMaybeString,
1592
     "Change the instance's OS without reinstalling the instance"),
1593
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1594
    ("wait_for_sync", True, ht.TBool,
1595
     "Whether to wait for the disk to synchronize, when changing template"),
1596
    ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1597
    ]
1598
  OP_RESULT = _TSetParamsResult
1599

    
1600

    
1601
class OpInstanceGrowDisk(OpCode):
1602
  """Grow a disk of an instance."""
1603
  OP_DSC_FIELD = "instance_name"
1604
  OP_PARAMS = [
1605
    _PInstanceName,
1606
    _PWaitForSync,
1607
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1608
    ("amount", ht.NoDefault, ht.TNonNegativeInt,
1609
     "Amount of disk space to add (megabytes)"),
1610
    ("absolute", False, ht.TBool,
1611
     "Whether the amount parameter is an absolute target or a relative one"),
1612
    ]
1613
  OP_RESULT = ht.TNone
1614

    
1615

    
1616
class OpInstanceChangeGroup(OpCode):
1617
  """Moves an instance to another node group."""
1618
  OP_DSC_FIELD = "instance_name"
1619
  OP_PARAMS = [
1620
    _PInstanceName,
1621
    _PEarlyRelease,
1622
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1623
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1624
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1625
    ]
1626
  OP_RESULT = TJobIdListOnly
1627

    
1628

    
1629
# Node group opcodes
1630

    
1631
class OpGroupAdd(OpCode):
1632
  """Add a node group to the cluster."""
1633
  OP_DSC_FIELD = "group_name"
1634
  OP_PARAMS = [
1635
    _PGroupName,
1636
    _PNodeGroupAllocPolicy,
1637
    _PGroupNodeParams,
1638
    _PDiskParams,
1639
    _PHvState,
1640
    _PDiskState,
1641
    ("ipolicy", None, ht.TMaybeDict,
1642
     "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1643
    ]
1644
  OP_RESULT = ht.TNone
1645

    
1646

    
1647
class OpGroupAssignNodes(OpCode):
1648
  """Assign nodes to a node group."""
1649
  OP_DSC_FIELD = "group_name"
1650
  OP_PARAMS = [
1651
    _PGroupName,
1652
    _PForce,
1653
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1654
     "List of nodes to assign"),
1655
    ]
1656
  OP_RESULT = ht.TNone
1657

    
1658

    
1659
class OpGroupQuery(OpCode):
1660
  """Compute the list of node groups."""
1661
  OP_PARAMS = [
1662
    _POutputFields,
1663
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1664
     "Empty list to query all groups, group names otherwise"),
1665
    ]
1666
  OP_RESULT = _TOldQueryResult
1667

    
1668

    
1669
class OpGroupSetParams(OpCode):
1670
  """Change the parameters of a node group."""
1671
  OP_DSC_FIELD = "group_name"
1672
  OP_PARAMS = [
1673
    _PGroupName,
1674
    _PNodeGroupAllocPolicy,
1675
    _PGroupNodeParams,
1676
    _PDiskParams,
1677
    _PHvState,
1678
    _PDiskState,
1679
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1680
    ]
1681
  OP_RESULT = _TSetParamsResult
1682

    
1683

    
1684
class OpGroupRemove(OpCode):
1685
  """Remove a node group from the cluster."""
1686
  OP_DSC_FIELD = "group_name"
1687
  OP_PARAMS = [
1688
    _PGroupName,
1689
    ]
1690
  OP_RESULT = ht.TNone
1691

    
1692

    
1693
class OpGroupRename(OpCode):
1694
  """Rename a node group in the cluster."""
1695
  OP_PARAMS = [
1696
    _PGroupName,
1697
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1698
    ]
1699
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1700

    
1701

    
1702
class OpGroupEvacuate(OpCode):
1703
  """Evacuate a node group in the cluster."""
1704
  OP_DSC_FIELD = "group_name"
1705
  OP_PARAMS = [
1706
    _PGroupName,
1707
    _PEarlyRelease,
1708
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1709
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1710
     "Destination group names or UUIDs"),
1711
    ]
1712
  OP_RESULT = TJobIdListOnly
1713

    
1714

    
1715
# OS opcodes
1716
class OpOsDiagnose(OpCode):
1717
  """Compute the list of guest operating systems."""
1718
  OP_PARAMS = [
1719
    _POutputFields,
1720
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1721
     "Which operating systems to diagnose"),
1722
    ]
1723
  OP_RESULT = _TOldQueryResult
1724

    
1725

    
1726
# Exports opcodes
1727
class OpBackupQuery(OpCode):
1728
  """Compute the list of exported images."""
1729
  OP_PARAMS = [
1730
    _PUseLocking,
1731
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1732
     "Empty list to query all nodes, node names otherwise"),
1733
    ]
1734
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1735
                         ht.TOr(ht.Comment("False on error")(ht.TBool),
1736
                                ht.TListOf(ht.TNonEmptyString)))
1737

    
1738

    
1739
class OpBackupPrepare(OpCode):
1740
  """Prepares an instance export.
1741

1742
  @ivar instance_name: Instance name
1743
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1744

1745
  """
1746
  OP_DSC_FIELD = "instance_name"
1747
  OP_PARAMS = [
1748
    _PInstanceName,
1749
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1750
     "Export mode"),
1751
    ]
1752
  OP_RESULT = ht.TOr(ht.TNone, ht.TDict)
1753

    
1754

    
1755
class OpBackupExport(OpCode):
1756
  """Export an instance.
1757

1758
  For local exports, the export destination is the node name. For remote
1759
  exports, the export destination is a list of tuples, each consisting of
1760
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1761
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1762
  destination X509 CA must be a signed certificate.
1763

1764
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1765
  @ivar target_node: Export destination
1766
  @ivar x509_key_name: X509 key to use (remote export only)
1767
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1768
                             only)
1769

1770
  """
1771
  OP_DSC_FIELD = "instance_name"
1772
  OP_PARAMS = [
1773
    _PInstanceName,
1774
    _PShutdownTimeout,
1775
    # TODO: Rename target_node as it changes meaning for different export modes
1776
    # (e.g. "destination")
1777
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1778
     "Destination information, depends on export mode"),
1779
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1780
    ("remove_instance", False, ht.TBool,
1781
     "Whether to remove instance after export"),
1782
    ("ignore_remove_failures", False, ht.TBool,
1783
     "Whether to ignore failures while removing instances"),
1784
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1785
     "Export mode"),
1786
    ("x509_key_name", None, ht.TOr(ht.TList, ht.TNone),
1787
     "Name of X509 key (remote export only)"),
1788
    ("destination_x509_ca", None, ht.TMaybeString,
1789
     "Destination X509 CA (remote export only)"),
1790
    ]
1791
  OP_RESULT = \
1792
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1793
      ht.Comment("Finalizing status")(ht.TBool),
1794
      ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1795
      ]))
1796

    
1797

    
1798
class OpBackupRemove(OpCode):
1799
  """Remove an instance's export."""
1800
  OP_DSC_FIELD = "instance_name"
1801
  OP_PARAMS = [
1802
    _PInstanceName,
1803
    ]
1804
  OP_RESULT = ht.TNone
1805

    
1806

    
1807
# Tags opcodes
1808
class OpTagsGet(OpCode):
1809
  """Returns the tags of the given object."""
1810
  OP_DSC_FIELD = "name"
1811
  OP_PARAMS = [
1812
    _PTagKind,
1813
    # Not using _PUseLocking as the default is different for historical reasons
1814
    ("use_locking", True, ht.TBool, "Whether to use synchronization"),
1815
    # Name is only meaningful for nodes and instances
1816
    ("name", ht.NoDefault, ht.TMaybeString,
1817
     "Name of object to retrieve tags from"),
1818
    ]
1819
  OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1820

    
1821

    
1822
class OpTagsSearch(OpCode):
1823
  """Searches the tags in the cluster for a given pattern."""
1824
  OP_DSC_FIELD = "pattern"
1825
  OP_PARAMS = [
1826
    ("pattern", ht.NoDefault, ht.TNonEmptyString,
1827
     "Search pattern (regular expression)"),
1828
    ]
1829
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1830
    ht.TNonEmptyString,
1831
    ht.TNonEmptyString,
1832
    ])))
1833

    
1834

    
1835
class OpTagsSet(OpCode):
1836
  """Add a list of tags on a given object."""
1837
  OP_PARAMS = [
1838
    _PTagKind,
1839
    _PTags,
1840
    # Name is only meaningful for groups, nodes and instances
1841
    ("name", ht.NoDefault, ht.TMaybeString,
1842
     "Name of object where tag(s) should be added"),
1843
    ]
1844
  OP_RESULT = ht.TNone
1845

    
1846

    
1847
class OpTagsDel(OpCode):
1848
  """Remove a list of tags from a given object."""
1849
  OP_PARAMS = [
1850
    _PTagKind,
1851
    _PTags,
1852
    # Name is only meaningful for groups, nodes and instances
1853
    ("name", ht.NoDefault, ht.TMaybeString,
1854
     "Name of object where tag(s) should be deleted"),
1855
    ]
1856
  OP_RESULT = ht.TNone
1857

    
1858

    
1859
# Test opcodes
1860
class OpTestDelay(OpCode):
1861
  """Sleeps for a configured amount of time.
1862

1863
  This is used just for debugging and testing.
1864

1865
  Parameters:
1866
    - duration: the time to sleep
1867
    - on_master: if true, sleep on the master
1868
    - on_nodes: list of nodes in which to sleep
1869

1870
  If the on_master parameter is true, it will execute a sleep on the
1871
  master (before any node sleep).
1872

1873
  If the on_nodes list is not empty, it will sleep on those nodes
1874
  (after the sleep on the master, if that is enabled).
1875

1876
  As an additional feature, the case of duration < 0 will be reported
1877
  as an execution error, so this opcode can be used as a failure
1878
  generator. The case of duration == 0 will not be treated specially.
1879

1880
  """
1881
  OP_DSC_FIELD = "duration"
1882
  OP_PARAMS = [
1883
    ("duration", ht.NoDefault, ht.TNumber, None),
1884
    ("on_master", True, ht.TBool, None),
1885
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1886
    ("repeat", 0, ht.TNonNegativeInt, None),
1887
    ]
1888

    
1889

    
1890
class OpTestAllocator(OpCode):
1891
  """Allocator framework testing.
1892

1893
  This opcode has two modes:
1894
    - gather and return allocator input for a given mode (allocate new
1895
      or replace secondary) and a given instance definition (direction
1896
      'in')
1897
    - run a selected allocator for a given operation (as above) and
1898
      return the allocator output (direction 'out')
1899

1900
  """
1901
  OP_DSC_FIELD = "allocator"
1902
  OP_PARAMS = [
1903
    ("direction", ht.NoDefault,
1904
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1905
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1906
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1907
    ("nics", ht.NoDefault,
1908
     ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
1909
                                            constants.INIC_IP,
1910
                                            "bridge"]),
1911
                                ht.TOr(ht.TNone, ht.TNonEmptyString))),
1912
     None),
1913
    ("disks", ht.NoDefault, ht.TOr(ht.TNone, ht.TList), None),
1914
    ("hypervisor", None, ht.TMaybeString, None),
1915
    ("allocator", None, ht.TMaybeString, None),
1916
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1917
    ("memory", None, ht.TOr(ht.TNone, ht.TNonNegativeInt), None),
1918
    ("vcpus", None, ht.TOr(ht.TNone, ht.TNonNegativeInt), None),
1919
    ("os", None, ht.TMaybeString, None),
1920
    ("disk_template", None, ht.TMaybeString, None),
1921
    ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1922
    ("evac_mode", None,
1923
     ht.TOr(ht.TNone, ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1924
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1925
    ("spindle_use", 1, ht.TNonNegativeInt, None),
1926
    ("count", 1, ht.TNonNegativeInt, None),
1927
    ]
1928

    
1929

    
1930
class OpTestJqueue(OpCode):
1931
  """Utility opcode to test some aspects of the job queue.
1932

1933
  """
1934
  OP_PARAMS = [
1935
    ("notify_waitlock", False, ht.TBool, None),
1936
    ("notify_exec", False, ht.TBool, None),
1937
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1938
    ("fail", False, ht.TBool, None),
1939
    ]
1940

    
1941

    
1942
class OpTestDummy(OpCode):
1943
  """Utility opcode used by unittests.
1944

1945
  """
1946
  OP_PARAMS = [
1947
    ("result", ht.NoDefault, ht.NoType, None),
1948
    ("messages", ht.NoDefault, ht.NoType, None),
1949
    ("fail", ht.NoDefault, ht.NoType, None),
1950
    ("submit_jobs", None, ht.NoType, None),
1951
    ]
1952
  WITH_LU = False
1953

    
1954

    
1955
def _GetOpList():
1956
  """Returns list of all defined opcodes.
1957

1958
  Does not eliminate duplicates by C{OP_ID}.
1959

1960
  """
1961
  return [v for v in globals().values()
1962
          if (isinstance(v, type) and issubclass(v, OpCode) and
1963
              hasattr(v, "OP_ID") and v is not OpCode)]
1964

    
1965

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