Statistics
| Branch: | Tag: | Revision:

root / lib / opcodes.py @ d634b4e0

History | View | Annotate | Download (67.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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 outils
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
#: Opportunistic locking
163
_POpportunisticLocking = \
164
  ("opportunistic_locking", False, ht.TBool,
165
   ("Whether to employ opportunistic locking for nodes, meaning nodes"
166
    " already locked by another opcode won't be considered for instance"
167
    " allocation (only when an iallocator is used)"))
168

    
169
_PIgnoreIpolicy = ("ignore_ipolicy", False, ht.TBool,
170
                   "Whether to ignore ipolicy violations")
171

    
172
# Allow runtime changes while migrating
173
_PAllowRuntimeChgs = ("allow_runtime_changes", True, ht.TBool,
174
                      "Allow runtime changes (eg. memory ballooning)")
175

    
176
#: IAllocator field builder
177
_PIAllocFromDesc = lambda desc: ("iallocator", None, ht.TMaybeString, desc)
178

    
179
#: a required network name
180
_PNetworkName = ("network_name", ht.NoDefault, ht.TNonEmptyString,
181
                 "Set network name")
182

    
183
_PTargetGroups = \
184
  ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString),
185
   "Destination group names or UUIDs (defaults to \"all but current group\")")
186

    
187
#: OP_ID conversion regular expression
188
_OPID_RE = re.compile("([a-z])([A-Z])")
189

    
190
#: Utility function for L{OpClusterSetParams}
191
_TestClusterOsListItem = \
192
  ht.TAnd(ht.TIsLength(2), ht.TItems([
193
    ht.TElemOf(constants.DDMS_VALUES),
194
    ht.TNonEmptyString,
195
    ]))
196

    
197
_TestClusterOsList = ht.TMaybeListOf(_TestClusterOsListItem)
198

    
199
# TODO: Generate check from constants.INIC_PARAMS_TYPES
200
#: Utility function for testing NIC definitions
201
_TestNicDef = \
202
  ht.Comment("NIC parameters")(ht.TDictOf(ht.TElemOf(constants.INIC_PARAMS),
203
                                          ht.TMaybeString))
204

    
205
_TSetParamsResultItemItems = [
206
  ht.Comment("name of changed parameter")(ht.TNonEmptyString),
207
  ht.Comment("new value")(ht.TAny),
208
  ]
209

    
210
_TSetParamsResult = \
211
  ht.TListOf(ht.TAnd(ht.TIsLength(len(_TSetParamsResultItemItems)),
212
                     ht.TItems(_TSetParamsResultItemItems)))
213

    
214
# In the disks option we can provide arbitrary parameters too, which
215
# we may not be able to validate at this level, so we just check the
216
# format of the dict here and the checks concerning IDISK_PARAMS will
217
# happen at the LU level
218
_TDiskParams = \
219
  ht.Comment("Disk parameters")(ht.TDictOf(ht.TNonEmptyString,
220
                                           ht.TOr(ht.TNonEmptyString, ht.TInt)))
221

    
222
_TQueryRow = \
223
  ht.TListOf(ht.TAnd(ht.TIsLength(2),
224
                     ht.TItems([ht.TElemOf(constants.RS_ALL),
225
                                ht.TAny])))
226

    
227
_TQueryResult = ht.TListOf(_TQueryRow)
228

    
229
_TOldQueryRow = ht.TListOf(ht.TAny)
230

    
231
_TOldQueryResult = ht.TListOf(_TOldQueryRow)
232

    
233

    
234
_SUMMARY_PREFIX = {
235
  "CLUSTER_": "C_",
236
  "GROUP_": "G_",
237
  "NODE_": "N_",
238
  "INSTANCE_": "I_",
239
  }
240

    
241
#: Attribute name for dependencies
242
DEPEND_ATTR = "depends"
243

    
244
#: Attribute name for comment
245
COMMENT_ATTR = "comment"
246

    
247

    
248
def _NameComponents(name):
249
  """Split an opcode class name into its components
250

251
  @type name: string
252
  @param name: the class name, as OpXxxYyy
253
  @rtype: array of strings
254
  @return: the components of the name
255

256
  """
257
  assert name.startswith("Op")
258
  # Note: (?<=[a-z])(?=[A-Z]) would be ideal, since it wouldn't
259
  # consume any input, and hence we would just have all the elements
260
  # in the list, one by one; but it seems that split doesn't work on
261
  # non-consuming input, hence we have to process the input string a
262
  # bit
263
  name = _OPID_RE.sub(r"\1,\2", name)
264
  elems = name.split(",")
265
  return elems
266

    
267

    
268
def _NameToId(name):
269
  """Convert an opcode class name to an OP_ID.
270

271
  @type name: string
272
  @param name: the class name, as OpXxxYyy
273
  @rtype: string
274
  @return: the name in the OP_XXXX_YYYY format
275

276
  """
277
  if not name.startswith("Op"):
278
    return None
279
  return "_".join(n.upper() for n in _NameComponents(name))
280

    
281

    
282
def NameToReasonSrc(name):
283
  """Convert an opcode class name to a source string for the reason trail
284

285
  @type name: string
286
  @param name: the class name, as OpXxxYyy
287
  @rtype: string
288
  @return: the name in the OP_XXXX_YYYY format
289

290
  """
291
  if not name.startswith("Op"):
292
    return None
293
  return "%s:%s" % (constants.OPCODE_REASON_SRC_OPCODE,
294
                    "_".join(n.lower() for n in _NameComponents(name)))
295

    
296

    
297
def _GenerateObjectTypeCheck(obj, fields_types):
298
  """Helper to generate type checks for objects.
299

300
  @param obj: The object to generate type checks
301
  @param fields_types: The fields and their types as a dict
302
  @return: A ht type check function
303

304
  """
305
  assert set(obj.GetAllSlots()) == set(fields_types.keys()), \
306
    "%s != %s" % (set(obj.GetAllSlots()), set(fields_types.keys()))
307
  return ht.TStrictDict(True, True, fields_types)
308

    
309

    
310
_TQueryFieldDef = \
311
  _GenerateObjectTypeCheck(objects.QueryFieldDefinition, {
312
    "name": ht.TNonEmptyString,
313
    "title": ht.TNonEmptyString,
314
    "kind": ht.TElemOf(constants.QFT_ALL),
315
    "doc": ht.TNonEmptyString,
316
    })
317

    
318

    
319
def RequireFileStorage():
320
  """Checks that file storage is enabled.
321

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

325
  @raise errors.OpPrereqError: when file storage is disabled
326

327
  """
328
  if not constants.ENABLE_FILE_STORAGE:
329
    raise errors.OpPrereqError("File storage disabled at configure time",
330
                               errors.ECODE_INVAL)
331

    
332

    
333
def RequireSharedFileStorage():
334
  """Checks that shared file storage is enabled.
335

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

339
  @raise errors.OpPrereqError: when shared file storage is disabled
340

341
  """
342
  if not constants.ENABLE_SHARED_FILE_STORAGE:
343
    raise errors.OpPrereqError("Shared file storage disabled at"
344
                               " configure time", errors.ECODE_INVAL)
345

    
346

    
347
@ht.WithDesc("CheckFileStorage")
348
def _CheckFileStorage(value):
349
  """Ensures file storage is enabled if used.
350

351
  """
352
  if value == constants.DT_FILE:
353
    RequireFileStorage()
354
  elif value == constants.DT_SHARED_FILE:
355
    RequireSharedFileStorage()
356
  return True
357

    
358

    
359
def _BuildDiskTemplateCheck(accept_none):
360
  """Builds check for disk template.
361

362
  @type accept_none: bool
363
  @param accept_none: whether to accept None as a correct value
364
  @rtype: callable
365

366
  """
367
  template_check = ht.TElemOf(constants.DISK_TEMPLATES)
368

    
369
  if accept_none:
370
    template_check = ht.TMaybe(template_check)
371

    
372
  return ht.TAnd(template_check, _CheckFileStorage)
373

    
374

    
375
def _CheckStorageType(storage_type):
376
  """Ensure a given storage type is valid.
377

378
  """
379
  if storage_type not in constants.VALID_STORAGE_TYPES:
380
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
381
                               errors.ECODE_INVAL)
382
  if storage_type == constants.ST_FILE:
383
    # TODO: What about shared file storage?
384
    RequireFileStorage()
385
  return True
386

    
387

    
388
#: Storage type parameter
389
_PStorageType = ("storage_type", ht.NoDefault, _CheckStorageType,
390
                 "Storage type")
391

    
392

    
393
@ht.WithDesc("IPv4 network")
394
def _CheckCIDRNetNotation(value):
395
  """Ensure a given CIDR notation type is valid.
396

397
  """
398
  try:
399
    ipaddr.IPv4Network(value)
400
  except ipaddr.AddressValueError:
401
    return False
402
  return True
403

    
404

    
405
@ht.WithDesc("IPv4 address")
406
def _CheckCIDRAddrNotation(value):
407
  """Ensure a given CIDR notation type is valid.
408

409
  """
410
  try:
411
    ipaddr.IPv4Address(value)
412
  except ipaddr.AddressValueError:
413
    return False
414
  return True
415

    
416

    
417
@ht.WithDesc("IPv6 address")
418
def _CheckCIDR6AddrNotation(value):
419
  """Ensure a given CIDR notation type is valid.
420

421
  """
422
  try:
423
    ipaddr.IPv6Address(value)
424
  except ipaddr.AddressValueError:
425
    return False
426
  return True
427

    
428

    
429
@ht.WithDesc("IPv6 network")
430
def _CheckCIDR6NetNotation(value):
431
  """Ensure a given CIDR notation type is valid.
432

433
  """
434
  try:
435
    ipaddr.IPv6Network(value)
436
  except ipaddr.AddressValueError:
437
    return False
438
  return True
439

    
440

    
441
_TIpAddress4 = ht.TAnd(ht.TString, _CheckCIDRAddrNotation)
442
_TIpAddress6 = ht.TAnd(ht.TString, _CheckCIDR6AddrNotation)
443
_TIpNetwork4 = ht.TAnd(ht.TString, _CheckCIDRNetNotation)
444
_TIpNetwork6 = ht.TAnd(ht.TString, _CheckCIDR6NetNotation)
445
_TMaybeAddr4List = ht.TMaybe(ht.TListOf(_TIpAddress4))
446

    
447

    
448
class _AutoOpParamSlots(outils.AutoSlots):
449
  """Meta class for opcode definitions.
450

451
  """
