Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ fd9f58fd

History | View | Annotate | Download (64.7 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
import ipaddr
39

    
40
from ganeti import constants
41
from ganeti import errors
42
from ganeti import ht
43
from ganeti import objects
44
from ganeti import objectutils
45

    
46

    
47
# Common opcode attributes
48

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
152
# Disk parameters
153
_PDiskParams = \
154
  ("diskparams", None,
155
   ht.TMaybe(ht.TDictOf(ht.TElemOf(constants.DISK_TEMPLATES), ht.TDict)),
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
#: a required network name
171
_PNetworkName = ("network_name", ht.NoDefault, ht.TNonEmptyString,
172
                 "Set network name")
173

    
174
#: OP_ID conversion regular expression
175
_OPID_RE = re.compile("([a-z])([A-Z])")
176

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

    
184
_TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
185

    
186
# TODO: Generate check from constants.INIC_PARAMS_TYPES
187
#: Utility function for testing NIC definitions
188
_TestNicDef = \
189
  ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
190
                                          ht.TMaybeString))
191

    
192
_TSetParamsResultItemItems = [
193
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
194
  ht.Comment("new value")(ht.TAny),
195
  ]
196

    
197
_TSetParamsResult = \
198
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
199
                     ht.TItems(_TSetParamsResultItemItems)))
200

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

    
207
_TQueryRow = \
208
  ht.TListOf(ht.TAnd(ht.TIsLength(2),
209
                     ht.TItems([ht.TElemOf(constants.RS_ALL),
210
                                ht.TAny])))
211

    
212
_TQueryResult = ht.TListOf(_TQueryRow)
213

    
214
_TOldQueryRow = ht.TListOf(ht.TAny)
215

    
216
_TOldQueryResult = ht.TListOf(_TOldQueryRow)
217

    
218

    
219
_SUMMARY_PREFIX = {
220
  "CLUSTER_": "C_",
221
  "GROUP_": "G_",
222
  "NODE_": "N_",
223
  "INSTANCE_": "I_",
224
  }
225

    
226
#: Attribute name for dependencies
227
DEPEND_ATTR = "depends"
228

    
229
#: Attribute name for comment
230
COMMENT_ATTR = "comment"
231

    
232

    
233
def _NameToId(name):
234
  """Convert an opcode class name to an OP_ID.
235

236
  @type name: string
237
  @param name: the class name, as OpXxxYyy
238
  @rtype: string
239
  @return: the name in the OP_XXXX_YYYY format
240

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

    
253

    
254
def _GenerateObjectTypeCheck(obj, fields_types):
255
  """Helper to generate type checks for objects.
256

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

261
  """
262
  assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
263
    "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
264
  return ht.TStrictDict(True, True, fields_types)
265

    
266

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

    
275

    
276
def RequireFileStorage():
277
  """Checks that file storage is enabled.
278

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

282
  @raise errors.OpPrereqError: when file storage is disabled
283

284
  """
285
  if not constants.ENABLE_FILE_STORAGE:
286
    raise errors.OpPrereqError("File storage disabled at configure time",
287
                               errors.ECODE_INVAL)
288

    
289

    
290
def RequireSharedFileStorage():
291
  """Checks that shared file storage is enabled.
292

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

296
  @raise errors.OpPrereqError: when shared file storage is disabled
297

298
  """
299
  if not constants.ENABLE_SHARED_FILE_STORAGE:
300
    raise errors.OpPrereqError("Shared file storage disabled at"
301
                               " configure time", errors.ECODE_INVAL)
302

    
303

    
304
@ht.WithDesc("CheckFileStorage")
305
def _CheckFileStorage(value):
306
  """Ensures file storage is enabled if used.
307

308
  """
309
  if value == constants.DT_FILE:
310
    RequireFileStorage()
311
  elif value == constants.DT_SHARED_FILE:
312
    RequireSharedFileStorage()
313
  return True
314

    
315

    
316
def _BuildDiskTemplateCheck(accept_none):
317
  """Builds check for disk template.
318

319
  @type accept_none: bool
320
  @param accept_none: whether to accept None as a correct value
321
  @rtype: callable
322

323
  """
324
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
325

    
326
  if accept_none:
327
    template_check = ht.TMaybe(template_check)
328

    
329
  return ht.TAnd(template_check, _CheckFileStorage)
330

    
331

    
332
def _CheckStorageType(storage_type):
333
  """Ensure a given storage type is valid.
334

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

    
344

    
345
#: Storage type parameter
346
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
347
                 "Storage type")
348

    
349
_CheckNetworkType = ht.TElemOf(constants.NETWORK_VALID_TYPES)
350

    
351
#: Network type parameter
352
_PNetworkType = ("network_type", None, ht.TMaybe(_CheckNetworkType),
353
                 "Network type")
354

    
355

    
356
def _CheckCIDRNetNotation(value):
357
  """Ensure a given cidr notation type is valid.
358

359
  """
360
  try:
361
    ipaddr.IPv4Network(value)
362
  except ipaddr.AddressValueError:
363
    return False
364
  return True
365

    
366

    
367
def _CheckCIDRAddrNotation(value):
368
  """Ensure a given cidr notation type is valid.
369

370
  """
371
  try:
372
    ipaddr.IPv4Address(value)
373
  except ipaddr.AddressValueError:
374
    return False
375
  return True
376

    
377

    
378
def _CheckCIDR6AddrNotation(value):
379
  """Ensure a given cidr notation type is valid.
380

381
  """
382
  try:
383
    ipaddr.IPv6Address(value)
384
  except ipaddr.AddressValueError:
385
    return False
386
  return True
387

    
388

    
389
def _CheckCIDR6NetNotation(value):
390
  """Ensure a given cidr notation type is valid.
391

392
  """
393
  try:
394
    ipaddr.IPv6Network(value)
395
  except ipaddr.AddressValueError:
396
    return False
397
  return True
398

    
399

    
400
_TIpAddress = ht.TOr(ht.TNone, ht.TAnd(ht.TString, _CheckCIDRNetNotation))
401
_TIpAddress6 = ht.TOr(ht.TNone, ht.TAnd(ht.TString, _CheckCIDR6NetNotation))
402

    
403

    
404
class _AutoOpParamSlots(objectutils.AutoSlots):
405
  """Meta class for opcode definitions.
406

407
  """
408
  def __new__(mcs, name, bases, attrs):
409
    """Called when a class should be created.
410

411
    @param mcs: The meta class
412
    @param name: Name of created class
413
    @param bases: Base classes
414
    @type attrs: dict
415
    @param attrs: Class attributes
416

417
    """
418
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
419

    
420
    slots = mcs._GetSlots(attrs)
421
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
422
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
423

    
424
    attrs["OP_ID"] = _NameToId(name)
425

    
426
    return objectutils.AutoSlots.__new__(mcs, name, bases, attrs)
427

    
428
  @classmethod
429
  def _GetSlots(mcs, attrs):
430
    """Build the slots out of OP_PARAMS.
431

432
    """
433
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
434
    params = attrs.setdefault("OP_PARAMS", [])
435

    
436
    # Use parameter names as slots
437
    return [pname for (pname, _, _, _) in params]
438

    
439

    
440
class BaseOpCode(objectutils.ValidatedSlots):
441
  """A simple serializable object.
442

443
  This object serves as a parent class for OpCode without any custom
444
  field handling.
445

446
  """
447
  # pylint: disable=E1101
448
  # as OP_ID is dynamically defined
449
  __metaclass__ = _AutoOpParamSlots
450

    
451
  def __getstate__(self):
452
    """Generic serializer.
453

454
    This method just returns the contents of the instance as a
455
    dictionary.
456

457
    @rtype:  C{dict}
458
    @return: the instance attributes and their values
459

460
    """
461
    state = {}
462
    for name in self.GetAllSlots():
463
      if hasattr(self, name):
464
        state[name] = getattr(self, name)
465
    return state
466

    
467
  def __setstate__(self, state):
468
    """Generic unserializer.
469

470
    This method just restores from the serialized state the attributes
471
    of the current instance.
472

473
    @param state: the serialized opcode data
474
    @type state:  C{dict}
475

476
    """
477
    if not isinstance(state, dict):
478
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
479
                       type(state))
480

    
481
    for name in self.GetAllSlots():
482
      if name not in state and hasattr(self, name):
483
        delattr(self, name)
