Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 11b61970

History | View | Annotate | Download (136.3 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
"""Module dealing with command line parsing"""
23

    
24

    
25
import sys
26
import textwrap
27
import os.path
28
import time
29
import logging
30
import errno
31
import itertools
32
import shlex
33
from cStringIO import StringIO
34

    
35
from ganeti import utils
36
from ganeti import errors
37
from ganeti import constants
38
from ganeti import opcodes
39
from ganeti import luxi
40
from ganeti import ssconf
41
from ganeti import rpc
42
from ganeti import ssh
43
from ganeti import compat
44
from ganeti import netutils
45
from ganeti import qlang
46
from ganeti import objects
47
from ganeti import pathutils
48

    
49
from optparse import (OptionParser, TitledHelpFormatter,
50
                      Option, OptionValueError)
51

    
52

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

    
295
NO_PREFIX = "no_"
296
UN_PREFIX = "-"
297

    
298
#: Priorities (sorted)
299
_PRIORITY_NAMES = [
300
  ("low", constants.OP_PRIO_LOW),
301
  ("normal", constants.OP_PRIO_NORMAL),
302
  ("high", constants.OP_PRIO_HIGH),
303
  ]
304

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

    
310
# Query result status for clients
311
(QR_NORMAL,
312
 QR_UNKNOWN,
313
 QR_INCOMPLETE) = range(3)
314

    
315
#: Maximum batch size for ChooseJob
316
_CHOOSE_BATCH = 25
317

    
318

    
319
# constants used to create InstancePolicy dictionary
320
TISPECS_GROUP_TYPES = {
321
  constants.ISPECS_MIN: constants.VTYPE_INT,
322
  constants.ISPECS_MAX: constants.VTYPE_INT,
323
  }
324

    
325
TISPECS_CLUSTER_TYPES = {
326
  constants.ISPECS_MIN: constants.VTYPE_INT,
327
  constants.ISPECS_MAX: constants.VTYPE_INT,
328
  constants.ISPECS_STD: constants.VTYPE_INT,
329
  }
330

    
331
#: User-friendly names for query2 field types
332
_QFT_NAMES = {
333
  constants.QFT_UNKNOWN: "Unknown",
334
  constants.QFT_TEXT: "Text",
335
  constants.QFT_BOOL: "Boolean",
336
  constants.QFT_NUMBER: "Number",
337
  constants.QFT_UNIT: "Storage size",
338
  constants.QFT_TIMESTAMP: "Timestamp",
339
  constants.QFT_OTHER: "Custom",
340
  }
341

    
342

    
343
class _Argument:
344
  def __init__(self, min=0, max=None): # pylint: disable=W0622
345
    self.min = min
346
    self.max = max
347

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

    
352

    
353
class ArgSuggest(_Argument):
354
  """Suggesting argument.
355

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

358
  """
359
  # pylint: disable=W0622
360
  def __init__(self, min=0, max=None, choices=None):
361
    _Argument.__init__(self, min=min, max=max)
362
    self.choices = choices
363

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

    
368

    
369
class ArgChoice(ArgSuggest):
370
  """Choice argument.
371

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

375
  """
376

    
377

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

381
  """
382

    
383

    
384
class ArgInstance(_Argument):
385
  """Instances argument.
386

387
  """
388

    
389

    
390
class ArgNode(_Argument):
391
  """Node argument.
392

393
  """
394

    
395

    
396
class ArgNetwork(_Argument):
397
  """Network argument.
398

399
  """
400

    
401

    
402
class ArgGroup(_Argument):
403
  """Node group argument.
404

405
  """
406

    
407

    
408
class ArgJobId(_Argument):
409
  """Job ID argument.
410

411
  """
412

    
413

    
414
class ArgFile(_Argument):
415
  """File path argument.
416

417
  """
418

    
419

    
420
class ArgCommand(_Argument):
421
  """Command argument.
422

423
  """
424

    
425

    
426
class ArgHost(_Argument):
427
  """Host argument.
428

429
  """
430

    
431

    
432
class ArgOs(_Argument):
433
  """OS argument.
434

435
  """
436

    
437

    
438
class ArgExtStorage(_Argument):
439
  """ExtStorage argument.
440

441
  """
442

    
443

    
444
ARGS_NONE = []
445
ARGS_MANY_INSTANCES = [ArgInstance()]
446
ARGS_MANY_NETWORKS = [ArgNetwork()]
447
ARGS_MANY_NODES = [ArgNode()]
448
ARGS_MANY_GROUPS = [ArgGroup()]
449
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
450
ARGS_ONE_NETWORK = [ArgNetwork(min=1, max=1)]
451
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
452
# TODO
453
ARGS_ONE_GROUP = [ArgGroup(min=1, max=1)]
454
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
455

    
456

    
457
def _ExtractTagsObject(opts, args):
458
  """Extract the tag type object.
459

460
  Note that this function will modify its args parameter.
461

462
  """
463
  if not hasattr(opts, "tag_type"):
464
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
465
  kind = opts.tag_type
466
  if kind == constants.TAG_CLUSTER:
467
    retval = kind, None
468
  elif kind in (constants.TAG_NODEGROUP,
469
                constants.TAG_NODE,
470
                constants.TAG_NETWORK,
471
                constants.TAG_INSTANCE):
472
    if not args:
473
      raise errors.OpPrereqError("no arguments passed to the command",
474
                                 errors.ECODE_INVAL)
475
    name = args.pop(0)
476
    retval = kind, name
477
  else:
478
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
479
  return retval
480

    
481

    
482
def _ExtendTags(opts, args):
483
  """Extend the args if a source file has been given.
484

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

489
  """
490
  fname = opts.tags_source
491
  if fname is None:
492
    return
493
  if fname == "-":
494
    new_fh = sys.stdin
495
  else:
496
    new_fh = open(fname, "r")
497
  new_data = []
498
  try:
499
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
500
    # because of python bug 1633941
501
    while True:
502
      line = new_fh.readline()
503
      if not line:
504
        break
505
      new_data.append(line.strip())
506
  finally:
507
    new_fh.close()
508
  args.extend(new_data)
509

    
510

    
511
def ListTags(opts, args):
512
  """List the tags on a given object.
513

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

519
  """
520
  kind, name = _ExtractTagsObject(opts, args)
521
  cl = GetClient(query=True)
522
  result = cl.QueryTags(kind, name)
523
  result = list(result)
524
  result.sort()
525
  for tag in result:
526
    ToStdout(tag)
527

    
528

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

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

537
  """
538
  kind, name = _ExtractTagsObject(opts, args)
539
  _ExtendTags(opts, args)
540
  if not args:
541
    raise errors.OpPrereqError("No tags to be added", errors.ECODE_INVAL)
542
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
543
  SubmitOrSend(op, opts)
544

    
545

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

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

554
  """
555
  kind, name = _ExtractTagsObject(opts, args)
556
  _ExtendTags(opts, args)
557
  if not args:
558
    raise errors.OpPrereqError("No tags to be removed", errors.ECODE_INVAL)
559
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
560
  SubmitOrSend(op, opts)
561

    
562

    
563
def check_unit(option, opt, value): # pylint: disable=W0613
564
  """OptParsers custom converter for units.
565

566
  """
567
  try:
568
    return utils.ParseUnit(value)
569
  except errors.UnitParseError, err:
570
    raise OptionValueError("option %s: %s" % (opt, err))
571

    
572

    
573
def _SplitKeyVal(opt, data, parse_prefixes):
574
  """Convert a KeyVal string into a dict.
575

576
  This function will convert a key=val[,...] string into a dict. Empty
577
  values will be converted specially: keys which have the prefix 'no_'
578
  will have the value=False and the prefix stripped, keys with the prefix
579
  "-" will have value=None and the prefix stripped, and the others will
580
  have value=True.
581

582
  @type opt: string
583
  @param opt: a string holding the option name for which we process the
584
      data, used in building error messages
585
  @type data: string
586
  @param data: a string of the format key=val,key=val,...
587
  @type parse_prefixes: bool
588
  @param parse_prefixes: whether to handle prefixes specially
589
  @rtype: dict
590
  @return: {key=val, key=val}
591
  @raises errors.ParameterError: if there are duplicate keys
592

593
  """
594
  kv_dict = {}
595
  if data:
596
    for elem in utils.UnescapeAndSplit(data, sep=","):
597
      if "=" in elem:
598
        key, val = elem.split("=", 1)
599
      elif parse_prefixes:
600
        if elem.startswith(NO_PREFIX):
601
          key, val = elem[len(NO_PREFIX):], False
602
        elif elem.startswith(UN_PREFIX):
603
          key, val = elem[len(UN_PREFIX):], None
604
        else:
605
          key, val = elem, True
606
      else:
607
        raise errors.ParameterError("Missing value for key '%s' in option %s" %
608
                                    (elem, opt))
609
      if key in kv_dict:
610
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
611
                                    (key, opt))
612
      kv_dict[key] = val
613
  return kv_dict
614

    
615

    
616
def _SplitIdentKeyVal(opt, value, parse_prefixes):
617
  """Helper function to parse "ident:key=val,key=val" options.
618

619
  @type opt: string
620
  @param opt: option name, used in error messages
621
  @type value: string
622
  @param value: expected to be in the format "ident:key=val,key=val,..."
623
  @type parse_prefixes: bool
624
  @param parse_prefixes: whether to handle prefixes specially (see
625
      L{_SplitKeyVal})
626
  @rtype: tuple
627
  @return: (ident, {key=val, key=val})
628
  @raises errors.ParameterError: in case of duplicates or other parsing errors
629

630
  """
631
  if ":" not in value:
632
    ident, rest = value, ""
633
  else:
634
    ident, rest = value.split(":", 1)
635

    
636
  if parse_prefixes and ident.startswith(NO_PREFIX):
637
    if rest:
638
      msg = "Cannot pass options when removing parameter groups: %s" % value
639
      raise errors.ParameterError(msg)
640
    retval = (ident[len(NO_PREFIX):], False)
641
  elif (parse_prefixes and ident.startswith(UN_PREFIX) and
642
        (len(ident) <= len(UN_PREFIX) or not ident[len(UN_PREFIX)].isdigit())):
643
    if rest:
644
      msg = "Cannot pass options when removing parameter groups: %s" % value
645
      raise errors.ParameterError(msg)
646
    retval = (ident[len(UN_PREFIX):], None)
647
  else:
648
    kv_dict = _SplitKeyVal(opt, rest, parse_prefixes)
649
    retval = (ident, kv_dict)
650
  return retval
651

    
652

    
653
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
654
  """Custom parser for ident:key=val,key=val options.
655

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

659
  """
660
  return _SplitIdentKeyVal(opt, value, True)
661

    
662

    
663
def check_key_val(option, opt, value):  # pylint: disable=W0613
664
  """Custom parser class for key=val,key=val options.
665

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

668
  """
669
  return _SplitKeyVal(opt, value, True)
670

    
671

    
672
def _SplitListKeyVal(opt, value):
673
  retval = {}
674
  for elem in value.split("/"):
675
    if not elem:
676
      raise errors.ParameterError("Empty section in option '%s'" % opt)
677
    (ident, valdict) = _SplitIdentKeyVal(opt, elem, False)
678
    if ident in retval:
679
      msg = ("Duplicated parameter '%s' in parsing %s: %s" %
680
             (ident, opt, elem))
681
      raise errors.ParameterError(msg)
682
    retval[ident] = valdict
683
  return retval
684

    
685

    
686
def check_multilist_ident_key_val(_, opt, value):
687
  """Custom parser for "ident:key=val,key=val/ident:key=val//ident:.." options.
688

689
  @rtype: list of dictionary
690
  @return: [{ident: {key: val, key: val}, ident: {key: val}}, {ident:..}]
691

692
  """
693
  retval = []
694
  for line in value.split("//"):
695
    retval.append(_SplitListKeyVal(opt, line))
696
  return retval
697

    
698

    
699
def check_bool(option, opt, value): # pylint: disable=W0613
700
  """Custom parser for yes/no options.
701

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

704
  """
705
  value = value.lower()
706
  if value == constants.VALUE_FALSE or value == "no":
707
    return False
708
  elif value == constants.VALUE_TRUE or value == "yes":
709
    return True
710
  else:
711
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
712

    
713

    
714
def check_list(option, opt, value): # pylint: disable=W0613
715
  """Custom parser for comma-separated lists.
716

717
  """
718
  # we have to make this explicit check since "".split(",") is [""],
719
  # not an empty list :(
720
  if not value:
721
    return []
722
  else:
723
    return utils.UnescapeAndSplit(value)
724

    
725

    
726
def check_maybefloat(option, opt, value): # pylint: disable=W0613
727
  """Custom parser for float numbers which might be also defaults.
728

729
  """
730
  value = value.lower()
731

    
732
  if value == constants.VALUE_DEFAULT:
733
    return value
734
  else:
735
    return float(value)
736

    
737

    
738
# completion_suggestion is normally a list. Using numeric values not evaluating
739
# to False for dynamic completion.
740
(OPT_COMPL_MANY_NODES,
741
 OPT_COMPL_ONE_NODE,
742
 OPT_COMPL_ONE_INSTANCE,
743
 OPT_COMPL_ONE_OS,
744
 OPT_COMPL_ONE_EXTSTORAGE,
745
 OPT_COMPL_ONE_IALLOCATOR,
746
 OPT_COMPL_ONE_NETWORK,
747
 OPT_COMPL_INST_ADD_NODES,
748
 OPT_COMPL_ONE_NODEGROUP) = range(100, 109)
749

    
750
OPT_COMPL_ALL = compat.UniqueFrozenset([
751
  OPT_COMPL_MANY_NODES,
752
  OPT_COMPL_ONE_NODE,
753
  OPT_COMPL_ONE_INSTANCE,
754
  OPT_COMPL_ONE_OS,
755
  OPT_COMPL_ONE_EXTSTORAGE,
756
  OPT_COMPL_ONE_IALLOCATOR,
757
  OPT_COMPL_ONE_NETWORK,
758
  OPT_COMPL_INST_ADD_NODES,
759
  OPT_COMPL_ONE_NODEGROUP,
760
  ])
761

    
762

    
763
class CliOption(Option):
764
  """Custom option class for optparse.
765

766
  """
767
  ATTRS = Option.ATTRS + [
768
    "completion_suggest",
769
    ]
770
  TYPES = Option.TYPES + (
771
    "multilistidentkeyval",
772
    "identkeyval",
773
    "keyval",
774
    "unit",
775
    "bool",
776
    "list",
777
    "maybefloat",
778
    )
779
  TYPE_CHECKER = Option.TYPE_CHECKER.copy()
780
  TYPE_CHECKER["multilistidentkeyval"] = check_multilist_ident_key_val
781
  TYPE_CHECKER["identkeyval"] = check_ident_key_val
782
  TYPE_CHECKER["keyval"] = check_key_val
783
  TYPE_CHECKER["unit"] = check_unit
784
  TYPE_CHECKER["bool"] = check_bool
785
  TYPE_CHECKER["list"] = check_list
786
  TYPE_CHECKER["maybefloat"] = check_maybefloat
787

    
788

    
789
# optparse.py sets make_option, so we do it for our own option class, too
790
cli_option = CliOption
791

    
792

    
793
_YORNO = "yes|no"
794

    
795
DEBUG_OPT = cli_option("-d", "--debug", default=0, action="count",
796
                       help="Increase debugging level")
797

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

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

    
807
USEUNITS_OPT = cli_option("--units", default=None,
808
                          dest="units", choices=("h", "m", "g", "t"),
809
                          help="Specify units for output (one of h/m/g/t)")
810

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

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

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

    
821
IGNORE_OFFLINE_OPT = cli_option("--ignore-offline", dest="ignore_offline",
822
                                  action="store_true", default=False,
823
                                  help=("Ignore offline nodes and do as much"
824
                                        " as possible"))
825

    
826
TAG_ADD_OPT = cli_option("--tags", dest="tags",
827
                         default=None, help="Comma-separated list of instance"
828
                                            " tags")
829

    
830
TAG_SRC_OPT = cli_option("--from", dest="tags_source",
831
                         default=None, help="File with tag names")
832

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

    
838
SYNC_OPT = cli_option("--sync", dest="do_locking",
839
                      default=False, action="store_true",
840
                      help=("Grab locks while doing the queries"
841
                            " in order to ensure more consistent results"))
842

    
843
DRY_RUN_OPT = cli_option("--dry-run", default=False,
844
                         action="store_true",
845
                         help=("Do not execute the operation, just run the"
846
                               " check steps and verify if it could be"
847
                               " executed"))
848

    
849
VERBOSE_OPT = cli_option("-v", "--verbose", default=False,
850
                         action="store_true",
851
                         help="Increase the verbosity of the operation")
852

    
853
DEBUG_SIMERR_OPT = cli_option("--debug-simulate-errors", default=False,
854
                              action="store_true", dest="simulate_errors",
855
                              help="Debugging option that makes the operation"
856
                              " treat most runtime checks as failed")
857

    
858
NWSYNC_OPT = cli_option("--no-wait-for-sync", dest="wait_for_sync",
859
                        default=True, action="store_false",
860
                        help="Don't wait for sync (DANGEROUS!)")
861

    
862
WFSYNC_OPT = cli_option("--wait-for-sync", dest="wait_for_sync",
863
                        default=False, action="store_true",
864
                        help="Wait for disks to sync")
865

    
866
ONLINE_INST_OPT = cli_option("--online", dest="online_inst",
867
                             action="store_true", default=False,
868
                             help="Enable offline instance")
869

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

    
874
DISK_TEMPLATE_OPT = cli_option("-t", "--disk-template", dest="disk_template",
875
                               help=("Custom disk setup (%s)" %
876
                                     utils.CommaJoin(constants.DISK_TEMPLATES)),
877
                               default=None, metavar="TEMPL",
878
                               choices=list(constants.DISK_TEMPLATES))
879

    
880
NONICS_OPT = cli_option("--no-nics", default=False, action="store_true",
881
                        help="Do not create any network cards for"
882
                        " the instance")
883

    
884
FILESTORE_DIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
885
                               help="Relative path under default cluster-wide"
886
                               " file storage dir to store file-based disks",
887
                               default=None, metavar="<DIR>")
888

    
889
FILESTORE_DRIVER_OPT = cli_option("--file-driver", dest="file_driver",
890
                                  help="Driver to use for image files",
891
                                  default=None, metavar="<DRIVER>",
892
                                  choices=list(constants.FILE_DRIVER))
893

    
894
IALLOCATOR_OPT = cli_option("-I", "--iallocator", metavar="<NAME>",
895
                            help="Select nodes for the instance automatically"
896
                            " using the <NAME> iallocator plugin",
897
                            default=None, type="string",
898
                            completion_suggest=OPT_COMPL_ONE_IALLOCATOR)
899

    
900
DEFAULT_IALLOCATOR_OPT = cli_option("-I", "--default-iallocator",
901
                                    metavar="<NAME>",
902
                                    help="Set the default instance"
903
                                    " allocator plugin",
904
                                    default=None, type="string",
905
                                    completion_suggest=OPT_COMPL_ONE_IALLOCATOR)
906

    
907
OS_OPT = cli_option("-o", "--os-type", dest="os", help="What OS to run",
908
                    metavar="<os>",
909
                    completion_suggest=OPT_COMPL_ONE_OS)
910

    
911
OSPARAMS_OPT = cli_option("-O", "--os-parameters", dest="osparams",
912
                          type="keyval", default={},
913
                          help="OS parameters")
914

    
915
FORCE_VARIANT_OPT = cli_option("--force-variant", dest="force_variant",
916
                               action="store_true", default=False,
917
                               help="Force an unknown variant")
918

    
919
NO_INSTALL_OPT = cli_option("--no-install", dest="no_install",
920
                            action="store_true", default=False,
921
                            help="Do not install the OS (will"
922
                            " enable no-start)")
923

    
924
NORUNTIME_CHGS_OPT = cli_option("--no-runtime-changes",
925
                                dest="allow_runtime_chgs",
926
                                default=True, action="store_false",
927
                                help="Don't allow runtime changes")
928

    
929
BACKEND_OPT = cli_option("-B", "--backend-parameters", dest="beparams",
930
                         type="keyval", default={},
931
                         help="Backend parameters")
932

    
933
HVOPTS_OPT = cli_option("-H", "--hypervisor-parameters", type="keyval",
934
                        default={}, dest="hvparams",
935
                        help="Hypervisor parameters")
936

    
937
DISK_PARAMS_OPT = cli_option("-D", "--disk-parameters", dest="diskparams",
938
                             help="Disk template parameters, in the format"
939
                             " template:option=value,option=value,...",
940
                             type="identkeyval", action="append", default=[])
941

    
942
SPECS_MEM_SIZE_OPT = cli_option("--specs-mem-size", dest="ispecs_mem_size",
943
                                 type="keyval", default={},
944
                                 help="Memory size specs: list of key=value,"
945
                                " where key is one of min, max, std"
946
                                 " (in MB or using a unit)")
947

    
948
SPECS_CPU_COUNT_OPT = cli_option("--specs-cpu-count", dest="ispecs_cpu_count",
949
                                 type="keyval", default={},
950
                                 help="CPU count specs: list of key=value,"
951
                                 " where key is one of min, max, std")
952

    
953
SPECS_DISK_COUNT_OPT = cli_option("--specs-disk-count",
954
                                  dest="ispecs_disk_count",
955
                                  type="keyval", default={},
956
                                  help="Disk count specs: list of key=value,"
957
                                  " where key is one of min, max, std")
958

    
959
SPECS_DISK_SIZE_OPT = cli_option("--specs-disk-size", dest="ispecs_disk_size",
960
                                 type="keyval", default={},
961
                                 help="Disk size specs: list of key=value,"
962
                                 " where key is one of min, max, std"
963
                                 " (in MB or using a unit)")
964

    
965
SPECS_NIC_COUNT_OPT = cli_option("--specs-nic-count", dest="ispecs_nic_count",
966
                                 type="keyval", default={},
967
                                 help="NIC count specs: list of key=value,"
968
                                 " where key is one of min, max, std")
969

    
970
IPOLICY_BOUNDS_SPECS_STR = "--ipolicy-bounds-specs"
971
IPOLICY_BOUNDS_SPECS_OPT = cli_option(IPOLICY_BOUNDS_SPECS_STR,
972
                                      dest="ipolicy_bounds_specs",
973
                                      type="multilistidentkeyval", default=None,
974
                                      help="Complete instance specs limits")
975

    
976
IPOLICY_STD_SPECS_STR = "--ipolicy-std-specs"
977
IPOLICY_STD_SPECS_OPT = cli_option(IPOLICY_STD_SPECS_STR,
978
                                   dest="ipolicy_std_specs",
979
                                   type="keyval", default=None,
980
                                   help="Complte standard instance specs")
981

    
982
IPOLICY_DISK_TEMPLATES = cli_option("--ipolicy-disk-templates",
983
                                    dest="ipolicy_disk_templates",
984
                                    type="list", default=None,
985
                                    help="Comma-separated list of"
986
                                    " enabled disk templates")
987

    
988
IPOLICY_VCPU_RATIO = cli_option("--ipolicy-vcpu-ratio",
989
                                 dest="ipolicy_vcpu_ratio",
990
                                 type="maybefloat", default=None,
991
                                 help="The maximum allowed vcpu-to-cpu ratio")
992

    
993
IPOLICY_SPINDLE_RATIO = cli_option("--ipolicy-spindle-ratio",
994
                                   dest="ipolicy_spindle_ratio",
995
                                   type="maybefloat", default=None,
996
                                   help=("The maximum allowed instances to"
997
                                         " spindle ratio"))
998

    
999
HYPERVISOR_OPT = cli_option("-H", "--hypervisor-parameters", dest="hypervisor",
1000
                            help="Hypervisor and hypervisor options, in the"
1001
                            " format hypervisor:option=value,option=value,...",
1002
                            default=None, type="identkeyval")
1003

    
1004
HVLIST_OPT = cli_option("-H", "--hypervisor-parameters", dest="hvparams",
1005
                        help="Hypervisor and hypervisor options, in the"
1006
                        " format hypervisor:option=value,option=value,...",
1007
                        default=[], action="append", type="identkeyval")
1008

    
1009
NOIPCHECK_OPT = cli_option("--no-ip-check", dest="ip_check", default=True,
1010
                           action="store_false",
1011
                           help="Don't check that the instance's IP"
1012
                           " is alive")
1013

    
1014
NONAMECHECK_OPT = cli_option("--no-name-check", dest="name_check",
1015
                             default=True, action="store_false",
1016
                             help="Don't check that the instance's name"
1017
                             " is resolvable")
1018

    
1019
NET_OPT = cli_option("--net",
1020
                     help="NIC parameters", default=[],
1021
                     dest="nics", action="append", type="identkeyval")
1022

    
1023
DISK_OPT = cli_option("--disk", help="Disk parameters", default=[],
1024
                      dest="disks", action="append", type="identkeyval")
1025

    
1026
DISKIDX_OPT = cli_option("--disks", dest="disks", default=None,
1027
                         help="Comma-separated list of disks"
1028
                         " indices to act on (e.g. 0,2) (optional,"
1029
                         " defaults to all disks)")
1030

    
1031
OS_SIZE_OPT = cli_option("-s", "--os-size", dest="sd_size",
1032
                         help="Enforces a single-disk configuration using the"
1033
                         " given disk size, in MiB unless a suffix is used",
1034
                         default=None, type="unit", metavar="<size>")
1035

    
1036
IGNORE_CONSIST_OPT = cli_option("--ignore-consistency",
1037
                                dest="ignore_consistency",
1038
                                action="store_true", default=False,
1039
                                help="Ignore the consistency of the disks on"
1040
                                " the secondary")
1041

    
1042
ALLOW_FAILOVER_OPT = cli_option("--allow-failover",
1043
                                dest="allow_failover",
1044
                                action="store_true", default=False,
1045
                                help="If migration is not possible fallback to"
1046
                                     " failover")
1047

    
1048
NONLIVE_OPT = cli_option("--non-live", dest="live",
1049
                         default=True, action="store_false",
1050
                         help="Do a non-live migration (this usually means"
1051
                         " freeze the instance, save the state, transfer and"
1052
                         " only then resume running on the secondary node)")
1053

    
1054
MIGRATION_MODE_OPT = cli_option("--migration-mode", dest="migration_mode",
1055
                                default=None,
1056
                                choices=list(constants.HT_MIGRATION_MODES),
1057
                                help="Override default migration mode (choose"
1058
                                " either live or non-live")
1059

    
1060
NODE_PLACEMENT_OPT = cli_option("-n", "--node", dest="node",
1061
                                help="Target node and optional secondary node",
1062
                                metavar="<pnode>[:<snode>]",
1063
                                completion_suggest=OPT_COMPL_INST_ADD_NODES)
1064

    
1065
NODE_LIST_OPT = cli_option("-n", "--node", dest="nodes", default=[],
1066
                           action="append", metavar="<node>",
1067
                           help="Use only this node (can be used multiple"
1068
                           " times, if not given defaults to all nodes)",
1069
                           completion_suggest=OPT_COMPL_ONE_NODE)
1070

    
1071
NODEGROUP_OPT_NAME = "--node-group"
1072
NODEGROUP_OPT = cli_option("-g", NODEGROUP_OPT_NAME,
1073
                           dest="nodegroup",
1074
                           help="Node group (name or uuid)",
1075
                           metavar="<nodegroup>",
1076
                           default=None, type="string",
1077
                           completion_suggest=OPT_COMPL_ONE_NODEGROUP)
1078

    
1079
SINGLE_NODE_OPT = cli_option("-n", "--node", dest="node", help="Target node",
1080
                             metavar="<node>",
1081
                             completion_suggest=OPT_COMPL_ONE_NODE)
1082

    
1083
NOSTART_OPT = cli_option("--no-start", dest="start", default=True,
1084
                         action="store_false",
1085
                         help="Don't start the instance after creation")
1086

    
1087
SHOWCMD_OPT = cli_option("--show-cmd", dest="show_command",
1088
                         action="store_true", default=False,
1089
                         help="Show command instead of executing it")
1090

    
1091
CLEANUP_OPT = cli_option("--cleanup", dest="cleanup",
1092
                         default=False, action="store_true",
1093
                         help="Instead of performing the migration/failover,"
1094
                         " try to recover from a failed cleanup. This is safe"
1095
                         " to run even if the instance is healthy, but it"
1096
                         " will create extra replication traffic and "
1097
                         " disrupt briefly the replication (like during the"
1098
                         " migration/failover")
1099

    
1100
STATIC_OPT = cli_option("-s", "--static", dest="static",
1101
                        action="store_true", default=False,
1102
                        help="Only show configuration data, not runtime data")
1103

    
1104
ALL_OPT = cli_option("--all", dest="show_all",
1105
                     default=False, action="store_true",
1106
                     help="Show info on all instances on the cluster."
1107
                     " This can take a long time to run, use wisely")
1108

    
1109
SELECT_OS_OPT = cli_option("--select-os", dest="select_os",
1110
                           action="store_true", default=False,
1111
                           help="Interactive OS reinstall, lists available"
1112
                           " OS templates for selection")
1113

    
1114
IGNORE_FAILURES_OPT = cli_option("--ignore-failures", dest="ignore_failures",
1115
                                 action="store_true", default=False,
1116
                                 help="Remove the instance from the cluster"
1117
                                 " configuration even if there are failures"
1118
                                 " during the removal process")
1119

    
1120
IGNORE_REMOVE_FAILURES_OPT = cli_option("--ignore-remove-failures",
1121
                                        dest="ignore_remove_failures",
1122
                                        action="store_true", default=False,
1123
                                        help="Remove the instance from the"
1124
                                        " cluster configuration even if there"
1125
                                        " are failures during the removal"
1126
                                        " process")
1127

    
1128
REMOVE_INSTANCE_OPT = cli_option("--remove-instance", dest="remove_instance",
1129
                                 action="store_true", default=False,
1130
                                 help="Remove the instance from the cluster")
1131

    
1132
DST_NODE_OPT = cli_option("-n", "--target-node", dest="dst_node",
1133
                               help="Specifies the new node for the instance",
1134
                               metavar="NODE", default=None,
1135
                               completion_suggest=OPT_COMPL_ONE_NODE)
1136

    
1137
NEW_SECONDARY_OPT = cli_option("-n", "--new-secondary", dest="dst_node",
1138
                               help="Specifies the new secondary node",
1139
                               metavar="NODE", default=None,
1140
                               completion_suggest=OPT_COMPL_ONE_NODE)
1141

    
1142
NEW_PRIMARY_OPT = cli_option("--new-primary", dest="new_primary_node",
1143
                             help="Specifies the new primary node",
1144
                             metavar="<node>", default=None,
1145
                             completion_suggest=OPT_COMPL_ONE_NODE)
1146

    
1147
ON_PRIMARY_OPT = cli_option("-p", "--on-primary", dest="on_primary",
1148
                            default=False, action="store_true",
1149
                            help="Replace the disk(s) on the primary"
1150
                                 " node (applies only to internally mirrored"
1151
                                 " disk templates, e.g. %s)" %
1152
                                 utils.CommaJoin(constants.DTS_INT_MIRROR))
1153

    
1154
ON_SECONDARY_OPT = cli_option("-s", "--on-secondary", dest="on_secondary",
1155
                              default=False, action="store_true",
1156
                              help="Replace the disk(s) on the secondary"
1157
                                   " node (applies only to internally mirrored"
1158
                                   " disk templates, e.g. %s)" %
1159
                                   utils.CommaJoin(constants.DTS_INT_MIRROR))
1160

    
1161
AUTO_PROMOTE_OPT = cli_option("--auto-promote", dest="auto_promote",
1162
                              default=False, action="store_true",
1163
                              help="Lock all nodes and auto-promote as needed"
1164
                              " to MC status")
1165

    
1166
AUTO_REPLACE_OPT = cli_option("-a", "--auto", dest="auto",
1167
                              default=False, action="store_true",
1168
                              help="Automatically replace faulty disks"
1169
                                   " (applies only to internally mirrored"
1170
                                   " disk templates, e.g. %s)" %
1171
                                   utils.CommaJoin(constants.DTS_INT_MIRROR))
1172

    
1173
IGNORE_SIZE_OPT = cli_option("--ignore-size", dest="ignore_size",
1174
                             default=False, action="store_true",
1175
                             help="Ignore current recorded size"
1176
                             " (useful for forcing activation when"
1177
                             " the recorded size is wrong)")
1178

    
1179
SRC_NODE_OPT = cli_option("--src-node", dest="src_node", help="Source node",
1180
                          metavar="<node>",
1181
                          completion_suggest=OPT_COMPL_ONE_NODE)
1182

    
1183
SRC_DIR_OPT = cli_option("--src-dir", dest="src_dir", help="Source directory",
1184
                         metavar="<dir>")
1185

    
1186
SECONDARY_IP_OPT = cli_option("-s", "--secondary-ip", dest="secondary_ip",
1187
                              help="Specify the secondary ip for the node",
1188
                              metavar="ADDRESS", default=None)
1189

    
1190
READD_OPT = cli_option("--readd", dest="readd",
1191
                       default=False, action="store_true",
1192
                       help="Readd old node after replacing it")
1193

    
1194
NOSSH_KEYCHECK_OPT = cli_option("--no-ssh-key-check", dest="ssh_key_check",
1195
                                default=True, action="store_false",
1196
                                help="Disable SSH key fingerprint checking")
1197

    
1198
NODE_FORCE_JOIN_OPT = cli_option("--force-join", dest="force_join",
1199
                                 default=False, action="store_true",
1200
                                 help="Force the joining of a node")
1201

    
1202
MC_OPT = cli_option("-C", "--master-candidate", dest="master_candidate",
1203
                    type="bool", default=None, metavar=_YORNO,
1204
                    help="Set the master_candidate flag on the node")
1205

    
1206
OFFLINE_OPT = cli_option("-O", "--offline", dest="offline", metavar=_YORNO,
1207
                         type="bool", default=None,
1208
                         help=("Set the offline flag on the node"
1209
                               " (cluster does not communicate with offline"
1210
                               " nodes)"))
1211

    
1212
DRAINED_OPT = cli_option("-D", "--drained", dest="drained", metavar=_YORNO,
1213
                         type="bool", default=None,
1214
                         help=("Set the drained flag on the node"
1215
                               " (excluded from allocation operations)"))
1216

    
1217
CAPAB_MASTER_OPT = cli_option("--master-capable", dest="master_capable",
1218
                              type="bool", default=None, metavar=_YORNO,
1219
                              help="Set the master_capable flag on the node")
1220

    
1221
CAPAB_VM_OPT = cli_option("--vm-capable", dest="vm_capable",
1222
                          type="bool", default=None, metavar=_YORNO,
1223
                          help="Set the vm_capable flag on the node")
1224

    
1225
ALLOCATABLE_OPT = cli_option("--allocatable", dest="allocatable",
1226
                             type="bool", default=None, metavar=_YORNO,
1227
                             help="Set the allocatable flag on a volume")
1228

    
1229
NOLVM_STORAGE_OPT = cli_option("--no-lvm-storage", dest="lvm_storage",
1230
                               help="Disable support for lvm based instances"
1231
                               " (cluster-wide)",
1232
                               action="store_false", default=True)
1233

    
1234
ENABLED_HV_OPT = cli_option("--enabled-hypervisors",
1235
                            dest="enabled_hypervisors",
1236
                            help="Comma-separated list of hypervisors",
1237
                            type="string", default=None)
1238

    
1239
ENABLED_DISK_TEMPLATES_OPT = cli_option("--enabled-disk-templates",
1240
                                        dest="enabled_disk_templates",
1241
                                        help="Comma-separated list of "
1242
                                             "disk templates",
1243
                                        type="string", default=None)
1244

    
1245
NIC_PARAMS_OPT = cli_option("-N", "--nic-parameters", dest="nicparams",
1246
                            type="keyval", default={},
1247
                            help="NIC parameters")
1248

    
1249
CP_SIZE_OPT = cli_option("-C", "--candidate-pool-size", default=None,
1250
                         dest="candidate_pool_size", type="int",
1251
                         help="Set the candidate pool size")
1252

    
1253
VG_NAME_OPT = cli_option("--vg-name", dest="vg_name",
1254
                         help=("Enables LVM and specifies the volume group"
1255
                               " name (cluster-wide) for disk allocation"
1256
                               " [%s]" % constants.DEFAULT_VG),
1257
                         metavar="VG", default=None)
1258

    
1259
YES_DOIT_OPT = cli_option("--yes-do-it", "--ya-rly", dest="yes_do_it",
1260
                          help="Destroy cluster", action="store_true")
1261

    
1262
NOVOTING_OPT = cli_option("--no-voting", dest="no_voting",
1263
                          help="Skip node agreement check (dangerous)",
1264
                          action="store_true", default=False)
1265

    
1266
MAC_PREFIX_OPT = cli_option("-m", "--mac-prefix", dest="mac_prefix",
1267
                            help="Specify the mac prefix for the instance IP"
1268
                            " addresses, in the format XX:XX:XX",
1269
                            metavar="PREFIX",
1270
                            default=None)
1271

    
1272
MASTER_NETDEV_OPT = cli_option("--master-netdev", dest="master_netdev",
1273
                               help="Specify the node interface (cluster-wide)"
1274
                               " on which the master IP address will be added"
1275
                               " (cluster init default: %s)" %
1276
                               constants.DEFAULT_BRIDGE,
1277
                               metavar="NETDEV",
1278
                               default=None)
1279

    
1280
MASTER_NETMASK_OPT = cli_option("--master-netmask", dest="master_netmask",
1281
                                help="Specify the netmask of the master IP",
1282
                                metavar="NETMASK",
1283
                                default=None)
1284

    
1285
USE_EXTERNAL_MIP_SCRIPT = cli_option("--use-external-mip-script",
1286
                                     dest="use_external_mip_script",
1287
                                     help="Specify whether to run a"
1288
                                     " user-provided script for the master"
1289
                                     " IP address turnup and"
1290
                                     " turndown operations",
1291
                                     type="bool", metavar=_YORNO, default=None)
1292

    
1293
GLOBAL_FILEDIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
1294
                                help="Specify the default directory (cluster-"
1295
                                "wide) for storing the file-based disks [%s]" %
1296
                                pathutils.DEFAULT_FILE_STORAGE_DIR,
1297
                                metavar="DIR",
1298
                                default=pathutils.DEFAULT_FILE_STORAGE_DIR)
1299

    
1300
GLOBAL_SHARED_FILEDIR_OPT = cli_option(
1301
  "--shared-file-storage-dir",
1302
  dest="shared_file_storage_dir",
1303
  help="Specify the default directory (cluster-wide) for storing the"
1304
  " shared file-based disks [%s]" %
1305
  pathutils.DEFAULT_SHARED_FILE_STORAGE_DIR,
1306
  metavar="SHAREDDIR", default=pathutils.DEFAULT_SHARED_FILE_STORAGE_DIR)
1307

    
1308
NOMODIFY_ETCHOSTS_OPT = cli_option("--no-etc-hosts", dest="modify_etc_hosts",
1309
                                   help="Don't modify %s" % pathutils.ETC_HOSTS,
1310
                                   action="store_false", default=True)
1311

    
1312
MODIFY_ETCHOSTS_OPT = \
1313
 cli_option("--modify-etc-hosts", dest="modify_etc_hosts", metavar=_YORNO,
1314
            default=None, type="bool",
1315
            help="Defines whether the cluster should autonomously modify"
1316
            " and keep in sync the /etc/hosts file of the nodes")
1317

    
1318
NOMODIFY_SSH_SETUP_OPT = cli_option("--no-ssh-init", dest="modify_ssh_setup",
1319
                                    help="Don't initialize SSH keys",
1320
                                    action="store_false", default=True)
1321

    
1322
ERROR_CODES_OPT = cli_option("--error-codes", dest="error_codes",
1323
                             help="Enable parseable error messages",
1324
                             action="store_true", default=False)
1325

    
1326
NONPLUS1_OPT = cli_option("--no-nplus1-mem", dest="skip_nplusone_mem",
1327
                          help="Skip N+1 memory redundancy tests",
1328
                          action="store_true", default=False)
1329

    
1330
REBOOT_TYPE_OPT = cli_option("-t", "--type", dest="reboot_type",
1331
                             help="Type of reboot: soft/hard/full",
1332
                             default=constants.INSTANCE_REBOOT_HARD,
1333
                             metavar="<REBOOT>",
1334
                             choices=list(constants.REBOOT_TYPES))
1335

    
1336
IGNORE_SECONDARIES_OPT = cli_option("--ignore-secondaries",
1337
                                    dest="ignore_secondaries",
1338
                                    default=False, action="store_true",
1339
                                    help="Ignore errors from secondaries")
1340

    
1341
NOSHUTDOWN_OPT = cli_option("--noshutdown", dest="shutdown",
1342
                            action="store_false", default=True,
1343
                            help="Don't shutdown the instance (unsafe)")
1344

    
1345
TIMEOUT_OPT = cli_option("--timeout", dest="timeout", type="int",
1346
                         default=constants.DEFAULT_SHUTDOWN_TIMEOUT,
1347
                         help="Maximum time to wait")
1348

    
1349
SHUTDOWN_TIMEOUT_OPT = cli_option("--shutdown-timeout",
1350
                                  dest="shutdown_timeout", type="int",
1351
                                  default=constants.DEFAULT_SHUTDOWN_TIMEOUT,
1352
                                  help="Maximum time to wait for instance"
1353
                                  " shutdown")
1354

    
1355
INTERVAL_OPT = cli_option("--interval", dest="interval", type="int",
1356
                          default=None,
1357
                          help=("Number of seconds between repetions of the"
1358
                                " command"))
1359

    
1360
EARLY_RELEASE_OPT = cli_option("--early-release",
1361
                               dest="early_release", default=False,
1362
                               action="store_true",
1363
                               help="Release the locks on the secondary"
1364
                               " node(s) early")
1365

    
1366
NEW_CLUSTER_CERT_OPT = cli_option("--new-cluster-certificate",
1367
                                  dest="new_cluster_cert",
1368
                                  default=False, action="store_true",
1369
                                  help="Generate a new cluster certificate")
1370

    
1371
RAPI_CERT_OPT = cli_option("--rapi-certificate", dest="rapi_cert",
1372
                           default=None,
1373
                           help="File containing new RAPI certificate")
1374

    
1375
NEW_RAPI_CERT_OPT = cli_option("--new-rapi-certificate", dest="new_rapi_cert",
1376
                               default=None, action="store_true",
1377
                               help=("Generate a new self-signed RAPI"
1378
                                     " certificate"))
1379

    
1380
SPICE_CERT_OPT = cli_option("--spice-certificate", dest="spice_cert",
1381
                            default=None,
1382
                            help="File containing new SPICE certificate")
1383

    
1384
SPICE_CACERT_OPT = cli_option("--spice-ca-certificate", dest="spice_cacert",
1385
                              default=None,
1386
                              help="File containing the certificate of the CA"
1387
                              " which signed the SPICE certificate")
1388

    
1389
NEW_SPICE_CERT_OPT = cli_option("--new-spice-certificate",
1390
                                dest="new_spice_cert", default=None,
1391
                                action="store_true",
1392
                                help=("Generate a new self-signed SPICE"
1393
                                      " certificate"))
1394

    
1395
NEW_CONFD_HMAC_KEY_OPT = cli_option("--new-confd-hmac-key",
1396
                                    dest="new_confd_hmac_key",
1397
                                    default=False, action="store_true",
1398
                                    help=("Create a new HMAC key for %s" %
1399
                                          constants.CONFD))
1400

    
1401
CLUSTER_DOMAIN_SECRET_OPT = cli_option("--cluster-domain-secret",
1402
                                       dest="cluster_domain_secret",
1403
                                       default=None,
1404
                                       help=("Load new new cluster domain"
1405
                                             " secret from file"))
1406

    
1407
NEW_CLUSTER_DOMAIN_SECRET_OPT = cli_option("--new-cluster-domain-secret",
1408
                                           dest="new_cluster_domain_secret",
1409
                                           default=False, action="store_true",
1410
                                           help=("Create a new cluster domain"
1411
                                                 " secret"))
1412

    
1413
USE_REPL_NET_OPT = cli_option("--use-replication-network",
1414
                              dest="use_replication_network",
1415
                              help="Whether to use the replication network"
1416
                              " for talking to the nodes",
1417
                              action="store_true", default=False)
1418

    
1419
MAINTAIN_NODE_HEALTH_OPT = \
1420
    cli_option("--maintain-node-health", dest="maintain_node_health",
1421
               metavar=_YORNO, default=None, type="bool",
1422
               help="Configure the cluster to automatically maintain node"
1423
               " health, by shutting down unknown instances, shutting down"
1424
               " unknown DRBD devices, etc.")
1425

    
1426
IDENTIFY_DEFAULTS_OPT = \
1427
    cli_option("--identify-defaults", dest="identify_defaults",
1428
               default=False, action="store_true",
1429
               help="Identify which saved instance parameters are equal to"
1430
               " the current cluster defaults and set them as such, instead"
1431
               " of marking them as overridden")
1432

    
1433
UIDPOOL_OPT = cli_option("--uid-pool", default=None,
1434
                         action="store", dest="uid_pool",
1435
                         help=("A list of user-ids or user-id"
1436
                               " ranges separated by commas"))
1437

    
1438
ADD_UIDS_OPT = cli_option("--add-uids", default=None,
1439
                          action="store", dest="add_uids",
1440
                          help=("A list of user-ids or user-id"
1441
                                " ranges separated by commas, to be"
1442
                                " added to the user-id pool"))
1443

    
1444
REMOVE_UIDS_OPT = cli_option("--remove-uids", default=None,
1445
                             action="store", dest="remove_uids",
1446
                             help=("A list of user-ids or user-id"
1447
                                   " ranges separated by commas, to be"
1448
                                   " removed from the user-id pool"))
1449

    
1450
RESERVED_LVS_OPT = cli_option("--reserved-lvs", default=None,
1451
                              action="store", dest="reserved_lvs",
1452
                              help=("A comma-separated list of reserved"
1453
                                    " logical volumes names, that will be"
1454
                                    " ignored by cluster verify"))
1455

    
1456
ROMAN_OPT = cli_option("--roman",
1457
                       dest="roman_integers", default=False,
1458
                       action="store_true",
1459
                       help="Use roman numbers for positive integers")
1460

    
1461
DRBD_HELPER_OPT = cli_option("--drbd-usermode-helper", dest="drbd_helper",
1462
                             action="store", default=None,
1463
                             help="Specifies usermode helper for DRBD")
1464

    
1465
NODRBD_STORAGE_OPT = cli_option("--no-drbd-storage", dest="drbd_storage",
1466
                                action="store_false", default=True,
1467
                                help="Disable support for DRBD")
1468

    
1469
PRIMARY_IP_VERSION_OPT = \
1470
    cli_option("--primary-ip-version", default=constants.IP4_VERSION,
1471
               action="store", dest="primary_ip_version",
1472
               metavar="%d|%d" % (constants.IP4_VERSION,
1473
                                  constants.IP6_VERSION),
1474
               help="Cluster-wide IP version for primary IP")
1475

    
1476
SHOW_MACHINE_OPT = cli_option("-M", "--show-machine-names", default=False,
1477
                              action="store_true",
1478
                              help="Show machine name for every line in output")
1479

    
1480
FAILURE_ONLY_OPT = cli_option("--failure-only", default=False,
1481
                              action="store_true",
1482
                              help=("Hide successful results and show failures"
1483
                                    " only (determined by the exit code)"))
1484

    
1485
REASON_OPT = cli_option("--reason", default=None,
1486
                        help="The reason for executing the command")
1487

    
1488

    
1489
def _PriorityOptionCb(option, _, value, parser):
1490
  """Callback for processing C{--priority} option.
1491

1492
  """
1493
  value = _PRIONAME_TO_VALUE[value]
1494

    
1495
  setattr(parser.values, option.dest, value)
1496

    
1497

    
1498
PRIORITY_OPT = cli_option("--priority", default=None, dest="priority",
1499
                          metavar="|".join(name for name, _ in _PRIORITY_NAMES),
1500
                          choices=_PRIONAME_TO_VALUE.keys(),
1501
                          action="callback", type="choice",
1502
                          callback=_PriorityOptionCb,
1503
                          help="Priority for opcode processing")
1504

    
1505
HID_OS_OPT = cli_option("--hidden", dest="hidden",
1506
                        type="bool", default=None, metavar=_YORNO,
1507
                        help="Sets the hidden flag on the OS")
1508

    
1509
BLK_OS_OPT = cli_option("--blacklisted", dest="blacklisted",
1510
                        type="bool", default=None, metavar=_YORNO,
1511
                        help="Sets the blacklisted flag on the OS")
1512

    
1513
PREALLOC_WIPE_DISKS_OPT = cli_option("--prealloc-wipe-disks", default=None,
1514
                                     type="bool", metavar=_YORNO,
1515
                                     dest="prealloc_wipe_disks",
1516
                                     help=("Wipe disks prior to instance"
1517
                                           " creation"))
1518

    
1519
NODE_PARAMS_OPT = cli_option("--node-parameters", dest="ndparams",
1520
                             type="keyval", default=None,
1521
                             help="Node parameters")
1522

    
1523
ALLOC_POLICY_OPT = cli_option("--alloc-policy", dest="alloc_policy",
1524
                              action="store", metavar="POLICY", default=None,
1525
                              help="Allocation policy for the node group")
1526

    
1527
NODE_POWERED_OPT = cli_option("--node-powered", default=None,
1528
                              type="bool", metavar=_YORNO,
1529
                              dest="node_powered",
1530
                              help="Specify if the SoR for node is powered")
1531

    
1532
OOB_TIMEOUT_OPT = cli_option("--oob-timeout", dest="oob_timeout", type="int",
1533
                             default=constants.OOB_TIMEOUT,
1534
                             help="Maximum time to wait for out-of-band helper")
1535

    
1536
POWER_DELAY_OPT = cli_option("--power-delay", dest="power_delay", type="float",
1537
                             default=constants.OOB_POWER_DELAY,
1538
                             help="Time in seconds to wait between power-ons")
1539

    
1540
FORCE_FILTER_OPT = cli_option("-F", "--filter", dest="force_filter",
1541
                              action="store_true", default=False,
1542
                              help=("Whether command argument should be treated"
1543
                                    " as filter"))
1544

    
1545
NO_REMEMBER_OPT = cli_option("--no-remember",
1546
                             dest="no_remember",
1547
                             action="store_true", default=False,
1548
                             help="Perform but do not record the change"
1549
                             " in the configuration")
1550

    
1551
PRIMARY_ONLY_OPT = cli_option("-p", "--primary-only",
1552
                              default=False, action="store_true",
1553
                              help="Evacuate primary instances only")
1554

    
1555
SECONDARY_ONLY_OPT = cli_option("-s", "--secondary-only",
1556
                                default=False, action="store_true",
1557
                                help="Evacuate secondary instances only"
1558
                                     " (applies only to internally mirrored"
1559
                                     " disk templates, e.g. %s)" %
1560
                                     utils.CommaJoin(constants.DTS_INT_MIRROR))
1561

    
1562
STARTUP_PAUSED_OPT = cli_option("--paused", dest="startup_paused",
1563
                                action="store_true", default=False,
1564
                                help="Pause instance at startup")
1565

    
1566
TO_GROUP_OPT = cli_option("--to", dest="to", metavar="<group>",
1567
                          help="Destination node group (name or uuid)",
1568
                          default=None, action="append",
1569
                          completion_suggest=OPT_COMPL_ONE_NODEGROUP)
1570

    
1571
IGNORE_ERRORS_OPT = cli_option("-I", "--ignore-errors", default=[],
1572
                               action="append", dest="ignore_errors",
1573
                               choices=list(constants.CV_ALL_ECODES_STRINGS),
1574
                               help="Error code to be ignored")
1575

    
1576
DISK_STATE_OPT = cli_option("--disk-state", default=[], dest="disk_state",
1577
                            action="append",
1578
                            help=("Specify disk state information in the"
1579
                                  " format"
1580
                                  " storage_type/identifier:option=value,...;"
1581
                                  " note this is unused for now"),
1582
                            type="identkeyval")
1583

    
1584
HV_STATE_OPT = cli_option("--hypervisor-state", default=[], dest="hv_state",
1585
                          action="append",
1586
                          help=("Specify hypervisor state information in the"
1587
                                " format hypervisor:option=value,...;"
1588
                                " note this is unused for now"),
1589
                          type="identkeyval")
1590

    
1591
IGNORE_IPOLICY_OPT = cli_option("--ignore-ipolicy", dest="ignore_ipolicy",
1592
                                action="store_true", default=False,
1593
                                help="Ignore instance policy violations")
1594

    
1595
RUNTIME_MEM_OPT = cli_option("-m", "--runtime-memory", dest="runtime_mem",
1596
                             help="Sets the instance's runtime memory,"
1597
                             " ballooning it up or down to the new value",
1598
                             default=None, type="unit", metavar="<size>")
1599

    
1600
ABSOLUTE_OPT = cli_option("--absolute", dest="absolute",
1601
                          action="store_true", default=False,
1602
                          help="Marks the grow as absolute instead of the"
1603
                          " (default) relative mode")
1604

    
1605
NETWORK_OPT = cli_option("--network",
1606
                         action="store", default=None, dest="network",
1607
                         help="IP network in CIDR notation")
1608

    
1609
GATEWAY_OPT = cli_option("--gateway",
1610
                         action="store", default=None, dest="gateway",
1611
                         help="IP address of the router (gateway)")
1612

    
1613
ADD_RESERVED_IPS_OPT = cli_option("--add-reserved-ips",
1614
                                  action="store", default=None,
1615
                                  dest="add_reserved_ips",
1616
                                  help="Comma-separated list of"
1617
                                  " reserved IPs to add")
1618

    
1619
REMOVE_RESERVED_IPS_OPT = cli_option("--remove-reserved-ips",
1620
                                     action="store", default=None,
1621
                                     dest="remove_reserved_ips",
1622
                                     help="Comma-delimited list of"
1623
                                     " reserved IPs to remove")
1624

    
1625
NETWORK6_OPT = cli_option("--network6",
1626
                          action="store", default=None, dest="network6",
1627
                          help="IP network in CIDR notation")
1628

    
1629
GATEWAY6_OPT = cli_option("--gateway6",
1630
                          action="store", default=None, dest="gateway6",
1631
                          help="IP6 address of the router (gateway)")
1632

    
1633
NOCONFLICTSCHECK_OPT = cli_option("--no-conflicts-check",
1634
                                  dest="conflicts_check",
1635
                                  default=True,
1636
                                  action="store_false",
1637
                                  help="Don't check for conflicting IPs")
1638

    
1639
INCLUDEDEFAULTS_OPT = cli_option("--include-defaults", dest="include_defaults",
1640
                                 default=False, action="store_true",
1641
                                 help="Include default values")
1642

    
1643
HOTPLUG_OPT = cli_option("--hotplug", dest="hotplug",
1644
                         action="store_true", default=False,
1645
                         help="Try to hotplug device")
1646

    
1647
KEEPDISKS_OPT = cli_option("--keep-disks", dest="keep_disks",
1648
                           action="store_true", default=False,
1649
                           help="Do not remove disks")
1650

    
1651
#: Options provided by all commands
1652
COMMON_OPTS = [DEBUG_OPT, REASON_OPT]
1653

    
1654
# common options for creating instances. add and import then add their own
1655
# specific ones.
1656
COMMON_CREATE_OPTS = [
1657
  BACKEND_OPT,
1658
  DISK_OPT,
1659
  DISK_TEMPLATE_OPT,
1660
  FILESTORE_DIR_OPT,
1661
  FILESTORE_DRIVER_OPT,
1662
  HYPERVISOR_OPT,
1663
  IALLOCATOR_OPT,
1664
  NET_OPT,
1665
  NODE_PLACEMENT_OPT,
1666
  NOIPCHECK_OPT,
1667
  NOCONFLICTSCHECK_OPT,
1668
  NONAMECHECK_OPT,
1669
  NONICS_OPT,
1670
  NWSYNC_OPT,
1671
  OSPARAMS_OPT,
1672
  OS_SIZE_OPT,
1673
  SUBMIT_OPT,
1674
  TAG_ADD_OPT,
1675
  DRY_RUN_OPT,
1676
  PRIORITY_OPT,
1677
  ]
1678

    
1679
# common instance policy options
1680
INSTANCE_POLICY_OPTS = [
1681
  IPOLICY_BOUNDS_SPECS_OPT,
1682
  IPOLICY_DISK_TEMPLATES,
1683
  IPOLICY_VCPU_RATIO,
1684
  IPOLICY_SPINDLE_RATIO,
1685
  ]
1686

    
1687
# instance policy split specs options
1688
SPLIT_ISPECS_OPTS = [
1689
  SPECS_CPU_COUNT_OPT,
1690
  SPECS_DISK_COUNT_OPT,
1691
  SPECS_DISK_SIZE_OPT,
1692
  SPECS_MEM_SIZE_OPT,
1693
  SPECS_NIC_COUNT_OPT,
1694
  ]
1695

    
1696

    
1697
class _ShowUsage(Exception):
1698
  """Exception class for L{_ParseArgs}.
1699

1700
  """
1701
  def __init__(self, exit_error):
1702
    """Initializes instances of this class.
1703

1704
    @type exit_error: bool
1705
    @param exit_error: Whether to report failure on exit
1706

1707
    """
1708
    Exception.__init__(self)
1709
    self.exit_error = exit_error
1710

    
1711

    
1712
class _ShowVersion(Exception):
1713
  """Exception class for L{_ParseArgs}.
1714

1715
  """
1716

    
1717

    
1718
def _ParseArgs(binary, argv, commands, aliases, env_override):
1719
  """Parser for the command line arguments.
1720

1721
  This function parses the arguments and returns the function which
1722
  must be executed together with its (modified) arguments.
1723

1724
  @param binary: Script name
1725
  @param argv: Command line arguments
1726
  @param commands: Dictionary containing command definitions
1727
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1728
  @param env_override: list of env variables allowed for default args
1729
  @raise _ShowUsage: If usage description should be shown
1730
  @raise _ShowVersion: If version should be shown
1731

1732
  """
1733
  assert not (env_override - set(commands))
1734
  assert not (set(aliases.keys()) & set(commands.keys()))
1735

    
1736
  if len(argv) > 1:
1737
    cmd = argv[1]
1738
  else:
1739
    # No option or command given
1740
    raise _ShowUsage(exit_error=True)
1741

    
1742
  if cmd == "--version":
1743
    raise _ShowVersion()
1744
  elif cmd == "--help":
1745
    raise _ShowUsage(exit_error=False)
1746
  elif not (cmd in commands or cmd in aliases):
1747
    raise _ShowUsage(exit_error=True)
1748

    
1749
  # get command, unalias it, and look it up in commands
1750
  if cmd in aliases:
1751
    if aliases[cmd] not in commands:
1752
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1753
                                   " command '%s'" % (cmd, aliases[cmd]))
1754

    
1755
    cmd = aliases[cmd]
1756

    
1757
  if cmd in env_override:
1758
    args_env_name = ("%s_%s" % (binary.replace("-", "_"), cmd)).upper()
1759
    env_args = os.environ.get(args_env_name)
1760
    if env_args:
1761
      argv = utils.InsertAtPos(argv, 2, shlex.split(env_args))
1762

    
1763
  func, args_def, parser_opts, usage, description = commands[cmd]
1764
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1765
                        description=description,
1766
                        formatter=TitledHelpFormatter(),
1767
                        usage="%%prog %s %s" % (cmd, usage))
1768
  parser.disable_interspersed_args()
1769
  options, args = parser.parse_args(args=argv[2:])
1770

    
1771
  if not _CheckArguments(cmd, args_def, args):
1772
    return None, None, None
1773

    
1774
  return func, options, args
1775

    
1776

    
1777
def _FormatUsage(binary, commands):
1778
  """Generates a nice description of all commands.
1779

1780
  @param binary: Script name
1781
  @param commands: Dictionary containing command definitions
1782

1783
  """
1784
  # compute the max line length for cmd + usage
1785
  mlen = min(60, max(map(len, commands)))
1786

    
1787
  yield "Usage: %s {command} [options...] [argument...]" % binary
1788
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1789
  yield ""
1790
  yield "Commands:"
1791

    
1792
  # and format a nice command list
1793
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1794
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1795
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1796
    for line in help_lines:
1797
      yield " %-*s   %s" % (mlen, "", line)
1798

    
1799
  yield ""
1800

    
1801

    
1802
def _CheckArguments(cmd, args_def, args):
1803
  """Verifies the arguments using the argument definition.
1804

1805
  Algorithm:
1806

1807
    1. Abort with error if values specified by user but none expected.
1808

1809
    1. For each argument in definition
1810

1811
      1. Keep running count of minimum number of values (min_count)
1812
      1. Keep running count of maximum number of values (max_count)
1813
      1. If it has an unlimited number of values
1814

1815
        1. Abort with error if it's not the last argument in the definition
1816

1817
    1. If last argument has limited number of values
1818

1819
      1. Abort with error if number of values doesn't match or is too large
1820

1821
    1. Abort with error if user didn't pass enough values (min_count)
1822

1823
  """
1824
  if args and not args_def:
1825
    ToStderr("Error: Command %s expects no arguments", cmd)
1826
    return False
1827

    
1828
  min_count = None
1829
  max_count = None
1830
  check_max = None
1831

    
1832
  last_idx = len(args_def) - 1
1833

    
1834
  for idx, arg in enumerate(args_def):
1835
    if min_count is None:
1836
      min_count = arg.min
1837
    elif arg.min is not None:
1838
      min_count += arg.min
1839

    
1840
    if max_count is None:
1841
      max_count = arg.max
1842
    elif arg.max is not None:
1843
      max_count += arg.max
1844

    
1845
    if idx == last_idx:
1846
      check_max = (arg.max is not None)
1847

    
1848
    elif arg.max is None:
1849
      raise errors.ProgrammerError("Only the last argument can have max=None")
1850

    
1851
  if check_max:
1852
    # Command with exact number of arguments
1853
    if (min_count is not None and max_count is not None and
1854
        min_count == max_count and len(args) != min_count):
1855
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1856
      return False
1857

    
1858
    # Command with limited number of arguments
1859
    if max_count is not None and len(args) > max_count:
1860
      ToStderr("Error: Command %s expects only %d argument(s)",
1861
               cmd, max_count)
1862
      return False
1863

    
1864
  # Command with some required arguments
1865
  if min_count is not None and len(args) < min_count:
1866
    ToStderr("Error: Command %s expects at least %d argument(s)",
1867
             cmd, min_count)
1868
    return False
1869

    
1870
  return True
1871

    
1872

    
1873
def SplitNodeOption(value):
1874
  """Splits the value of a --node option.
1875

1876
  """
1877
  if value and ":" in value:
1878
    return value.split(":", 1)
1879
  else:
1880
    return (value, None)
1881

    
1882

    
1883
def CalculateOSNames(os_name, os_variants):
1884
  """Calculates all the names an OS can be called, according to its variants.
1885

1886
  @type os_name: string
1887
  @param os_name: base name of the os
1888
  @type os_variants: list or None
1889
  @param os_variants: list of supported variants
1890
  @rtype: list
1891
  @return: list of valid names
1892

1893
  """
1894
  if os_variants:
1895
    return ["%s+%s" % (os_name, v) for v in os_variants]
1896
  else:
1897
    return [os_name]
1898

    
1899

    
1900
def ParseFields(selected, default):
1901
  """Parses the values of "--field"-like options.
1902

1903
  @type selected: string or None
1904
  @param selected: User-selected options
1905
  @type default: list
1906
  @param default: Default fields
1907

1908
  """
1909
  if selected is None:
1910
    return default
1911

    
1912
  if selected.startswith("+"):
1913
    return default + selected[1:].split(",")
1914

    
1915
  return selected.split(",")
1916

    
1917

    
1918
UsesRPC = rpc.RunWithRPC
1919

    
1920

    
1921
def AskUser(text, choices=None):
1922
  """Ask the user a question.
1923

1924
  @param text: the question to ask
1925

1926
  @param choices: list with elements tuples (input_char, return_value,
1927
      description); if not given, it will default to: [('y', True,
1928
      'Perform the operation'), ('n', False, 'Do no do the operation')];
1929
      note that the '?' char is reserved for help
1930

1931
  @return: one of the return values from the choices list; if input is
1932
      not possible (i.e. not running with a tty, we return the last
1933
      entry from the list
1934

1935
  """
1936
  if choices is None:
1937
    choices = [("y", True, "Perform the operation"),
1938
               ("n", False, "Do not perform the operation")]
1939
  if not choices or not isinstance(choices, list):
1940
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1941
  for entry in choices:
1942
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1943
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1944

    
1945
  answer = choices[-1][1]
1946
  new_text = []
1947
  for line in text.splitlines():
1948
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1949
  text = "\n".join(new_text)
1950
  try:
1951
    f = file("/dev/tty", "a+")
1952
  except IOError:
1953
    return answer
1954
  try:
1955
    chars = [entry[0] for entry in choices]
1956
    chars[-1] = "[%s]" % chars[-1]
1957
    chars.append("?")
1958
    maps = dict([(entry[0], entry[1]) for entry in choices])
1959
    while True:
1960
      f.write(text)
1961
      f.write("\n")
1962
      f.write("/".join(chars))
1963
      f.write(": ")
1964
      line = f.readline(2).strip().lower()
1965
      if line in maps:
1966
        answer = maps[line]
1967
        break
1968
      elif line == "?":
1969
        for entry in choices:
1970
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1971
        f.write("\n")
1972
        continue
1973
  finally:
1974
    f.close()
1975
  return answer
1976

    
1977

    
1978
class JobSubmittedException(Exception):
1979
  """Job was submitted, client should exit.
1980

1981
  This exception has one argument, the ID of the job that was
1982
  submitted. The handler should print this ID.
1983

1984
  This is not an error, just a structured way to exit from clients.
1985

1986
  """
1987

    
1988

    
1989
def SendJob(ops, cl=None):
1990
  """Function to submit an opcode without waiting for the results.
1991

1992
  @type ops: list
1993
  @param ops: list of opcodes
1994
  @type cl: luxi.Client
1995
  @param cl: the luxi client to use for communicating with the master;
1996
             if None, a new client will be created
1997

1998
  """
1999
  if cl is None:
2000
    cl = GetClient()
2001

    
2002
  job_id = cl.SubmitJob(ops)
2003

    
2004
  return job_id
2005

    
2006

    
2007
def GenericPollJob(job_id, cbs, report_cbs):
2008
  """Generic job-polling function.
2009

2010
  @type job_id: number
2011
  @param job_id: Job ID
2012
  @type cbs: Instance of L{JobPollCbBase}
2013
  @param cbs: Data callbacks
2014
  @type report_cbs: Instance of L{JobPollReportCbBase}
2015
  @param report_cbs: Reporting callbacks
2016

2017
  """
2018
  prev_job_info = None
2019
  prev_logmsg_serial = None
2020

    
2021
  status = None
2022

    
2023
  while True:
2024
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
2025
                                      prev_logmsg_serial)
2026
    if not result:
2027
      # job not found, go away!
2028
      raise errors.JobLost("Job with id %s lost" % job_id)
2029

    
2030
    if result == constants.JOB_NOTCHANGED:
2031
      report_cbs.ReportNotChanged(job_id, status)
2032

    
2033
      # Wait again
2034
      continue
2035

    
2036
    # Split result, a tuple of (field values, log entries)
2037
    (job_info, log_entries) = result
2038
    (status, ) = job_info
2039

    
2040
    if log_entries:
2041
      for log_entry in log_entries:
2042
        (serial, timestamp, log_type, message) = log_entry
2043
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
2044
                                    log_type, message)
2045
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
2046

    
2047
    # TODO: Handle canceled and archived jobs
2048
    elif status in (constants.JOB_STATUS_SUCCESS,
2049
                    constants.JOB_STATUS_ERROR,
2050
                    constants.JOB_STATUS_CANCELING,
2051
                    constants.JOB_STATUS_CANCELED):
2052
      break
2053

    
2054
    prev_job_info = job_info
2055

    
2056
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
2057
  if not jobs:
2058
    raise errors.JobLost("Job with id %s lost" % job_id)
2059

    
2060
  status, opstatus, result = jobs[0]
2061

    
2062
  if status == constants.JOB_STATUS_SUCCESS:
2063
    return result
2064

    
2065
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
2066
    raise errors.OpExecError("Job was canceled")
2067

    
2068
  has_ok = False
2069
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
2070
    if status == constants.OP_STATUS_SUCCESS:
2071
      has_ok = True
2072
    elif status == constants.OP_STATUS_ERROR:
2073
      errors.MaybeRaise(msg)
2074

    
2075
      if has_ok:
2076
        raise errors.OpExecError("partial failure (opcode %d): %s" %
2077
                                 (idx, msg))
2078

    
2079
      raise errors.OpExecError(str(msg))
2080

    
2081
  # default failure mode
2082
  raise errors.OpExecError(result)
2083

    
2084

    
2085
class JobPollCbBase:
2086
  """Base class for L{GenericPollJob} callbacks.
2087

2088
  """
2089
  def __init__(self):
2090
    """Initializes this class.
2091

2092
    """
2093

    
2094
  def WaitForJobChangeOnce(self, job_id, fields,
2095
                           prev_job_info, prev_log_serial):
2096
    """Waits for changes on a job.
2097

2098
    """
2099
    raise NotImplementedError()
2100

    
2101
  def QueryJobs(self, job_ids, fields):
2102
    """Returns the selected fields for the selected job IDs.
2103

2104
    @type job_ids: list of numbers
2105
    @param job_ids: Job IDs
2106
    @type fields: list of strings
2107
    @param fields: Fields
2108

2109
    """
2110
    raise NotImplementedError()
2111

    
2112

    
2113
class JobPollReportCbBase:
2114
  """Base class for L{GenericPollJob} reporting callbacks.
2115

2116
  """
2117
  def __init__(self):
2118
    """Initializes this class.
2119

2120
    """
2121

    
2122
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2123
    """Handles a log message.
2124

2125
    """
2126
    raise NotImplementedError()
2127

    
2128
  def ReportNotChanged(self, job_id, status):
2129
    """Called for if a job hasn't changed in a while.
2130

2131
    @type job_id: number
2132
    @param job_id: Job ID
2133
    @type status: string or None
2134
    @param status: Job status if available
2135

2136
    """
2137
    raise NotImplementedError()
2138

    
2139

    
2140
class _LuxiJobPollCb(JobPollCbBase):
2141
  def __init__(self, cl):
2142
    """Initializes this class.
2143

2144
    """
2145
    JobPollCbBase.__init__(self)
2146
    self.cl = cl
2147

    
2148
  def WaitForJobChangeOnce(self, job_id, fields,
2149
                           prev_job_info, prev_log_serial):
2150
    """Waits for changes on a job.
2151

2152
    """
2153
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2154
                                        prev_job_info, prev_log_serial)
2155

    
2156
  def QueryJobs(self, job_ids, fields):
2157
    """Returns the selected fields for the selected job IDs.
2158

2159
    """
2160
    return self.cl.QueryJobs(job_ids, fields)
2161

    
2162

    
2163
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2164
  def __init__(self, feedback_fn):
2165
    """Initializes this class.
2166

2167
    """
2168
    JobPollReportCbBase.__init__(self)
2169

    
2170
    self.feedback_fn = feedback_fn
2171

    
2172
    assert callable(feedback_fn)
2173

    
2174
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2175
    """Handles a log message.
2176

2177
    """
2178
    self.feedback_fn((timestamp, log_type, log_msg))
2179

    
2180
  def ReportNotChanged(self, job_id, status):
2181
    """Called if a job hasn't changed in a while.
2182

2183
    """
2184
    # Ignore
2185

    
2186

    
2187
class StdioJobPollReportCb(JobPollReportCbBase):
2188
  def __init__(self):
2189
    """Initializes this class.
2190

2191
    """
2192
    JobPollReportCbBase.__init__(self)
2193

    
2194
    self.notified_queued = False
2195
    self.notified_waitlock = False
2196

    
2197
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2198
    """Handles a log message.
2199

2200
    """
2201
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2202
             FormatLogMessage(log_type, log_msg))
2203

    
2204
  def ReportNotChanged(self, job_id, status):
2205
    """Called if a job hasn't changed in a while.
2206

2207
    """
2208
    if status is None:
2209
      return
2210

    
2211
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2212
      ToStderr("Job %s is waiting in queue", job_id)
2213
      self.notified_queued = True
2214

    
2215
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2216
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2217
      self.notified_waitlock = True
2218

    
2219

    
2220
def FormatLogMessage(log_type, log_msg):
2221
  """Formats a job message according to its type.
2222

2223
  """
2224
  if log_type != constants.ELOG_MESSAGE:
2225
    log_msg = str(log_msg)
2226

    
2227
  return utils.SafeEncode(log_msg)
2228

    
2229

    
2230
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2231
  """Function to poll for the result of a job.
2232

2233
  @type job_id: job identified
2234
  @param job_id: the job to poll for results
2235
  @type cl: luxi.Client
2236
  @param cl: the luxi client to use for communicating with the master;
2237
             if None, a new client will be created
2238

2239
  """
2240
  if cl is None:
2241
    cl = GetClient()
2242

    
2243
  if reporter is None:
2244
    if feedback_fn:
2245
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2246
    else:
2247
      reporter = StdioJobPollReportCb()
2248
  elif feedback_fn:
2249
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2250

    
2251
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2252

    
2253

    
2254
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2255
  """Legacy function to submit an opcode.
2256

2257
  This is just a simple wrapper over the construction of the processor
2258
  instance. It should be extended to better handle feedback and
2259
  interaction functions.
2260

2261
  """
2262
  if cl is None:
2263
    cl = GetClient()
2264

    
2265
  SetGenericOpcodeOpts([op], opts)
2266

    
2267
  job_id = SendJob([op], cl=cl)
2268

    
2269
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2270
                       reporter=reporter)
2271

    
2272
  return op_results[0]
2273

    
2274

    
2275
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2276
  """Wrapper around SubmitOpCode or SendJob.
2277

2278
  This function will decide, based on the 'opts' parameter, whether to
2279
  submit and wait for the result of the opcode (and return it), or
2280
  whether to just send the job and print its identifier. It is used in
2281
  order to simplify the implementation of the '--submit' option.
2282

2283
  It will also process the opcodes if we're sending the via SendJob
2284
  (otherwise SubmitOpCode does it).
2285

2286
  """
2287
  if opts and opts.submit_only:
2288
    job = [op]
2289
    SetGenericOpcodeOpts(job, opts)
2290
    job_id = SendJob(job, cl=cl)
2291
    raise JobSubmittedException(job_id)
2292
  else:
2293
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2294

    
2295

    
2296
def _InitReasonTrail(op, opts):
2297
  """Builds the first part of the reason trail
2298

2299
  Builds the initial part of the reason trail, adding the user provided reason
2300
  (if it exists) and the name of the command starting the operation.
2301

2302
  @param op: the opcode the reason trail will be added to
2303
  @param opts: the command line options selected by the user
2304

2305
  """
2306
  assert len(sys.argv) >= 2
2307
  trail = []
2308

    
2309
  if opts.reason:
2310
    trail.append((constants.OPCODE_REASON_SRC_USER,
2311
                  opts.reason,
2312
                  utils.EpochNano()))
2313

    
2314
  binary = os.path.basename(sys.argv[0])
2315
  source = "%s:%s" % (constants.OPCODE_REASON_SRC_CLIENT, binary)
2316
  command = sys.argv[1]
2317
  trail.append((source, command, utils.EpochNano()))
2318
  op.reason = trail
2319

    
2320

    
2321
def SetGenericOpcodeOpts(opcode_list, options):
2322
  """Processor for generic options.
2323

2324
  This function updates the given opcodes based on generic command
2325
  line options (like debug, dry-run, etc.).
2326

2327
  @param opcode_list: list of opcodes
2328
  @param options: command line options or None
2329
  @return: None (in-place modification)
2330

2331
  """
2332
  if not options:
2333
    return
2334
  for op in opcode_list:
2335
    op.debug_level = options.debug
2336
    if hasattr(options, "dry_run"):
2337
      op.dry_run = options.dry_run
2338
    if getattr(options, "priority", None) is not None:
2339
      op.priority = options.priority
2340
    _InitReasonTrail(op, options)
2341

    
2342

    
2343
def GetClient(query=False):
2344
  """Connects to the a luxi socket and returns a client.
2345

2346
  @type query: boolean
2347
  @param query: this signifies that the client will only be
2348
      used for queries; if the build-time parameter
2349
      enable-split-queries is enabled, then the client will be
2350
      connected to the query socket instead of the masterd socket
2351

2352
  """
2353
  override_socket = os.getenv(constants.LUXI_OVERRIDE, "")
2354
  if override_socket:
2355
    if override_socket == constants.LUXI_OVERRIDE_MASTER:
2356
      address = pathutils.MASTER_SOCKET
2357
    elif override_socket == constants.LUXI_OVERRIDE_QUERY:
2358
      address = pathutils.QUERY_SOCKET
2359
    else:
2360
      address = override_socket
2361
  elif query and constants.ENABLE_SPLIT_QUERY:
2362
    address = pathutils.QUERY_SOCKET
2363
  else:
2364
    address = None
2365
  # TODO: Cache object?
2366
  try:
2367
    client = luxi.Client(address=address)
2368
  except luxi.NoMasterError:
2369
    ss = ssconf.SimpleStore()
2370

    
2371
    # Try to read ssconf file
2372
    try:
2373
      ss.GetMasterNode()
2374
    except errors.ConfigurationError:
2375
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2376
                                 " not part of a cluster",
2377
                                 errors.ECODE_INVAL)
2378

    
2379
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2380
    if master != myself:
2381
      raise errors.OpPrereqError("This is not the master node, please connect"
2382
                                 " to node '%s' and rerun the command" %
2383
                                 master, errors.ECODE_INVAL)
2384
    raise
2385
  return client
2386

    
2387

    
2388
def FormatError(err):
2389
  """Return a formatted error message for a given error.
2390

2391
  This function takes an exception instance and returns a tuple
2392
  consisting of two values: first, the recommended exit code, and
2393
  second, a string describing the error message (not
2394
  newline-terminated).
2395

2396
  """
2397
  retcode = 1
2398
  obuf = StringIO()
2399
  msg = str(err)
2400
  if isinstance(err, errors.ConfigurationError):
2401
    txt = "Corrupt configuration file: %s" % msg
2402
    logging.error(txt)
2403
    obuf.write(txt + "\n")
2404
    obuf.write("Aborting.")
2405
    retcode = 2
2406
  elif isinstance(err, errors.HooksAbort):
2407
    obuf.write("Failure: hooks execution failed:\n")
2408
    for node, script, out in err.args[0]:
2409
      if out:
2410
        obuf.write("  node: %s, script: %s, output: %s\n" %
2411
                   (node, script, out))
2412
      else:
2413
        obuf.write("  node: %s, script: %s (no output)\n" %
2414
                   (node, script))
2415
  elif isinstance(err, errors.HooksFailure):
2416
    obuf.write("Failure: hooks general failure: %s" % msg)
2417
  elif isinstance(err, errors.ResolverError):
2418
    this_host = netutils.Hostname.GetSysName()
2419
    if err.args[0] == this_host:
2420
      msg = "Failure: can't resolve my own hostname ('%s')"
2421
    else:
2422
      msg = "Failure: can't resolve hostname '%s'"
2423
    obuf.write(msg % err.args[0])
2424
  elif isinstance(err, errors.OpPrereqError):
2425
    if len(err.args) == 2:
2426
      obuf.write("Failure: prerequisites not met for this"
2427
                 " operation:\nerror type: %s, error details:\n%s" %
2428
                 (err.args[1], err.args[0]))
2429
    else:
2430
      obuf.write("Failure: prerequisites not met for this"
2431
                 " operation:\n%s" % msg)
2432
  elif isinstance(err, errors.OpExecError):
2433
    obuf.write("Failure: command execution error:\n%s" % msg)
2434
  elif isinstance(err, errors.TagError):
2435
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
2436
  elif isinstance(err, errors.JobQueueDrainError):
2437
    obuf.write("Failure: the job queue is marked for drain and doesn't"
2438
               " accept new requests\n")
2439
  elif isinstance(err, errors.JobQueueFull):
2440
    obuf.write("Failure: the job queue is full and doesn't accept new"
2441
               " job submissions until old jobs are archived\n")
2442
  elif isinstance(err, errors.TypeEnforcementError):
2443
    obuf.write("Parameter Error: %s" % msg)
2444
  elif isinstance(err, errors.ParameterError):
2445
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
2446
  elif isinstance(err, luxi.NoMasterError):
2447
    if err.args[0] == pathutils.MASTER_SOCKET:
2448
      daemon = "the master daemon"
2449
    elif err.args[0] == pathutils.QUERY_SOCKET:
2450
      daemon = "the config daemon"
2451
    else:
2452
      daemon = "socket '%s'" % str(err.args[0])
2453
    obuf.write("Cannot communicate with %s.\nIs the process running"
2454
               " and listening for connections?" % daemon)
2455
  elif isinstance(err, luxi.TimeoutError):
2456
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
2457
               " been submitted and will continue to run even if the call"
2458
               " timed out. Useful commands in this situation are \"gnt-job"
2459
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
2460
    obuf.write(msg)
2461
  elif isinstance(err, luxi.PermissionError):
2462
    obuf.write("It seems you don't have permissions to connect to the"
2463
               " master daemon.\nPlease retry as a different user.")
2464
  elif isinstance(err, luxi.ProtocolError):
2465
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
2466
               "%s" % msg)
2467
  elif isinstance(err, errors.JobLost):
2468
    obuf.write("Error checking job status: %s" % msg)
2469
  elif isinstance(err, errors.QueryFilterParseError):
2470
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
2471
    obuf.write("\n".join(err.GetDetails()))
2472
  elif isinstance(err, errors.GenericError):
2473
    obuf.write("Unhandled Ganeti error: %s" % msg)
2474
  elif isinstance(err, JobSubmittedException):
2475
    obuf.write("JobID: %s\n" % err.args[0])
2476
    retcode = 0
2477
  else:
2478
    obuf.write("Unhandled exception: %s" % msg)
2479
  return retcode, obuf.getvalue().rstrip("\n")
2480

    
2481

    
2482
def GenericMain(commands, override=None, aliases=None,
2483
                env_override=frozenset()):
2484
  """Generic main function for all the gnt-* commands.
2485

2486
  @param commands: a dictionary with a special structure, see the design doc
2487
                   for command line handling.
2488
  @param override: if not None, we expect a dictionary with keys that will
2489
                   override command line options; this can be used to pass
2490
                   options from the scripts to generic functions
2491
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2492
  @param env_override: list of environment names which are allowed to submit
2493
                       default args for commands
2494

2495
  """
2496
  # save the program name and the entire command line for later logging
2497
  if sys.argv:
2498
    binary = os.path.basename(sys.argv[0])
2499
    if not binary:
2500
      binary = sys.argv[0]
2501

    
2502
    if len(sys.argv) >= 2:
2503
      logname = utils.ShellQuoteArgs([binary, sys.argv[1]])
2504
    else:
2505
      logname = binary
2506

    
2507
    cmdline = utils.ShellQuoteArgs([binary] + sys.argv[1:])
2508
  else:
2509
    binary = "<unknown program>"
2510
    cmdline = "<unknown>"
2511

    
2512
  if aliases is None:
2513
    aliases = {}
2514

    
2515
  try:
2516
    (func, options, args) = _ParseArgs(binary, sys.argv, commands, aliases,
2517
                                       env_override)
2518
  except _ShowVersion:
2519
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
2520
             constants.RELEASE_VERSION)
2521
    return constants.EXIT_SUCCESS
2522
  except _ShowUsage, err:
2523
    for line in _FormatUsage(binary, commands):
2524
      ToStdout(line)
2525

    
2526
    if err.exit_error:
2527
      return constants.EXIT_FAILURE
2528
    else:
2529
      return constants.EXIT_SUCCESS
2530
  except errors.ParameterError, err:
2531
    result, err_msg = FormatError(err)
2532
    ToStderr(err_msg)
2533
    return 1
2534

    
2535
  if func is None: # parse error
2536
    return 1
2537

    
2538
  if override is not None:
2539
    for key, val in override.iteritems():
2540
      setattr(options, key, val)
2541

    
2542
  utils.SetupLogging(pathutils.LOG_COMMANDS, logname, debug=options.debug,
2543
                     stderr_logging=True)
2544

    
2545
  logging.info("Command line: %s", cmdline)
2546

    
2547
  try:
2548
    result = func(options, args)
2549
  except (errors.GenericError, luxi.ProtocolError,
2550
          JobSubmittedException), err:
2551
    result, err_msg = FormatError(err)
2552
    logging.exception("Error during command processing")
2553
    ToStderr(err_msg)
2554
  except KeyboardInterrupt:
2555
    result = constants.EXIT_FAILURE
2556
    ToStderr("Aborted. Note that if the operation created any jobs, they"
2557
             " might have been submitted and"
2558
             " will continue to run in the background.")
2559
  except IOError, err:
2560
    if err.errno == errno.EPIPE:
2561
      # our terminal went away, we'll exit
2562
      sys.exit(constants.EXIT_FAILURE)
2563
    else:
2564
      raise
2565

    
2566
  return result
2567

    
2568

    
2569
def ParseNicOption(optvalue):
2570
  """Parses the value of the --net option(s).
2571

2572
  """
2573
  try:
2574
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2575
  except (TypeError, ValueError), err:
2576
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2577
                               errors.ECODE_INVAL)
2578

    
2579
  nics = [{}] * nic_max
2580
  for nidx, ndict in optvalue:
2581
    nidx = int(nidx)
2582

    
2583
    if not isinstance(ndict, dict):
2584
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2585
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2586

    
2587
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2588

    
2589
    nics[nidx] = ndict
2590

    
2591
  return nics
2592

    
2593

    
2594
def GenericInstanceCreate(mode, opts, args):
2595
  """Add an instance to the cluster via either creation or import.
2596

2597
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2598
  @param opts: the command line options selected by the user
2599
  @type args: list
2600
  @param args: should contain only one element, the new instance name
2601
  @rtype: int
2602
  @return: the desired exit code
2603

2604
  """
2605
  instance = args[0]
2606

    
2607
  (pnode, snode) = SplitNodeOption(opts.node)
2608

    
2609
  hypervisor = None
2610
  hvparams = {}
2611
  if opts.hypervisor:
2612
    hypervisor, hvparams = opts.hypervisor
2613

    
2614
  if opts.nics:
2615
    nics = ParseNicOption(opts.nics)
2616
  elif opts.no_nics:
2617
    # no nics
2618
    nics = []
2619
  elif mode == constants.INSTANCE_CREATE:
2620
    # default of one nic, all auto
2621
    nics = [{}]
2622
  else:
2623
    # mode == import
2624
    nics = []
2625

    
2626
  if opts.disk_template == constants.DT_DISKLESS:
2627
    if opts.disks or opts.sd_size is not None:
2628
      raise errors.OpPrereqError("Diskless instance but disk"
2629
                                 " information passed", errors.ECODE_INVAL)
2630
    disks = []
2631
  else:
2632
    if (not opts.disks and not opts.sd_size
2633
        and mode == constants.INSTANCE_CREATE):
2634
      raise errors.OpPrereqError("No disk information specified",
2635
                                 errors.ECODE_INVAL)
2636
    if opts.disks and opts.sd_size is not None:
2637
      raise errors.OpPrereqError("Please use either the '--disk' or"
2638
                                 " '-s' option", errors.ECODE_INVAL)
2639
    if opts.sd_size is not None:
2640
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2641

    
2642
    if opts.disks:
2643
      try:
2644
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2645
      except ValueError, err:
2646
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
2647
                                   errors.ECODE_INVAL)
2648
      disks = [{}] * disk_max
2649
    else:
2650
      disks = []
2651
    for didx, ddict in opts.disks:
2652
      didx = int(didx)
2653
      if not isinstance(ddict, dict):
2654
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2655
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
2656
      elif constants.IDISK_SIZE in ddict:
2657
        if constants.IDISK_ADOPT in ddict:
2658
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2659
                                     " (disk %d)" % didx, errors.ECODE_INVAL)
2660
        try:
2661
          ddict[constants.IDISK_SIZE] = \
2662
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2663
        except ValueError, err:
2664
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2665
                                     (didx, err), errors.ECODE_INVAL)
2666
      elif constants.IDISK_ADOPT in ddict:
2667
        if mode == constants.INSTANCE_IMPORT:
2668
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2669
                                     " import", errors.ECODE_INVAL)
2670
        ddict[constants.IDISK_SIZE] = 0
2671
      else:
2672
        raise errors.OpPrereqError("Missing size or adoption source for"
2673
                                   " disk %d" % didx, errors.ECODE_INVAL)
2674
      disks[didx] = ddict
2675

    
2676
  if opts.tags is not None:
2677
    tags = opts.tags.split(",")
2678
  else:
2679
    tags = []
2680

    
2681
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT)
2682
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2683

    
2684
  if mode == constants.INSTANCE_CREATE:
2685
    start = opts.start
2686
    os_type = opts.os
2687
    force_variant = opts.force_variant
2688
    src_node = None
2689
    src_path = None
2690
    no_install = opts.no_install
2691
    identify_defaults = False
2692
  elif mode == constants.INSTANCE_IMPORT:
2693
    start = False
2694
    os_type = None
2695
    force_variant = False
2696
    src_node = opts.src_node
2697
    src_path = opts.src_dir
2698
    no_install = None
2699
    identify_defaults = opts.identify_defaults
2700
  else:
2701
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2702

    
2703
  op = opcodes.OpInstanceCreate(instance_name=instance,
2704
                                disks=disks,
2705
                                disk_template=opts.disk_template,
2706
                                nics=nics,
2707
                                conflicts_check=opts.conflicts_check,
2708
                                pnode=pnode, snode=snode,
2709
                                ip_check=opts.ip_check,
2710
                                name_check=opts.name_check,
2711
                                wait_for_sync=opts.wait_for_sync,
2712
                                file_storage_dir=opts.file_storage_dir,
2713
                                file_driver=opts.file_driver,
2714
                                iallocator=opts.iallocator,
2715
                                hypervisor=hypervisor,
2716
                                hvparams=hvparams,
2717
                                beparams=opts.beparams,
2718
                                osparams=opts.osparams,
2719
                                mode=mode,
2720
                                start=start,
2721
                                os_type=os_type,
2722
                                force_variant=force_variant,
2723
                                src_node=src_node,
2724
                                src_path=src_path,
2725
                                tags=tags,
2726
                                no_install=no_install,
2727
                                identify_defaults=identify_defaults,
2728
                                ignore_ipolicy=opts.ignore_ipolicy)
2729

    
2730
  SubmitOrSend(op, opts)
2731
  return 0
2732

    
2733

    
2734
class _RunWhileClusterStoppedHelper:
2735
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2736

2737
  """
2738
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2739
    """Initializes this class.
2740

2741
    @type feedback_fn: callable
2742
    @param feedback_fn: Feedback function
2743
    @type cluster_name: string
2744
    @param cluster_name: Cluster name
2745
    @type master_node: string
2746
    @param master_node Master node name
2747
    @type online_nodes: list
2748
    @param online_nodes: List of names of online nodes
2749

2750
    """
2751
    self.feedback_fn = feedback_fn
2752
    self.cluster_name = cluster_name
2753
    self.master_node = master_node
2754
    self.online_nodes = online_nodes
2755

    
2756
    self.ssh = ssh.SshRunner(self.cluster_name)
2757

    
2758
    self.nonmaster_nodes = [name for name in online_nodes
2759
                            if name != master_node]
2760

    
2761
    assert self.master_node not in self.nonmaster_nodes
2762

    
2763
  def _RunCmd(self, node_name, cmd):
2764
    """Runs a command on the local or a remote machine.
2765

2766
    @type node_name: string
2767
    @param node_name: Machine name
2768
    @type cmd: list
2769
    @param cmd: Command
2770

2771
    """
2772
    if node_name is None or node_name == self.master_node:
2773
      # No need to use SSH
2774
      result = utils.RunCmd(cmd)
2775
    else:
2776
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2777
                            utils.ShellQuoteArgs(cmd))
2778

    
2779
    if result.failed:
2780
      errmsg = ["Failed to run command %s" % result.cmd]
2781
      if node_name:
2782
        errmsg.append("on node %s" % node_name)
2783
      errmsg.append(": exitcode %s and error %s" %
2784
                    (result.exit_code, result.output))
2785
      raise errors.OpExecError(" ".join(errmsg))
2786

    
2787
  def Call(self, fn, *args):
2788
    """Call function while all daemons are stopped.
2789

2790
    @type fn: callable
2791
    @param fn: Function to be called
2792

2793
    """
2794
    # Pause watcher by acquiring an exclusive lock on watcher state file
2795
    self.feedback_fn("Blocking watcher")
2796
    watcher_block = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
2797
    try:
2798
      # TODO: Currently, this just blocks. There's no timeout.
2799
      # TODO: Should it be a shared lock?
2800
      watcher_block.Exclusive(blocking=True)
2801

    
2802
      # Stop master daemons, so that no new jobs can come in and all running
2803
      # ones are finished
2804
      self.feedback_fn("Stopping master daemons")
2805
      self._RunCmd(None, [pathutils.DAEMON_UTIL, "stop-master"])
2806
      try:
2807
        # Stop daemons on all nodes
2808
        for node_name in self.online_nodes:
2809
          self.feedback_fn("Stopping daemons on %s" % node_name)
2810
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "stop-all"])
2811

    
2812
        # All daemons are shut down now