452
  def __new__(mcs, name, bases, attrs):
453
    """Called when a class should be created.
454

455
    @param mcs: The meta class
456
    @param name: Name of created class
457
    @param bases: Base classes
458
    @type attrs: dict
459
    @param attrs: Class attributes
460

461
    """
462
    assert "OP_ID" not in attrs, "Class '%s' defining OP_ID" % name
463

    
464
    slots = mcs._GetSlots(attrs)
465
    assert "OP_DSC_FIELD" not in attrs or attrs["OP_DSC_FIELD"] in slots, \
466
      "Class '%s' uses unknown field in OP_DSC_FIELD" % name
467
    assert ("OP_DSC_FORMATTER" not in attrs or
468
            callable(attrs["OP_DSC_FORMATTER"])), \
469
      ("Class '%s' uses non-callable in OP_DSC_FORMATTER (%s)" %
470
       (name, type(attrs["OP_DSC_FORMATTER"])))
471

    
472
    attrs["OP_ID"] = _NameToId(name)
473

    
474
    return outils.AutoSlots.__new__(mcs, name, bases, attrs)
475

    
476
  @classmethod
477
  def _GetSlots(mcs, attrs):
478
    """Build the slots out of OP_PARAMS.
479

480
    """
481
    # Always set OP_PARAMS to avoid duplicates in BaseOpCode.GetAllParams
482
    params = attrs.setdefault("OP_PARAMS", [])
483

    
484
    # Use parameter names as slots
485
    return [pname for (pname, _, _, _) in params]
486

    
487

    
488
class BaseOpCode(outils.ValidatedSlots):
489
  """A simple serializable object.
490

491
  This object serves as a parent class for OpCode without any custom
492
  field handling.
493

494
  """
495
  # pylint: disable=E1101
496
  # as OP_ID is dynamically defined
497
  __metaclass__ = _AutoOpParamSlots
498

    
499
  def __getstate__(self):
500
    """Generic serializer.
501

502
    This method just returns the contents of the instance as a
503
    dictionary.
504

505
    @rtype:  C{dict}
506
    @return: the instance attributes and their values
507

508
    """
509
    state = {}
510
    for name in self.GetAllSlots():
511
      if hasattr(self, name):
512
        state[name] = getattr(self, name)
513
    return state
514

    
515
  def __setstate__(self, state):
516
    """Generic unserializer.
517

518
    This method just restores from the serialized state the attributes
519
    of the current instance.
520

521
    @param state: the serialized opcode data
522
    @type state:  C{dict}
523

524
    """
525
    if not isinstance(state, dict):
526
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
527
                       type(state))
528

    
529
    for name in self.GetAllSlots():
530
      if name not in state and hasattr(self, name):
531
        delattr(self, name)
532

    
533
    for name in state:
534
      setattr(self, name, state[name])
535

    
536
  @classmethod
537
  def GetAllParams(cls):
538
    """Compute list of all parameters for an opcode.
539

540
    """
541
    slots = []
542
    for parent in cls.__mro__:
543
      slots.extend(getattr(parent, "OP_PARAMS", []))
544
    return slots
545

    
546
  def Validate(self, set_defaults): # pylint: disable=W0221
547
    """Validate opcode parameters, optionally setting default values.
548

549
    @type set_defaults: bool
550
    @param set_defaults: Whether to set default values
551
    @raise errors.OpPrereqError: When a parameter value doesn't match
552
                                 requirements
553

554
    """
555
    for (attr_name, default, test, _) in self.GetAllParams():
556
      assert test == ht.NoType or callable(test)
557

    
558
      if not hasattr(self, attr_name):
559
        if default == ht.NoDefault:
560
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
561
                                     (self.OP_ID, attr_name),
562
                                     errors.ECODE_INVAL)
563
        elif set_defaults:
564
          if callable(default):
565
            dval = default()
566
          else:
567
            dval = default
568
          setattr(self, attr_name, dval)
569

    
570
      if test == ht.NoType:
571
        # no tests here
572
        continue
573

    
574
      if set_defaults or hasattr(self, attr_name):
575
        attr_val = getattr(self, attr_name)
576
        if not test(attr_val):
577
          logging.error("OpCode %s, parameter %s, has invalid type %s/value"
578
                        " '%s' expecting type %s",
579
                        self.OP_ID, attr_name, type(attr_val), attr_val, test)
580
          raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
581
                                     (self.OP_ID, attr_name),
582
                                     errors.ECODE_INVAL)
583

    
584

    
585
def _BuildJobDepCheck(relative):
586
  """Builds check for job dependencies (L{DEPEND_ATTR}).
587

588
  @type relative: bool
589
  @param relative: Whether to accept relative job IDs (negative)
590
  @rtype: callable
591

592
  """
593
  if relative:
594
    job_id = ht.TOr(ht.TJobId, ht.TRelativeJobId)
595
  else:
596
    job_id = ht.TJobId
597

    
598
  job_dep = \
599
    ht.TAnd(ht.TOr(ht.TList, ht.TTuple),
600
            ht.TIsLength(2),
601
            ht.TItems([job_id,
602
                       ht.TListOf(ht.TElemOf(constants.JOBS_FINALIZED))]))
603

    
604
  return ht.TMaybeListOf(job_dep)
605

    
606

    
607
TNoRelativeJobDependencies = _BuildJobDepCheck(False)
608

    
609
#: List of submission status and job ID as returned by C{SubmitManyJobs}
610
_TJobIdListItem = \
611
  ht.TAnd(ht.TIsLength(2),
612
          ht.TItems([ht.Comment("success")(ht.TBool),
613
                     ht.Comment("Job ID if successful, error message"
614
                                " otherwise")(ht.TOr(ht.TString,
615
                                                     ht.TJobId))]))
616
TJobIdList = ht.TListOf(_TJobIdListItem)
617

    
618
#: Result containing only list of submitted jobs
619
TJobIdListOnly = ht.TStrictDict(True, True, {
620
  constants.JOB_IDS_KEY: ht.Comment("List of submitted jobs")(TJobIdList),
621
  })
622

    
623

    
624
class OpCode(BaseOpCode):
625
  """Abstract OpCode.
626

627
  This is the root of the actual OpCode hierarchy. All clases derived
628
  from this class should override OP_ID.
629

630
  @cvar OP_ID: The ID of this opcode. This should be unique amongst all
631
               children of this class.
632
  @cvar OP_DSC_FIELD: The name of a field whose value will be included in the
633
                      string returned by Summary(); see the docstring of that
634
                      method for details).
635
  @cvar OP_DSC_FORMATTER: A callable that should format the OP_DSC_FIELD; if
636
                          not present, then the field will be simply converted
637
                          to string
638
  @cvar OP_PARAMS: List of opcode attributes, the default values they should
639
                   get if not already defined, and types they must match.
640
  @cvar OP_RESULT: Callable to verify opcode result
641
  @cvar WITH_LU: Boolean that specifies whether this should be included in
642
      mcpu's dispatch table
643
  @ivar dry_run: Whether the LU should be run in dry-run mode, i.e. just
644
                 the check steps
645
  @ivar priority: Opcode priority for queue
646

647
  """
648
  # pylint: disable=E1101
649
  # as OP_ID is dynamically defined
650
  WITH_LU = True
651
  OP_PARAMS = [
652
    ("dry_run", None, ht.TMaybeBool, "Run checks only, don't execute"),
653
    ("debug_level", None, ht.TMaybe(ht.TNonNegativeInt), "Debug level"),
654
    ("priority", constants.OP_PRIO_DEFAULT,
655
     ht.TElemOf(constants.OP_PRIO_SUBMIT_VALID), "Opcode priority"),
656
    (DEPEND_ATTR, None, _BuildJobDepCheck(True),
657
     "Job dependencies; if used through ``SubmitManyJobs`` relative (negative)"
658
     " job IDs can be used; see :doc:`design document <design-chained-jobs>`"
659
     " for details"),
660
    (COMMENT_ATTR, None, ht.TMaybeString,
661
     "Comment describing the purpose of the opcode"),
662
    ]
663
  OP_RESULT = None
664

    
665
  def __getstate__(self):
666
    """Specialized getstate for opcodes.
667

668
    This method adds to the state dictionary the OP_ID of the class,
669
    so that on unload we can identify the correct class for
670
    instantiating the opcode.
671

672
    @rtype:   C{dict}
673
    @return:  the state as a dictionary
674

675
    """
676
    data = BaseOpCode.__getstate__(self)
677
    data["OP_ID"] = self.OP_ID
678
    return data
679

    
680
  @classmethod
681
  def LoadOpCode(cls, data):
682
    """Generic load opcode method.
683

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

688
    @type data:  C{dict}
689
    @param data: the serialized opcode
690

691
    """
692
    if not isinstance(data, dict):
693
      raise ValueError("Invalid data to LoadOpCode (%s)" % type(data))
694
    if "OP_ID" not in data:
695
      raise ValueError("Invalid data to LoadOpcode, missing OP_ID")
696
    op_id = data["OP_ID"]
697
    op_class = None
698
    if op_id in OP_MAPPING:
699
      op_class = OP_MAPPING[op_id]
700
    else:
701
      raise ValueError("Invalid data to LoadOpCode: OP_ID %s unsupported" %
702
                       op_id)
703
    op = op_class()
704
    new_data = data.copy()
705
    del new_data["OP_ID"]
706
    op.__setstate__(new_data)
707
    return op
708

    
709
  def Summary(self):
710
    """Generates a summary description of this opcode.
711

712
    The summary is the value of the OP_ID attribute (without the "OP_"
713
    prefix), plus the value of the OP_DSC_FIELD attribute, if one was
714
    defined; this field should allow to easily identify the operation
715
    (for an instance creation job, e.g., it would be the instance
716
    name).
717

718
    """
719
    assert self.OP_ID is not None and len(self.OP_ID) > 3
720
    # all OP_ID start with OP_, we remove that
721
    txt = self.OP_ID[3:]
722
    field_name = getattr(self, "OP_DSC_FIELD", None)
723
    if field_name:
724
      field_value = getattr(self, field_name, None)
725
      field_formatter = getattr(self, "OP_DSC_FORMATTER", None)
726
      if callable(field_formatter):
727
        field_value = field_formatter(field_value)
728
      elif isinstance(field_value, (list, tuple)):
729
        field_value = ",".join(str(i) for i in field_value)
730
      txt = "%s(%s)" % (txt, field_value)
731
    return txt
732

    
733
  def TinySummary(self):
734
    """Generates a compact summary description of the opcode.
735

736
    """
737
    assert self.OP_ID.startswith("OP_")
738

    
739
    text = self.OP_ID[3:]
740

    
741
    for (prefix, supplement) in _SUMMARY_PREFIX.items():
742
      if text.startswith(prefix):
743
        return supplement + text[len(prefix):]
744

    
745
    return text
746

    
747

    
748
# cluster opcodes
749

    
750
class OpClusterPostInit(OpCode):
751
  """Post cluster initialization.
752

753
  This opcode does not touch the cluster at all. Its purpose is to run hooks
754
  after the cluster has been initialized.
755

756
  """
757
  OP_RESULT = ht.TBool
758

    
759

    
760
class OpClusterDestroy(OpCode):
761
  """Destroy the cluster.
762

763
  This opcode has no other parameters. All the state is irreversibly
764
  lost after the execution of this opcode.
765

766
  """
767
  OP_RESULT = ht.TNonEmptyString
768

    
769

    
770
class OpClusterQuery(OpCode):
771
  """Query cluster information."""
772
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TAny)
773

    
774

    
775
class OpClusterVerify(OpCode):
776
  """Submits all jobs necessary to verify the cluster.
777

778
  """
779
  OP_PARAMS = [
780
    _PDebugSimulateErrors,
781
    _PErrorCodes,
782
    _PSkipChecks,
783
    _PIgnoreErrors,
784
    _PVerbose,
785
    ("group_name", None, ht.TMaybeString, "Group to verify"),
786
    ]
787
  OP_RESULT = TJobIdListOnly
788

    
789

    
790
class OpClusterVerifyConfig(OpCode):
791
  """Verify the cluster config.
792

793
  """
794
  OP_PARAMS = [
795
    _PDebugSimulateErrors,
796
    _PErrorCodes,
797
    _PIgnoreErrors,
798
    _PVerbose,
799
    ]
800
  OP_RESULT = ht.TBool
801

    
802

    
803
class OpClusterVerifyGroup(OpCode):
804
  """Run verify on a node group from the cluster.
805

806
  @type skip_checks: C{list}
807
  @ivar skip_checks: steps to be skipped from the verify process; this
808
                     needs to be a subset of
809
                     L{constants.VERIFY_OPTIONAL_CHECKS}; currently
810
                     only L{constants.VERIFY_NPLUSONE_MEM} can be passed
811

812
  """
813
  OP_DSC_FIELD = "group_name"
814
  OP_PARAMS = [
815
    _PGroupName,
816
    _PDebugSimulateErrors,
817
    _PErrorCodes,
818
    _PSkipChecks,
819
    _PIgnoreErrors,
820
    _PVerbose,
821
    ]
822
  OP_RESULT = ht.TBool
823

    
824

    
825
class OpClusterVerifyDisks(OpCode):
826
  """Verify the cluster disks.
827

828
  """
829
  OP_RESULT = TJobIdListOnly
830

    
831

    
832
class OpGroupVerifyDisks(OpCode):
833
  """Verifies the status of all disks in a node group.
834

835
  Result: a tuple of three elements:
836
    - dict of node names with issues (values: error msg)
837
    - list of instances with degraded disks (that should be activated)
838
    - dict of instances with missing logical volumes (values: (node, vol)
839
      pairs with details about the missing volumes)
840

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

846
  Note that only instances that are drbd-based are taken into
847
  consideration. This might need to be revisited in the future.
848

849
  """
850
  OP_DSC_FIELD = "group_name"
851
  OP_PARAMS = [
852
    _PGroupName,
853
    ]
854
  OP_RESULT = \
855
    ht.TAnd(ht.TIsLength(3),
856
            ht.TItems([ht.TDictOf(ht.TString, ht.TString),
857
                       ht.TListOf(ht.TString),
858
                       ht.TDictOf(ht.TString,
859
                                  ht.TListOf(ht.TListOf(ht.TString)))]))
860

    
861

    
862
class OpClusterRepairDiskSizes(OpCode):
863
  """Verify the disk sizes of the instances and fixes configuration
864
  mimatches.
865

866
  Parameters: optional instances list, in case we want to restrict the
867
  checks to only a subset of the instances.
868

869
  Result: a list of tuples, (instance, disk, new-size) for changed
870
  configurations.
871

872
  In normal operation, the list should be empty.
873

874
  @type instances: list
875
  @ivar instances: the list of instances to check, or empty for all instances
876

877
  """
878
  OP_PARAMS = [
879
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
880
    ]
881
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
882
                                 ht.TItems([ht.TNonEmptyString,
883
                                            ht.TNonNegativeInt,
884
                                            ht.TNonNegativeInt])))
885

    
886

    
887
class OpClusterConfigQuery(OpCode):
888
  """Query cluster configuration values."""
889
  OP_PARAMS = [
890
    _POutputFields,
891
    ]
892
  OP_RESULT = ht.TListOf(ht.TAny)
893

    
894

    
895
class OpClusterRename(OpCode):
896
  """Rename the cluster.
897

898
  @type name: C{str}
899
  @ivar name: The new name of the cluster. The name and/or the master IP
900
              address will be changed to match the new name and its IP
901
              address.
902

903
  """
904
  OP_DSC_FIELD = "name"
905
  OP_PARAMS = [
906
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
907
    ]
908
  OP_RESULT = ht.TNonEmptyString
909

    
910

    
911
class OpClusterSetParams(OpCode):
912
  """Change the parameters of the cluster.
913

914
  @type vg_name: C{str} or C{None}
915
  @ivar vg_name: The new volume group name or None to disable LVM usage.
916

917
  """
918
  OP_PARAMS = [
919
    _PHvState,
920
    _PDiskState,
921
    ("vg_name", None, ht.TMaybe(ht.TString), "Volume group name"),
922
    ("enabled_hypervisors", None,
923
     ht.TMaybe(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)),
924
                       ht.TTrue)),
925
     "List of enabled hypervisors"),
926
    ("hvparams", None,
927
     ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
928
     "Cluster-wide hypervisor parameter defaults, hypervisor-dependent"),
929
    ("beparams", None, ht.TMaybeDict,
930
     "Cluster-wide backend parameter defaults"),
931
    ("os_hvp", None, ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
932
     "Cluster-wide per-OS hypervisor parameter defaults"),
933
    ("osparams", None,
934
     ht.TMaybe(ht.TDictOf(ht.TNonEmptyString, ht.TDict)),
935
     "Cluster-wide OS parameter defaults"),
936
    _PDiskParams,
937
    ("candidate_pool_size", None, ht.TMaybe(ht.TPositiveInt),
938
     "Master candidate pool size"),
939
    ("uid_pool", None, ht.NoType,
940
     "Set UID pool, must be list of lists describing UID ranges (two items,"
941
     " start and end inclusive)"),
942
    ("add_uids", None, ht.NoType,
943
     "Extend UID pool, must be list of lists describing UID ranges (two"
944
     " items, start and end inclusive) to be added"),
945
    ("remove_uids", None, ht.NoType,
946
     "Shrink UID pool, must be list of lists describing UID ranges (two"
947
     " items, start and end inclusive) to be removed"),
948
    ("maintain_node_health", None, ht.TMaybeBool,
949
     "Whether to automatically maintain node health"),
950
    ("prealloc_wipe_disks", None, ht.TMaybeBool,
951
     "Whether to wipe disks before allocating them to instances"),
952
    ("nicparams", None, ht.TMaybeDict, "Cluster-wide NIC parameter defaults"),
953
    ("ndparams", None, ht.TMaybeDict, "Cluster-wide node parameter defaults"),
954
    ("ipolicy", None, ht.TMaybeDict,
955
     "Cluster-wide :ref:`instance policy <rapi-ipolicy>` specs"),
956
    ("drbd_helper", None, ht.TMaybe(ht.TString), "DRBD helper program"),
957
    ("default_iallocator", None, ht.TMaybe(ht.TString),
958
     "Default iallocator for cluster"),
959
    ("master_netdev", None, ht.TMaybe(ht.TString),
960
     "Master network device"),
961
    ("master_netmask", None, ht.TMaybe(ht.TNonNegativeInt),
962
     "Netmask of the master IP"),
963
    ("reserved_lvs", None, ht.TMaybeListOf(ht.TNonEmptyString),
964
     "List of reserved LVs"),
965
    ("hidden_os", None, _TestClusterOsList,
966
     "Modify list of hidden operating systems: each modification must have"
967
     " two items, the operation and the OS name; the operation can be"
968
     " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
969
    ("blacklisted_os", None, _TestClusterOsList,
970
     "Modify list of blacklisted operating systems: each modification must"
971
     " have two items, the operation and the OS name; the operation can be"
972
     " ``%s`` or ``%s``" % (constants.DDM_ADD, constants.DDM_REMOVE)),
973
    ("use_external_mip_script", None, ht.TMaybeBool,
974
     "Whether to use an external master IP address setup script"),
975
    ("enabled_disk_templates", None,
976
     ht.TMaybe(ht.TAnd(ht.TListOf(ht.TElemOf(constants.DISK_TEMPLATES)),
977
                       ht.TTrue)),
978
     "List of enabled disk templates"),
979
    ]
980
  OP_RESULT = ht.TNone
981

    
982

    
983
class OpClusterRedistConf(OpCode):
984
  """Force a full push of the cluster configuration.
985

986
  """
987
  OP_RESULT = ht.TNone
988

    
989

    
990
class OpClusterActivateMasterIp(OpCode):
991
  """Activate the master IP on the master node.
992

993
  """
994
  OP_RESULT = ht.TNone
995

    
996

    
997
class OpClusterDeactivateMasterIp(OpCode):
998
  """Deactivate the master IP on the master node.
999

1000
  """
1001
  OP_RESULT = ht.TNone