484

    
485
    for name in state:
486
      setattr(self, name, state[name])
487

    
488
  @classmethod
489
  def GetAllParams(cls):
490
    """Compute list of all parameters for an opcode.
491

492
    """
493
    slots = []
494
    for parent in cls.__mro__:
495
      slots.extend(getattr(parent, "OP_PARAMS", []))
496
    return slots
497

    
498
  def Validate(self, set_defaults): # pylint: disable=W0221
499
    """Validate opcode parameters, optionally setting default values.
500

501
    @type set_defaults: bool
502
    @param set_defaults: Whether to set default values
503
    @raise errors.OpPrereqError: When a parameter value doesn't match
504
                                 requirements
505

506
    """
507
    for (attr_name, default, test, _) in self.GetAllParams():
508
      assert test == ht.NoType or callable(test)
509

    
510
      if not hasattr(self, attr_name):
511
        if default == ht.NoDefault:
512
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
513
                                     (self.OP_ID, attr_name),
514
                                     errors.ECODE_INVAL)
515
        elif set_defaults:
516
          if callable(default):
517
            dval = default()
518
          else:
519
            dval = default
520
          setattr(self, attr_name, dval)
521

    
522
      if test == ht.NoType:
523
        # no tests here
524
        continue
525

    
526
      if set_defaults or hasattr(self, attr_name):
527
        attr_val = getattr(self, attr_name)
528
        if not test(attr_val):
529
          logging.error("OpCode %s, parameter %s, has invalid type %s/value"
530
                        " '%s' expecting type %s",
531
                        self.OP_ID, attr_name, type(attr_val), attr_val, test)
532
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
533
                                     (self.OP_ID, attr_name),
534
                                     errors.ECODE_INVAL)
535

    
536

    
537
def _BuildJobDepCheck(relative):
538
  """Builds check for job dependencies (L{DEPEND_ATTR}).
539

540
  @type relative: bool
541
  @param relative: Whether to accept relative job IDs (negative)
542
  @rtype: callable
543

544
  """
545
  if relative:
546
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
547
  else:
548
    job_id = ht.TJobId
549

    
550
  job_dep = \
551
    ht.TAnd(ht.TIsLength(2),
552
            ht.TItems([job_id,
553
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
554

    
555
  return ht.TMaybeListOf(job_dep)
556

    
557

    
558
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
559

    
560
#: List of submission status and job ID as returned by C{SubmitManyJobs}
561
_TJobIdListItem = \
562
  ht.TAnd(ht.TIsLength(2),
563
          ht.TItems([ht.Comment("success")(ht.TBool),
564
                     ht.Comment("Job ID if successful, error message"
565
                                " otherwise")(ht.TOr(ht.TString,
566
                                                     ht.TJobId))]))
567
TJobIdList = ht.TListOf(_TJobIdListItem)
568

    
569
#: Result containing only list of submitted jobs
570
TJobIdListOnly = ht.TStrictDict(True, True, {
571
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
572
  })
573

    
574

    
575
class OpCode(BaseOpCode):
576
  """Abstract OpCode.
577

578
  This is the root of the actual OpCode hierarchy. All clases derived
579
  from this class should override OP_ID.
580

581
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
582
               children of this class.
583
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
584
                      string returned by Summary(); see the docstring of that
585
                      method for details).
586
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
587
                   get if not already defined, and types they must match.
588
  @cvar OP_RESULT: Callable to verify opcode result
589
  @cvar WITH_LU: Boolean that specifies whether this should be included in
590
      mcpu's dispatch table
591
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
592
                 the check steps
593
  @ivar priority: Opcode priority for queue
594

595
  """
596
  # pylint: disable=E1101
597
  # as OP_ID is dynamically defined
598
  WITH_LU = True
599
  OP_PARAMS = [
600
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
601
    ("debug_level", None, ht.TMaybe(ht.TNonNegativeInt), "Debug level"),
602
    ("priority", constants.OP_PRIO_DEFAULT,
603
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
604
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
605
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
606
     " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
607
     " for details"),
608
    (COMMENT_ATTR, None, ht.TMaybeString,
609
     "Comment describing the purpose of the opcode"),
610
    ]
611
  OP_RESULT = None
612

    
613
  def __getstate__(self):
614
    """Specialized getstate for opcodes.
615

616
    This method adds to the state dictionary the OP_ID of the class,
617
    so that on unload we can identify the correct class for
618
    instantiating the opcode.
619

620
    @rtype:   C{dict}
621
    @return:  the state as a dictionary
622

623
    """
624
    data = BaseOpCode.__getstate__(self)
625
    data["OP_ID"] = self.OP_ID
626
    return data
627

    
628
  @classmethod
629
  def LoadOpCode(cls, data):
630
    """Generic load opcode method.
631

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

636
    @type data:  C{dict}
637
    @param data: the serialized opcode
638

639
    """
640
    if not isinstance(data, dict):
641
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
642
    if "OP_ID" not in data:
643
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
644
    op_id = data["OP_ID"]
645
    op_class = None
646
    if op_id in OP_MAPPING:
647
      op_class = OP_MAPPING[op_id]
648
    else:
649
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
650
                       op_id)
651
    op = op_class()
652
    new_data = data.copy()
653
    del new_data["OP_ID"]
654
    op.__setstate__(new_data)
655
    return op
656

    
657
  def Summary(self):
658
    """Generates a summary description of this opcode.
659

660
    The summary is the value of the OP_ID attribute (without the "OP_"
661
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
662
    defined; this field should allow to easily identify the operation
663
    (for an instance creation job, e.g., it would be the instance
664
    name).
665

666
    """
667
    assert self.OP_ID is not None and len(self.OP_ID) > 3
668
    # all OP_ID start with OP_, we remove that
669
    txt = self.OP_ID[3:]
670
    field_name = getattr(self, "OP_DSC_FIELD", None)
671
    if field_name:
672
      field_value = getattr(self, field_name, None)
673
      if isinstance(field_value, (list, tuple)):
674
        field_value = ",".join(str(i) for i in field_value)
675
      txt = "%s(%s)" % (txt, field_value)
676
    return txt
677

    
678
  def TinySummary(self):
679
    """Generates a compact summary description of the opcode.
680

681
    """
682
    assert self.OP_ID.startswith("OP_")
683

    
684
    text = self.OP_ID[3:]
685

    
686
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
687
      if text.startswith(prefix):
688
        return supplement + text[len(prefix):]
689

    
690
    return text
691

    
692

    
693
# cluster opcodes
694

    
695
class OpClusterPostInit(OpCode):
696
  """Post cluster initialization.
697

698
  This opcode does not touch the cluster at all. Its purpose is to run hooks
699
  after the cluster has been initialized.
700

701
  """
702
  OP_RESULT = ht.TBool
703

    
704

    
705
class OpClusterDestroy(OpCode):
706
  """Destroy the cluster.
707

708
  This opcode has no other parameters. All the state is irreversibly
709
  lost after the execution of this opcode.
710

711
  """
712
  OP_RESULT = ht.TNonEmptyString
713

    
714

    
715
class OpClusterQuery(OpCode):
716
  """Query cluster information."""
717
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
718

    
719

    
720
class OpClusterVerify(OpCode):
721
  """Submits all jobs necessary to verify the cluster.
722

723
  """
724
  OP_PARAMS = [
725
    _PDebugSimulateErrors,
726
    _PErrorCodes,
727
    _PSkipChecks,
728
    _PIgnoreErrors,
729
    _PVerbose,
730
    ("group_name", None, ht.TMaybeString, "Group to verify"),
731
    ]
732
  OP_RESULT = TJobIdListOnly
733

    
734

    
735
class OpClusterVerifyConfig(OpCode):
736
  """Verify the cluster config.
737

738
  """
739
  OP_PARAMS = [
740
    _PDebugSimulateErrors,
741
    _PErrorCodes,
742
    _PIgnoreErrors,
743
    _PVerbose,
744
    ]
745
  OP_RESULT = ht.TBool
746

    
747

    
748
class OpClusterVerifyGroup(OpCode):
749
  """Run verify on a node group from the cluster.
750

751
  @type skip_checks: C{list}
752
  @ivar skip_checks: steps to be skipped from the verify process; this
753
                     needs to be a subset of
754
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
755
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
756

757
  """
758
  OP_DSC_FIELD = "group_name"
759
  OP_PARAMS = [
760
    _PGroupName,
761
    _PDebugSimulateErrors,
762
    _PErrorCodes,
763
    _PSkipChecks,
764
    _PIgnoreErrors,
765
    _PVerbose,
766
    ]
767
  OP_RESULT = ht.TBool
768

    
769

    
770
class OpClusterVerifyDisks(OpCode):
771
  """Verify the cluster disks.
772

773
  """
774
  OP_RESULT = TJobIdListOnly
775

    
776

    
777
class OpGroupVerifyDisks(OpCode):
778
  """Verifies the status of all disks in a node group.
779

780
  Result: a tuple of three elements:
781
    - dict of node names with issues (values: error msg)
782
    - list of instances with degraded disks (that should be activated)
783
    - dict of instances with missing logical volumes (values: (node, vol)
784
      pairs with details about the missing volumes)
785

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

791
  Note that only instances that are drbd-based are taken into
792
  consideration. This might need to be revisited in the future.
793

794
  """
795
  OP_DSC_FIELD = "group_name"
796
  OP_PARAMS = [
797
    _PGroupName,
798
    ]
799
  OP_RESULT = \
800
    ht.TAnd(ht.TIsLength(3),
801
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
802
                       ht.TListOf(ht.TString),
803
                       ht.TDictOf(ht.TString,
804
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
805

    
806

    
807
class OpClusterRepairDiskSizes(OpCode):
808
  """Verify the disk sizes of the instances and fixes configuration
809
  mimatches.
810

811
  Parameters: optional instances list, in case we want to restrict the
812
  checks to only a subset of the instances.
813

814
  Result: a list of tuples, (instance, disk, new-size) for changed
815
  configurations.
816

817
  In normal operation, the list should be empty.
818

819
  @type instances: list
820
  @ivar instances: the list of instances to check, or empty for all instances
821

822
  """
823
  OP_PARAMS = [
824
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
825
    ]
826
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
827
                                 ht.TItems([ht.TNonEmptyString,
828
                                            ht.TNonNegativeInt,
829
                                            ht.TNonNegativeInt])))
830

    
831

    
832
class OpClusterConfigQuery(OpCode):
833
  """Query cluster configuration values."""
834
  OP_PARAMS = [
835
    _POutputFields,
836
    ]
837
  OP_RESULT = ht.TListOf(ht.TAny)
838

    
839

    
840
class OpClusterRename(OpCode):
841
  """Rename the cluster.
842

843
  @type name: C{str}
844
  @ivar name: The new name of the cluster. The name and/or the master IP
845
              address will be changed to match the new name and its IP
846
              address.
847

848
  """
849
  OP_DSC_FIELD = "name"
850
  OP_PARAMS = [
851
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
852
    ]
853
  OP_RESULT = ht.TNonEmptyString
854

    
855

    
856
class OpClusterSetParams(OpCode):
857
  """Change the parameters of the cluster.
858

859
  @type vg_name: C{str} or C{None}
860
  @ivar vg_name: The new volume group name or None to disable LVM usage.
861

862
  """
863
  OP_PARAMS = [
864
    _PHvState,
865
    _PDiskState,
866
    ("vg_name", None, ht.TMaybe(ht.TString), "Volume group name"),
867
    ("enabled_hypervisors", None,
868
     ht.TMaybe(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)),
869
                       ht.TTrue)),
870
     "List of enabled hypervisors"),
