cli.py 144 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
#
Iustin Pop's avatar
Iustin Pop committed
2
3
#

4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Module dealing with command line parsing"""


import sys
import textwrap
import os.path
28
import time
Iustin Pop's avatar
Iustin Pop committed
29
import logging
30
import errno
31
import itertools
32
import shlex
33
from cStringIO import StringIO
Iustin Pop's avatar
Iustin Pop committed
34
35
36
37

from ganeti import utils
from ganeti import errors
from ganeti import constants
38
from ganeti import opcodes
39
import ganeti.rpc.errors as rpcerr
40
import ganeti.rpc.node as rpc
41
from ganeti import ssh
42
from ganeti import compat
43
from ganeti import netutils
44
from ganeti import qlang
45
from ganeti import objects
46
from ganeti import pathutils
47
from ganeti import serializer
Iustin Pop's avatar
Iustin Pop committed
48

49
50
from ganeti.runtime import (GetClient)

51
from optparse import (OptionParser, TitledHelpFormatter,
Iustin Pop's avatar
Iustin Pop committed
52
                      Option, OptionValueError)
Iustin Pop's avatar
Iustin Pop committed
53

54

55
56
__all__ = [
  # Command line options
57
  "ABSOLUTE_OPT",
58
  "ADD_UIDS_OPT",
59
  "ADD_RESERVED_IPS_OPT",
60
  "ALLOCATABLE_OPT",
61
  "ALLOC_POLICY_OPT",
62
  "ALL_OPT",
63
  "ALLOW_FAILOVER_OPT",
64
  "AUTO_PROMOTE_OPT",
65
  "AUTO_REPLACE_OPT",
66
  "BACKEND_OPT",
67
  "BLK_OS_OPT",
68
  "CAPAB_MASTER_OPT",
Iustin Pop's avatar
Iustin Pop committed
69
  "CAPAB_VM_OPT",
70
  "CLEANUP_OPT",
Michael Hanselmann's avatar
Michael Hanselmann committed
71
  "CLUSTER_DOMAIN_SECRET_OPT",
72
  "CONFIRM_OPT",
73
  "CP_SIZE_OPT",
74
  "DEBUG_OPT",
75
  "DEBUG_SIMERR_OPT",
76
  "DISKIDX_OPT",
77
  "DISK_OPT",
78
  "DISK_PARAMS_OPT",
79
  "DISK_TEMPLATE_OPT",
80
  "DRAINED_OPT",
81
  "DRY_RUN_OPT",
82
  "DRBD_HELPER_OPT",
83
  "DST_NODE_OPT",
84
  "EARLY_RELEASE_OPT",
85
  "ENABLED_HV_OPT",
86
  "ENABLED_DISK_TEMPLATES_OPT",
87
  "ERROR_CODES_OPT",
88
  "FAILURE_ONLY_OPT",
89
  "FIELDS_OPT",
90
  "FILESTORE_DIR_OPT",
91
  "FILESTORE_DRIVER_OPT",
92
  "FORCE_FILTER_OPT",
93
94
  "FORCE_OPT",
  "FORCE_VARIANT_OPT",
95
96
  "GATEWAY_OPT",
  "GATEWAY6_OPT",
97
  "GLOBAL_FILEDIR_OPT",
98
  "HID_OS_OPT",
99
  "GLOBAL_GLUSTER_FILEDIR_OPT",
100
  "GLOBAL_SHARED_FILEDIR_OPT",
Dimitris Aragiorgis's avatar
Dimitris Aragiorgis committed
101
  "HOTPLUG_OPT",
102
  "HOTPLUG_IF_POSSIBLE_OPT",
103
  "HVLIST_OPT",
104
  "HVOPTS_OPT",
105
  "HYPERVISOR_OPT",
106
  "IALLOCATOR_OPT",
107
  "DEFAULT_IALLOCATOR_OPT",
108
  "DEFAULT_IALLOCATOR_PARAMS_OPT",
109
  "IDENTIFY_DEFAULTS_OPT",
110
  "IGNORE_CONSIST_OPT",
111
  "IGNORE_ERRORS_OPT",
112
  "IGNORE_FAILURES_OPT",
113
  "IGNORE_OFFLINE_OPT",
114
  "IGNORE_REMOVE_FAILURES_OPT",
115
  "IGNORE_SECONDARIES_OPT",
116
  "IGNORE_SIZE_OPT",
117
  "INCLUDEDEFAULTS_OPT",
Michael Hanselmann's avatar
Michael Hanselmann committed
118
  "INTERVAL_OPT",
119
  "INSTANCE_COMMUNICATION_OPT",
120
  "MAC_PREFIX_OPT",
121
  "MAINTAIN_NODE_HEALTH_OPT",
122
  "MASTER_NETDEV_OPT",
123
  "MASTER_NETMASK_OPT",
124
  "MC_OPT",
125
  "MIGRATION_MODE_OPT",
126
  "MODIFY_ETCHOSTS_OPT",
Iustin Pop's avatar
Iustin Pop committed
127
  "NET_OPT",
128
129
  "NETWORK_OPT",
  "NETWORK6_OPT",
130
  "NEW_CLUSTER_CERT_OPT",
131
  "NEW_NODE_CERT_OPT",
Michael Hanselmann's avatar
Michael Hanselmann committed
132
  "NEW_CLUSTER_DOMAIN_SECRET_OPT",
133
  "NEW_CONFD_HMAC_KEY_OPT",
134
  "NEW_RAPI_CERT_OPT",
135
  "NEW_PRIMARY_OPT",
136
  "NEW_SECONDARY_OPT",
137
  "NEW_SPICE_CERT_OPT",
138
  "NIC_PARAMS_OPT",
139
  "NOCONFLICTSCHECK_OPT",
140
  "NODE_FORCE_JOIN_OPT",
141
  "NODE_LIST_OPT",
142
  "NODE_PLACEMENT_OPT",
143
  "NODEGROUP_OPT",
144
  "NODE_PARAMS_OPT",
145
  "NODE_POWERED_OPT",
146
  "NOHDR_OPT",
147
  "NOIPCHECK_OPT",
148
  "NO_INSTALL_OPT",
149
  "NONAMECHECK_OPT",
150
  "NOMODIFY_ETCHOSTS_OPT",
151
  "NOMODIFY_SSH_SETUP_OPT",
Iustin Pop's avatar
Iustin Pop committed
152
  "NONICS_OPT",
Iustin Pop's avatar
Iustin Pop committed
153
  "NONLIVE_OPT",
154
  "NONPLUS1_OPT",
155
  "NORUNTIME_CHGS_OPT",
156
  "NOSHUTDOWN_OPT",
157
  "NOSTART_OPT",
158
  "NOSSH_KEYCHECK_OPT",
159
  "NOVOTING_OPT",
160
  "NO_REMEMBER_OPT",
161
  "NWSYNC_OPT",
162
163
  "OFFLINE_INST_OPT",
  "ONLINE_INST_OPT",
164
  "ON_PRIMARY_OPT",
165
  "ON_SECONDARY_OPT",
166
  "OFFLINE_OPT",
167
  "OS_OPT",
168
  "OSPARAMS_OPT",
169
170
  "OSPARAMS_PRIVATE_OPT",
  "OSPARAMS_SECRET_OPT",
Iustin Pop's avatar
Iustin Pop committed
171
  "OS_SIZE_OPT",
172
  "OOB_TIMEOUT_OPT",
173
  "POWER_DELAY_OPT",
174
  "PREALLOC_WIPE_DISKS_OPT",
175
  "PRIMARY_IP_VERSION_OPT",
176
  "PRIMARY_ONLY_OPT",
177
  "PRINT_JOBID_OPT",
178
  "PRIORITY_OPT",
179
  "RAPI_CERT_OPT",
180
  "READD_OPT",
181
  "REASON_OPT",
182
  "REBOOT_TYPE_OPT",
183
  "REMOVE_INSTANCE_OPT",
184
  "REMOVE_RESERVED_IPS_OPT",
185
  "REMOVE_UIDS_OPT",
186
  "RESERVED_LVS_OPT",
187
  "RQL_OPT",
188
  "INSTANCE_COMMUNICATION_NETWORK_OPT",
189
  "RUNTIME_MEM_OPT",
190
  "ROMAN_OPT",
191
  "SECONDARY_IP_OPT",
192
  "SECONDARY_ONLY_OPT",
193
  "SELECT_OS_OPT",
194
  "SEP_OPT",
195
  "SHOWCMD_OPT",
196
  "SHOW_MACHINE_OPT",
197
  "COMPRESS_OPT",
198
  "TRANSPORT_COMPRESSION_OPT",
Guido Trotter's avatar
Guido Trotter committed
199
  "SHUTDOWN_TIMEOUT_OPT",
200
  "SINGLE_NODE_OPT",
201
202
203
204
205
  "SPECS_CPU_COUNT_OPT",
  "SPECS_DISK_COUNT_OPT",
  "SPECS_DISK_SIZE_OPT",
  "SPECS_MEM_SIZE_OPT",
  "SPECS_NIC_COUNT_OPT",
206
  "SPLIT_ISPECS_OPTS",
207
  "IPOLICY_STD_SPECS_OPT",
208
  "IPOLICY_DISK_TEMPLATES",
209
  "IPOLICY_VCPU_RATIO",
210
211
  "SPICE_CACERT_OPT",
  "SPICE_CERT_OPT",
212
213
  "SRC_DIR_OPT",
  "SRC_NODE_OPT",
214
  "SUBMIT_OPT",
215
  "SUBMIT_OPTS",
216
  "STARTUP_PAUSED_OPT",
217
  "STATIC_OPT",
218
  "SYNC_OPT",
219
  "TAG_ADD_OPT",
220
  "TAG_SRC_OPT",
Guido Trotter's avatar
Guido Trotter committed
221
  "TIMEOUT_OPT",
222
  "TO_GROUP_OPT",
223
  "UIDPOOL_OPT",
224
  "USEUNITS_OPT",
225
  "USE_EXTERNAL_MIP_SCRIPT",
226
  "USE_REPL_NET_OPT",
227
  "VERBOSE_OPT",
Iustin Pop's avatar
Iustin Pop committed
228
  "VG_NAME_OPT",
229
  "WFSYNC_OPT",
230
  "YES_DOIT_OPT",
Hrvoje Ribicic's avatar
Hrvoje Ribicic committed
231
  "ZEROING_IMAGE_OPT",
232
  "ZERO_FREE_SPACE_OPT",
233
234
  "ZEROING_TIMEOUT_FIXED_OPT",
  "ZEROING_TIMEOUT_PER_MIB_OPT",
235
236
  "DISK_STATE_OPT",
  "HV_STATE_OPT",
237
  "IGNORE_IPOLICY_OPT",
238
  "INSTANCE_POLICY_OPTS",
239
  # Generic functions for CLI programs
240
  "ConfirmOperation",
241
  "CreateIPolicyFromOpts",
242
  "GenericMain",
Iustin Pop's avatar
Iustin Pop committed
243
  "GenericInstanceCreate",
244
245
  "GenericList",
  "GenericListFields",
246
247
  "GetClient",
  "GetOnlineNodes",
248
  "GetNodesSshPorts",
249
250
251
  "JobExecutor",
  "JobSubmittedException",
  "ParseTimespec",
252
  "RunWhileClusterStopped",
253
  "SubmitOpCode",
254
  "SubmitOpCodeToDrainedQueue",
255
256
257
258
259
  "SubmitOrSend",
  "UsesRPC",
  # Formatting functions
  "ToStderr", "ToStdout",
  "FormatError",
260
  "FormatQueryResult",
261
  "FormatParamsDictInfo",
262
  "FormatPolicyInfo",
263
  "PrintIPolicyCommand",
264
  "PrintGenericInfo",
265
266
267
  "GenerateTable",
  "AskUser",
  "FormatTimestamp",
268
  "FormatLogMessage",
269
270
271
272
273
274
275
  # Tags functions
  "ListTags",
  "AddTags",
  "RemoveTags",
  # command line options support infrastructure
  "ARGS_MANY_INSTANCES",
  "ARGS_MANY_NODES",
276
  "ARGS_MANY_GROUPS",
277
  "ARGS_MANY_NETWORKS",
278
279
280
  "ARGS_NONE",
  "ARGS_ONE_INSTANCE",
  "ARGS_ONE_NODE",
281
  "ARGS_ONE_GROUP",
282
  "ARGS_ONE_OS",
283
  "ARGS_ONE_NETWORK",
284
285
286
  "ArgChoice",
  "ArgCommand",
  "ArgFile",
287
  "ArgGroup",
288
289
290
  "ArgHost",
  "ArgInstance",
  "ArgJobId",
291
  "ArgNetwork",
292
  "ArgNode",
293
  "ArgOs",
294
  "ArgExtStorage",
295
296
297
298
299
300
301
  "ArgSuggest",
  "ArgUnknown",
  "OPT_COMPL_INST_ADD_NODES",
  "OPT_COMPL_MANY_NODES",
  "OPT_COMPL_ONE_IALLOCATOR",
  "OPT_COMPL_ONE_INSTANCE",
  "OPT_COMPL_ONE_NODE",
302
  "OPT_COMPL_ONE_NODEGROUP",
303
  "OPT_COMPL_ONE_NETWORK",
304
  "OPT_COMPL_ONE_OS",
305
  "OPT_COMPL_ONE_EXTSTORAGE",
306
  "cli_option",
307
  "FixHvParams",
308
  "SplitNodeOption",
Guido Trotter's avatar
Guido Trotter committed
309
  "CalculateOSNames",
310
  "ParseFields",
311
  "COMMON_CREATE_OPTS",
312
  ]
313

314
315
NO_PREFIX = "no_"
UN_PREFIX = "-"
316

317
318
319
320
321
322
323
324
325
326
327
328
#: Priorities (sorted)
_PRIORITY_NAMES = [
  ("low", constants.OP_PRIO_LOW),
  ("normal", constants.OP_PRIO_NORMAL),
  ("high", constants.OP_PRIO_HIGH),
  ]

#: Priority dictionary for easier lookup
# TODO: Replace this and _PRIORITY_NAMES with a single sorted dictionary once
# we migrate to Python 2.6
_PRIONAME_TO_VALUE = dict(_PRIORITY_NAMES)

329
330
331
332
333
# Query result status for clients
(QR_NORMAL,
 QR_UNKNOWN,
 QR_INCOMPLETE) = range(3)

334
335
336
#: Maximum batch size for ChooseJob
_CHOOSE_BATCH = 25

337

338
339
340
341
342
343
344
345
346
347
348
349
# constants used to create InstancePolicy dictionary
TISPECS_GROUP_TYPES = {
  constants.ISPECS_MIN: constants.VTYPE_INT,
  constants.ISPECS_MAX: constants.VTYPE_INT,
  }

TISPECS_CLUSTER_TYPES = {
  constants.ISPECS_MIN: constants.VTYPE_INT,
  constants.ISPECS_MAX: constants.VTYPE_INT,
  constants.ISPECS_STD: constants.VTYPE_INT,
  }

350
351
352
353
354
355
#: User-friendly names for query2 field types
_QFT_NAMES = {
  constants.QFT_UNKNOWN: "Unknown",
  constants.QFT_TEXT: "Text",
  constants.QFT_BOOL: "Boolean",
  constants.QFT_NUMBER: "Number",
Klaus Aehlig's avatar
Klaus Aehlig committed
356
  constants.QFT_NUMBER_FLOAT: "Floating-point number",
357
358
359
360
361
  constants.QFT_UNIT: "Storage size",
  constants.QFT_TIMESTAMP: "Timestamp",
  constants.QFT_OTHER: "Custom",
  }

362

363
class _Argument:
364
  def __init__(self, min=0, max=None): # pylint: disable=W0622
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    self.min = min
    self.max = max

  def __repr__(self):
    return ("<%s min=%s max=%s>" %
            (self.__class__.__name__, self.min, self.max))


class ArgSuggest(_Argument):
  """Suggesting argument.

  Value can be any of the ones passed to the constructor.

  """
379
  # pylint: disable=W0622
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
  def __init__(self, min=0, max=None, choices=None):
    _Argument.__init__(self, min=min, max=max)
    self.choices = choices

  def __repr__(self):
    return ("<%s min=%s max=%s choices=%r>" %
            (self.__class__.__name__, self.min, self.max, self.choices))


class ArgChoice(ArgSuggest):
  """Choice argument.

  Value can be any of the ones passed to the constructor. Like L{ArgSuggest},
  but value must be one of the choices.

  """


class ArgUnknown(_Argument):
  """Unknown argument to program (e.g. determined at runtime).

  """


class ArgInstance(_Argument):
  """Instances argument.

  """


class ArgNode(_Argument):
  """Node argument.

  """

415

416
417
418
419
420
class ArgNetwork(_Argument):
  """Network argument.

  """

421

422
423
424
425
426
427
class ArgGroup(_Argument):
  """Node group argument.

  """


428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
class ArgJobId(_Argument):
  """Job ID argument.

  """


class ArgFile(_Argument):
  """File path argument.

  """


class ArgCommand(_Argument):
  """Command argument.

  """


Michael Hanselmann's avatar
Michael Hanselmann committed
446
447
448
449
450
451
class ArgHost(_Argument):
  """Host argument.

  """


452
453
454
455
456
457
class ArgOs(_Argument):
  """OS argument.

  """


458
459
460
461
462
463
class ArgExtStorage(_Argument):
  """ExtStorage argument.

  """


464
465
ARGS_NONE = []
ARGS_MANY_INSTANCES = [ArgInstance()]
466
ARGS_MANY_NETWORKS = [ArgNetwork()]
467
ARGS_MANY_NODES = [ArgNode()]
468
ARGS_MANY_GROUPS = [ArgGroup()]
469
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
470
ARGS_ONE_NETWORK = [ArgNetwork(min=1, max=1)]
471
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
472
473
# TODO
ARGS_ONE_GROUP = [ArgGroup(min=1, max=1)]
474
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
475
476


477
478
479
480
481
482
483
484
485
486
def _ExtractTagsObject(opts, args):
  """Extract the tag type object.

  Note that this function will modify its args parameter.

  """
  if not hasattr(opts, "tag_type"):
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
  kind = opts.tag_type
  if kind == constants.TAG_CLUSTER:
Jose A. Lopes's avatar
Jose A. Lopes committed
487
    retval = kind, ""
488
489
  elif kind in (constants.TAG_NODEGROUP,
                constants.TAG_NODE,
490
                constants.TAG_NETWORK,
491
                constants.TAG_INSTANCE):
492
    if not args:
493
494
      raise errors.OpPrereqError("no arguments passed to the command",
                                 errors.ECODE_INVAL)
495
496
497
498
499
500
501
    name = args.pop(0)
    retval = kind, name
  else:
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
  return retval


502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def _ExtendTags(opts, args):
  """Extend the args if a source file has been given.

  This function will extend the tags with the contents of the file
  passed in the 'tags_source' attribute of the opts parameter. A file
  named '-' will be replaced by stdin.

  """
  fname = opts.tags_source
  if fname is None:
    return
  if fname == "-":
    new_fh = sys.stdin
  else:
    new_fh = open(fname, "r")
  new_data = []
  try:
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
    # because of python bug 1633941
    while True:
      line = new_fh.readline()
      if not line:
        break
      new_data.append(line.strip())
  finally:
    new_fh.close()
  args.extend(new_data)


531
532
533
534
535
536
537
538
539
540
def ListTags(opts, args):
  """List the tags on a given object.

  This is a generic implementation that knows how to deal with all
  three cases of tag objects (cluster, node, instance). The opts
  argument is expected to contain a tag_type field denoting what
  object type we work on.

  """
  kind, name = _ExtractTagsObject(opts, args)
541
  cl = GetClient()
Iustin Pop's avatar
Iustin Pop committed
542
  result = cl.QueryTags(kind, name)
543
544
545
  result = list(result)
  result.sort()
  for tag in result:
546
    ToStdout(tag)
547
548
549
550
551
552
553
554
555
556
557
558


def AddTags(opts, args):
  """Add tags on a given object.

  This is a generic implementation that knows how to deal with all
  three cases of tag objects (cluster, node, instance). The opts
  argument is expected to contain a tag_type field denoting what
  object type we work on.

  """
  kind, name = _ExtractTagsObject(opts, args)
559
  _ExtendTags(opts, args)
560
  if not args:
561
    raise errors.OpPrereqError("No tags to be added", errors.ECODE_INVAL)
Iustin Pop's avatar
Iustin Pop committed
562
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
563
  SubmitOrSend(op, opts)
564
565
566
567
568
569
570
571
572
573
574
575


def RemoveTags(opts, args):
  """Remove tags from a given object.

  This is a generic implementation that knows how to deal with all
  three cases of tag objects (cluster, node, instance). The opts
  argument is expected to contain a tag_type field denoting what
  object type we work on.

  """
  kind, name = _ExtractTagsObject(opts, args)
576
  _ExtendTags(opts, args)
577
  if not args:
578
    raise errors.OpPrereqError("No tags to be removed", errors.ECODE_INVAL)
Iustin Pop's avatar
Iustin Pop committed
579
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
580
  SubmitOrSend(op, opts)
581

Iustin Pop's avatar
Iustin Pop committed
582

583
def check_unit(option, opt, value): # pylint: disable=W0613
Iustin Pop's avatar
Iustin Pop committed
584
585
586
  """OptParsers custom converter for units.

  """
Iustin Pop's avatar
Iustin Pop committed
587
588
589
  try:
    return utils.ParseUnit(value)
  except errors.UnitParseError, err:
590
    raise OptionValueError("option %s: %s" % (opt, err))
Iustin Pop's avatar
Iustin Pop committed
591
592


593
def _SplitKeyVal(opt, data, parse_prefixes):
594
595
596
597
  """Convert a KeyVal string into a dict.

  This function will convert a key=val[,...] string into a dict. Empty
  values will be converted specially: keys which have the prefix 'no_'