1002

    
1003

    
1004
class OpQuery(OpCode):
1005
  """Query for resources/items.
1006

1007
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
1008
  @ivar fields: List of fields to retrieve
1009
  @ivar qfilter: Query filter
1010

1011
  """
1012
  OP_DSC_FIELD = "what"
1013
  OP_PARAMS = [
1014
    _PQueryWhat,
1015
    _PUseLocking,
1016
    ("fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1017
     "Requested fields"),
1018
    ("qfilter", None, ht.TMaybe(ht.TList),
1019
     "Query filter"),
1020
    ]
1021
  OP_RESULT = \
1022
    _GenerateObjectTypeCheck(objects.QueryResponse, {
1023
      "fields": ht.TListOf(_TQueryFieldDef),
1024
      "data": _TQueryResult,
1025
      })
1026

    
1027

    
1028
class OpQueryFields(OpCode):
1029
  """Query for available resource/item fields.
1030

1031
  @ivar what: Resources to query for, must be one of L{constants.QR_VIA_OP}
1032
  @ivar fields: List of fields to retrieve
1033

1034
  """
1035
  OP_DSC_FIELD = "what"
1036
  OP_PARAMS = [
1037
    _PQueryWhat,
1038
    ("fields", None, ht.TMaybeListOf(ht.TNonEmptyString),
1039
     "Requested fields; if not given, all are returned"),
1040
    ]
1041
  OP_RESULT = \
1042
    _GenerateObjectTypeCheck(objects.QueryFieldsResponse, {
1043
      "fields": ht.TListOf(_TQueryFieldDef),
1044
      })
1045

    
1046

    
1047
class OpOobCommand(OpCode):
1048
  """Interact with OOB."""
1049
  OP_PARAMS = [
1050
    ("node_names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1051
     "List of nodes to run the OOB command against"),
1052
    ("command", ht.NoDefault, ht.TElemOf(constants.OOB_COMMANDS),
1053
     "OOB command to be run"),
1054
    ("timeout", constants.OOB_TIMEOUT, ht.TInt,
1055
     "Timeout before the OOB helper will be terminated"),
1056
    ("ignore_status", False, ht.TBool,
1057
     "Ignores the node offline status for power off"),
1058
    ("power_delay", constants.OOB_POWER_DELAY, ht.TNonNegativeFloat,
1059
     "Time in seconds to wait between powering on nodes"),
1060
    ]
1061
  # Fixme: Make it more specific with all the special cases in LUOobCommand
1062
  OP_RESULT = _TQueryResult
1063

    
1064

    
1065
class OpRestrictedCommand(OpCode):
1066
  """Runs a restricted command on node(s).
1067

1068
  """
1069
  OP_PARAMS = [
1070
    _PUseLocking,
1071
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1072
     "Nodes on which the command should be run (at least one)"),
1073
    ("command", ht.NoDefault, ht.TNonEmptyString,
1074
     "Command name (no parameters)"),
1075
    ]
1076

    
1077
  _RESULT_ITEMS = [
1078
    ht.Comment("success")(ht.TBool),
1079
    ht.Comment("output or error message")(ht.TString),
1080
    ]
1081

    
1082
  OP_RESULT = \
1083
    ht.TListOf(ht.TAnd(ht.TIsLength(len(_RESULT_ITEMS)),
1084
                       ht.TItems(_RESULT_ITEMS)))
1085

    
1086

    
1087
# node opcodes
1088

    
1089
class OpNodeRemove(OpCode):
1090
  """Remove a node.
1091

1092
  @type node_name: C{str}
1093
  @ivar node_name: The name of the node to remove. If the node still has
1094
                   instances on it, the operation will fail.
1095

1096
  """
1097
  OP_DSC_FIELD = "node_name"
1098
  OP_PARAMS = [
1099
    _PNodeName,
1100
    ]
1101
  OP_RESULT = ht.TNone
1102

    
1103

    
1104
class OpNodeAdd(OpCode):
1105
  """Add a node to the cluster.
1106

1107
  @type node_name: C{str}
1108
  @ivar node_name: The name of the node to add. This can be a short name,
1109
                   but it will be expanded to the FQDN.
1110
  @type primary_ip: IP address
1111
  @ivar primary_ip: The primary IP of the node. This will be ignored when the
1112
                    opcode is submitted, but will be filled during the node
1113
                    add (so it will be visible in the job query).
1114
  @type secondary_ip: IP address
1115
  @ivar secondary_ip: The secondary IP of the node. This needs to be passed
1116
                      if the cluster has been initialized in 'dual-network'
1117
                      mode, otherwise it must not be given.
1118
  @type readd: C{bool}
1119
  @ivar readd: Whether to re-add an existing node to the cluster. If
1120
               this is not passed, then the operation will abort if the node
1121
               name is already in the cluster; use this parameter to 'repair'
1122
               a node that had its configuration broken, or was reinstalled
1123
               without removal from the cluster.
1124
  @type group: C{str}
1125
  @ivar group: The node group to which this node will belong.
1126
  @type vm_capable: C{bool}
1127
  @ivar vm_capable: The vm_capable node attribute
1128
  @type master_capable: C{bool}
1129
  @ivar master_capable: The master_capable node attribute
1130

1131
  """
1132
  OP_DSC_FIELD = "node_name"
1133
  OP_PARAMS = [
1134
    _PNodeName,
1135
    _PHvState,
1136
    _PDiskState,
1137
    ("primary_ip", None, ht.NoType, "Primary IP address"),
1138
    ("secondary_ip", None, ht.TMaybeString, "Secondary IP address"),
1139
    ("readd", False, ht.TBool, "Whether node is re-added to cluster"),
1140
    ("group", None, ht.TMaybeString, "Initial node group"),
1141
    ("master_capable", None, ht.TMaybeBool,
1142
     "Whether node can become master or master candidate"),
1143
    ("vm_capable", None, ht.TMaybeBool,
1144
     "Whether node can host instances"),
1145
    ("ndparams", None, ht.TMaybeDict, "Node parameters"),
1146
    ]
1147
  OP_RESULT = ht.TNone
1148

    
1149

    
1150
class OpNodeQuery(OpCode):
1151
  """Compute the list of nodes."""
1152
  OP_PARAMS = [
1153
    _POutputFields,
1154
    _PUseLocking,
1155
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1156
     "Empty list to query all nodes, node names otherwise"),
1157
    ]
1158
  OP_RESULT = _TOldQueryResult
1159

    
1160

    
1161
class OpNodeQueryvols(OpCode):
1162
  """Get list of volumes on node."""
1163
  OP_PARAMS = [
1164
    _POutputFields,
1165
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1166
     "Empty list to query all nodes, node names otherwise"),
1167
    ]
1168
  OP_RESULT = ht.TListOf(ht.TAny)
1169

    
1170

    
1171
class OpNodeQueryStorage(OpCode):
1172
  """Get information on storage for node(s)."""
1173
  OP_PARAMS = [
1174
    _POutputFields,
1175
    _PStorageType,
1176
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "List of nodes"),
1177
    ("name", None, ht.TMaybeString, "Storage name"),
1178
    ]
1179
  OP_RESULT = _TOldQueryResult
1180

    
1181

    
1182
class OpNodeModifyStorage(OpCode):
1183
  """Modifies the properies of a storage unit"""
1184
  OP_DSC_FIELD = "node_name"
1185
  OP_PARAMS = [
1186
    _PNodeName,
1187
    _PStorageType,
1188
    _PStorageName,
1189
    ("changes", ht.NoDefault, ht.TDict, "Requested changes"),
1190
    ]
1191
  OP_RESULT = ht.TNone
1192

    
1193

    
1194
class OpRepairNodeStorage(OpCode):
1195
  """Repairs the volume group on a node."""
1196
  OP_DSC_FIELD = "node_name"
1197
  OP_PARAMS = [
1198
    _PNodeName,
1199
    _PStorageType,
1200
    _PStorageName,
1201
    _PIgnoreConsistency,
1202
    ]
1203
  OP_RESULT = ht.TNone
1204

    
1205

    
1206
class OpNodeSetParams(OpCode):
1207
  """Change the parameters of a node."""
1208
  OP_DSC_FIELD = "node_name"
1209
  OP_PARAMS = [
1210
    _PNodeName,
1211
    _PForce,
1212
    _PHvState,
1213
    _PDiskState,
1214
    ("master_candidate", None, ht.TMaybeBool,
1215
     "Whether the node should become a master candidate"),
1216
    ("offline", None, ht.TMaybeBool,
1217
     "Whether the node should be marked as offline"),
1218
    ("drained", None, ht.TMaybeBool,
1219
     "Whether the node should be marked as drained"),
1220
    ("auto_promote", False, ht.TBool,
1221
     "Whether node(s) should be promoted to master candidate if necessary"),
1222
    ("master_capable", None, ht.TMaybeBool,
1223
     "Denote whether node can become master or master candidate"),
1224
    ("vm_capable", None, ht.TMaybeBool,
1225
     "Denote whether node can host instances"),
1226
    ("secondary_ip", None, ht.TMaybeString,
1227
     "Change node's secondary IP address"),
1228
    ("ndparams", None, ht.TMaybeDict, "Set node parameters"),
1229
    ("powered", None, ht.TMaybeBool,
1230
     "Whether the node should be marked as powered"),
1231
    ]
1232
  OP_RESULT = _TSetParamsResult
1233

    
1234

    
1235
class OpNodePowercycle(OpCode):
1236
  """Tries to powercycle a node."""
1237
  OP_DSC_FIELD = "node_name"
1238
  OP_PARAMS = [
1239
    _PNodeName,
1240
    _PForce,
1241
    ]
1242
  OP_RESULT = ht.TMaybeString
1243

    
1244

    
1245
class OpNodeMigrate(OpCode):
1246
  """Migrate all instances from a node."""
1247
  OP_DSC_FIELD = "node_name"
1248
  OP_PARAMS = [
1249
    _PNodeName,
1250
    _PMigrationMode,
1251
    _PMigrationLive,
1252
    _PMigrationTargetNode,
1253
    _PAllowRuntimeChgs,
1254
    _PIgnoreIpolicy,
1255
    _PIAllocFromDesc("Iallocator for deciding the target node"
1256
                     " for shared-storage instances"),
1257
    ]