2813
        try:
2814
          return fn(self, *args)
2815
        except Exception, err:
2816
          _, errmsg = FormatError(err)
2817
          logging.exception("Caught exception")
2818
          self.feedback_fn(errmsg)
2819
          raise
2820
      finally:
2821
        # Start cluster again, master node last
2822
        for node_name in self.nonmaster_nodes + [self.master_node]:
2823
          self.feedback_fn("Starting daemons on %s" % node_name)
2824
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "start-all"])
2825
    finally:
2826
      # Resume watcher
2827
      watcher_block.Close()
2828

    
2829

    
2830
def RunWhileClusterStopped(feedback_fn, fn, *args):
2831
  """Calls a function while all cluster daemons are stopped.
2832

2833
  @type feedback_fn: callable
2834
  @param feedback_fn: Feedback function
2835
  @type fn: callable
2836
  @param fn: Function to be called when daemons are stopped
2837

2838
  """
2839
  feedback_fn("Gathering cluster information")
2840

    
2841
  # This ensures we're running on the master daemon
2842
  cl = GetClient()
2843

    
2844
  (cluster_name, master_node) = \
2845
    cl.QueryConfigValues(["cluster_name", "master_node"])
2846

    
2847
  online_nodes = GetOnlineNodes([], cl=cl)