871
    ("hvparams", None,
872
     ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
873
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
874
    ("beparams", None, ht.TMaybeDict,
875
     "Cluster-wide backend parameter defaults"),
876
    ("os_hvp", None, ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
877
     "Cluster-wide per-OS hypervisor parameter defaults"),
878
    ("osparams", None,
879
     ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
880
     "Cluster-wide OS parameter defaults"),
881
    _PDiskParams,
882
    ("candidate_pool_size", None, ht.TMaybe(ht.TPositiveInt),
883
     "Master candidate pool size"),
884
    ("uid_pool", None, ht.NoType,
885
     "Set UID pool, must be list of lists describing UID ranges (two items,"
886
     " start and end inclusive)"),
887
    ("add_uids", None, ht.NoType,
888
     "Extend UID pool, must be list of lists describing UID ranges (two"
889
     " items, start and end inclusive) to be added"),
890
    ("remove_uids", None, ht.NoType,
891
     "Shrink UID pool, must be list of lists describing UID ranges (two"
892
     " items, start and end inclusive) to be removed"),
893
    ("maintain_node_health", None, ht.TMaybeBool,
894
     "Whether to automatically maintain node health"),
895
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
896
     "Whether to wipe disks before allocating them to instances"),
897
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
898
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
899
    ("ipolicy", None, ht.TMaybeDict,
900
     "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
901
    ("drbd_helper", None, ht.TMaybe(ht.TString), "DRBD helper program"),
902
    ("default_iallocator", None, ht.TMaybe(ht.TString),
903
     "Default iallocator for cluster"),
904
    ("master_netdev", None, ht.TMaybe(ht.TString),
905
     "Master network device"),
906
    ("master_netmask", None, ht.TMaybe(ht.TNonNegativeInt),
907
     "Netmask of the master IP"),
908
    ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
909
     "List of reserved LVs"),
910
    ("hidden_os", None, _TestClusterOsList,
911
     "Modify list of hidden operating systems: each modification must have"
912
     " two items, the operation and the OS name; the operation can be"
913
     " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
914
    ("blacklisted_os", None, _TestClusterOsList,
915
     "Modify list of blacklisted operating systems: each modification must"
916
     " have two items, the operation and the OS name; the operation can be"
917
     " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
918
    ("use_external_mip_script", None, ht.TMaybeBool,
919
     "Whether to use an external master IP address setup script"),
920
    ]
921
  OP_RESULT = ht.TNone
922

    
923

    
924
class OpClusterRedistConf(OpCode):
925
  """Force a full push of the cluster configuration.
926

927
  """
928
  OP_RESULT = ht.TNone
929

    
930

    
931
class OpClusterActivateMasterIp(OpCode):
932
  """Activate the master IP on the master node.
933

934
  """
935
  OP_RESULT = ht.TNone
936

    
937

    
938
class OpClusterDeactivateMasterIp(OpCode):
939
  """Deactivate the master IP on the master node.
940

941
  """
942
  OP_RESULT = ht.TNone
943

    
944

    
945
class OpQuery(OpCode):
946
  """Query for resources/items.
947

948
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
949
  @ivar fields: List of fields to retrieve
950
  @ivar qfilter: Query filter
951

952
  """
953
  OP_DSC_FIELD = "what"
954
  OP_PARAMS = [
955
    _PQueryWhat,
956
    _PUseLocking,
957
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
958
     "Requested fields"),
959
    ("qfilter", None, ht.TMaybe(ht.TList),
960
     "Query filter"),
961
    ]
962
  OP_RESULT = \
963
    _GenerateObjectTypeCheck(objects.QueryResponse, {
964
      "fields": ht.TListOf(_TQueryFieldDef),
965
      "data": _TQueryResult,
966
      })
967

    
968

    
969
class OpQueryFields(OpCode):
970
  """Query for available resource/item fields.
971

972
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
973
  @ivar fields: List of fields to retrieve
974

975
  """
976
  OP_DSC_FIELD = "what"
977
  OP_PARAMS = [
978
    _PQueryWhat,
979
    ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
980
     "Requested fields; if not given, all are returned"),
981
    ]
982
  OP_RESULT = \
983
    _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
984
      "fields": ht.TListOf(_TQueryFieldDef),
985
      })
986

    
987

    
988
class OpOobCommand(OpCode):
989
  """Interact with OOB."""
990
  OP_PARAMS = [
991
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
992
     "List of nodes to run the OOB command against"),
993
    ("command", ht.NoDefault, ht.TElemOf(constants.OOB_COMMANDS),
994
     "OOB command to be run"),
995
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
996
     "Timeout before the OOB helper will be terminated"),
997
    ("ignore_status", False, ht.TBool,
998
     "Ignores the node offline status for power off"),
999
    ("power_delay", constants.OOB_POWER_DELAY, ht.TNonNegativeFloat,
1000
     "Time in seconds to wait between powering on nodes"),
1001
    ]
1002
  # Fixme: Make it more specific with all the special cases in LUOobCommand
1003
  OP_RESULT = _TQueryResult