1258
  OP_RESULT = TJobIdListOnly
1259

    
1260

    
1261
class OpNodeEvacuate(OpCode):
1262
  """Evacuate instances off a number of nodes."""
1263
  OP_DSC_FIELD = "node_name"
1264
  OP_PARAMS = [
1265
    _PEarlyRelease,
1266
    _PNodeName,
1267
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1268
    _PIAllocFromDesc("Iallocator for computing solution"),
1269
    ("mode", ht.NoDefault, ht.TElemOf(constants.NODE_EVAC_MODES),
1270
     "Node evacuation mode"),
1271
    ]
1272
  OP_RESULT = TJobIdListOnly
1273

    
1274

    
1275
# instance opcodes
1276

    
1277
class OpInstanceCreate(OpCode):
1278
  """Create an instance.
1279

1280
  @ivar instance_name: Instance name
1281
  @ivar mode: Instance creation mode (one of L{constants.INSTANCE_CREATE_MODES})
1282
  @ivar source_handshake: Signed handshake from source (remote import only)
1283
  @ivar source_x509_ca: Source X509 CA in PEM format (remote import only)
1284
  @ivar source_instance_name: Previous name of instance (remote import only)
1285
  @ivar source_shutdown_timeout: Shutdown timeout used for source instance
1286
    (remote import only)
1287

1288
  """
1289
  OP_DSC_FIELD = "instance_name"
1290
  OP_PARAMS = [
1291
    _PInstanceName,
1292
    _PForceVariant,
1293
    _PWaitForSync,
1294
    _PNameCheck,
1295
    _PIgnoreIpolicy,
1296
    _POpportunisticLocking,
1297
    ("beparams", ht.EmptyDict, ht.TDict, "Backend parameters for instance"),
1298
    ("disks", ht.NoDefault, ht.TListOf(_TDiskParams),
1299
     "Disk descriptions, for example ``[{\"%s\": 100}, {\"%s\": 5}]``;"
1300
     " each disk definition must contain a ``%s`` value and"
1301
     " can contain an optional ``%s`` value denoting the disk access mode"
1302
     " (%s)" %
1303
     (constants.IDISK_SIZE, constants.IDISK_SIZE, constants.IDISK_SIZE,
1304
      constants.IDISK_MODE,
1305
      " or ".join("``%s``" % i for i in sorted(constants.DISK_ACCESS_SET)))),
1306
    ("disk_template", ht.NoDefault, _BuildDiskTemplateCheck(True),
1307
     "Disk template"),
1308
    ("file_driver", None, ht.TMaybe(ht.TElemOf(constants.FILE_DRIVER)),
1309
     "Driver for file-backed disks"),
1310
    ("file_storage_dir", None, ht.TMaybeString,
1311
     "Directory for storing file-backed disks"),
1312
    ("hvparams", ht.EmptyDict, ht.TDict,
1313
     "Hypervisor parameters for instance, hypervisor-dependent"),
1314
    ("hypervisor", None, ht.TMaybeString, "Hypervisor"),
1315
    _PIAllocFromDesc("Iallocator for deciding which node(s) to use"),
1316
    ("identify_defaults", False, ht.TBool,
1317
     "Reset instance parameters to default if equal"),
1318
    ("ip_check", True, ht.TBool, _PIpCheckDoc),
1319
    ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1320
    ("mode", ht.NoDefault, ht.TElemOf(constants.INSTANCE_CREATE_MODES),
1321
     "Instance creation mode"),
1322
    ("nics", ht.NoDefault, ht.TListOf(_TestNicDef),
1323
     "List of NIC (network interface) definitions, for example"
1324
     " ``[{}, {}, {\"%s\": \"198.51.100.4\"}]``; each NIC definition can"
1325
     " contain the optional values %s" %
1326
     (constants.INIC_IP,
1327
      ", ".join("``%s``" % i for i in sorted(constants.INIC_PARAMS)))),
1328
    ("no_install", None, ht.TMaybeBool,
1329
     "Do not install the OS (will disable automatic start)"),
1330
    ("osparams", ht.EmptyDict, ht.TDict, "OS parameters for instance"),
1331
    ("os_type", None, ht.TMaybeString, "Operating system"),
1332
    ("pnode", None, ht.TMaybeString, "Primary node"),
1333
    ("snode", None, ht.TMaybeString, "Secondary node"),
1334
    ("source_handshake", None, ht.TMaybe(ht.TList),
1335
     "Signed handshake from source (remote import only)"),
1336
    ("source_instance_name", None, ht.TMaybeString,
1337
     "Source instance name (remote import only)"),
1338
    ("source_shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
1339
     ht.TNonNegativeInt,
1340
     "How long source instance was given to shut down (remote import only)"),
1341
    ("source_x509_ca", None, ht.TMaybeString,
1342
     "Source X509 CA in PEM format (remote import only)"),
1343
    ("src_node", None, ht.TMaybeString, "Source node for import"),
1344
    ("src_path", None, ht.TMaybeString, "Source directory for import"),
1345
    ("start", True, ht.TBool, "Whether to start instance after creation"),
1346
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Instance tags"),
1347
    ]
1348
  OP_RESULT = ht.Comment("instance nodes")(ht.TListOf(ht.TNonEmptyString))
1349

    
1350

    
1351
class OpInstanceMultiAlloc(OpCode):
1352
  """Allocates multiple instances.
1353

1354
  """
1355
  OP_PARAMS = [
1356
    _POpportunisticLocking,
1357
    _PIAllocFromDesc("Iallocator used to allocate all the instances"),
1358
    ("instances", ht.EmptyList, ht.TListOf(ht.TInstanceOf(OpInstanceCreate)),
1359
     "List of instance create opcodes describing the instances to allocate"),
1360
    ]
1361
  _JOB_LIST = ht.Comment("List of submitted jobs")(TJobIdList)
1362
  ALLOCATABLE_KEY = "allocatable"
1363
  FAILED_KEY = "allocatable"
1364
  OP_RESULT = ht.TStrictDict(True, True, {
1365
    constants.JOB_IDS_KEY: _JOB_LIST,
1366
    ALLOCATABLE_KEY: ht.TListOf(ht.TNonEmptyString),
1367
    FAILED_KEY: ht.TListOf(ht.TNonEmptyString),
1368
    })
1369

    
1370
  def __getstate__(self):
1371
    """Generic serializer.
1372

1373
    """
1374
    state = OpCode.__getstate__(self)
1375
    if hasattr(self, "instances"):
1376
      # pylint: disable=E1101
1377
      state["instances"] = [inst.__getstate__() for inst in self.instances]
1378
    return state
1379

    
1380
  def __setstate__(self, state):
1381
    """Generic unserializer.
1382

1383
    This method just restores from the serialized state the attributes
1384
    of the current instance.
1385

1386
    @param state: the serialized opcode data
1387
    @type state: C{dict}
1388

1389
    """
1390
    if not isinstance(state, dict):
1391
      raise ValueError("Invalid data to __setstate__: expected dict, got %s" %
1392
                       type(state))
1393

    
1394
    if "instances" in state:
1395
      state["instances"] = map(OpCode.LoadOpCode, state["instances"])
1396

    
1397
    return OpCode.__setstate__(self, state)
1398

    
1399
  def Validate(self, set_defaults):
1400
    """Validates this opcode.
1401

1402
    We do this recursively.
1403

1404
    """
1405
    OpCode.Validate(self, set_defaults)
1406

    
1407
    for inst in self.instances: # pylint: disable=E1101
1408
      inst.Validate(set_defaults)
1409

    
1410

    
1411
class OpInstanceReinstall(OpCode):
1412
  """Reinstall an instance's OS."""
1413
  OP_DSC_FIELD = "instance_name"
1414
  OP_PARAMS = [
1415
    _PInstanceName,
1416
    _PForceVariant,
1417
    ("os_type", None, ht.TMaybeString, "Instance operating system"),
1418
    ("osparams", None, ht.TMaybeDict, "Temporary OS parameters"),
1419
    ]
1420
  OP_RESULT = ht.TNone
1421

    
1422

    
1423
class OpInstanceRemove(OpCode):
1424
  """Remove an instance."""
1425
  OP_DSC_FIELD = "instance_name"
1426
  OP_PARAMS = [
1427
    _PInstanceName,
1428
    _PShutdownTimeout,
1429
    ("ignore_failures", False, ht.TBool,
1430
     "Whether to ignore failures during removal"),
1431
    ]
1432
  OP_RESULT = ht.TNone
1433

    
1434

    
1435
class OpInstanceRename(OpCode):
1436
  """Rename an instance."""
1437
  OP_PARAMS = [
1438
    _PInstanceName,
1439
    _PNameCheck,
1440
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New instance name"),
1441
    ("ip_check", False, ht.TBool, _PIpCheckDoc),
1442
    ]
1443
  OP_RESULT = ht.Comment("New instance name")(ht.TNonEmptyString)
1444

    
1445

    
1446
class OpInstanceStartup(OpCode):
1447
  """Startup an instance."""
1448
  OP_DSC_FIELD = "instance_name"
1449
  OP_PARAMS = [
1450
    _PInstanceName,
1451
    _PForce,
1452
    _PIgnoreOfflineNodes,
1453
    ("hvparams", ht.EmptyDict, ht.TDict,
1454
     "Temporary hypervisor parameters, hypervisor-dependent"),
1455
    ("beparams", ht.EmptyDict, ht.TDict, "Temporary backend parameters"),
1456
    _PNoRemember,
1457
    _PStartupPaused,
1458
    ]
1459
  OP_RESULT = ht.TNone
1460

    
1461

    
1462
class OpInstanceShutdown(OpCode):
1463
  """Shutdown an instance."""
1464
  OP_DSC_FIELD = "instance_name"
1465
  OP_PARAMS = [
1466
    _PInstanceName,
1467
    _PForce,
1468
    _PIgnoreOfflineNodes,
1469
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, ht.TNonNegativeInt,
1470
     "How long to wait for instance to shut down"),
1471
    _PNoRemember,
1472
    ]
1473
  OP_RESULT = ht.TNone
1474

    
1475

    
1476
class OpInstanceReboot(OpCode):
1477
  """Reboot an instance."""
1478
  OP_DSC_FIELD = "instance_name"