2848

    
2849
  # Don't keep a reference to the client. The master daemon will go away.
2850
  del cl
2851

    
2852
  assert master_node in online_nodes
2853

    
2854
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2855
                                       online_nodes).Call(fn, *args)
2856

    
2857

    
2858
def GenerateTable(headers, fields, separator, data,
2859
                  numfields=None, unitfields=None,
2860
                  units=None):
2861
  """Prints a table with headers and different fields.
2862

2863
  @type headers: dict
2864
  @param headers: dictionary mapping field names to headers for
2865
      the table
2866
  @type fields: list
2867
  @param fields: the field names corresponding to each row in
2868
      the data field
2869
  @param separator: the separator to be used; if this is None,
2870
      the default 'smart' algorithm is used which computes optimal
2871
      field width, otherwise just the separator is used between
2872
      each field
2873
  @type data: list
2874
  @param data: a list of lists, each sublist being one row to be output
2875
  @type numfields: list
2876
  @param numfields: a list with the fields that hold numeric
2877
      values and thus should be right-aligned
2878
  @type unitfields: list
2879
  @param unitfields: a list with the fields that hold numeric
2880
      values that should be formatted with the units field
2881
  @type units: string or None
2882
  @param units: the units we should use for formatting, or None for
2883
      automatic choice (human-readable for non-separator usage, otherwise
2884
      megabytes); this is a one-letter string
2885

2886
  """