1004

    
1005

    
1006
class OpRestrictedCommand(OpCode):
1007
  """Runs a restricted command on node(s).
1008

1009
  """
1010
  OP_PARAMS = [
1011
    _PUseLocking,
1012
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1013
     "Nodes on which the command should be run (at least one)"),
1014
    ("command", ht.NoDefault, ht.TNonEmptyString,
1015
     "Command name (no parameters)"),
1016
    ]
1017

    
1018
  _RESULT_ITEMS = [
1019
    ht.Comment("success")(ht.TBool),
1020
    ht.Comment("output or error message")(ht.TString),
1021
    ]
1022

    
1023
  OP_RESULT = \
1024
    ht.TListOf(ht.TAnd(ht.TIsLength(len(_RESULT_ITEMS)),
1025
                       ht.TItems(_RESULT_ITEMS)))
1026

    
1027

    
1028
# node opcodes
1029

    
1030
class OpNodeRemove(OpCode):
1031
  """Remove a node.
1032

1033
  @type node_name: C{str}
1034
  @ivar node_name: The name of the node to remove. If the node still has
1035
                   instances on it, the operation will fail.
1036

1037
  """
1038
  OP_DSC_FIELD = "node_name"
1039
  OP_PARAMS = [
1040
    _PNodeName,
1041
    ]
1042
  OP_RESULT = ht.TNone
1043

    
1044

    
1045
class OpNodeAdd(OpCode):
1046
  """Add a node to the cluster.
1047

1048
  @type node_name: C{str}
1049
  @ivar node_name: The name of the node to add. This can be a short name,
1050
                   but it will be expanded to the FQDN.
1051
  @type primary_ip: IP address
1052
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
1053
                    opcode is submitted, but will be filled during the node
1054
                    add (so it will be visible in the job query).
1055
  @type secondary_ip: IP address
1056
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
1057
                      if the cluster has been initialized in 'dual-network'
1058
                      mode, otherwise it must not be given.
1059
  @type readd: C{bool}
1060
  @ivar readd: Whether to re-add an existing node to the cluster. If
1061
               this is not passed, then the operation will abort if the node
1062
               name is already in the cluster; use this parameter to 'repair'
1063
               a node that had its configuration broken, or was reinstalled
1064
               without removal from the cluster.
1065
  @type group: C{str}
1066
  @ivar group: The node group to which this node will belong.
1067
  @type vm_capable: C{bool}
1068
  @ivar vm_capable: The vm_capable node attribute
1069
  @type master_capable: C{bool}
1070
  @ivar master_capable: The master_capable node attribute
1071

1072
  """
1073
  OP_DSC_FIELD = "node_name"
1074
  OP_PARAMS = [
1075
    _PNodeName,
1076
    _PHvState,
1077
    _PDiskState,
1078
    ("primary_ip", None, ht.NoType, "Primary IP address"),
1079
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1080
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1081
    ("group", None, ht.TMaybeString, "Initial node group"),
1082
    ("master_capable", None, ht.TMaybeBool,
1083
     "Whether node can become master or master candidate"),
1084
    ("vm_capable", None, ht.TMaybeBool,
1085
     "Whether node can host instances"),
1086
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1087
    ]
1088
  OP_RESULT = ht.TNone
1089

    
1090

    
1091
class OpNodeQuery(OpCode):
1092
  """Compute the list of nodes."""
1093
  OP_PARAMS = [
1094
    _POutputFields,
1095
    _PUseLocking,
1096
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1097
     "Empty list to query all nodes, node names otherwise"),
1098
    ]
1099
  OP_RESULT = _TOldQueryResult
1100

    
1101

    
1102
class OpNodeQueryvols(OpCode):
1103
  """Get list of volumes on node."""
1104
  OP_PARAMS = [
1105
    _POutputFields,
1106
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1107
     "Empty list to query all nodes, node names otherwise"),
1108
    ]
1109
  OP_RESULT = ht.TListOf(ht.TAny)
1110

    
1111

    
1112
class OpNodeQueryStorage(OpCode):
1113
  """Get information on storage for node(s)."""
1114
  OP_PARAMS = [
1115
    _POutputFields,
1116
    _PStorageType,
1117
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1118
    ("name", None, ht.TMaybeString, "Storage name"),
1119
    ]
1120
  OP_RESULT = _TOldQueryResult
1121

    
1122

    
1123
class OpNodeModifyStorage(OpCode):
1124
  """Modifies the properies of a storage unit"""
1125
  OP_DSC_FIELD = "node_name"
1126
  OP_PARAMS = [
1127
    _PNodeName,
1128
    _PStorageType,
1129
    _PStorageName,
1130
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1131
    ]
1132
  OP_RESULT = ht.TNone
1133

    
1134

    
1135
class OpRepairNodeStorage(OpCode):
1136
  """Repairs the volume group on a node."""
1137
  OP_DSC_FIELD = "node_name"
1138
  OP_PARAMS = [
1139
    _PNodeName,
1140
    _PStorageType,
1141
    _PStorageName,
1142
    _PIgnoreConsistency,
1143
    ]
1144
  OP_RESULT = ht.TNone
1145

    
1146

    
1147
class OpNodeSetParams(OpCode):
1148
  """Change the parameters of a node."""
1149
  OP_DSC_FIELD = "node_name"
1150
  OP_PARAMS = [
1151
    _PNodeName,
1152
    _PForce,
1153
    _PHvState,
1154
    _PDiskState,
1155
    ("master_candidate", None, ht.TMaybeBool,
1156
     "Whether the node should become a master candidate"),
1157
    ("offline", None, ht.TMaybeBool,
1158
     "Whether the node should be marked as offline"),
1159
    ("drained", None, ht.TMaybeBool,
1160
     "Whether the node should be marked as drained"),
1161
    ("auto_promote", False, ht.TBool,
1162
     "Whether node(s) should be promoted to master candidate if necessary"),
1163
    ("master_capable", None, ht.TMaybeBool,
1164
     "Denote whether node can become master or master candidate"),
1165
    ("vm_capable", None, ht.TMaybeBool,
1166
     "Denote whether node can host instances"),
1167
    ("secondary_ip", None, ht.TMaybeString,
1168
     "Change node's secondary IP address"),
1169
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1170
    ("powered", None, ht.TMaybeBool,
1171
     "Whether the node should be marked as powered"),
1172
    ]
1173
  OP_RESULT = _TSetParamsResult
1174

    
1175

    
1176
class OpNodePowercycle(OpCode):
1177
  """Tries to powercycle a node."""
1178
  OP_DSC_FIELD = "node_name"
1179
  OP_PARAMS = [
1180
    _PNodeName,
1181
    _PForce,
1182
    ]
1183
  OP_RESULT = ht.TMaybeString
1184

    
1185

    
1186
class OpNodeMigrate(OpCode):
1187
  """Migrate all instances from a node."""
1188
  OP_DSC_FIELD = "node_name"
1189
  OP_PARAMS = [
1190
    _PNodeName,
1191
    _PMigrationMode,
1192
    _PMigrationLive,
1193
    _PMigrationTargetNode,
1194
    _PAllowRuntimeChgs,
1195
    _PIgnoreIpolicy,
1196
    ("iallocator", None, ht.TMaybeString,
1197
     "Iallocator for deciding the target node for shared-storage instances"),
1198
    ]
1199
  OP_RESULT = TJobIdListOnly
1200

    
1201

    
1202
class OpNodeEvacuate(OpCode):
1203
  """Evacuate instances off a number of nodes."""
1204
  OP_DSC_FIELD = "node_name"
1205
  OP_PARAMS = [
1206
    _PEarlyRelease,
1207
    _PNodeName,
1208
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1209
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1210
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1211
     "Node evacuation mode"),
1212
    ]
1213
  OP_RESULT = TJobIdListOnly
1214

    
1215

    
1216
# instance opcodes
1217

    
1218
class OpInstanceCreate(OpCode):
1219
  """Create an instance.
1220

1221
  @ivar instance_name: Instance name
1222
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1223
  @ivar source_handshake: Signed handshake from source (remote import only)
1224
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1225
  @ivar source_instance_name: Previous name of instance (remote import only)
1226
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1227
    (remote import only)
1228

1229
  """
1230
  OP_DSC_FIELD = "instance_name"