1479
  OP_PARAMS = [
1480
    _PInstanceName,
1481
    _PShutdownTimeout,
1482
    ("ignore_secondaries", False, ht.TBool,
1483
     "Whether to start the instance even if secondary disks are failing"),
1484
    ("reboot_type", ht.NoDefault, ht.TElemOf(constants.REBOOT_TYPES),
1485
     "How to reboot instance"),
1486
    ]
1487
  OP_RESULT = ht.TNone
1488

    
1489

    
1490
class OpInstanceReplaceDisks(OpCode):
1491
  """Replace the disks of an instance."""
1492
  OP_DSC_FIELD = "instance_name"
1493
  OP_PARAMS = [
1494
    _PInstanceName,
1495
    _PEarlyRelease,
1496
    _PIgnoreIpolicy,
1497
    ("mode", ht.NoDefault, ht.TElemOf(constants.REPLACE_MODES),
1498
     "Replacement mode"),
1499
    ("disks", ht.EmptyList, ht.TListOf(ht.TNonNegativeInt),
1500
     "Disk indexes"),
1501
    ("remote_node", None, ht.TMaybeString, "New secondary node"),
1502
    _PIAllocFromDesc("Iallocator for deciding new secondary node"),
1503
    ]
1504
  OP_RESULT = ht.TNone
1505

    
1506

    
1507
class OpInstanceFailover(OpCode):
1508
  """Failover an instance."""
1509
  OP_DSC_FIELD = "instance_name"
1510
  OP_PARAMS = [
1511
    _PInstanceName,
1512
    _PShutdownTimeout,
1513
    _PIgnoreConsistency,
1514
    _PMigrationTargetNode,
1515
    _PIgnoreIpolicy,
1516
    _PIAllocFromDesc("Iallocator for deciding the target node for"
1517
                     " shared-storage instances"),
1518
    ]
1519
  OP_RESULT = ht.TNone
1520

    
1521

    
1522
class OpInstanceMigrate(OpCode):
1523
  """Migrate an instance.
1524

1525
  This migrates (without shutting down an instance) to its secondary
1526
  node.
1527

1528
  @ivar instance_name: the name of the instance
1529
  @ivar mode: the migration mode (live, non-live or None for auto)
1530

1531
  """
1532
  OP_DSC_FIELD = "instance_name"
1533
  OP_PARAMS = [
1534
    _PInstanceName,
1535
    _PMigrationMode,
1536
    _PMigrationLive,
1537
    _PMigrationTargetNode,
1538
    _PAllowRuntimeChgs,
1539
    _PIgnoreIpolicy,
1540
    ("cleanup", False, ht.TBool,
1541
     "Whether a previously failed migration should be cleaned up"),
1542
    _PIAllocFromDesc("Iallocator for deciding the target node for"
1543
                     " shared-storage instances"),
1544
    ("allow_failover", False, ht.TBool,
1545
     "Whether we can fallback to failover if migration is not possible"),
1546
    ]
1547
  OP_RESULT = ht.TNone
1548

    
1549

    
1550
class OpInstanceMove(OpCode):
1551
  """Move an instance.
1552

1553
  This move (with shutting down an instance and data copying) to an
1554
  arbitrary node.
1555

1556
  @ivar instance_name: the name of the instance
1557
  @ivar target_node: the destination node
1558

1559
  """
1560
  OP_DSC_FIELD = "instance_name"
1561
  OP_PARAMS = [
1562
    _PInstanceName,
1563
    _PShutdownTimeout,
1564
    _PIgnoreIpolicy,
1565
    ("target_node", ht.NoDefault, ht.TNonEmptyString, "Target node"),
1566
    _PIgnoreConsistency,
1567
    ]
1568
  OP_RESULT = ht.TNone
1569

    
1570

    
1571
class OpInstanceConsole(OpCode):
1572
  """Connect to an instance's console."""
1573
  OP_DSC_FIELD = "instance_name"
1574
  OP_PARAMS = [
1575
    _PInstanceName,
1576
    ]
1577
  OP_RESULT = ht.TDict
1578

    
1579

    
1580
class OpInstanceActivateDisks(OpCode):
1581
  """Activate an instance's disks."""
1582
  OP_DSC_FIELD = "instance_name"
1583
  OP_PARAMS = [
1584
    _PInstanceName,
1585
    ("ignore_size", False, ht.TBool, "Whether to ignore recorded size"),
1586
    _PWaitForSyncFalse,
1587
    ]
1588
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(3),
1589
                                 ht.TItems([ht.TNonEmptyString,
1590
                                            ht.TNonEmptyString,
1591
                                            ht.TNonEmptyString])))
1592

    
1593

    
1594
class OpInstanceDeactivateDisks(OpCode):
1595
  """Deactivate an instance's disks."""
1596
  OP_DSC_FIELD = "instance_name"
1597
  OP_PARAMS = [
1598
    _PInstanceName,
1599
    _PForce,
1600
    ]
1601
  OP_RESULT = ht.TNone
1602

    
1603

    
1604
class OpInstanceRecreateDisks(OpCode):
1605
  """Recreate an instance's disks."""
1606
  _TDiskChanges = \
1607
    ht.TAnd(ht.TIsLength(2),
1608
            ht.TItems([ht.Comment("Disk index")(ht.TNonNegativeInt),
1609
                       ht.Comment("Parameters")(_TDiskParams)]))
1610

    
1611
  OP_DSC_FIELD = "instance_name"
1612
  OP_PARAMS = [
1613
    _PInstanceName,
1614
    ("disks", ht.EmptyList,
1615
     ht.TOr(ht.TListOf(ht.TNonNegativeInt), ht.TListOf(_TDiskChanges)),
1616
     "List of disk indexes (deprecated) or a list of tuples containing a disk"
1617
     " index and a possibly empty dictionary with disk parameter changes"),
1618
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1619
     "New instance nodes, if relocation is desired"),
1620
    _PIAllocFromDesc("Iallocator for deciding new nodes"),
1621
    ]
1622
  OP_RESULT = ht.TNone
1623

    
1624

    
1625
class OpInstanceQuery(OpCode):
1626
  """Compute the list of instances."""
1627
  OP_PARAMS = [
1628
    _POutputFields,
1629
    _PUseLocking,
1630
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1631
     "Empty list to query all instances, instance names otherwise"),
1632
    ]
1633
  OP_RESULT = _TOldQueryResult
1634

    
1635

    
1636
class OpInstanceQueryData(OpCode):
1637
  """Compute the run-time status of instances."""
1638
  OP_PARAMS = [
1639
    _PUseLocking,
1640
    ("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1641
     "Instance names"),
1642
    ("static", False, ht.TBool,
1643
     "Whether to only return configuration data without querying"
1644
     " nodes"),
1645
    ]
1646
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString, ht.TDict)
1647

    
1648

    
1649
def _TestInstSetParamsModList(fn):
1650
  """Generates a check for modification lists.
1651

1652
  """
1653
  # Old format
1654
  # TODO: Remove in version 2.8 including support in LUInstanceSetParams
1655
  old_mod_item_fn = \
1656
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1657
      ht.TOr(ht.TElemOf(constants.DDMS_VALUES), ht.TNonNegativeInt),
1658
      fn,
1659
      ]))
1660

    
1661
  # New format, supporting adding/removing disks/NICs at arbitrary indices
1662
  mod_item_fn = \
1663
    ht.TAnd(ht.TIsLength(3), ht.TItems([
1664
      ht.TElemOf(constants.DDMS_VALUES_WITH_MODIFY),
1665
      ht.Comment("Device index, can be negative, e.g. -1 for last disk")
1666
                 (ht.TOr(ht.TInt, ht.TString)),
1667
      fn,
1668
      ]))
1669

    
1670
  return ht.TOr(ht.Comment("Recommended")(ht.TListOf(mod_item_fn)),
1671
                ht.Comment("Deprecated")(ht.TListOf(old_mod_item_fn)))
1672

    
1673

    
1674
class OpInstanceSetParams(OpCode):
1675
  """Change the parameters of an instance.
1676

1677
  """
1678
  TestNicModifications = _TestInstSetParamsModList(_TestNicDef)
1679
  TestDiskModifications = _TestInstSetParamsModList(_TDiskParams)
1680

    
1681
  OP_DSC_FIELD = "instance_name"
1682
  OP_PARAMS = [
1683
    _PInstanceName,
1684
    _PForce,
1685
    _PForceVariant,
1686
    _PIgnoreIpolicy,
1687
    ("nics", ht.EmptyList, TestNicModifications,
1688
     "List of NIC changes: each item is of the form"
1689
     " ``(op, identifier, settings)``, ``op`` is one of ``%s``, ``%s`` or"
1690
     " ``%s``, ``identifier`` can be a zero-based index number (or -1 to refer"
1691
     " to the last position), the NIC's UUID of the NIC's name; a"
1692
     " deprecated version of this parameter used the form ``(op, settings)``,"
1693
     " where ``op`` can be ``%s`` to add a new NIC with the specified"
1694
     " settings, ``%s`` to remove the last NIC or a number to modify the"
1695
     " settings of the NIC with that index" %
1696
     (constants.DDM_ADD, constants.DDM_MODIFY, constants.DDM_REMOVE,
1697
      constants.DDM_ADD, constants.DDM_REMOVE)),
1698
    ("disks", ht.EmptyList, TestDiskModifications,
1699
     "List of disk changes; see ``nics``"),
1700
    ("beparams", ht.EmptyDict, ht.TDict, "Per-instance backend parameters"),
1701
    ("runtime_mem", None, ht.TMaybePositiveInt, "New runtime memory"),
1702
    ("hvparams", ht.EmptyDict, ht.TDict,
1703
     "Per-instance hypervisor parameters, hypervisor-dependent"),
1704
    ("disk_template", None, ht.TMaybe(_BuildDiskTemplateCheck(False)),
1705
     "Disk template for instance"),
1706
    ("pnode", None, ht.TMaybeString, "New primary node"),
1707
    ("remote_node", None, ht.TMaybeString,
1708
     "Secondary node (used when changing disk template)"),
1709
    ("os_name", None, ht.TMaybeString,
1710
     "Change the instance's OS without reinstalling the instance"),
1711
    ("osparams", None, ht.TMaybeDict, "Per-instance OS parameters"),
1712
    ("wait_for_sync", True, ht.TBool,
1713
     "Whether to wait for the disk to synchronize, when changing template"),
1714
    ("offline", None, ht.TMaybeBool, "Whether to mark instance as offline"),
1715
    ("conflicts_check", True, ht.TBool, "Check for conflicting IPs"),
1716
    ]