2887
  if units is None:
2888
    if separator:
2889
      units = "m"
2890
    else:
2891
      units = "h"
2892

    
2893
  if numfields is None:
2894
    numfields = []
2895
  if unitfields is None:
2896
    unitfields = []
2897

    
2898
  numfields = utils.FieldSet(*numfields)   # pylint: disable=W0142
2899
  unitfields = utils.FieldSet(*unitfields) # pylint: disable=W0142
2900

    
2901
  format_fields = []
2902
  for field in fields:
2903
    if headers and field not in headers:
2904
      # TODO: handle better unknown fields (either revert to old
2905
      # style of raising exception, or deal more intelligently with
2906
      # variable fields)
2907
      headers[field] = field
2908
    if separator is not None:
2909
      format_fields.append("%s")
2910
    elif numfields.Matches(field):
2911
      format_fields.append("%*s")
2912
    else:
2913
      format_fields.append("%-*s")
2914

    
2915
  if separator is None:
2916
    mlens = [0 for name in fields]
2917
    format_str = " ".join(format_fields)
2918
  else:
2919
    format_str = separator.replace("%", "%%").join(format_fields)
2920

    
2921
  for row in data:
2922
    if row is None:
2923
      continue
2924
    for idx, val in enumerate(row):
2925
      if unitfields.Matches(fields[idx]):