1231
  OP_PARAMS = [
1232
    _PInstanceName,
1233
    _PForceVariant,
1234
    _PWaitForSync,
1235
    _PNameCheck,
1236
    _PIgnoreIpolicy,
1237
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1238
    ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1239
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1240
     " each disk definition must contain a ``%s`` value and"
1241
     " can contain an optional ``%s`` value denoting the disk access mode"
1242
     " (%s)" %
1243
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1244
      constants.IDISK_MODE,
1245
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1246
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1247
     "Disk template"),
1248
    ("file_driver", None, ht.TMaybe(ht.TElemOf(constants.FILE_DRIVER)),
1249
     "Driver for file-backed disks"),
1250
    ("file_storage_dir", None, ht.TMaybeString,
1251
     "Directory for storing file-backed disks"),
1252
    ("hvparams", ht.EmptyDict, ht.TDict,
1253
     "Hypervisor parameters for instance, hypervisor-dependent"),
1254
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1255
    ("iallocator", None, ht.TMaybeString,
1256
     "Iallocator for deciding which node(s) to use"),
1257
    ("identify_defaults", False, ht.TBool,
1258
     "Reset instance parameters to default if equal"),
1259
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1260
    ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1261
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1262
     "Instance creation mode"),
1263
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1264
     "List of NIC (network interface) definitions, for example"
1265
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1266
     " contain the optional values %s" %
1267
     (constants.INIC_IP,
1268
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1269
    ("no_install", None, ht.TMaybeBool,
1270
     "Do not install the OS (will disable automatic start)"),
1271
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1272
    ("os_type", None, ht.TMaybeString, "Operating system"),
1273
    ("pnode", None, ht.TMaybeString, "Primary node"),
1274
    ("snode", None, ht.TMaybeString, "Secondary node"),
1275
    ("source_handshake", None, ht.TMaybe(ht.TList),
1276
     "Signed handshake from source (remote import only)"),
1277
    ("source_instance_name", None, ht.TMaybeString,
1278
     "Source instance name (remote import only)"),
1279
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1280
     ht.TNonNegativeInt,
1281
     "How long source instance was given to shut down (remote import only)"),
1282
    ("source_x509_ca", None, ht.TMaybeString,
1283
     "Source X509 CA in PEM format (remote import only)"),
1284
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1285
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1286
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1287
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1288
    ]
1289
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1290

    
1291

    
1292
class OpInstanceMultiAlloc(OpCode):
1293
  """Allocates multiple instances.
1294

1295
  """
1296
  OP_PARAMS = [
1297
    ("iallocator", None, ht.TMaybeString,
1298
     "Iallocator used to allocate all the instances"),
1299
    ("instances", [], ht.TListOf(ht.TInstanceOf(OpInstanceCreate)),
1300
     "List of instance create opcodes describing the instances to allocate"),
1301
    ]
1302
  _JOB_LIST = ht.Comment("List of submitted jobs")(TJobIdList)
1303
  ALLOCATABLE_KEY = "allocatable"
1304
  FAILED_KEY = "allocatable"
1305
  OP_RESULT = ht.TStrictDict(True, True, {
1306
    constants.JOB_IDS_KEY: _JOB_LIST,
1307
    ALLOCATABLE_KEY: ht.TListOf(ht.TNonEmptyString),
1308
    FAILED_KEY: ht.TListOf(ht.TNonEmptyString),
1309
    })
1310

    
1311
  def __getstate__(self):
1312
    """Generic serializer.
1313

1314
    """
1315
    state = OpCode.__getstate__(self)
1316
    if hasattr(self, "instances"):
1317
      # pylint: disable=E1101
1318
      state["instances"] = [inst.__getstate__() for inst in self.instances]
1319
    return state
1320

    
1321
  def __setstate__(self, state):
1322
    """Generic unserializer.
1323

1324
    This method just restores from the serialized state the attributes
1325
    of the current instance.
1326

1327
    @param state: the serialized opcode data
1328
    @type state: C{dict}
1329

1330
    """
1331
    if not isinstance(state, dict):
1332
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
1333
                       type(state))
1334

    
1335
    if "instances" in state:
1336
      insts = [OpCode.LoadOpCode(inst) for inst in state["instances"]]
1337
      state["instances"] = insts
1338
    return OpCode.__setstate__(self, state)
1339

    
1340
  def Validate(self, set_defaults):
1341
    """Validates this opcode.
1342

1343
    We do this recursively.
1344

1345
    """
1346
    OpCode.Validate(self, set_defaults)
1347

    
1348
    for inst in self.instances: # pylint: disable=E1101
1349
      inst.Validate(set_defaults)
1350

    
1351

    
1352
class OpInstanceReinstall(OpCode):
1353
  """Reinstall an instance's OS."""
1354
  OP_DSC_FIELD = "instance_name"
1355
  OP_PARAMS = [
1356
    _PInstanceName,
1357
    _PForceVariant,
1358
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1359
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1360
    ]
1361
  OP_RESULT = ht.TNone
1362

    
1363

    
1364
class OpInstanceRemove(OpCode):
1365
  """Remove an instance."""
1366
  OP_DSC_FIELD = "instance_name"
1367
  OP_PARAMS = [
1368
    _PInstanceName,
1369
    _PShutdownTimeout,
1370
    ("ignore_failures", False, ht.TBool,
1371
     "Whether to ignore failures during removal"),
1372
    ]
1373
  OP_RESULT = ht.TNone
1374

    
1375

    
1376
class OpInstanceRename(OpCode):
1377
  """Rename an instance."""
1378
  OP_PARAMS = [
1379
    _PInstanceName,
1380
    _PNameCheck,
1381
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1382
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1383
    ]
1384
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1385

    
1386

    
1387
class OpInstanceStartup(OpCode):
1388
  """Startup an instance."""
1389
  OP_DSC_FIELD = "instance_name"
1390
  OP_PARAMS = [
1391
    _PInstanceName,
1392
    _PForce,
1393
    _PIgnoreOfflineNodes,
1394
    ("hvparams", ht.EmptyDict, ht.TDict,
1395
     "Temporary hypervisor parameters, hypervisor-dependent"),
1396
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1397
    _PNoRemember,
1398
    _PStartupPaused,
1399
    ]
1400
  OP_RESULT = ht.TNone
1401

    
1402

    
1403
class OpInstanceShutdown(OpCode):
1404
  """Shutdown an instance."""
1405
  OP_DSC_FIELD = "instance_name"
1406
  OP_PARAMS = [
1407
    _PInstanceName,
1408
    _PIgnoreOfflineNodes,
1409
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TNonNegativeInt,
1410
     "How long to wait for instance to shut down"),
1411
    _PNoRemember,
1412
    ]
1413
  OP_RESULT = ht.TNone
1414

    
1415

    
1416
class OpInstanceReboot(OpCode):
1417
  """Reboot an instance."""
1418
  OP_DSC_FIELD = "instance_name"
1419
  OP_PARAMS = [
1420
    _PInstanceName,
1421
    _PShutdownTimeout,
1422
    ("ignore_secondaries", False, ht.TBool,
1423
     "Whether to start the instance even if secondary disks are failing"),
1424
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1425
     "How to reboot instance"),
1426
    ]
1427
  OP_RESULT = ht.TNone
1428

    
1429

    
1430
class OpInstanceReplaceDisks(OpCode):
1431
  """Replace the disks of an instance."""
1432
  OP_DSC_FIELD = "instance_name"
1433
  OP_PARAMS = [
1434
    _PInstanceName,
1435
    _PEarlyRelease,
1436
    _PIgnoreIpolicy,
1437
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1438
     "Replacement mode"),
1439
    ("disks", ht.EmptyList, ht.TListOf(ht.TNonNegativeInt),
1440
     "Disk indexes"),
1441
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1442
    ("iallocator", None, ht.TMaybeString,
1443
     "Iallocator for deciding new secondary node"),
1444
    ]
1445
  OP_RESULT = ht.TNone
1446

    
1447

    
1448
class OpInstanceFailover(OpCode):
1449
  """Failover an instance."""
1450
  OP_DSC_FIELD = "instance_name"
1451
  OP_PARAMS = [
1452
    _PInstanceName,
1453
    _PShutdownTimeout,
1454
    _PIgnoreConsistency,
1455
    _PMigrationTargetNode,
1456
    _PIgnoreIpolicy,
1457
    ("iallocator", None, ht.TMaybeString,
1458
     "Iallocator for deciding the target node for shared-storage instances"),
1459
    ]