598
599
  will have the value=False and the prefix stripped, keys with the prefix
  "-" will have value=None and the prefix stripped, and the others will
600
601
602
603
604
605
606
  have value=True.

  @type opt: string
  @param opt: a string holding the option name for which we process the
      data, used in building error messages
  @type data: string
  @param data: a string of the format key=val,key=val,...
607
608
  @type parse_prefixes: bool
  @param parse_prefixes: whether to handle prefixes specially
609
610
611
612
613
614
  @rtype: dict
  @return: {key=val, key=val}
  @raises errors.ParameterError: if there are duplicate keys

  """
  kv_dict = {}
615
  if data:
616
    for elem in utils.UnescapeAndSplit(data, sep=","):
617
618
      if "=" in elem:
        key, val = elem.split("=", 1)
619
      elif parse_prefixes:
620
621
622
623
624
625
        if elem.startswith(NO_PREFIX):
          key, val = elem[len(NO_PREFIX):], False
        elif elem.startswith(UN_PREFIX):
          key, val = elem[len(UN_PREFIX):], None
        else:
          key, val = elem, True
626
627
628
      else:
        raise errors.ParameterError("Missing value for key '%s' in option %s" %
                                    (elem, opt))
629
630
631
632
      if key in kv_dict:
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
                                    (key, opt))
      kv_dict[key] = val
633
634
635
  return kv_dict


636
637
def _SplitIdentKeyVal(opt, value, parse_prefixes):
  """Helper function to parse "ident:key=val,key=val" options.