2926
        try:
2927
          val = int(val)
2928
        except (TypeError, ValueError):
2929
          pass
2930
        else:
2931
          val = row[idx] = utils.FormatUnit(val, units)
2932
      val = row[idx] = str(val)
2933
      if separator is None:
2934
        mlens[idx] = max(mlens[idx], len(val))
2935

    
2936
  result = []
2937
  if headers:
2938
    args = []
2939
    for idx, name in enumerate(fields):
2940
      hdr = headers[name]
2941
      if separator is None:
2942
        mlens[idx] = max(mlens[idx], len(hdr))
2943
        args.append(mlens[idx])
2944
      args.append(hdr)
2945
    result.append(format_str % tuple(args))
2946

    
2947
  if separator is None:
2948
    assert len(mlens) == len(fields)
2949

    
2950
    if fields and not numfields.Matches(fields[-1]):
2951
      mlens[-1] = 0
2952

    
2953
  for line in data:
2954
    args = []
2955
    if line is None:
2956
      line = ["-" for _ in fields]
2957
    for idx in range(len(fields)):
2958
      if separator is None:
2959
        args.append(mlens[idx])
2960
      args.append(line[idx])
2961
    result.append(format_str % tuple(args))
2962

    
2963
  return result
2964

    
2965

    
2966
def _FormatBool(value):
2967
  """Formats a boolean value as a string.
2968

2969
  """