1460
  OP_RESULT = ht.TNone
1461

    
1462

    
1463
class OpInstanceMigrate(OpCode):
1464
  """Migrate an instance.
1465

1466
  This migrates (without shutting down an instance) to its secondary
1467
  node.
1468

1469
  @ivar instance_name: the name of the instance
1470
  @ivar mode: the migration mode (live, non-live or None for auto)
1471

1472
  """
1473
  OP_DSC_FIELD = "instance_name"
1474
  OP_PARAMS = [
1475
    _PInstanceName,
1476
    _PMigrationMode,
1477
    _PMigrationLive,
1478
    _PMigrationTargetNode,
1479
    _PAllowRuntimeChgs,
1480
    _PIgnoreIpolicy,
1481
    ("cleanup", False, ht.TBool,
1482
     "Whether a previously failed migration should be cleaned up"),
1483
    ("iallocator", None, ht.TMaybeString,
1484
     "Iallocator for deciding the target node for shared-storage instances"),
1485
    ("allow_failover", False, ht.TBool,
1486
     "Whether we can fallback to failover if migration is not possible"),
1487
    ]
1488
  OP_RESULT = ht.TNone
1489

    
1490

    
1491
class OpInstanceMove(OpCode):
1492
  """Move an instance.
1493

1494
  This move (with shutting down an instance and data copying) to an
1495
  arbitrary node.
1496

1497
  @ivar instance_name: the name of the instance
1498
  @ivar target_node: the destination node
1499

1500
  """
1501
  OP_DSC_FIELD = "instance_name"
1502
  OP_PARAMS = [
1503
    _PInstanceName,
1504
    _PShutdownTimeout,
1505
    _PIgnoreIpolicy,
1506
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1507
    _PIgnoreConsistency,
1508
    ]
1509
  OP_RESULT = ht.TNone
1510

    
1511

    
1512
class OpInstanceConsole(OpCode):
1513
  """Connect to an instance's console."""
1514
  OP_DSC_FIELD = "instance_name"
1515
  OP_PARAMS = [
1516
    _PInstanceName,
1517
    ]
1518
  OP_RESULT = ht.TDict
1519

    
1520

    
1521
class OpInstanceActivateDisks(OpCode):
1522
  """Activate an instance's disks."""
1523
  OP_DSC_FIELD = "instance_name"
1524
  OP_PARAMS = [
1525
    _PInstanceName,
1526
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1527
    _PWaitForSyncFalse,
1528
    ]
1529
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1530
                                 ht.TItems([ht.TNonEmptyString,
1531
                                            ht.TNonEmptyString,
1532
                                            ht.TNonEmptyString])))
1533

    
1534

    
1535
class OpInstanceDeactivateDisks(OpCode):
1536
  """Deactivate an instance's disks."""
1537
  OP_DSC_FIELD = "instance_name"
1538
  OP_PARAMS = [
1539
    _PInstanceName,
1540
    _PForce,
1541
    ]
1542
  OP_RESULT = ht.TNone
1543

    
1544

    
1545
class OpInstanceRecreateDisks(OpCode):
1546
  """Recreate an instance's disks."""
1547
  _TDiskChanges = \
1548
    ht.TAnd(ht.TIsLength(2),
1549
            ht.TItems([ht.Comment("Disk index")(ht.TNonNegativeInt),
1550
                       ht.Comment("Parameters")(_TDiskParams)]))
1551

    
1552
  OP_DSC_FIELD = "instance_name"
1553
  OP_PARAMS = [
1554
    _PInstanceName,
1555
    ("disks", ht.EmptyList,
1556
     ht.TOr(ht.TListOf(ht.TNonNegativeInt), ht.TListOf(_TDiskChanges)),
1557
     "List of disk indexes (deprecated) or a list of tuples containing a disk"
1558
     " index and a possibly empty dictionary with disk parameter changes"),
1559
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1560
     "New instance nodes, if relocation is desired"),
1561
    ("iallocator", None, ht.TMaybeString,
1562
     "Iallocator for deciding new nodes"),
1563
    ]
1564
  OP_RESULT = ht.TNone
1565

    
1566

    
1567
class OpInstanceQuery(OpCode):
1568
  """Compute the list of instances."""
1569
  OP_PARAMS = [
1570
    _POutputFields,
1571
    _PUseLocking,
1572
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1573
     "Empty list to query all instances, instance names otherwise"),
1574
    ]
1575
  OP_RESULT = _TOldQueryResult
1576

    
1577

    
1578
class OpInstanceQueryData(OpCode):
1579
  """Compute the run-time status of instances."""
1580
  OP_PARAMS = [
1581
    _PUseLocking,
1582
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1583
     "Instance names"),
1584
    ("static", False, ht.TBool,
1585
     "Whether to only return configuration data without querying"
1586
     " nodes"),
1587
    ]
1588
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1589

    
1590

    
1591
def _TestInstSetParamsModList(fn):
1592
  """Generates a check for modification lists.
1593

1594
  """
1595
  # Old format
1596
  # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1597
  old_mod_item_fn = \
1598
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1599
      ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TNonNegativeInt),
1600
      fn,
1601
      ]))
1602

    
1603
  # New format, supporting adding/removing disks/NICs at arbitrary indices
1604
  mod_item_fn = \
1605
    ht.TAnd(ht.TIsLength(3), ht.TItems([
1606
      ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1607
      ht.Comment("Disk index, can be negative, e.g. -1 for last disk")(ht.TInt),
1608
      fn,
1609
      ]))
1610

    
1611
  return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1612
                ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1613

    
1614

    
1615
class OpInstanceSetParams(OpCode):
1616
  """Change the parameters of an instance.
1617

1618
  """
1619
  TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1620
  TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1621

    
1622
  OP_DSC_FIELD = "instance_name"
1623
  OP_PARAMS = [
1624
    _PInstanceName,
1625
    _PForce,
1626
    _PForceVariant,
1627
    _PIgnoreIpolicy,
1628
    ("nics", ht.EmptyList, TestNicModifications,
1629
     "List of NIC changes: each item is of the form ``(op, index, settings)``,"
1630
     " ``op`` is one of ``%s``, ``%s`` or ``%s``, ``index`` can be either -1"
1631
     " to refer to the last position, or a zero-based index number; a"
1632
     " deprecated version of this parameter used the form ``(op, settings)``,"
1633
     " where ``op`` can be ``%s`` to add a new NIC with the specified"
1634
     " settings, ``%s`` to remove the last NIC or a number to modify the"
1635
     " settings of the NIC with that index" %
1636
     (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1637
      constants.DDM_ADD, constants.DDM_REMOVE)),
1638
    ("disks", ht.EmptyList, TestDiskModifications,
1639
     "List of disk changes; see ``nics``"),
1640
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1641
    ("runtime_mem", None, ht.TMaybePositiveInt, "New runtime memory"),
1642
    ("hvparams", ht.EmptyDict, ht.TDict,
1643
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1644
    ("disk_template", None, ht.TMaybe(_BuildDiskTemplateCheck(False)),
1645
     "Disk template for instance"),
1646
    ("remote_node", None, ht.TMaybeString,
1647
     "Secondary node (used when changing disk template)"),
1648
    ("os_name", None, ht.TMaybeString,
1649
     "Change the instance's OS without reinstalling the instance"),
1650
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1651
    ("wait_for_sync", True, ht.TBool,
1652
     "Whether to wait for the disk to synchronize, when changing template"),
1653
    ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1654
    ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1655
    ]
1656
  OP_RESULT = _TSetParamsResult
1657

    
1658

    
1659
class OpInstanceGrowDisk(OpCode):
1660
  """Grow a disk of an instance."""
1661
  OP_DSC_FIELD = "instance_name"
1662
  OP_PARAMS = [
1663
    _PInstanceName,
1664
    _PWaitForSync,
1665
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1666
    ("amount", ht.NoDefault, ht.TNonNegativeInt,
1667
     "Amount of disk space to add (megabytes)"),
1668
    ("absolute", False, ht.TBool,
1669
     "Whether the amount parameter is an absolute target or a relative one"),
1670
    ]
1671
  OP_RESULT = ht.TNone
1672

    
1673

    
1674
class OpInstanceChangeGroup(OpCode):
1675
  """Moves an instance to another node group."""
1676
  OP_DSC_FIELD = "instance_name"
1677
  OP_PARAMS = [
1678
    _PInstanceName,
1679
    _PEarlyRelease,
1680
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1681
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1682
     "Destination group names or UUIDs (defaults to \"all but current group\""),
1683
    ]