638

639
640
641
642
643
644
645
646
647
648
  @type opt: string
  @param opt: option name, used in error messages
  @type value: string
  @param value: expected to be in the format "ident:key=val,key=val,..."
  @type parse_prefixes: bool
  @param parse_prefixes: whether to handle prefixes specially (see
      L{_SplitKeyVal})
  @rtype: tuple
  @return: (ident, {key=val, key=val})
  @raises errors.ParameterError: in case of duplicates or other parsing errors
649
650
651

  """
  if ":" not in value:
Iustin Pop's avatar
Iustin Pop committed
652
    ident, rest = value, ""
653
654
  else:
    ident, rest = value.split(":", 1)
655

656
  if parse_prefixes and ident.startswith(NO_PREFIX):
657
658
659
660
    if rest:
      msg = "Cannot pass options when removing parameter groups: %s" % value
      raise errors.ParameterError(msg)
    retval = (ident[len(NO_PREFIX):], False)
661
662
  elif (parse_prefixes and ident.startswith(UN_PREFIX) and
        (len(ident) <= len(UN_PREFIX) or not ident[len(UN_PREFIX)].isdigit())):
663
664
665
666
667
    if rest:
      msg = "Cannot pass options when removing parameter groups: %s" % value
      raise errors.ParameterError(msg)
    retval = (ident[len(UN_PREFIX):], None)
  else:
668
    kv_dict = _SplitKeyVal(opt, rest, parse_prefixes)
669
670
671
672
    retval = (ident, kv_dict)
  return retval


673
674
675
676
677
678
679
680
681
682
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
  """Custom parser for ident:key=val,key=val options.

  This will store the parsed values as a tuple (ident, {key: val}). As such,
  multiple uses of this option via action=append is possible.

  """
  return _SplitIdentKeyVal(opt, value, True)


683
def check_key_val(option, opt, value):  # pylint: disable=W0613
684
685
686
  """Custom parser class for key=val,key=val options.

  This will store the parsed values as a dict {key: val}.