2970
  if value:
2971
    return "Y"
2972
  return "N"
2973

    
2974

    
2975
#: Default formatting for query results; (callback, align right)
2976
_DEFAULT_FORMAT_QUERY = {
2977
  constants.QFT_TEXT: (str, False),
2978
  constants.QFT_BOOL: (_FormatBool, False),
2979
  constants.QFT_NUMBER: (str, True),
2980
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2981
  constants.QFT_OTHER: (str, False),
2982
  constants.QFT_UNKNOWN: (str, False),
2983
  }
2984

    
2985

    
2986
def _GetColumnFormatter(fdef, override, unit):
2987
  """Returns formatting function for a field.
2988

2989
  @type fdef: L{objects.QueryFieldDefinition}
2990
  @type override: dict
2991
  @param override: Dictionary for overriding field formatting functions,
2992
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2993
  @type unit: string
2994
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2995
  @rtype: tuple; (callable, bool)
2996
  @return: Returns the function to format a value (takes one parameter) and a
2997
    boolean for aligning the value on the right-hand side
2998

2999
  """
3000
  fmt = override.get(fdef.name, None)
3001
  if fmt is not None:
3002
    return fmt
3003

    
3004
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
3005

    
3006
  if fdef.kind == constants.QFT_UNIT:
3007
    # Can't keep this information in the static dictionary
3008
    return (lambda value: utils.FormatUnit(value, unit), True)
3009

    
3010
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
3011
  if fmt is not None:
3012
    return fmt
3013

    
3014
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
3015

    
3016

    
3017
class _QueryColumnFormatter:
3018
  """Callable class for formatting fields of a query.
3019

3020
  """
3021
  def __init__(self, fn, status_fn, verbose):
3022
    """Initializes this class.
3023

3024
    @type fn: callable
3025
    @param fn: Formatting function
3026
    @type status_fn: callable
3027
    @param status_fn: Function to report fields' status
3028
    @type verbose: boolean
3029
    @param verbose: whether to use verbose field descriptions or not
3030

3031
    """
3032
    self._fn = fn
3033
    self._status_fn = status_fn
3034
    self._verbose = verbose
3035

    
3036
  def __call__(self, data):
3037
    """Returns a field's string representation.
3038

3039
    """
3040
    (status, value) = data
3041

    
3042
    # Report status
3043
    self._status_fn(status)
3044

    
3045
    if status == constants.RS_NORMAL:
3046
      return self._fn(value)
3047

    
3048
    assert value is None, \
3049
           "Found value %r for abnormal status %s" % (value, status)
3050

    
3051
    return FormatResultError(status, self._verbose)
3052

    
3053

    
3054
def FormatResultError(status, verbose):
3055
  """Formats result status other than L{constants.RS_NORMAL}.
3056

3057
  @param status: The result status
3058
  @type verbose: boolean
3059
  @param verbose: Whether to return the verbose text
3060
  @return: Text of result status
3061

3062
  """
3063
  assert status != constants.RS_NORMAL, \
3064
         "FormatResultError called with status equal to constants.RS_NORMAL"
3065
  try:
3066
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
3067
  except KeyError:
3068
    raise NotImplementedError("Unknown status %s" % status)
3069
  else:
3070
    if verbose:
3071
      return verbose_text
3072
    return normal_text
3073

    
3074

    
3075
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
3076
                      header=False, verbose=False):
3077
  """Formats data in L{objects.QueryResponse}.
3078

3079
  @type result: L{objects.QueryResponse}
3080
  @param result: result of query operation
3081
  @type unit: string
3082
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
3083
    see L{utils.text.FormatUnit}
3084
  @type format_override: dict
3085
  @param format_override: Dictionary for overriding field formatting functions,
3086
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3087
  @type separator: string or None
3088
  @param separator: String used to separate fields
3089
  @type header: bool
3090
  @param header: Whether to output header row
3091
  @type verbose: boolean
3092
  @param verbose: whether to use verbose field descriptions or not
3093

3094
  """
3095
  if unit is None:
3096
    if separator:
3097
      unit = "m"
3098
    else:
3099
      unit = "h"
3100

    
3101
  if format_override is None:
3102
    format_override = {}
3103

    
3104
  stats = dict.fromkeys(constants.RS_ALL, 0)
3105

    
3106
  def _RecordStatus(status):
3107
    if status in stats:
3108
      stats[status] += 1
3109

    
3110
  columns = []
3111
  for fdef in result.fields:
3112
    assert fdef.title and fdef.name
3113
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
3114
    columns.append(TableColumn(fdef.title,
3115
                               _QueryColumnFormatter(fn, _RecordStatus,
3116
                                                     verbose),
3117
                               align_right))
3118

    
3119
  table = FormatTable(result.data, columns, header, separator)
3120

    
3121
  # Collect statistics
3122
  assert len(stats) == len(constants.RS_ALL)
3123
  assert compat.all(count >= 0 for count in stats.values())
3124

    
3125
  # Determine overall status. If there was no data, unknown fields must be
3126
  # detected via the field definitions.
3127
  if (stats[constants.RS_UNKNOWN] or
3128
      (not result.data and _GetUnknownFields(result.fields))):
3129
    status = QR_UNKNOWN
3130
  elif compat.any(count > 0 for key, count in stats.items()
3131
                  if key != constants.RS_NORMAL):
3132
    status = QR_INCOMPLETE
3133
  else:
3134
    status = QR_NORMAL
3135

    
3136
  return (status, table)
3137

    
3138

    
3139
def _GetUnknownFields(fdefs):
3140
  """Returns list of unknown fields included in C{fdefs}.
3141

3142
  @type fdefs: list of L{objects.QueryFieldDefinition}
3143

3144
  """