1717
  OP_RESULT = _TSetParamsResult
1718

    
1719

    
1720
class OpInstanceGrowDisk(OpCode):
1721
  """Grow a disk of an instance."""
1722
  OP_DSC_FIELD = "instance_name"
1723
  OP_PARAMS = [
1724
    _PInstanceName,
1725
    _PWaitForSync,
1726
    ("disk", ht.NoDefault, ht.TInt, "Disk index"),
1727
    ("amount", ht.NoDefault, ht.TNonNegativeInt,
1728
     "Amount of disk space to add (megabytes)"),
1729
    ("absolute", False, ht.TBool,
1730
     "Whether the amount parameter is an absolute target or a relative one"),
1731
    ]
1732
  OP_RESULT = ht.TNone
1733

    
1734

    
1735
class OpInstanceChangeGroup(OpCode):
1736
  """Moves an instance to another node group."""
1737
  OP_DSC_FIELD = "instance_name"
1738
  OP_PARAMS = [
1739
    _PInstanceName,
1740
    _PEarlyRelease,
1741
    _PIAllocFromDesc("Iallocator for computing solution"),
1742
    _PTargetGroups,
1743
    ]
1744
  OP_RESULT = TJobIdListOnly
1745

    
1746

    
1747
# Node group opcodes
1748

    
1749
class OpGroupAdd(OpCode):
1750
  """Add a node group to the cluster."""
1751
  OP_DSC_FIELD = "group_name"
1752
  OP_PARAMS = [
1753
    _PGroupName,
1754
    _PNodeGroupAllocPolicy,
1755
    _PGroupNodeParams,
1756
    _PDiskParams,
1757
    _PHvState,
1758
    _PDiskState,
1759
    ("ipolicy", None, ht.TMaybeDict,
1760
     "Group-wide :ref:`instance policy <rapi-ipolicy>` specs"),
1761
    ]
1762
  OP_RESULT = ht.TNone
1763

    
1764

    
1765
class OpGroupAssignNodes(OpCode):
1766
  """Assign nodes to a node group."""
1767
  OP_DSC_FIELD = "group_name"
1768
  OP_PARAMS = [
1769
    _PGroupName,
1770
    _PForce,
1771
    ("nodes", ht.NoDefault, ht.TListOf(ht.TNonEmptyString),
1772
     "List of nodes to assign"),
1773
    ]
1774
  OP_RESULT = ht.TNone
1775

    
1776

    
1777
class OpGroupQuery(OpCode):
1778
  """Compute the list of node groups."""
1779
  OP_PARAMS = [
1780
    _POutputFields,
1781
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1782
     "Empty list to query all groups, group names otherwise"),
1783
    ]
1784
  OP_RESULT = _TOldQueryResult
1785

    
1786

    
1787
class OpGroupSetParams(OpCode):
1788
  """Change the parameters of a node group."""
1789
  OP_DSC_FIELD = "group_name"
1790
  OP_PARAMS = [
1791
    _PGroupName,
1792
    _PNodeGroupAllocPolicy,
1793
    _PGroupNodeParams,
1794
    _PDiskParams,
1795
    _PHvState,
1796
    _PDiskState,
1797
    ("ipolicy", None, ht.TMaybeDict, "Group-wide instance policy specs"),
1798
    ]
1799
  OP_RESULT = _TSetParamsResult
1800

    
1801

    
1802
class OpGroupRemove(OpCode):
1803
  """Remove a node group from the cluster."""
1804
  OP_DSC_FIELD = "group_name"
1805
  OP_PARAMS = [
1806
    _PGroupName,
1807
    ]
1808
  OP_RESULT = ht.TNone
1809

    
1810

    
1811
class OpGroupRename(OpCode):
1812
  """Rename a node group in the cluster."""
1813
  OP_PARAMS = [
1814
    _PGroupName,
1815
    ("new_name", ht.NoDefault, ht.TNonEmptyString, "New group name"),
1816
    ]
1817
  OP_RESULT = ht.Comment("New group name")(ht.TNonEmptyString)
1818

    
1819

    
1820
class OpGroupEvacuate(OpCode):
1821
  """Evacuate a node group in the cluster."""
1822
  OP_DSC_FIELD = "group_name"
1823
  OP_PARAMS = [
1824
    _PGroupName,
1825
    _PEarlyRelease,
1826
    _PIAllocFromDesc("Iallocator for computing solution"),
1827
    _PTargetGroups,
1828
    ]
1829
  OP_RESULT = TJobIdListOnly
1830

    
1831

    
1832
# OS opcodes
1833
class OpOsDiagnose(OpCode):
1834
  """Compute the list of guest operating systems."""
1835
  OP_PARAMS = [
1836
    _POutputFields,
1837
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1838
     "Which operating systems to diagnose"),
1839
    ]
1840
  OP_RESULT = _TOldQueryResult
1841

    
1842

    
1843
# ExtStorage opcodes
1844
class OpExtStorageDiagnose(OpCode):
1845
  """Compute the list of external storage providers."""
1846
  OP_PARAMS = [
1847
    _POutputFields,
1848
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1849
     "Which ExtStorage Provider to diagnose"),
1850
    ]
1851
  OP_RESULT = _TOldQueryResult
1852

    
1853

    
1854
# Exports opcodes
1855
class OpBackupQuery(OpCode):
1856
  """Compute the list of exported images."""
1857
  OP_PARAMS = [
1858
    _PUseLocking,
1859
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
1860
     "Empty list to query all nodes, node names otherwise"),
1861
    ]
1862
  OP_RESULT = ht.TDictOf(ht.TNonEmptyString,
1863
                         ht.TOr(ht.Comment("False on error")(ht.TBool),
1864
                                ht.TListOf(ht.TNonEmptyString)))
1865

    
1866

    
1867
class OpBackupPrepare(OpCode):
1868
  """Prepares an instance export.
1869

1870
  @ivar instance_name: Instance name
1871
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1872

1873
  """
1874
  OP_DSC_FIELD = "instance_name"
1875
  OP_PARAMS = [
1876
    _PInstanceName,
1877
    ("mode", ht.NoDefault, ht.TElemOf(constants.EXPORT_MODES),
1878
     "Export mode"),
1879
    ]
1880
  OP_RESULT = ht.TMaybeDict
1881

    
1882

    
1883
class OpBackupExport(OpCode):
1884
  """Export an instance.
1885

1886
  For local exports, the export destination is the node name. For
1887
  remote exports, the export destination is a list of tuples, each
1888
  consisting of hostname/IP address, port, magic, HMAC and HMAC
1889
  salt. The HMAC is calculated using the cluster domain secret over
1890
  the value "${index}:${hostname}:${port}". The destination X509 CA
1891
  must be a signed certificate.
1892

1893
  @ivar mode: Export mode (one of L{constants.EXPORT_MODES})
1894
  @ivar target_node: Export destination
1895
  @ivar x509_key_name: X509 key to use (remote export only)
1896
  @ivar destination_x509_ca: Destination X509 CA in PEM format (remote export
1897
                             only)
1898

1899
  """
1900
  OP_DSC_FIELD = "instance_name"
1901
  OP_PARAMS = [
1902
    _PInstanceName,
1903
    _PShutdownTimeout,
1904
    # TODO: Rename target_node as it changes meaning for different export modes
1905
    # (e.g. "destination")
1906
    ("target_node", ht.NoDefault, ht.TOr(ht.TNonEmptyString, ht.TList),
1907
     "Destination information, depends on export mode"),
1908
    ("shutdown", True, ht.TBool, "Whether to shutdown instance before export"),
1909
    ("remove_instance", False, ht.TBool,
1910
     "Whether to remove instance after export"),
1911
    ("ignore_remove_failures", False, ht.TBool,
1912
     "Whether to ignore failures while removing instances"),
1913
    ("mode", constants.EXPORT_MODE_LOCAL, ht.TElemOf(constants.EXPORT_MODES),
1914
     "Export mode"),
1915
    ("x509_key_name", None, ht.TMaybe(ht.TList),
1916
     "Name of X509 key (remote export only)"),
1917
    ("destination_x509_ca", None, ht.TMaybeString,
1918
     "Destination X509 CA (remote export only)"),
1919
    ]
1920
  OP_RESULT = \
1921
    ht.TAnd(ht.TIsLength(2), ht.TItems([
1922
      ht.Comment("Finalizing status")(ht.TBool),
1923
      ht.Comment("Status for every exported disk")(ht.TListOf(ht.TBool)),
1924
      ]))
1925

    
1926

    
1927
class OpBackupRemove(OpCode):
1928
  """Remove an instance's export."""
1929
  OP_DSC_FIELD = "instance_name"
1930
  OP_PARAMS = [
1931
    _PInstanceName,
1932
    ]
1933
  OP_RESULT = ht.TNone
1934

    
1935

    
1936
# Tags opcodes
1937
class OpTagsGet(OpCode):
1938
  """Returns the tags of the given object."""
1939
  OP_DSC_FIELD = "name"
1940
  OP_PARAMS = [
1941
    _PTagKind,
1942
    # Not using _PUseLocking as the default is different for historical reasons
1943
    ("use_locking", True, ht.TBool, "Whether to use synchronization"),
1944
    # Name is only meaningful for nodes and instances
1945
    ("name", ht.NoDefault, ht.TMaybeString,
1946
     "Name of object to retrieve tags from"),
1947
    ]
1948
  OP_RESULT = ht.TListOf(ht.TNonEmptyString)
1949

    
1950

    
1951
class OpTagsSearch(OpCode):
1952
  """Searches the tags in the cluster for a given pattern."""
1953
  OP_DSC_FIELD = "pattern"
1954
  OP_PARAMS = [
1955
    ("pattern", ht.NoDefault, ht.TNonEmptyString,
1956
     "Search pattern (regular expression)"),
1957
    ]
1958
  OP_RESULT = ht.TListOf(ht.TAnd(ht.TIsLength(2), ht.TItems([
1959
    ht.TNonEmptyString,
1960
    ht.TNonEmptyString,
1961
    ])))