1684
  OP_RESULT = TJobIdListOnly
1685

    
1686

    
1687
# Node group opcodes
1688

    
1689
class OpGroupAdd(OpCode):
1690
  """Add a node group to the cluster."""
1691
  OP_DSC_FIELD = "group_name"
1692
  OP_PARAMS = [
1693
    _PGroupName,
1694
    _PNodeGroupAllocPolicy,
1695
    _PGroupNodeParams,
1696
    _PDiskParams,
1697
    _PHvState,
1698
    _PDiskState,
1699
    ("ipolicy", None, ht.TMaybeDict,
1700
     "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1701
    ]
1702
  OP_RESULT = ht.TNone
1703

    
1704

    
1705
class OpGroupAssignNodes(OpCode):
1706
  """Assign nodes to a node group."""
1707
  OP_DSC_FIELD = "group_name"
1708
  OP_PARAMS = [
1709
    _PGroupName,
1710
    _PForce,
1711
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1712
     "List of nodes to assign"),
1713
    ]
1714
  OP_RESULT = ht.TNone
1715

    
1716

    
1717
class OpGroupQuery(OpCode):
1718
  """Compute the list of node groups."""
1719
  OP_PARAMS = [
1720
    _POutputFields,
1721
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1722
     "Empty list to query all groups, group names otherwise"),
1723
    ]
1724
  OP_RESULT = _TOldQueryResult
1725

    
1726

    
1727
class OpGroupSetParams(OpCode):
1728
  """Change the parameters of a node group."""
1729
  OP_DSC_FIELD = "group_name"
1730
  OP_PARAMS = [
1731
    _PGroupName,
1732
    _PNodeGroupAllocPolicy,
1733
    _PGroupNodeParams,
1734
    _PDiskParams,
1735
    _PHvState,
1736
    _PDiskState,
1737
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1738
    ]
1739
  OP_RESULT = _TSetParamsResult
1740

    
1741

    
1742
class OpGroupRemove(OpCode):
1743
  """Remove a node group from the cluster."""
1744
  OP_DSC_FIELD = "group_name"
1745
  OP_PARAMS = [
1746
    _PGroupName,
1747
    ]
1748
  OP_RESULT = ht.TNone
1749

    
1750

    
1751
class OpGroupRename(OpCode):
1752
  """Rename a node group in the cluster."""
1753
  OP_PARAMS = [
1754
    _PGroupName,
1755
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1756
    ]
1757
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1758

    
1759

    
1760
class OpGroupEvacuate(OpCode):
1761
  """Evacuate a node group in the cluster."""
1762
  OP_DSC_FIELD = "group_name"
1763
  OP_PARAMS = [
1764
    _PGroupName,
1765
    _PEarlyRelease,
1766
    ("iallocator", None, ht.TMaybeString, "Iallocator for computing solution"),
1767
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
1768
     "Destination group names or UUIDs"),
1769
    ]
1770
  OP_RESULT = TJobIdListOnly
1771

    
1772

    
1773
# OS opcodes
1774
class OpOsDiagnose(OpCode):
1775
  """Compute the list of guest operating systems."""
1776
  OP_PARAMS = [
1777
    _POutputFields,
1778
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1779
     "Which operating systems to diagnose"),
1780
    ]
1781
  OP_RESULT = _TOldQueryResult
1782

    
1783

    
1784
# Exports opcodes
1785
class OpBackupQuery(OpCode):
1786
  """Compute the list of exported images."""
1787
  OP_PARAMS = [
1788
    _PUseLocking,
1789
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1790
     "Empty list to query all nodes, node names otherwise"),
1791
    ]
1792
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1793
                         ht.TOr(ht.Comment("False on error")(ht.TBool),
1794
                                ht.TListOf(ht.TNonEmptyString)))
1795

    
1796

    
1797
class OpBackupPrepare(OpCode):
1798
  """Prepares an instance export.
1799

1800
  @ivar instance_name: Instance name
1801
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1802

1803
  """
1804
  OP_DSC_FIELD = "instance_name"
1805
  OP_PARAMS = [
1806
    _PInstanceName,
1807
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1808
     "Export mode"),
1809
    ]
1810
  OP_RESULT = ht.TMaybeDict
1811

    
1812

    
1813
class OpBackupExport(OpCode):
1814
  """Export an instance.
1815

1816
  For local exports, the export destination is the node name. For remote
1817
  exports, the export destination is a list of tuples, each consisting of
1818
  hostname/IP address, port, HMAC and HMAC salt. The HMAC is calculated using
1819
  the cluster domain secret over the value "${index}:${hostname}:${port}". The
1820
  destination X509 CA must be a signed certificate.
1821

1822
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1823
  @ivar target_node: Export destination
1824
  @ivar x509_key_name: X509 key to use (remote export only)
1825
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1826
                             only)
1827

1828
  """
1829
  OP_DSC_FIELD = "instance_name"
1830
  OP_PARAMS = [
1831
    _PInstanceName,
1832
    _PShutdownTimeout,
1833
    # TODO: Rename target_node as it changes meaning for different export modes
1834
    # (e.g. "destination")
1835
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1836
     "Destination information, depends on export mode"),
1837
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1838
    ("remove_instance", False, ht.TBool,
1839
     "Whether to remove instance after export"),
1840
    ("ignore_remove_failures", False, ht.TBool,
1841
     "Whether to ignore failures while removing instances"),
1842
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1843
     "Export mode"),
1844
    ("x509_key_name", None, ht.TMaybe(ht.TList),
1845
     "Name of X509 key (remote export only)"),
1846
    ("destination_x509_ca", None, ht.TMaybeString,
1847
     "Destination X509 CA (remote export only)"),
1848
    ]
1849
  OP_RESULT = \
1850
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1851
      ht.Comment("Finalizing status")(ht.TBool),
1852
      ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1853
      ]))
1854

    
1855

    
1856
class OpBackupRemove(OpCode):
1857
  """Remove an instance's export."""
1858
  OP_DSC_FIELD = "instance_name"
1859
  OP_PARAMS = [
1860
    _PInstanceName,
1861
    ]
1862
  OP_RESULT = ht.TNone
1863

    
1864

    
1865
# Tags opcodes
1866
class OpTagsGet(OpCode):
1867
  """Returns the tags of the given object."""
1868
  OP_DSC_FIELD = "name"
1869
  OP_PARAMS = [
1870
    _PTagKind,
1871
    # Not using _PUseLocking as the default is different for historical reasons
1872
    ("use_locking", True, ht.TBool, "Whether to use synchronization"),
1873
    # Name is only meaningful for nodes and instances
1874
    ("name", ht.NoDefault, ht.TMaybeString,
1875
     "Name of object to retrieve tags from"),
1876
    ]
1877
  OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1878

    
1879

    
1880
class OpTagsSearch(OpCode):
1881
  """Searches the tags in the cluster for a given pattern."""
1882
  OP_DSC_FIELD = "pattern"
1883
  OP_PARAMS = [
1884
    ("pattern", ht.NoDefault, ht.TNonEmptyString,
1885
     "Search pattern (regular expression)"),
1886
    ]
1887
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1888
    ht.TNonEmptyString,
1889
    ht.TNonEmptyString,
1890
    ])))
1891

    
1892

    
1893
class OpTagsSet(OpCode):
1894
  """Add a list of tags on a given object."""
1895
  OP_PARAMS = [
1896
    _PTagKind,
1897
    _PTags,
1898
    # Name is only meaningful for groups, nodes and instances
1899
    ("name", ht.NoDefault, ht.TMaybeString,
1900
     "Name of object where tag(s) should be added"),
1901
    ]
1902
  OP_RESULT = ht.TNone
1903

    
1904

    
1905
class OpTagsDel(OpCode):
1906
  """Remove a list of tags from a given object."""
1907
  OP_PARAMS = [
1908
    _PTagKind,
1909
    _PTags,
1910
    # Name is only meaningful for groups, nodes and instances
1911
    ("name", ht.NoDefault, ht.TMaybeString,
1912
     "Name of object where tag(s) should be deleted"),
1913
    ]
1914
  OP_RESULT = ht.TNone