3145
  return [fdef for fdef in fdefs
3146
          if fdef.kind == constants.QFT_UNKNOWN]
3147

    
3148

    
3149
def _WarnUnknownFields(fdefs):
3150
  """Prints a warning to stderr if a query included unknown fields.
3151

3152
  @type fdefs: list of L{objects.QueryFieldDefinition}
3153

3154
  """
3155
  unknown = _GetUnknownFields(fdefs)
3156
  if unknown:
3157
    ToStderr("Warning: Queried for unknown fields %s",
3158
             utils.CommaJoin(fdef.name for fdef in unknown))
3159
    return True
3160

    
3161
  return False
3162

    
3163

    
3164
def GenericList(resource, fields, names, unit, separator, header, cl=None,
3165
                format_override=None, verbose=False, force_filter=False,
3166
                namefield=None, qfilter=None, isnumeric=False):
3167
  """Generic implementation for listing all items of a resource.
3168

3169
  @param resource: One of L{constants.QR_VIA_LUXI}
3170
  @type fields: list of strings
3171
  @param fields: List of fields to query for
3172
  @type names: list of strings
3173
  @param names: Names of items to query for
3174
  @type unit: string or None
3175
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3176
    None for automatic choice (human-readable for non-separator usage,
3177
    otherwise megabytes); this is a one-letter string
3178
  @type separator: string or None
3179
  @param separator: String used to separate fields
3180
  @type header: bool
3181
  @param header: Whether to show header row
3182
  @type force_filter: bool
3183
  @param force_filter: Whether to always treat names as filter
3184
  @type format_override: dict
3185
  @param format_override: Dictionary for overriding field formatting functions,
3186
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3187
  @type verbose: boolean
3188
  @param verbose: whether to use verbose field descriptions or not
3189
  @type namefield: string
3190
  @param namefield: Name of field to use for simple filters (see
3191
    L{qlang.MakeFilter} for details)
3192
  @type qfilter: list or None
3193
  @param qfilter: Query filter (in addition to names)
3194
  @param isnumeric: bool
3195
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3196
    any simple filters built by namefield should use integer values to
3197
    reflect that
3198

3199
  """
3200
  if not names:
3201
    names = None
3202

    
3203
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3204
                                isnumeric=isnumeric)
3205

    
3206
  if qfilter is None:
3207
    qfilter = namefilter
3208
  elif namefilter is not None:
3209
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3210

    
3211
  if cl is None:
3212
    cl = GetClient()
3213

    
3214
  response = cl.Query(resource, fields, qfilter)
3215

    
3216
  found_unknown = _WarnUnknownFields(response.fields)
3217

    
3218
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3219
                                     header=header,
3220
                                     format_override=format_override,
3221
                                     verbose=verbose)
3222

    
3223
  for line in data:
3224
    ToStdout(line)
3225

    
3226
  assert ((found_unknown and status == QR_UNKNOWN) or
3227
          (not found_unknown and status != QR_UNKNOWN))
3228

    
3229
  if status == QR_UNKNOWN:
3230
    return constants.EXIT_UNKNOWN_FIELD
3231

    
3232
  # TODO: Should the list command fail if not all data could be collected?
3233
  return constants.EXIT_SUCCESS
3234

    
3235

    
3236
def _FieldDescValues(fdef):
3237
  """Helper function for L{GenericListFields} to get query field description.
3238

3239
  @type fdef: L{objects.QueryFieldDefinition}
3240
  @rtype: list
3241

3242
  """
3243
  return [
3244
    fdef.name,
3245
    _QFT_NAMES.get(fdef.kind, fdef.kind),
3246
    fdef.title,
3247
    fdef.doc,
3248
    ]
3249

    
3250

    
3251
def GenericListFields(resource, fields, separator, header, cl=None):
3252
  """Generic implementation for listing fields for a resource.
3253

3254
  @param resource: One of L{constants.QR_VIA_LUXI}
3255
  @type fields: list of strings
3256
  @param fields: List of fields to query for
3257
  @type separator: string or None
3258
  @param separator: String used to separate fields
3259
  @type header: bool
3260
  @param header: Whether to show header row
3261

3262
  """
3263
  if cl is None:
3264
    cl = GetClient()
3265

    
3266
  if not fields:
3267
    fields = None
3268

    
3269
  response = cl.QueryFields(resource, fields)
3270

    
3271
  found_unknown = _WarnUnknownFields(response.fields)
3272

    
3273
  columns = [
3274
    TableColumn("Name", str, False),
3275
    TableColumn("Type", str, False),
3276
    TableColumn("Title", str, False),
3277
    TableColumn("Description", str, False),
3278
    ]
3279

    
3280
  rows = map(_FieldDescValues, response.fields)
3281

    
3282
  for line in FormatTable(rows, columns, header, separator):
3283
    ToStdout(line)
3284

    
3285
  if found_unknown:
3286
    return constants.EXIT_UNKNOWN_FIELD
3287

    
3288
  return constants.EXIT_SUCCESS
3289

    
3290

    
3291
class TableColumn:
3292
  """Describes a column for L{FormatTable}.
3293

3294
  """
3295
  def __init__(self, title, fn, align_right):
3296
    """Initializes this class.
3297

3298
    @type title: string
3299
    @param title: Column title
3300
    @type fn: callable
3301
    @param fn: Formatting function
3302
    @type align_right: bool
3303
    @param align_right: Whether to align values on the right-hand side
3304

3305
    """
3306
    self.title = title
3307
    self.format = fn
3308
    self.align_right = align_right
3309

    
3310

    
3311
def _GetColFormatString(width, align_right):
3312
  """Returns the format string for a field.
3313

3314
  """
3315
  if align_right:
3316
    sign = ""
3317
  else:
3318
    sign = "-"
3319

    
3320
  return "%%%s%ss" % (sign, width)
3321

    
3322

    
3323
def FormatTable(rows, columns, header, separator):
3324
  """Formats data as a table.
3325

3326
  @type rows: list of lists
3327
  @param rows: Row data, one list per row
3328
  @type columns: list of L{TableColumn}
3329
  @param columns: Column descriptions
3330
  @type header: bool
3331
  @param header: Whether to show header row
3332
  @type separator: string or None
3333
  @param separator: String used to separate columns
3334

3335
  """
3336
  if header:
3337
    data = [[col.title for col in columns]]
3338
    colwidth = [len(col.title) for col in columns]
3339
  else:
3340
    data = []
3341
    colwidth = [0 for _ in columns]
3342

    
3343
  # Format row data
3344
  for row in rows:
3345
    assert len(row) == len(columns)
3346

    
3347
    formatted = [col.format(value) for value, col in zip(row, columns)]
3348

    
3349
    if separator is None:
3350
      # Update column widths
3351
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3352
        # Modifying a list's items while iterating is fine
3353
        colwidth[idx] = max(oldwidth, len(value))
3354

    
3355
    data.append(formatted)
3356

    
3357
  if separator is not None:
3358
    # Return early if a separator is used
3359
    return [separator.join(row) for row in data]
3360

    
3361
  if columns and not columns[-1].align_right:
3362
    # Avoid unnecessary spaces at end of line
3363
    colwidth[-1] = 0
3364

    
3365
  # Build format string
3366
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3367
                  for col, width in zip(columns, colwidth)])
3368

    
3369
  return [fmt % tuple(row) for row in data]
3370

    
3371

    
3372
def FormatTimestamp(ts):
3373
  """Formats a given timestamp.
3374

3375
  @type ts: timestamp
3376
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3377

3378
  @rtype: string
3379
  @return: a string with the formatted timestamp
3380

3381
  """
3382
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3383
    return "?"
3384

    
3385
  (sec, usecs) = ts
3386
  return utils.FormatTime(sec, usecs=usecs)
3387

    
3388

    
3389
def ParseTimespec(value):
3390
  """Parse a time specification.
3391

3392
  The following suffixed will be recognized:
3393

3394
    - s: seconds
3395
    - m: minutes
3396
    - h: hours
3397
    - d: day
3398
    - w: weeks
3399

3400
  Without any suffix, the value will be taken to be in seconds.
3401

3402
  """
3403
  value = str(value)
3404
  if not value:
3405
    raise errors.OpPrereqError("Empty time specification passed",
3406
                               errors.ECODE_INVAL)
3407
  suffix_map = {
3408
    "s": 1,
3409
    "m": 60,
3410
    "h": 3600,
3411
    "d": 86400,
3412
    "w": 604800,
3413
    }
3414
  if value[-1] not in suffix_map:
3415
    try:
3416
      value = int(value)
3417
    except (TypeError, ValueError):
3418
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3419
                                 errors.ECODE_INVAL)
3420
  else:
3421
    multiplier = suffix_map[value[-1]]
3422
    value = value[:-1]
3423
    if not value: # no data left after stripping the suffix
3424
      raise errors.OpPrereqError("Invalid time specification (only"
3425
                                 " suffix passed)", errors.ECODE_INVAL)
3426
    try:
3427
      value = int(value) * multiplier
3428
    except (TypeError, ValueError):
3429
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3430
                                 errors.ECODE_INVAL)
3431
  return value
3432

    
3433

    
3434
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3435
                   filter_master=False, nodegroup=None):
3436
  """Returns the names of online nodes.
3437

3438
  This function will also log a warning on stderr with the names of
3439
  the online nodes.
3440

3441
  @param nodes: if not empty, use only this subset of nodes (minus the
3442
      offline ones)
3443
  @param cl: if not None, luxi client to use
3444
  @type nowarn: boolean
3445
  @param nowarn: by default, this function will output a note with the
3446
      offline nodes that are skipped; if this parameter is True the
3447
      note is not displayed
3448
  @type secondary_ips: boolean
3449
  @param secondary_ips: if True, return the secondary IPs instead of the
3450
      names, useful for doing network traffic over the replication interface
3451
      (if any)
3452
  @type filter_master: boolean
3453
  @param filter_master: if True, do not return the master node in the list
3454
      (useful in coordination with secondary_ips where we cannot check our
3455
      node name against the list)
3456
  @type nodegroup: string
3457
  @param nodegroup: If set, only return nodes in this node group
3458

3459
  """
3460
  if cl is None:
3461
    cl = GetClient()
3462

    
3463
  qfilter = []
3464

    
3465
  if nodes:
3466
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3467

    
3468
  if nodegroup is not None:
3469
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3470
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3471

    
3472
  if filter_master:
3473
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3474

    
3475
  if qfilter:
3476
    if len(qfilter) > 1:
3477
      final_filter = [qlang.OP_AND] + qfilter
3478
    else:
3479
      assert len(qfilter) == 1
3480
      final_filter = qfilter[0]
3481
  else:
3482
    final_filter = None
3483

    
3484
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3485

    
3486
  def _IsOffline(row):
3487
    (_, (_, offline), _) = row
3488
    return offline
3489

    
3490
  def _GetName(row):
3491
    ((_, name), _, _) = row
3492
    return name
3493

    
3494
  def _GetSip(row):
3495
    (_, _, (_, sip)) = row
3496
    return sip
3497

    
3498
  (offline, online) = compat.partition(result.data, _IsOffline)
3499

    
3500
  if offline and not nowarn:
3501
    ToStderr("Note: skipping offline node(s): %s" %
3502
             utils.CommaJoin(map(_GetName, offline)))
3503

    
3504
  if secondary_ips:
3505
    fn = _GetSip
3506
  else:
3507
    fn = _GetName
3508

    
3509
  return map(fn, online)
3510

    
3511

    
3512
def _ToStream(stream, txt, *args):
3513
  """Write a message to a stream, bypassing the logging system
3514

3515
  @type stream: file object
3516
  @param stream: the file to which we should write
3517
  @type txt: str
3518
  @param txt: the message
3519

3520
  """
3521
  try:
3522
    if args:
3523
      args = tuple(args)
3524
      stream.write(txt % args)
3525
    else:
3526
      stream.write(txt)
3527
    stream.write("\n")
3528
    stream.flush()
3529
  except IOError, err:
3530
    if err.errno == errno.EPIPE:
3531
      # our terminal went away, we'll exit
3532
      sys.exit(constants.EXIT_FAILURE)
3533
    else:
3534
      raise
3535

    
3536

    
3537
def ToStdout(txt, *args):
3538
  """Write a message to stdout only, bypassing the logging system
3539

3540
  This is just a wrapper over _ToStream.
3541

3542
  @type txt: str
3543
  @param txt: the message
3544

3545
  """
3546
  _ToStream(sys.stdout, txt, *args)
3547

    
3548

    
3549
def ToStderr(txt, *args):
3550
  """Write a message to stderr only, bypassing the logging system
3551

3552
  This is just a wrapper over _ToStream.
3553

3554
  @type txt: str
3555
  @param txt: the message
3556

3557
  """
3558
  _ToStream(sys.stderr, txt, *args)
3559

    
3560

    
3561
class JobExecutor(object):
3562
  """Class which manages the submission and execution of multiple jobs.
3563

3564
  Note that instances of this class should not be reused between
3565
  GetResults() calls.
3566

3567
  """
3568
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3569
    self.queue = []
3570
    if cl is None:
3571
      cl = GetClient()
3572
    self.cl = cl
3573
    self.verbose = verbose
3574
    self.jobs = []
3575
    self.opts = opts
3576
    self.feedback_fn = feedback_fn
3577
    self._counter = itertools.count()
3578

    
3579
  @staticmethod
3580
  def _IfName(name, fmt):
3581
    """Helper function for formatting name.
3582

3583
    """
3584
    if name:
3585
      return fmt % name
3586

    
3587
    return ""
3588

    
3589
  def QueueJob(self, name, *ops):
3590
    """Record a job for later submit.
3591

3592
    @type name: string
3593
    @param name: a description of the job, will be used in WaitJobSet
3594

3595
    """
3596
    SetGenericOpcodeOpts(ops, self.opts)
3597
    self.queue.append((self._counter.next(), name, ops))
3598

    
3599
  def AddJobId(self, name, status, job_id):
3600
    """Adds a job ID to the internal queue.
3601

3602
    """
3603
    self.jobs.append((self._counter.next(), status, job_id, name))
3604

    
3605
  def SubmitPending(self, each=False):
3606
    """Submit all pending jobs.
3607

3608
    """
3609
    if each:
3610
      results = []
3611
      for (_, _, ops) in self.queue:
3612
        # SubmitJob will remove the success status, but raise an exception if
3613
        # the submission fails, so we'll notice that anyway.
3614
        results.append([True, self.cl.SubmitJob(ops)[0]])
3615
    else:
3616
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3617
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3618
      self.jobs.append((idx, status, data, name))
3619

    
3620
  def _ChooseJob(self):
3621
    """Choose a non-waiting/queued job to poll next.
3622

3623
    """
3624
    assert self.jobs, "_ChooseJob called with empty job list"
3625

    
3626
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3627
                               ["status"])
3628
    assert result
3629

    
3630
    for job_data, status in zip(self.jobs, result):
3631
      if (isinstance(status, list) and status and
3632
          status[0] in (constants.JOB_STATUS_QUEUED,
3633
                        constants.JOB_STATUS_WAITING,
3634
                        constants.JOB_STATUS_CANCELING)):
3635
        # job is still present and waiting
3636
        continue
3637
      # good candidate found (either running job or lost job)
3638
      self.jobs.remove(job_data)
3639
      return job_data
3640

    
3641
    # no job found
3642
    return self.jobs.pop(0)
3643

    
3644
  def GetResults(self):
3645
    """Wait for and return the results of all jobs.
3646

3647
    @rtype: list
3648
    @return: list of tuples (success, job results), in the same order
3649
        as the submitted jobs; if a job has failed, instead of the result
3650
        there will be the error message
3651

3652
    """
3653
    if not self.jobs:
3654
      self.SubmitPending()
3655
    results = []
3656
    if self.verbose:
3657
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3658
      if ok_jobs:
3659
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3660

    
3661
    # first, remove any non-submitted jobs
3662
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3663
    for idx, _, jid, name in failures:
3664
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3665
      results.append((idx, False, jid))
3666

    
3667
    while self.jobs:
3668
      (idx, _, jid, name) = self._ChooseJob()
3669
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3670
      try:
3671
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3672
        success = True
3673
      except errors.JobLost, err:
3674
        _, job_result = FormatError(err)
3675
        ToStderr("Job %s%s has been archived, cannot check its result",
3676
                 jid, self._IfName(name, " for %s"))
3677
        success = False
3678
      except (errors.GenericError, luxi.ProtocolError), err:
3679
        _, job_result = FormatError(err)
3680
        success = False
3681
        # the error message will always be shown, verbose or not
3682
        ToStderr("Job %s%s has failed: %s",
3683
                 jid, self._IfName(name, " for %s"), job_result)
3684

    
3685
      results.append((idx, success, job_result))
3686

    
3687
    # sort based on the index, then drop it
3688
    results.sort()
3689
    results = [i[1:] for i in results]
3690

    
3691
    return results
3692

    
3693
  def WaitOrShow(self, wait):
3694
    """Wait for job results or only print the job IDs.
3695

3696
    @type wait: boolean
3697
    @param wait: whether to wait or not
3698

3699
    """
3700
    if wait:
3701
      return self.GetResults()
3702
    else:
3703
      if not self.jobs:
3704
        self.SubmitPending()
3705
      for _, status, result, name in self.jobs:
3706
        if status:
3707
          ToStdout("%s: %s", result, name)
3708
        else:
3709
          ToStderr("Failure for %s: %s", name, result)
3710
      return [row[1:3] for row in self.jobs]