1962

    
1963

    
1964
class OpTagsSet(OpCode):
1965
  """Add a list of tags on a given object."""
1966
  OP_PARAMS = [
1967
    _PTagKind,
1968
    _PTags,
1969
    # Name is only meaningful for groups, nodes and instances
1970
    ("name", ht.NoDefault, ht.TMaybeString,
1971
     "Name of object where tag(s) should be added"),
1972
    ]
1973
  OP_RESULT = ht.TNone
1974

    
1975

    
1976
class OpTagsDel(OpCode):
1977
  """Remove a list of tags from a given object."""
1978
  OP_PARAMS = [
1979
    _PTagKind,
1980
    _PTags,
1981
    # Name is only meaningful for groups, nodes and instances
1982
    ("name", ht.NoDefault, ht.TMaybeString,
1983
     "Name of object where tag(s) should be deleted"),
1984
    ]
1985
  OP_RESULT = ht.TNone
1986

    
1987

    
1988
# Test opcodes
1989
class OpTestDelay(OpCode):
1990
  """Sleeps for a configured amount of time.
1991

1992
  This is used just for debugging and testing.
1993

1994
  Parameters:
1995
    - duration: the time to sleep, in seconds
1996
    - on_master: if true, sleep on the master
1997
    - on_nodes: list of nodes in which to sleep
1998

1999
  If the on_master parameter is true, it will execute a sleep on the
2000
  master (before any node sleep).
2001

2002
  If the on_nodes list is not empty, it will sleep on those nodes
2003
  (after the sleep on the master, if that is enabled).
2004

2005
  As an additional feature, the case of duration < 0 will be reported
2006
  as an execution error, so this opcode can be used as a failure
2007
  generator. The case of duration == 0 will not be treated specially.
2008

2009
  """
2010
  OP_DSC_FIELD = "duration"
2011
  OP_PARAMS = [
2012
    ("duration", ht.NoDefault, ht.TNumber, None),
2013
    ("on_master", True, ht.TBool, None),
2014
    ("on_nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
2015
    ("repeat", 0, ht.TNonNegativeInt, None),
2016
    ]
2017

    
2018
  def OP_DSC_FORMATTER(self, value): # pylint: disable=C0103,R0201
2019
    """Custom formatter for duration.
2020

2021
    """
2022
    try:
2023
      v = float(value)
2024
    except TypeError:
2025
      v = value
2026
    return str(v)
2027

    
2028

    
2029
class OpTestAllocator(OpCode):
2030
  """Allocator framework testing.
2031

2032
  This opcode has two modes:
2033
    - gather and return allocator input for a given mode (allocate new
2034
      or replace secondary) and a given instance definition (direction
2035
      'in')
2036
    - run a selected allocator for a given operation (as above) and
2037
      return the allocator output (direction 'out')
2038

2039
  """
2040
  OP_DSC_FIELD = "iallocator"
2041
  OP_PARAMS = [
2042
    ("direction", ht.NoDefault,
2043
     ht.TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS), None),
2044
    ("mode", ht.NoDefault, ht.TElemOf(constants.VALID_IALLOCATOR_MODES), None),
2045
    ("name", ht.NoDefault, ht.TNonEmptyString, None),
2046
    ("nics", ht.NoDefault,
2047
     ht.TMaybeListOf(ht.TDictOf(ht.TElemOf([constants.INIC_MAC,
2048
                                            constants.INIC_IP,
2049
                                            "bridge"]),
2050
                                ht.TMaybeString)),
2051
     None),
2052
    ("disks", ht.NoDefault, ht.TMaybe(ht.TList), None),
2053
    ("hypervisor", None, ht.TMaybeString, None),
2054
    _PIAllocFromDesc(None),
2055
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), None),
2056
    ("memory", None, ht.TMaybe(ht.TNonNegativeInt), None),
2057
    ("vcpus", None, ht.TMaybe(ht.TNonNegativeInt), None),
2058
    ("os", None, ht.TMaybeString, None),
2059
    ("disk_template", None, ht.TMaybeString, None),
2060
    ("instances", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
2061
    ("evac_mode", None,
2062
     ht.TMaybe(ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)), None),
2063
    ("target_groups", None, ht.TMaybeListOf(ht.TNonEmptyString), None),
2064
    ("spindle_use", 1, ht.TNonNegativeInt, None),
2065
    ("count", 1, ht.TNonNegativeInt, None),
2066
    ]
2067

    
2068

    
2069
class OpTestJqueue(OpCode):
2070
  """Utility opcode to test some aspects of the job queue.
2071

2072
  """
2073
  OP_PARAMS = [
2074
    ("notify_waitlock", False, ht.TBool, None),
2075
    ("notify_exec", False, ht.TBool, None),
2076
    ("log_messages", ht.EmptyList, ht.TListOf(ht.TString), None),
2077
    ("fail", False, ht.TBool, None),
2078
    ]
2079

    
2080

    
2081
class OpTestDummy(OpCode):
2082
  """Utility opcode used by unittests.
2083

2084
  """
2085
  OP_PARAMS = [
2086
    ("result", ht.NoDefault, ht.NoType, None),
2087
    ("messages", ht.NoDefault, ht.NoType, None),
2088
    ("fail", ht.NoDefault, ht.NoType, None),
2089
    ("submit_jobs", None, ht.NoType, None),
2090
    ]
2091
  WITH_LU = False
2092

    
2093

    
2094
# Network opcodes
2095
# Add a new network in the cluster
2096
class OpNetworkAdd(OpCode):
2097
  """Add an IP network to the cluster."""
2098
  OP_DSC_FIELD = "network_name"
2099
  OP_PARAMS = [
2100
    _PNetworkName,
2101
    ("network", ht.NoDefault, _TIpNetwork4, "IPv4 subnet"),
2102
    ("gateway", None, ht.TMaybe(_TIpAddress4), "IPv4 gateway"),
2103
    ("network6", None, ht.TMaybe(_TIpNetwork6), "IPv6 subnet"),
2104
    ("gateway6", None, ht.TMaybe(_TIpAddress6), "IPv6 gateway"),
2105
    ("mac_prefix", None, ht.TMaybeString,
2106
     "MAC address prefix that overrides cluster one"),
2107
    ("add_reserved_ips", None, _TMaybeAddr4List,
2108
     "Which IP addresses to reserve"),
2109
    ("conflicts_check", True, ht.TBool,
2110
     "Whether to check for conflicting IP addresses"),
2111
    ("tags", ht.EmptyList, ht.TListOf(ht.TNonEmptyString), "Network tags"),
2112
    ]
2113
  OP_RESULT = ht.TNone
2114

    
2115

    
2116
class OpNetworkRemove(OpCode):
2117
  """Remove an existing network from the cluster.
2118
     Must not be connected to any nodegroup.
2119

2120
  """
2121
  OP_DSC_FIELD = "network_name"
2122
  OP_PARAMS = [
2123
    _PNetworkName,
2124
    _PForce,
2125
    ]
2126
  OP_RESULT = ht.TNone
2127

    
2128

    
2129
class OpNetworkSetParams(OpCode):
2130
  """Modify Network's parameters except for IPv4 subnet"""
2131
  OP_DSC_FIELD = "network_name"
2132
  OP_PARAMS = [
2133
    _PNetworkName,
2134
    ("gateway", None, ht.TMaybeValueNone(_TIpAddress4), "IPv4 gateway"),
2135
    ("network6", None, ht.TMaybeValueNone(_TIpNetwork6), "IPv6 subnet"),
2136
    ("gateway6", None, ht.TMaybeValueNone(_TIpAddress6), "IPv6 gateway"),
2137
    ("mac_prefix", None, ht.TMaybeValueNone(ht.TString),
2138
     "MAC address prefix that overrides cluster one"),
2139
    ("add_reserved_ips", None, _TMaybeAddr4List,
2140
     "Which external IP addresses to reserve"),
2141
    ("remove_reserved_ips", None, _TMaybeAddr4List,
2142
     "Which external IP addresses to release"),
2143
    ]
2144
  OP_RESULT = ht.TNone
2145

    
2146

    
2147
class OpNetworkConnect(OpCode):
2148
  """Connect a Network to a specific Nodegroup with the defined netparams
2149
     (mode, link). Nics in this Network will inherit those params.
2150
     Produce errors if a NIC (that its not already assigned to a network)
2151
     has an IP that is contained in the Network this will produce error unless
2152
     --no-conflicts-check is passed.
2153

2154
  """
2155
  OP_DSC_FIELD = "network_name"
2156
  OP_PARAMS = [
2157
    _PGroupName,
2158
    _PNetworkName,
2159
    ("network_mode", ht.NoDefault, ht.TElemOf(constants.NIC_VALID_MODES),
2160
     "Connectivity mode"),
2161
    ("network_link", ht.NoDefault, ht.TString, "Connectivity link"),
2162
    ("conflicts_check", True, ht.TBool, "Whether to check for conflicting IPs"),
2163
    ]
2164
  OP_RESULT = ht.TNone
2165

    
2166

    
2167
class OpNetworkDisconnect(OpCode):
2168
  """Disconnect a Network from a Nodegroup. Produce errors if NICs are
2169
     present in the Network unless --no-conficts-check option is passed.
2170

2171
  """
2172
  OP_DSC_FIELD = "network_name"
2173
  OP_PARAMS = [
2174
    _PGroupName,
2175
    _PNetworkName,
2176
    ]
2177
  OP_RESULT = ht.TNone
2178

    
2179

    
2180
class OpNetworkQuery(OpCode):
2181
  """Compute the list of networks."""
2182
  OP_PARAMS = [
2183
    _POutputFields,
2184
    _PUseLocking,
2185
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString),
2186
     "Empty list to query all groups, group names otherwise"),
2187
    ]
2188
  OP_RESULT = _TOldQueryResult
2189

    
2190

    
2191
def _GetOpList():
2192
  """Returns list of all defined opcodes.
2193

2194
  Does not eliminate duplicates by C{OP_ID}.
2195

2196
  """
2197
  return [v for v in globals().values()
2198
          if (isinstance(v, type) and issubclass(v, OpCode) and
2199
              hasattr(v, "OP_ID") and v is not OpCode)]
2200

    
2201

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