1915

    
1916

    
1917
# Test opcodes
1918
class OpTestDelay(OpCode):
1919
  """Sleeps for a configured amount of time.
1920

1921
  This is used just for debugging and testing.
1922

1923
  Parameters:
1924
    - duration: the time to sleep
1925
    - on_master: if true, sleep on the master
1926
    - on_nodes: list of nodes in which to sleep
1927

1928
  If the on_master parameter is true, it will execute a sleep on the
1929
  master (before any node sleep).
1930

1931
  If the on_nodes list is not empty, it will sleep on those nodes
1932
  (after the sleep on the master, if that is enabled).
1933

1934
  As an additional feature, the case of duration < 0 will be reported
1935
  as an execution error, so this opcode can be used as a failure
1936
  generator. The case of duration == 0 will not be treated specially.
1937

1938
  """
1939
  OP_DSC_FIELD = "duration"
1940
  OP_PARAMS = [
1941
    ("duration", ht.NoDefault, ht.TNumber, None),
1942
    ("on_master", True, ht.TBool, None),
1943
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1944
    ("repeat", 0, ht.TNonNegativeInt, None),
1945
    ]
1946

    
1947

    
1948
class OpTestAllocator(OpCode):
1949
  """Allocator framework testing.
1950

1951
  This opcode has two modes:
1952
    - gather and return allocator input for a given mode (allocate new
1953
      or replace secondary) and a given instance definition (direction
1954
      'in')
1955
    - run a selected allocator for a given operation (as above) and
1956
      return the allocator output (direction 'out')
1957

1958
  """
1959
  OP_DSC_FIELD = "allocator"
1960
  OP_PARAMS = [
1961
    ("direction", ht.NoDefault,
1962
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
1963
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
1964
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
1965
    ("nics", ht.NoDefault,
1966
     ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
1967
                                            constants.INIC_IP,
1968
                                            "bridge"]),
1969
                                ht.TMaybeString)),
1970
     None),
1971
    ("disks", ht.NoDefault, ht.TMaybe(ht.TList), None),
1972
    ("hypervisor", None, ht.TMaybeString, None),
1973
    ("allocator", None, ht.TMaybeString, None),
1974
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
1975
    ("memory", None, ht.TMaybe(ht.TNonNegativeInt), None),
1976
    ("vcpus", None, ht.TMaybe(ht.TNonNegativeInt), None),
1977
    ("os", None, ht.TMaybeString, None),
1978
    ("disk_template", None, ht.TMaybeString, None),
1979
    ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1980
    ("evac_mode", None,
1981
     ht.TMaybe(ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
1982
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
1983
    ("spindle_use", 1, ht.TNonNegativeInt, None),
1984
    ("count", 1, ht.TNonNegativeInt, None),
1985
    ]
1986

    
1987

    
1988
class OpTestJqueue(OpCode):
1989
  """Utility opcode to test some aspects of the job queue.
1990

1991
  """
1992
  OP_PARAMS = [
1993
    ("notify_waitlock", False, ht.TBool, None),
1994
    ("notify_exec", False, ht.TBool, None),
1995
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
1996
    ("fail", False, ht.TBool, None),
1997
    ]
1998

    
1999

    
2000
class OpTestDummy(OpCode):
2001
  """Utility opcode used by unittests.
2002

2003
  """
2004
  OP_PARAMS = [
2005
    ("result", ht.NoDefault, ht.NoType, None),
2006
    ("messages", ht.NoDefault, ht.NoType, None),
2007
    ("fail", ht.NoDefault, ht.NoType, None),
2008
    ("submit_jobs", None, ht.NoType, None),
2009
    ]
2010
  WITH_LU = False
2011

    
2012

    
2013
# Network opcodes
2014
# Add a new network in the cluster
2015
class OpNetworkAdd(OpCode):
2016
  """Add an IP network to the cluster."""
2017
  OP_DSC_FIELD = "network_name"
2018
  OP_PARAMS = [
2019
    _PNetworkName,
2020
    _PNetworkType,
2021
    ("network", None, _TIpAddress, "IPv4 subnet"),
2022
    ("gateway", None, _TIpAddress, "IPv4 gateway"),
2023
    ("network6", None, _TIpAddress6, "IPv6 subnet"),
2024
    ("gateway6", None, _TIpAddress6, "IPv6 gateway"),
2025
    ("mac_prefix", None, ht.TMaybeString,
2026
     "MAC address prefix that overrides cluster one"),
2027
    ("add_reserved_ips", None,
2028
     ht.TMaybe(ht.TListOf(_CheckCIDRAddrNotation)),
2029
     "Which IP addresses to reserve"),
2030
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Network tags"),
2031
    ]
2032
  OP_RESULT = ht.TNone
2033

    
2034

    
2035
class OpNetworkRemove(OpCode):
2036
  """Remove an existing network from the cluster.
2037
     Must not be connected to any nodegroup.
2038

2039
  """
2040
  OP_DSC_FIELD = "network_name"
2041
  OP_PARAMS = [
2042
    _PNetworkName,
2043
    _PForce,
2044
    ]
2045
  OP_RESULT = ht.TNone
2046

    
2047

    
2048
class OpNetworkSetParams(OpCode):
2049
  """Modify Network's parameters except for IPv4 subnet"""
2050
  OP_DSC_FIELD = "network_name"
2051
  OP_PARAMS = [
2052
    _PNetworkName,
2053
    _PNetworkType,
2054
    ("gateway", None, _TIpAddress, "IPv4 gateway"),
2055
    ("network6", None, _TIpAddress6, "IPv6 subnet"),
2056
    ("gateway6", None, _TIpAddress6, "IPv6 gateway"),
2057
    ("mac_prefix", None, ht.TMaybeString,
2058
     "MAC address prefix that overrides cluster one"),
2059
    ("add_reserved_ips", None,
2060
     ht.TMaybe(ht.TListOf(_CheckCIDRAddrNotation)),
2061
     "Which external IP addresses to reserve"),
2062
    ("remove_reserved_ips", None,
2063
     ht.TMaybe(ht.TListOf(_CheckCIDRAddrNotation)),
2064
     "Which external IP addresses to release"),
2065
    ]
2066
  OP_RESULT = ht.TNone
2067

    
2068

    
2069
class OpNetworkConnect(OpCode):
2070
  """Connect a Network to a specific Nodegroup with the defined netparams
2071
     (mode, link). Nics in this Network will inherit those params.
2072
     Produce errors if a NIC (that its not already assigned to a network)
2073
     has an IP that is contained in the Network this will produce error unless
2074
     --no-conflicts-check is passed.
2075

2076
  """
2077
  OP_DSC_FIELD = "network_name"
2078
  OP_PARAMS = [
2079
    _PGroupName,
2080
    _PNetworkName,
2081
    ("network_mode", None, ht.TMaybeString, "Connectivity mode"),
2082
    ("network_link", None, ht.TMaybeString, "Connectivity link"),
2083
    ("conflicts_check", True, ht.TBool, "Whether to check for conflicting IPs"),
2084
    ]
2085
  OP_RESULT = ht.TNone
2086

    
2087

    
2088
class OpNetworkDisconnect(OpCode):
2089
  """Disconnect a Network from a Nodegroup. Produce errors if NICs are
2090
     present in the Network unless --no-conficts-check option is passed.
2091

2092
  """
2093
  OP_DSC_FIELD = "network_name"
2094
  OP_PARAMS = [
2095
    _PGroupName,
2096
    _PNetworkName,
2097
    ("conflicts_check", True, ht.TBool, "Whether to check for conflicting IPs"),
2098
    ]
2099
  OP_RESULT = ht.TNone
2100

    
2101

    
2102
class OpNetworkQuery(OpCode):
2103
  """Compute the list of networks."""
2104
  OP_PARAMS = [
2105
    _POutputFields,
2106
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
2107
     "Empty list to query all groups, group names otherwise"),
2108
    ]
2109
  OP_RESULT = _TOldQueryResult
2110

    
2111

    
2112
def _GetOpList():
2113
  """Returns list of all defined opcodes.
2114

2115
  Does not eliminate duplicates by C{OP_ID}.
2116

2117
  """
2118
  return [v for v in globals().values()
2119
          if (isinstance(v, type) and issubclass(v, OpCode) and
2120
              hasattr(v, "OP_ID") and v is not OpCode)]
2121

    
2122

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