3711

    
3712

    
3713
def FormatParamsDictInfo(param_dict, actual):
3714
  """Formats a parameter dictionary.
3715

3716
  @type param_dict: dict
3717
  @param param_dict: the own parameters
3718
  @type actual: dict
3719
  @param actual: the current parameter set (including defaults)
3720
  @rtype: dict
3721
  @return: dictionary where the value of each parameter is either a fully
3722
      formatted string or a dictionary containing formatted strings
3723

3724
  """
3725
  ret = {}
3726
  for (key, data) in actual.items():
3727
    if isinstance(data, dict) and data:
3728
      ret[key] = FormatParamsDictInfo(param_dict.get(key, {}), data)
3729
    else:
3730
      ret[key] = str(param_dict.get(key, "default (%s)" % data))
3731
  return ret
3732

    
3733

    
3734
def _FormatListInfoDefault(data, def_data):
3735
  if data is not None:
3736
    ret = utils.CommaJoin(data)
3737
  else:
3738
    ret = "default (%s)" % utils.CommaJoin(def_data)
3739
  return ret
3740

    
3741

    
3742
def FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster):
3743
  """Formats an instance policy.
3744

3745
  @type custom_ipolicy: dict
3746
  @param custom_ipolicy: own policy
3747
  @type eff_ipolicy: dict
3748
  @param eff_ipolicy: effective policy (including defaults); ignored for
3749
      cluster
3750
  @type iscluster: bool
3751
  @param iscluster: the policy is at cluster level
3752
  @rtype: list of pairs
3753
  @return: formatted data, suitable for L{PrintGenericInfo}
3754

3755
  """
3756
  if iscluster:
3757
    eff_ipolicy = custom_ipolicy
3758

    
3759
  minmax_out = []
3760
  custom_minmax = custom_ipolicy.get(constants.ISPECS_MINMAX)
3761
  if custom_minmax:
3762
    for (k, minmax) in enumerate(custom_minmax):
3763
      minmax_out.append([
3764
        ("%s/%s" % (key, k),
3765
         FormatParamsDictInfo(minmax[key], minmax[key]))
3766
        for key in constants.ISPECS_MINMAX_KEYS
3767
        ])
3768
  else:
3769
    for (k, minmax) in enumerate(eff_ipolicy[constants.ISPECS_MINMAX]):
3770
      minmax_out.append([
3771
        ("%s/%s" % (key, k),
3772
         FormatParamsDictInfo({}, minmax[key]))
3773
        for key in constants.ISPECS_MINMAX_KEYS
3774
        ])
3775
  ret = [("bounds specs", minmax_out)]
3776

    
3777
  if iscluster:
3778
    stdspecs = custom_ipolicy[constants.ISPECS_STD]
3779
    ret.append(
3780
      (constants.ISPECS_STD,
3781
       FormatParamsDictInfo(stdspecs, stdspecs))
3782
      )
3783

    
3784
  ret.append(
3785
    ("allowed disk templates",
3786
     _FormatListInfoDefault(custom_ipolicy.get(constants.IPOLICY_DTS),
3787
                            eff_ipolicy[constants.IPOLICY_DTS]))
3788
    )
3789
  ret.extend([
3790
    (key, str(custom_ipolicy.get(key, "default (%s)" % eff_ipolicy[key])))
3791
    for key in constants.IPOLICY_PARAMETERS
3792
    ])
3793
  return ret
3794

    
3795

    
3796
def _PrintSpecsParameters(buf, specs):
3797
  values = ("%s=%s" % (par, val) for (par, val) in sorted(specs.items()))
3798
  buf.write(",".join(values))
3799

    
3800

    
3801
def PrintIPolicyCommand(buf, ipolicy, isgroup):
3802
  """Print the command option used to generate the given instance policy.
3803

3804
  Currently only the parts dealing with specs are supported.
3805

3806
  @type buf: StringIO
3807
  @param buf: stream to write into
3808
  @type ipolicy: dict
3809
  @param ipolicy: instance policy
3810
  @type isgroup: bool
3811
  @param isgroup: whether the policy is at group level
3812

3813
  """
3814
  if not isgroup:
3815
    stdspecs = ipolicy.get("std")
3816
    if stdspecs:
3817
      buf.write(" %s " % IPOLICY_STD_SPECS_STR)
3818
      _PrintSpecsParameters(buf, stdspecs)
3819
  minmaxes = ipolicy.get("minmax", [])
3820
  first = True
3821
  for minmax in minmaxes:
3822
    minspecs = minmax.get("min")
3823
    maxspecs = minmax.get("max")
3824
    if minspecs and maxspecs:
3825
      if first:
3826
        buf.write(" %s " % IPOLICY_BOUNDS_SPECS_STR)
3827
        first = False
3828
      else:
3829
        buf.write("//")
3830
      buf.write("min:")
3831
      _PrintSpecsParameters(buf, minspecs)
3832
      buf.write("/max:")
3833
      _PrintSpecsParameters(buf, maxspecs)
3834

    
3835

    
3836
def ConfirmOperation(names, list_type, text, extra=""):
3837
  """Ask the user to confirm an operation on a list of list_type.
3838

3839
  This function is used to request confirmation for doing an operation
3840
  on a given list of list_type.
3841

3842
  @type names: list
3843
  @param names: the list of names that we display when
3844
      we ask for confirmation
3845
  @type list_type: str
3846
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3847
  @type text: str
3848
  @param text: the operation that the user should confirm
3849
  @rtype: boolean
3850
  @return: True or False depending on user's confirmation.
3851

3852
  """
3853
  count = len(names)
3854
  msg = ("The %s will operate on %d %s.\n%s"
3855
         "Do you want to continue?" % (text, count, list_type, extra))
3856
  affected = (("\nAffected %s:\n" % list_type) +
3857
              "\n".join(["  %s" % name for name in names]))
3858

    
3859
  choices = [("y", True, "Yes, execute the %s" % text),
3860
             ("n", False, "No, abort the %s" % text)]
3861

    
3862
  if count > 20:
3863
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3864
    question = msg
3865
  else:
3866
    question = msg + affected
3867

    
3868
  choice = AskUser(question, choices)
3869
  if choice == "v":
3870
    choices.pop(1)
3871
    choice = AskUser(msg + affected, choices)
3872
  return choice
3873

    
3874

    
3875
def _MaybeParseUnit(elements):
3876
  """Parses and returns an array of potential values with units.
3877

3878
  """
3879
  parsed = {}
3880
  for k, v in elements.items():
3881
    if v == constants.VALUE_DEFAULT:
3882
      parsed[k] = v
3883
    else:
3884
      parsed[k] = utils.ParseUnit(v)
3885
  return parsed
3886

    
3887

    
3888
def _InitISpecsFromSplitOpts(ipolicy, ispecs_mem_size, ispecs_cpu_count,
3889
                             ispecs_disk_count, ispecs_disk_size,
3890
                             ispecs_nic_count, group_ipolicy, fill_all):
3891
  try:
3892
    if ispecs_mem_size:
3893
      ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
3894
    if ispecs_disk_size:
3895
      ispecs_disk_size = _MaybeParseUnit(ispecs_disk_size)
3896
  except (TypeError, ValueError, errors.UnitParseError), err:
3897
    raise errors.OpPrereqError("Invalid disk (%s) or memory (%s) size"
3898
                               " in policy: %s" %
3899
                               (ispecs_disk_size, ispecs_mem_size, err),
3900
                               errors.ECODE_INVAL)
3901

    
3902
  # prepare ipolicy dict
3903
  ispecs_transposed = {
3904
    constants.ISPEC_MEM_SIZE: ispecs_mem_size,
3905
    constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
3906
    constants.ISPEC_DISK_COUNT: ispecs_disk_count,
3907
    constants.ISPEC_DISK_SIZE: ispecs_disk_size,
3908
    constants.ISPEC_NIC_COUNT: ispecs_nic_count,
3909
    }
3910

    
3911
  # first, check that the values given are correct
3912
  if group_ipolicy:
3913
    forced_type = TISPECS_GROUP_TYPES
3914
  else:
3915
    forced_type = TISPECS_CLUSTER_TYPES
3916
  for specs in ispecs_transposed.values():
3917
    assert type(specs) is dict
3918
    utils.ForceDictType(specs, forced_type)
3919

    
3920
  # then transpose
3921
  ispecs = {
3922
    constants.ISPECS_MIN: {},
3923
    constants.ISPECS_MAX: {},
3924
    constants.ISPECS_STD: {},
3925
    }
3926
  for (name, specs) in ispecs_transposed.iteritems():
3927
    assert name in constants.ISPECS_PARAMETERS
3928
    for key, val in specs.items(): # {min: .. ,max: .., std: ..}
3929
      assert key in ispecs
3930
      ispecs[key][name] = val
3931
  minmax_out = {}
3932
  for key in constants.ISPECS_MINMAX_KEYS:
3933
    if fill_all:
3934
      minmax_out[key] = \
3935
        objects.FillDict(constants.ISPECS_MINMAX_DEFAULTS[key], ispecs[key])
3936
    else:
3937
      minmax_out[key] = ispecs[key]
3938
  ipolicy[constants.ISPECS_MINMAX] = [minmax_out]
3939
  if fill_all:
3940
    ipolicy[constants.ISPECS_STD] = \
3941
        objects.FillDict(constants.IPOLICY_DEFAULTS[constants.ISPECS_STD],
3942
                         ispecs[constants.ISPECS_STD])
3943
  else:
3944
    ipolicy[constants.ISPECS_STD] = ispecs[constants.ISPECS_STD]
3945

    
3946

    
3947
def _ParseSpecUnit(spec, keyname):
3948
  ret = spec.copy()
3949
  for k in [constants.ISPEC_DISK_SIZE, constants.ISPEC_MEM_SIZE]:
3950
    if k in ret:
3951
      try:
3952
        ret[k] = utils.ParseUnit(ret[k])
3953
      except (TypeError, ValueError, errors.UnitParseError), err:
3954
        raise errors.OpPrereqError(("Invalid parameter %s (%s) in %s instance"
3955
                                    " specs: %s" % (k, ret[k], keyname, err)),
3956
                                   errors.ECODE_INVAL)
3957
  return ret
3958

    
3959

    
3960
def _ParseISpec(spec, keyname, required):
3961
  ret = _ParseSpecUnit(spec, keyname)
3962
  utils.ForceDictType(ret, constants.ISPECS_PARAMETER_TYPES)
3963
  missing = constants.ISPECS_PARAMETERS - frozenset(ret.keys())
3964
  if required and missing:
3965
    raise errors.OpPrereqError("Missing parameters in ipolicy spec %s: %s" %
3966
                               (keyname, utils.CommaJoin(missing)),
3967
                               errors.ECODE_INVAL)
3968
  return ret
3969

    
3970

    
3971
def _GetISpecsInAllowedValues(minmax_ispecs, allowed_values):
3972
  ret = None
3973
  if (minmax_ispecs and allowed_values and len(minmax_ispecs) == 1 and
3974
      len(minmax_ispecs[0]) == 1):
3975
    for (key, spec) in minmax_ispecs[0].items():
3976
      # This loop is executed exactly once
3977
      if key in allowed_values and not spec:
3978
        ret = key
3979
  return ret
3980

    
3981

    
3982
def _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
3983
                            group_ipolicy, allowed_values):
3984
  found_allowed = _GetISpecsInAllowedValues(minmax_ispecs, allowed_values)
3985
  if found_allowed is not None:
3986
    ipolicy_out[constants.ISPECS_MINMAX] = found_allowed
3987
  elif minmax_ispecs is not None:
3988
    minmax_out = []
3989
    for mmpair in minmax_ispecs:
3990
      mmpair_out = {}
3991
      for (key, spec) in mmpair.items():
3992
        if key not in constants.ISPECS_MINMAX_KEYS:
3993
          msg = "Invalid key in bounds instance specifications: %s" % key
3994
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3995
        mmpair_out[key] = _ParseISpec(spec, key, True)
3996
      minmax_out.append(mmpair_out)
3997
    ipolicy_out[constants.ISPECS_MINMAX] = minmax_out
3998
  if std_ispecs is not None:
3999
    assert not group_ipolicy # This is not an option for gnt-group
4000
    ipolicy_out[constants.ISPECS_STD] = _ParseISpec(std_ispecs, "std", False)
4001

    
4002

    
4003
def CreateIPolicyFromOpts(ispecs_mem_size=None,
4004
                          ispecs_cpu_count=None,
4005
                          ispecs_disk_count=None,
4006
                          ispecs_disk_size=None,
4007
                          ispecs_nic_count=None,
4008
                          minmax_ispecs=None,
4009
                          std_ispecs=None,
4010
                          ipolicy_disk_templates=None,
4011
                          ipolicy_vcpu_ratio=None,
4012
                          ipolicy_spindle_ratio=None,
4013
                          group_ipolicy=False,
4014
                          allowed_values=None,
4015
                          fill_all=False):
4016
  """Creation of instance policy based on command line options.
4017

4018
  @param fill_all: whether for cluster policies we should ensure that
4019
    all values are filled
4020

4021
  """
4022
  assert not (fill_all and allowed_values)
4023

    
4024
  split_specs = (ispecs_mem_size or ispecs_cpu_count or ispecs_disk_count or
4025
                 ispecs_disk_size or ispecs_nic_count)
4026
  if (split_specs and (minmax_ispecs is not None or std_ispecs is not None)):
4027
    raise errors.OpPrereqError("A --specs-xxx option cannot be specified"
4028
                               " together with any --ipolicy-xxx-specs option",
4029
                               errors.ECODE_INVAL)
4030

    
4031
  ipolicy_out = objects.MakeEmptyIPolicy()
4032
  if split_specs:
4033
    assert fill_all
4034
    _InitISpecsFromSplitOpts(ipolicy_out, ispecs_mem_size, ispecs_cpu_count,
4035
                             ispecs_disk_count, ispecs_disk_size,
4036
                             ispecs_nic_count, group_ipolicy, fill_all)
4037
  elif (minmax_ispecs is not None or std_ispecs is not None):
4038
    _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
4039
                            group_ipolicy, allowed_values)
4040

    
4041
  if ipolicy_disk_templates is not None:
4042
    if allowed_values and ipolicy_disk_templates in allowed_values:
4043
      ipolicy_out[constants.IPOLICY_DTS] = ipolicy_disk_templates
4044
    else:
4045
      ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
4046
  if ipolicy_vcpu_ratio is not None:
4047
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
4048
  if ipolicy_spindle_ratio is not None:
4049
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
4050

    
4051
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
4052

    
4053
  if not group_ipolicy and fill_all:
4054
    ipolicy_out = objects.FillIPolicy(constants.IPOLICY_DEFAULTS, ipolicy_out)
4055

    
4056
  return ipolicy_out
4057

    
4058

    
4059
def _SerializeGenericInfo(buf, data, level, afterkey=False):
4060
  """Formatting core of L{PrintGenericInfo}.
4061

4062
  @param buf: (string) stream to accumulate the result into
4063
  @param data: data to format
4064
  @type level: int
4065
  @param level: depth in the data hierarchy, used for indenting
4066
  @type afterkey: bool
4067
  @param afterkey: True when we are in the middle of a line after a key (used
4068
      to properly add newlines or indentation)
4069

4070
  """
4071
  baseind = "  "
4072
  if isinstance(data, dict):
4073
    if not data:
4074
      buf.write("\n")
4075
    else:
4076
      if afterkey:
4077
        buf.write("\n")
4078
        doindent = True
4079
      else:
4080
        doindent = False
4081
      for key in sorted(data):
4082
        if doindent:
4083
          buf.write(baseind * level)
4084
        else:
4085
          doindent = True
4086
        buf.write(key)
4087
        buf.write(": ")
4088
        _SerializeGenericInfo(buf, data[key], level + 1, afterkey=True)
4089
  elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], tuple):
4090
    # list of tuples (an ordered dictionary)
4091
    if afterkey:
4092
      buf.write("\n")
4093
      doindent = True
4094
    else:
4095
      doindent = False
4096
    for (key, val) in data:
4097
      if doindent:
4098
        buf.write(baseind * level)
4099
      else:
4100
        doindent = True
4101
      buf.write(key)
4102
      buf.write(": ")
4103
      _SerializeGenericInfo(buf, val, level + 1, afterkey=True)
4104
  elif isinstance(data, list):
4105
    if not data:
4106
      buf.write("\n")
4107
    else:
4108
      if afterkey:
4109
        buf.write("\n")
4110
        doindent = True
4111
      else:
4112
        doindent = False
4113
      for item in data:
4114
        if doindent:
4115
          buf.write(baseind * level)
4116
        else:
4117
          doindent = True
4118
        buf.write("-")
4119
        buf.write(baseind[1:])
4120
        _SerializeGenericInfo(buf, item, level + 1)
4121
  else:
4122
    # This branch should be only taken for strings, but it's practically
4123
    # impossible to guarantee that no other types are produced somewhere
4124
    buf.write(str(data))
4125
    buf.write("\n")
4126

    
4127

    
4128
def PrintGenericInfo(data):
4129
  """Print information formatted according to the hierarchy.
4130

4131
  The output is a valid YAML string.
4132

4133
  @param data: the data to print. It's a hierarchical structure whose elements
4134
      can be:
4135
        - dictionaries, where keys are strings and values are of any of the
4136
          types listed here
4137
        - lists of pairs (key, value), where key is a string and value is of
4138
          any of the types listed here; it's a way to encode ordered
4139
          dictionaries
4140
        - lists of any of the types listed here
4141
        - strings
4142

4143
  """
4144
  buf = StringIO()
4145
  _SerializeGenericInfo(buf, data, 0)
4146
  ToStdout(buf.getvalue().rstrip("\n"))