687
688

  """
689
690
691
  return _SplitKeyVal(opt, value, True)


692
693
694
695
696
697
698
699
700
def check_key_private_val(option, opt, value):  # pylint: disable=W0613
  """Custom parser class for private and secret key=val,key=val options.

  This will store the parsed values as a dict {key: val}.

  """
  return serializer.PrivateDict(_SplitKeyVal(opt, value, True))


701
702
703
704
705
706
707
708
709
710
711
712
713
714
def _SplitListKeyVal(opt, value):
  retval = {}
  for elem in value.split("/"):
    if not elem:
      raise errors.ParameterError("Empty section in option '%s'" % opt)
    (ident, valdict) = _SplitIdentKeyVal(opt, elem, False)
    if ident in retval:
      msg = ("Duplicated parameter '%s' in parsing %s: %s" %
             (ident, opt, elem))
      raise errors.ParameterError(msg)
    retval[ident] = valdict
  return retval


715
716
def check_multilist_ident_key_val(_, opt, value):
  """Custom parser for "ident:key=val,key=val/ident:key=val//ident:.." options.
717
718

  @rtype: list of dictionary
719
  @return: [{ident: {key: val, key: val}, ident: {key: val}}, {ident:..}]
720
721

  """
722
723
724
725
  retval = []
  for line in value.split("//"):
    retval.append(_SplitListKeyVal(opt, line))
  return retval
726
727


728
def check_bool(option, opt, value): # pylint: disable=W0613
Iustin Pop's avatar
Iustin Pop committed
729
730
731
732
733
734
735
736
737
738
739
740
741
742
  """Custom parser for yes/no options.

  This will store the parsed value as either True or False.

  """
  value = value.lower()
  if value == constants.VALUE_FALSE or value == "no":
    return False
  elif value == constants.VALUE_TRUE or value == "yes":
    return True
  else:
    raise errors.ParameterError("Invalid boolean value '%s'" % value)


Iustin Pop's avatar
Iustin Pop committed
743
744
745
746
747
748
749
750
751
752
753
754
def check_list(option, opt, value): # pylint: disable=W0613
  """Custom parser for comma-separated lists.

  """
  # we have to make this explicit check since "".split(",") is [""],
  # not an empty list :(
  if not value:
    return []
  else:
    return utils.UnescapeAndSplit(value)


755
756
757
758
759
760
761
762
763
764
765
766
def check_maybefloat(option, opt, value): # pylint: disable=W0613
  """Custom parser for float numbers which might be also defaults.

  """
  value = value.lower()

  if value == constants.VALUE_DEFAULT:
    return value
  else:
    return float(value)


767
768
769
770
771
772
# completion_suggestion is normally a list. Using numeric values not evaluating
# to False for dynamic completion.
(OPT_COMPL_MANY_NODES,
 OPT_COMPL_ONE_NODE,
 OPT_COMPL_ONE_INSTANCE,
 OPT_COMPL_ONE_OS,
773
 OPT_COMPL_ONE_EXTSTORAGE,
774
 OPT_COMPL_ONE_IALLOCATOR,
775
 OPT_COMPL_ONE_NETWORK,
776
 OPT_COMPL_INST_ADD_NODES,
777
 OPT_COMPL_ONE_NODEGROUP) = range(100, 109)
778

779
OPT_COMPL_ALL = compat.UniqueFrozenset([
780
781
782
783
  OPT_COMPL_MANY_NODES,
  OPT_COMPL_ONE_NODE,
  OPT_COMPL_ONE_INSTANCE,
  OPT_COMPL_ONE_OS,
784
  OPT_COMPL_ONE_EXTSTORAGE,
785
  OPT_COMPL_ONE_IALLOCATOR,
786
  OPT_COMPL_ONE_NETWORK,
787
  OPT_COMPL_INST_ADD_NODES,
788
  OPT_COMPL_ONE_NODEGROUP,
789
790
791
  ])


792
793
class CliOption(Option):
  """Custom option class for optparse.
794
795

  """
796
797
798
  ATTRS = Option.ATTRS + [
    "completion_suggest",
    ]
799
  TYPES = Option.TYPES + (
800
    "multilistidentkeyval",
801
802
    "identkeyval",
    "keyval",
803
    "keyprivateval",
804
    "unit",
Iustin Pop's avatar
Iustin Pop committed
805
    "bool",
Iustin Pop's avatar
Iustin Pop committed
806
    "list",
807
    "maybefloat",
808
809
    )
  TYPE_CHECKER = Option.TYPE_CHECKER.copy()
810
  TYPE_CHECKER["multilistidentkeyval"] = check_multilist_ident_key_val
811
  TYPE_CHECKER["identkeyval"] = check_ident_key_val
812
  TYPE_CHECKER["keyval"] = check_key_val
813
  TYPE_CHECKER["keyprivateval"] = check_key_private_val
814
  TYPE_CHECKER["unit"] = check_unit
Iustin Pop's avatar
Iustin Pop committed
815
  TYPE_CHECKER["bool"] = check_bool
Iustin Pop's avatar
Iustin Pop committed
816
  TYPE_CHECKER["list"] = check_list
817
  TYPE_CHECKER["maybefloat"] = check_maybefloat
818
819


Iustin Pop's avatar
Iustin Pop committed
820
821
822
823
# optparse.py sets make_option, so we do it for our own option class, too
cli_option = CliOption


824
825
_YORNO = "yes|no"

826
827
DEBUG_OPT = cli_option("-d", "--debug", default=0, action="count",
                       help="Increase debugging level")
828
829
830
831
832
833
834
835
836
837
838

NOHDR_OPT = cli_option("--no-headers", default=False,
                       action="store_true", dest="no_headers",
                       help="Don't display column headers")

SEP_OPT = cli_option("--separator", default=None,
                     action="store", dest="separator",
                     help=("Separator between output fields"
                           " (defaults to one space)"))

USEUNITS_OPT = cli_option("--units", default=None,
Iustin Pop's avatar
Iustin Pop committed
839
                          dest="units", choices=("h", "m", "g", "t"),
840
                          help="Specify units for output (one of h/m/g/t)")
841
842
843
844
845
846
847
848
849
850
851

FIELDS_OPT = cli_option("-o", "--output", dest="output", action="store",
                        type="string", metavar="FIELDS",
                        help="Comma separated list of output fields")

FORCE_OPT = cli_option("-f", "--force", dest="force", action="store_true",
                       default=False, help="Force the operation")

CONFIRM_OPT = cli_option("--yes", dest="confirm", action="store_true",
                         default=False, help="Do not require confirmation")

852
853
854
855
856
IGNORE_OFFLINE_OPT = cli_option("--ignore-offline", dest="ignore_offline",
                                  action="store_true", default=False,
                                  help=("Ignore offline nodes and do as much"
                                        " as possible"))

857
858
859
860
TAG_ADD_OPT = cli_option("--tags", dest="tags",
                         default=None, help="Comma-separated list of instance"
                                            " tags")

861
862
863
864
865
866
867
868
TAG_SRC_OPT = cli_option("--from", dest="tags_source",
                         default=None, help="File with tag names")

SUBMIT_OPT = cli_option("--submit", dest="submit_only",
                        default=False, action="store_true",
                        help=("Submit the job and return the job ID, but"
                              " don't wait for the job to finish"))

869
870
871
872
873
PRINT_JOBID_OPT = cli_option("--print-jobid", dest="print_jobid",
                             default=False, action="store_true",
                             help=("Additionally print the job as first line"
                                   " on stdout (for scripting)."))

874
875
876
877
878
SYNC_OPT = cli_option("--sync", dest="do_locking",
                      default=False, action="store_true",
                      help=("Grab locks while doing the queries"
                            " in order to ensure more consistent results"))

879
880
881
DRY_RUN_OPT = cli_option("--dry-run", default=False,
                         action="store_true",
                         help=("Do not execute the operation, just run the"
Michael Hanselmann's avatar
Michael Hanselmann committed
882
                               " check steps and verify if it could be"
883
                               " executed"))
884

885
886
887
888
VERBOSE_OPT = cli_option("-v", "--verbose", default=False,
                         action="store_true",
                         help="Increase the verbosity of the operation")

889
890
891
892
893
DEBUG_SIMERR_OPT = cli_option("--debug-simulate-errors", default=False,
                              action="store_true", dest="simulate_errors",
                              help="Debugging option that makes the operation"
                              " treat most runtime checks as failed")

894
895
896
897
NWSYNC_OPT = cli_option("--no-wait-for-sync", dest="wait_for_sync",
                        default=True, action="store_false",
                        help="Don't wait for sync (DANGEROUS!)")

898
899
900
901
WFSYNC_OPT = cli_option("--wait-for-sync", dest="wait_for_sync",
                        default=False, action="store_true",
                        help="Wait for disks to sync")

902
903
904
905
906
907
908
909
ONLINE_INST_OPT = cli_option("--online", dest="online_inst",
                             action="store_true", default=False,
                             help="Enable offline instance")

OFFLINE_INST_OPT = cli_option("--offline", dest="offline_inst",
                              action="store_true", default=False,
                              help="Disable down instance")

910
DISK_TEMPLATE_OPT = cli_option("-t", "--disk-template", dest="disk_template",
911
912
                               help=("Custom disk setup (%s)" %
                                     utils.CommaJoin(constants.DISK_TEMPLATES)),
913
914
915
                               default=None, metavar="TEMPL",
                               choices=list(constants.DISK_TEMPLATES))

Iustin Pop's avatar
Iustin Pop committed
916
917
918
919
NONICS_OPT = cli_option("--no-nics", default=False, action="store_true",
                        help="Do not create any network cards for"
                        " the instance")

920
921
922
923
924
FILESTORE_DIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
                               help="Relative path under default cluster-wide"
                               " file storage dir to store file-based disks",
                               default=None, metavar="<DIR>")

925
926
FILESTORE_DRIVER_OPT = cli_option("--file-driver", dest="file_driver",
                                  help="Driver to use for image files",
927
                                  default=None, metavar="<DRIVER>",
928
929
                                  choices=list(constants.FILE_DRIVER))

930
931
932
933
934
935
IALLOCATOR_OPT = cli_option("-I", "--iallocator", metavar="<NAME>",
                            help="Select nodes for the instance automatically"
                            " using the <NAME> iallocator plugin",
                            default=None, type="string",
                            completion_suggest=OPT_COMPL_ONE_IALLOCATOR)

936
DEFAULT_IALLOCATOR_OPT = cli_option("-I", "--default-iallocator",
Iustin Pop's avatar
Iustin Pop committed
937
938
939
940
941
                                    metavar="<NAME>",
                                    help="Set the default instance"
                                    " allocator plugin",
                                    default=None, type="string",
                                    completion_suggest=OPT_COMPL_ONE_IALLOCATOR)
942

943
944
945
946
947
948
949
950
951
DEFAULT_IALLOCATOR_PARAMS_OPT = cli_option("--default-iallocator-params",
                                           dest="default_iallocator_params",
                                           help="iallocator template"
                                           " parameters, in the format"
                                           " template:option=value,"
                                           " option=value,...",
                                           type="keyval",
                                           default={})

Iustin Pop's avatar
Iustin Pop committed
952
953
954
955
OS_OPT = cli_option("-o", "--os-type", dest="os", help="What OS to run",
                    metavar="<os>",
                    completion_suggest=OPT_COMPL_ONE_OS)

956
OSPARAMS_OPT = cli_option("-O", "--os-parameters", dest="osparams",
Iustin Pop's avatar
Iustin Pop committed
957
958
                          type="keyval", default={},
                          help="OS parameters")
959

960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
OSPARAMS_PRIVATE_OPT = cli_option("--os-parameters-private",
                                  dest="osparams_private",
                                  type="keyprivateval",
                                  default=serializer.PrivateDict(),
                                  help="Private OS parameters"
                                       " (won't be logged)")

OSPARAMS_SECRET_OPT = cli_option("--os-parameters-secret",
                                 dest="osparams_secret",
                                 type="keyprivateval",
                                 default=serializer.PrivateDict(),
                                 help="Secret OS parameters (won't be logged or"
                                      " saved; you must supply these for every"
                                      " operation.)")

975
976
977
978
FORCE_VARIANT_OPT = cli_option("--force-variant", dest="force_variant",
                               action="store_true", default=False,
                               help="Force an unknown variant")

979
980
981
982
983
NO_INSTALL_OPT = cli_option("--no-install", dest="no_install",
                            action="store_true", default=False,
                            help="Do not install the OS (will"
                            " enable no-start)")

984
985
986
987
988
NORUNTIME_CHGS_OPT = cli_option("--no-runtime-changes",
                                dest="allow_runtime_chgs",
                                default=True, action="store_false",
                                help="Don't allow runtime changes")

989
990
991
BACKEND_OPT = cli_option("-B", "--backend-parameters", dest="beparams",
                         type="keyval", default={},
                         help="Backend parameters")
992

Michael Hanselmann's avatar
Michael Hanselmann committed
993
994
995
HVOPTS_OPT = cli_option("-H", "--hypervisor-parameters", type="keyval",
                        default={}, dest="hvparams",
                        help="Hypervisor parameters")
996

997
998
999
1000
1001
DISK_PARAMS_OPT = cli_option("-D", "--disk-parameters", dest="diskparams",
                             help="Disk template parameters, in the format"
                             " template:option=value,option=value,...",
                             type="identkeyval", action="append", default=[])

1002
1003
SPECS_MEM_SIZE_OPT = cli_option("--specs-mem-size", dest="ispecs_mem_size",
                                 type="keyval", default={},
1004
1005
1006
                                 help="Memory size specs: list of key=value,"
                                " where key is one of min, max, std"
                                 " (in MB or using a unit)")
1007
1008
1009

SPECS_CPU_COUNT_OPT = cli_option("--specs-cpu-count", dest="ispecs_cpu_count",
                                 type="keyval", default={},
1010
1011
                                 help="CPU count specs: list of key=value,"
                                 " where key is one of min, max, std")
1012
1013
1014
1015

SPECS_DISK_COUNT_OPT = cli_option("--specs-disk-count",
                                  dest="ispecs_disk_count",
                                  type="keyval", default={},
1016
1017
                                  help="Disk count specs: list of key=value,"
                                  " where key is one of min, max, std")
1018
1019
1020

SPECS_DISK_SIZE_OPT = cli_option("--specs-disk-size", dest="ispecs_disk_size",
                                 type="keyval", default={},
1021
                                 help="Disk size specs: list of key=value,"
Iustin Pop's avatar
Iustin Pop committed
1022
                                 " where key is one of min, max, std"
1023
                                 " (in MB or using a unit)")
1024
1025
1026

SPECS_NIC_COUNT_OPT = cli_option("--specs-nic-count", dest="ispecs_nic_count",
                                 type="keyval", default={},
1027
1028
                                 help="NIC count specs: list of key=value,"
                                 " where key is one of min, max, std")
1029

1030
1031
1032
IPOLICY_BOUNDS_SPECS_STR = "--ipolicy-bounds-specs"
IPOLICY_BOUNDS_SPECS_OPT = cli_option(IPOLICY_BOUNDS_SPECS_STR,
                                      dest="ipolicy_bounds_specs",
1033
                                      type="multilistidentkeyval", default=None,
1034
1035
1036
1037
1038
1039
1040
1041
                                      help="Complete instance specs limits")

IPOLICY_STD_SPECS_STR = "--ipolicy-std-specs"
IPOLICY_STD_SPECS_OPT = cli_option(IPOLICY_STD_SPECS_STR,
                                   dest="ipolicy_std_specs",
                                   type="keyval", default=None,
                                   help="Complte standard instance specs")

1042
IPOLICY_DISK_TEMPLATES = cli_option("--ipolicy-disk-templates",
Iustin Pop's avatar
Iustin Pop committed
1043
1044
1045
1046
                                    dest="ipolicy_disk_templates",
                                    type="list", default=None,
                                    help="Comma-separated list of"
                                    " enabled disk templates")
1047

1048
1049
IPOLICY_VCPU_RATIO = cli_option("--ipolicy-vcpu-ratio",
                                 dest="ipolicy_vcpu_ratio",
1050
                                 type="maybefloat", default=None,