Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 26f15862

History | View | Annotate | Download (31 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 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 copy
29
import time
30
import logging
31
from cStringIO import StringIO
32

    
33
from ganeti import utils
34
from ganeti import errors
35
from ganeti import constants
36
from ganeti import opcodes
37
from ganeti import luxi
38
from ganeti import ssconf
39
from ganeti import rpc
40

    
41
from optparse import (OptionParser, make_option, TitledHelpFormatter,
42
                      Option, OptionValueError)
43

    
44
__all__ = ["DEBUG_OPT", "NOHDR_OPT", "SEP_OPT", "GenericMain",
45
           "SubmitOpCode", "GetClient",
46
           "cli_option", "ikv_option", "keyval_option",
47
           "GenerateTable", "AskUser",
48
           "ARGS_NONE", "ARGS_FIXED", "ARGS_ATLEAST", "ARGS_ANY", "ARGS_ONE",
49
           "USEUNITS_OPT", "FIELDS_OPT", "FORCE_OPT", "SUBMIT_OPT",
50
           "ListTags", "AddTags", "RemoveTags", "TAG_SRC_OPT",
51
           "FormatError", "SplitNodeOption", "SubmitOrSend",
52
           "JobSubmittedException", "FormatTimestamp", "ParseTimespec",
53
           "ValidateBeParams", "ToStderr", "ToStdout", "UsesRPC",
54
           "GetOnlineNodes", "JobExecutor",
55
           ]
56

    
57

    
58
def _ExtractTagsObject(opts, args):
59
  """Extract the tag type object.
60

61
  Note that this function will modify its args parameter.
62

63
  """
64
  if not hasattr(opts, "tag_type"):
65
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
66
  kind = opts.tag_type
67
  if kind == constants.TAG_CLUSTER:
68
    retval = kind, kind
69
  elif kind == constants.TAG_NODE or kind == constants.TAG_INSTANCE:
70
    if not args:
71
      raise errors.OpPrereqError("no arguments passed to the command")
72
    name = args.pop(0)
73
    retval = kind, name
74
  else:
75
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
76
  return retval
77

    
78

    
79
def _ExtendTags(opts, args):
80
  """Extend the args if a source file has been given.
81

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

86
  """
87
  fname = opts.tags_source
88
  if fname is None:
89
    return
90
  if fname == "-":
91
    new_fh = sys.stdin
92
  else:
93
    new_fh = open(fname, "r")
94
  new_data = []
95
  try:
96
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
97
    # because of python bug 1633941
98
    while True:
99
      line = new_fh.readline()
100
      if not line:
101
        break
102
      new_data.append(line.strip())
103
  finally:
104
    new_fh.close()
105
  args.extend(new_data)
106

    
107

    
108
def ListTags(opts, args):
109
  """List the tags on a given object.
110

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

116
  """
117
  kind, name = _ExtractTagsObject(opts, args)
118
  op = opcodes.OpGetTags(kind=kind, name=name)
119
  result = SubmitOpCode(op)
120
  result = list(result)
121
  result.sort()
122
  for tag in result:
123
    print tag
124

    
125

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

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

134
  """
135
  kind, name = _ExtractTagsObject(opts, args)
136
  _ExtendTags(opts, args)
137
  if not args:
138
    raise errors.OpPrereqError("No tags to be added")
139
  op = opcodes.OpAddTags(kind=kind, name=name, tags=args)
140
  SubmitOpCode(op)
141

    
142

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

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

151
  """
152
  kind, name = _ExtractTagsObject(opts, args)
153
  _ExtendTags(opts, args)
154
  if not args:
155
    raise errors.OpPrereqError("No tags to be removed")
156
  op = opcodes.OpDelTags(kind=kind, name=name, tags=args)
157
  SubmitOpCode(op)
158

    
159

    
160
DEBUG_OPT = make_option("-d", "--debug", default=False,
161
                        action="store_true",
162
                        help="Turn debugging on")
163

    
164
NOHDR_OPT = make_option("--no-headers", default=False,
165
                        action="store_true", dest="no_headers",
166
                        help="Don't display column headers")
167

    
168
SEP_OPT = make_option("--separator", default=None,
169
                      action="store", dest="separator",
170
                      help="Separator between output fields"
171
                      " (defaults to one space)")
172

    
173
USEUNITS_OPT = make_option("--units", default=None,
174
                           dest="units", choices=('h', 'm', 'g', 't'),
175
                           help="Specify units for output (one of hmgt)")
176

    
177
FIELDS_OPT = make_option("-o", "--output", dest="output", action="store",
178
                         type="string", help="Comma separated list of"
179
                         " output fields",
180
                         metavar="FIELDS")
181

    
182
FORCE_OPT = make_option("-f", "--force", dest="force", action="store_true",
183
                        default=False, help="Force the operation")
184

    
185
TAG_SRC_OPT = make_option("--from", dest="tags_source",
186
                          default=None, help="File with tag names")
187

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

    
193

    
194
def ARGS_FIXED(val):
195
  """Macro-like function denoting a fixed number of arguments"""
196
  return -val
197

    
198

    
199
def ARGS_ATLEAST(val):
200
  """Macro-like function denoting a minimum number of arguments"""
201
  return val
202

    
203

    
204
ARGS_NONE = None
205
ARGS_ONE = ARGS_FIXED(1)
206
ARGS_ANY = ARGS_ATLEAST(0)
207

    
208

    
209
def check_unit(option, opt, value):
210
  """OptParsers custom converter for units.
211

212
  """
213
  try:
214
    return utils.ParseUnit(value)
215
  except errors.UnitParseError, err:
216
    raise OptionValueError("option %s: %s" % (opt, err))
217

    
218

    
219
class CliOption(Option):
220
  """Custom option class for optparse.
221

222
  """
223
  TYPES = Option.TYPES + ("unit",)
224
  TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
225
  TYPE_CHECKER["unit"] = check_unit
226

    
227

    
228
def _SplitKeyVal(opt, data):
229
  """Convert a KeyVal string into a dict.
230

231
  This function will convert a key=val[,...] string into a dict. Empty
232
  values will be converted specially: keys which have the prefix 'no_'
233
  will have the value=False and the prefix stripped, the others will
234
  have value=True.
235

236
  @type opt: string
237
  @param opt: a string holding the option name for which we process the
238
      data, used in building error messages
239
  @type data: string
240
  @param data: a string of the format key=val,key=val,...
241
  @rtype: dict
242
  @return: {key=val, key=val}
243
  @raises errors.ParameterError: if there are duplicate keys
244

245
  """
246
  NO_PREFIX = "no_"
247
  UN_PREFIX = "-"
248
  kv_dict = {}
249
  for elem in data.split(","):
250
    if "=" in elem:
251
      key, val = elem.split("=", 1)
252
    else:
253
      if elem.startswith(NO_PREFIX):
254
        key, val = elem[len(NO_PREFIX):], False
255
      elif elem.startswith(UN_PREFIX):
256
        key, val = elem[len(UN_PREFIX):], None
257
      else:
258
        key, val = elem, True
259
    if key in kv_dict:
260
      raise errors.ParameterError("Duplicate key '%s' in option %s" %
261
                                  (key, opt))
262
    kv_dict[key] = val
263
  return kv_dict
264

    
265

    
266
def check_ident_key_val(option, opt, value):
267
  """Custom parser for the IdentKeyVal option type.
268

269
  """
270
  if ":" not in value:
271
    retval =  (value, {})
272
  else:
273
    ident, rest = value.split(":", 1)
274
    kv_dict = _SplitKeyVal(opt, rest)
275
    retval = (ident, kv_dict)
276
  return retval
277

    
278

    
279
class IdentKeyValOption(Option):
280
  """Custom option class for ident:key=val,key=val options.
281

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

285
  """
286
  TYPES = Option.TYPES + ("identkeyval",)
287
  TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
288
  TYPE_CHECKER["identkeyval"] = check_ident_key_val
289

    
290

    
291
def check_key_val(option, opt, value):
292
  """Custom parser for the KeyVal option type.
293

294
  """
295
  return _SplitKeyVal(opt, value)
296

    
297

    
298
class KeyValOption(Option):
299
  """Custom option class for key=val,key=val options.
300

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

303
  """
304
  TYPES = Option.TYPES + ("keyval",)
305
  TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER)
306
  TYPE_CHECKER["keyval"] = check_key_val
307

    
308

    
309
# optparse.py sets make_option, so we do it for our own option class, too
310
cli_option = CliOption
311
ikv_option = IdentKeyValOption
312
keyval_option = KeyValOption
313

    
314

    
315
def _ParseArgs(argv, commands, aliases):
316
  """Parser for the command line arguments.
317

318
  This function parses the arguements and returns the function which
319
  must be executed together with its (modified) arguments.
320

321
  @param argv: the command line
322
  @param commands: dictionary with special contents, see the design
323
      doc for cmdline handling
324
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
325

326
  """
327
  if len(argv) == 0:
328
    binary = "<command>"
329
  else:
330
    binary = argv[0].split("/")[-1]
331

    
332
  if len(argv) > 1 and argv[1] == "--version":
333
    print "%s (ganeti) %s" % (binary, constants.RELEASE_VERSION)
334
    # Quit right away. That way we don't have to care about this special
335
    # argument. optparse.py does it the same.
336
    sys.exit(0)
337

    
338
  if len(argv) < 2 or not (argv[1] in commands or
339
                           argv[1] in aliases):
340
    # let's do a nice thing
341
    sortedcmds = commands.keys()
342
    sortedcmds.sort()
343
    print ("Usage: %(bin)s {command} [options...] [argument...]"
344
           "\n%(bin)s <command> --help to see details, or"
345
           " man %(bin)s\n" % {"bin": binary})
346
    # compute the max line length for cmd + usage
347
    mlen = max([len(" %s" % cmd) for cmd in commands])
348
    mlen = min(60, mlen) # should not get here...
349
    # and format a nice command list
350
    print "Commands:"
351
    for cmd in sortedcmds:
352
      cmdstr = " %s" % (cmd,)
353
      help_text = commands[cmd][4]
354
      help_lines = textwrap.wrap(help_text, 79-3-mlen)
355
      print "%-*s - %s" % (mlen, cmdstr, help_lines.pop(0))
356
      for line in help_lines:
357
        print "%-*s   %s" % (mlen, "", line)
358
    print
359
    return None, None, None
360

    
361
  # get command, unalias it, and look it up in commands
362
  cmd = argv.pop(1)
363
  if cmd in aliases:
364
    if cmd in commands:
365
      raise errors.ProgrammerError("Alias '%s' overrides an existing"
366
                                   " command" % cmd)
367

    
368
    if aliases[cmd] not in commands:
369
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
370
                                   " command '%s'" % (cmd, aliases[cmd]))
371

    
372
    cmd = aliases[cmd]
373

    
374
  func, nargs, parser_opts, usage, description = commands[cmd]
375
  parser = OptionParser(option_list=parser_opts,
376
                        description=description,
377
                        formatter=TitledHelpFormatter(),
378
                        usage="%%prog %s %s" % (cmd, usage))
379
  parser.disable_interspersed_args()
380
  options, args = parser.parse_args()
381
  if nargs is None:
382
    if len(args) != 0:
383
      print >> sys.stderr, ("Error: Command %s expects no arguments" % cmd)
384
      return None, None, None
385
  elif nargs < 0 and len(args) != -nargs:
386
    print >> sys.stderr, ("Error: Command %s expects %d argument(s)" %
387
                         (cmd, -nargs))
388
    return None, None, None
389
  elif nargs >= 0 and len(args) < nargs:
390
    print >> sys.stderr, ("Error: Command %s expects at least %d argument(s)" %
391
                         (cmd, nargs))
392
    return None, None, None
393

    
394
  return func, options, args
395

    
396

    
397
def SplitNodeOption(value):
398
  """Splits the value of a --node option.
399

400
  """
401
  if value and ':' in value:
402
    return value.split(':', 1)
403
  else:
404
    return (value, None)
405

    
406

    
407
def ValidateBeParams(bep):
408
  """Parse and check the given beparams.
409

410
  The function will update in-place the given dictionary.
411

412
  @type bep: dict
413
  @param bep: input beparams
414
  @raise errors.ParameterError: if the input values are not OK
415
  @raise errors.UnitParseError: if the input values are not OK
416

417
  """
418
  if constants.BE_MEMORY in bep:
419
    bep[constants.BE_MEMORY] = utils.ParseUnit(bep[constants.BE_MEMORY])
420

    
421
  if constants.BE_VCPUS in bep:
422
    try:
423
      bep[constants.BE_VCPUS] = int(bep[constants.BE_VCPUS])
424
    except ValueError:
425
      raise errors.ParameterError("Invalid number of VCPUs")
426

    
427

    
428
def UsesRPC(fn):
429
  def wrapper(*args, **kwargs):
430
    rpc.Init()
431
    try:
432
      return fn(*args, **kwargs)
433
    finally:
434
      rpc.Shutdown()
435
  return wrapper
436

    
437

    
438
def AskUser(text, choices=None):
439
  """Ask the user a question.
440

441
  @param text: the question to ask
442

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

448
  @return: one of the return values from the choices list; if input is
449
      not possible (i.e. not running with a tty, we return the last
450
      entry from the list
451

452
  """
453
  if choices is None:
454
    choices = [('y', True, 'Perform the operation'),
455
               ('n', False, 'Do not perform the operation')]
456
  if not choices or not isinstance(choices, list):
457
    raise errors.ProgrammerError("Invalid choiches argument to AskUser")
458
  for entry in choices:
459
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == '?':
460
      raise errors.ProgrammerError("Invalid choiches element to AskUser")
461

    
462
  answer = choices[-1][1]
463
  new_text = []
464
  for line in text.splitlines():
465
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
466
  text = "\n".join(new_text)
467
  try:
468
    f = file("/dev/tty", "a+")
469
  except IOError:
470
    return answer
471
  try:
472
    chars = [entry[0] for entry in choices]
473
    chars[-1] = "[%s]" % chars[-1]
474
    chars.append('?')
475
    maps = dict([(entry[0], entry[1]) for entry in choices])
476
    while True:
477
      f.write(text)
478
      f.write('\n')
479
      f.write("/".join(chars))
480
      f.write(": ")
481
      line = f.readline(2).strip().lower()
482
      if line in maps:
483
        answer = maps[line]
484
        break
485
      elif line == '?':
486
        for entry in choices:
487
          f.write(" %s - %s\n" % (entry[0], entry[2]))
488
        f.write("\n")
489
        continue
490
  finally:
491
    f.close()
492
  return answer
493

    
494

    
495
class JobSubmittedException(Exception):
496
  """Job was submitted, client should exit.
497

498
  This exception has one argument, the ID of the job that was
499
  submitted. The handler should print this ID.
500

501
  This is not an error, just a structured way to exit from clients.
502

503
  """
504

    
505

    
506
def SendJob(ops, cl=None):
507
  """Function to submit an opcode without waiting for the results.
508

509
  @type ops: list
510
  @param ops: list of opcodes
511
  @type cl: luxi.Client
512
  @param cl: the luxi client to use for communicating with the master;
513
             if None, a new client will be created
514

515
  """
516
  if cl is None:
517
    cl = GetClient()
518

    
519
  job_id = cl.SubmitJob(ops)
520

    
521
  return job_id
522

    
523

    
524
def PollJob(job_id, cl=None, feedback_fn=None):
525
  """Function to poll for the result of a job.
526

527
  @type job_id: job identified
528
  @param job_id: the job to poll for results
529
  @type cl: luxi.Client
530
  @param cl: the luxi client to use for communicating with the master;
531
             if None, a new client will be created
532

533
  """
534
  if cl is None:
535
    cl = GetClient()
536

    
537
  prev_job_info = None
538
  prev_logmsg_serial = None
539

    
540
  while True:
541
    result = cl.WaitForJobChange(job_id, ["status"], prev_job_info,
542
                                 prev_logmsg_serial)
543
    if not result:
544
      # job not found, go away!
545
      raise errors.JobLost("Job with id %s lost" % job_id)
546

    
547
    # Split result, a tuple of (field values, log entries)
548
    (job_info, log_entries) = result
549
    (status, ) = job_info
550

    
551
    if log_entries:
552
      for log_entry in log_entries:
553
        (serial, timestamp, _, message) = log_entry
554
        if callable(feedback_fn):
555
          feedback_fn(log_entry[1:])
556
        else:
557
          encoded = utils.SafeEncode(message)
558
          print "%s %s" % (time.ctime(utils.MergeTime(timestamp)), encoded)
559
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
560

    
561
    # TODO: Handle canceled and archived jobs
562
    elif status in (constants.JOB_STATUS_SUCCESS,
563
                    constants.JOB_STATUS_ERROR,
564
                    constants.JOB_STATUS_CANCELING,
565
                    constants.JOB_STATUS_CANCELED):
566
      break
567

    
568
    prev_job_info = job_info
569

    
570
  jobs = cl.QueryJobs([job_id], ["status", "opstatus", "opresult"])
571
  if not jobs:
572
    raise errors.JobLost("Job with id %s lost" % job_id)
573

    
574
  status, opstatus, result = jobs[0]
575
  if status == constants.JOB_STATUS_SUCCESS:
576
    return result
577
  elif status in (constants.JOB_STATUS_CANCELING,
578
                  constants.JOB_STATUS_CANCELED):
579
    raise errors.OpExecError("Job was canceled")
580
  else:
581
    has_ok = False
582
    for idx, (status, msg) in enumerate(zip(opstatus, result)):
583
      if status == constants.OP_STATUS_SUCCESS:
584
        has_ok = True
585
      elif status == constants.OP_STATUS_ERROR:
586
        if has_ok:
587
          raise errors.OpExecError("partial failure (opcode %d): %s" %
588
                                   (idx, msg))
589
        else:
590
          raise errors.OpExecError(str(msg))
591
    # default failure mode
592
    raise errors.OpExecError(result)
593

    
594

    
595
def SubmitOpCode(op, cl=None, feedback_fn=None):
596
  """Legacy function to submit an opcode.
597

598
  This is just a simple wrapper over the construction of the processor
599
  instance. It should be extended to better handle feedback and
600
  interaction functions.
601

602
  """
603
  if cl is None:
604
    cl = GetClient()
605

    
606
  job_id = SendJob([op], cl)
607

    
608
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn)
609

    
610
  return op_results[0]
611

    
612

    
613
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
614
  """Wrapper around SubmitOpCode or SendJob.
615

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

621
  """
622
  if opts and opts.submit_only:
623
    job_id = SendJob([op], cl=cl)
624
    raise JobSubmittedException(job_id)
625
  else:
626
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn)
627

    
628

    
629
def GetClient():
630
  # TODO: Cache object?
631
  try:
632
    client = luxi.Client()
633
  except luxi.NoMasterError:
634
    master, myself = ssconf.GetMasterAndMyself()
635
    if master != myself:
636
      raise errors.OpPrereqError("This is not the master node, please connect"
637
                                 " to node '%s' and rerun the command" %
638
                                 master)
639
    else:
640
      raise
641
  return client
642

    
643

    
644
def FormatError(err):
645
  """Return a formatted error message for a given error.
646

647
  This function takes an exception instance and returns a tuple
648
  consisting of two values: first, the recommended exit code, and
649
  second, a string describing the error message (not
650
  newline-terminated).
651

652
  """
653
  retcode = 1
654
  obuf = StringIO()
655
  msg = str(err)
656
  if isinstance(err, errors.ConfigurationError):
657
    txt = "Corrupt configuration file: %s" % msg
658
    logging.error(txt)
659
    obuf.write(txt + "\n")
660
    obuf.write("Aborting.")
661
    retcode = 2
662
  elif isinstance(err, errors.HooksAbort):
663
    obuf.write("Failure: hooks execution failed:\n")
664
    for node, script, out in err.args[0]:
665
      if out:
666
        obuf.write("  node: %s, script: %s, output: %s\n" %
667
                   (node, script, out))
668
      else:
669
        obuf.write("  node: %s, script: %s (no output)\n" %
670
                   (node, script))
671
  elif isinstance(err, errors.HooksFailure):
672
    obuf.write("Failure: hooks general failure: %s" % msg)
673
  elif isinstance(err, errors.ResolverError):
674
    this_host = utils.HostInfo.SysName()
675
    if err.args[0] == this_host:
676
      msg = "Failure: can't resolve my own hostname ('%s')"
677
    else:
678
      msg = "Failure: can't resolve hostname '%s'"
679
    obuf.write(msg % err.args[0])
680
  elif isinstance(err, errors.OpPrereqError):
681
    obuf.write("Failure: prerequisites not met for this"
682
               " operation:\n%s" % msg)
683
  elif isinstance(err, errors.OpExecError):
684
    obuf.write("Failure: command execution error:\n%s" % msg)
685
  elif isinstance(err, errors.TagError):
686
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
687
  elif isinstance(err, errors.JobQueueDrainError):
688
    obuf.write("Failure: the job queue is marked for drain and doesn't"
689
               " accept new requests\n")
690
  elif isinstance(err, errors.JobQueueFull):
691
    obuf.write("Failure: the job queue is full and doesn't accept new"
692
               " job submissions until old jobs are archived\n")
693
  elif isinstance(err, errors.GenericError):
694
    obuf.write("Unhandled Ganeti error: %s" % msg)
695
  elif isinstance(err, luxi.NoMasterError):
696
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
697
               " and listening for connections?")
698
  elif isinstance(err, luxi.TimeoutError):
699
    obuf.write("Timeout while talking to the master daemon. Error:\n"
700
               "%s" % msg)
701
  elif isinstance(err, luxi.ProtocolError):
702
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
703
               "%s" % msg)
704
  elif isinstance(err, JobSubmittedException):
705
    obuf.write("JobID: %s\n" % err.args[0])
706
    retcode = 0
707
  else:
708
    obuf.write("Unhandled exception: %s" % msg)
709
  return retcode, obuf.getvalue().rstrip('\n')
710

    
711

    
712
def GenericMain(commands, override=None, aliases=None):
713
  """Generic main function for all the gnt-* commands.
714

715
  Arguments:
716
    - commands: a dictionary with a special structure, see the design doc
717
                for command line handling.
718
    - override: if not None, we expect a dictionary with keys that will
719
                override command line options; this can be used to pass
720
                options from the scripts to generic functions
721
    - aliases: dictionary with command aliases {'alias': 'target, ...}
722

723
  """
724
  # save the program name and the entire command line for later logging
725
  if sys.argv:
726
    binary = os.path.basename(sys.argv[0]) or sys.argv[0]
727
    if len(sys.argv) >= 2:
728
      binary += " " + sys.argv[1]
729
      old_cmdline = " ".join(sys.argv[2:])
730
    else:
731
      old_cmdline = ""
732
  else:
733
    binary = "<unknown program>"
734
    old_cmdline = ""
735

    
736
  if aliases is None:
737
    aliases = {}
738

    
739
  func, options, args = _ParseArgs(sys.argv, commands, aliases)
740
  if func is None: # parse error
741
    return 1
742

    
743
  if override is not None:
744
    for key, val in override.iteritems():
745
      setattr(options, key, val)
746

    
747
  utils.SetupLogging(constants.LOG_COMMANDS, debug=options.debug,
748
                     stderr_logging=True, program=binary)
749

    
750
  utils.debug = options.debug
751

    
752
  if old_cmdline:
753
    logging.info("run with arguments '%s'", old_cmdline)
754
  else:
755
    logging.info("run with no arguments")
756

    
757
  try:
758
    result = func(options, args)
759
  except (errors.GenericError, luxi.ProtocolError,
760
          JobSubmittedException), err:
761
    result, err_msg = FormatError(err)
762
    logging.exception("Error durring command processing")
763
    ToStderr(err_msg)
764

    
765
  return result
766

    
767

    
768
def GenerateTable(headers, fields, separator, data,
769
                  numfields=None, unitfields=None,
770
                  units=None):
771
  """Prints a table with headers and different fields.
772

773
  @type headers: dict
774
  @param headers: dictionary mapping field names to headers for
775
      the table
776
  @type fields: list
777
  @param fields: the field names corresponding to each row in
778
      the data field
779
  @param separator: the separator to be used; if this is None,
780
      the default 'smart' algorithm is used which computes optimal
781
      field width, otherwise just the separator is used between
782
      each field
783
  @type data: list
784
  @param data: a list of lists, each sublist being one row to be output
785
  @type numfields: list
786
  @param numfields: a list with the fields that hold numeric
787
      values and thus should be right-aligned
788
  @type unitfields: list
789
  @param unitfields: a list with the fields that hold numeric
790
      values that should be formatted with the units field
791
  @type units: string or None
792
  @param units: the units we should use for formatting, or None for
793
      automatic choice (human-readable for non-separator usage, otherwise
794
      megabytes); this is a one-letter string
795

796
  """
797
  if units is None:
798
    if separator:
799
      units = "m"
800
    else:
801
      units = "h"
802

    
803
  if numfields is None:
804
    numfields = []
805
  if unitfields is None:
806
    unitfields = []
807

    
808
  numfields = utils.FieldSet(*numfields)
809
  unitfields = utils.FieldSet(*unitfields)
810

    
811
  format_fields = []
812
  for field in fields:
813
    if headers and field not in headers:
814
      # FIXME: handle better unknown fields (either revert to old
815
      # style of raising exception, or deal more intelligently with
816
      # variable fields)
817
      headers[field] = field
818
    if separator is not None:
819
      format_fields.append("%s")
820
    elif numfields.Matches(field):
821
      format_fields.append("%*s")
822
    else:
823
      format_fields.append("%-*s")
824

    
825
  if separator is None:
826
    mlens = [0 for name in fields]
827
    format = ' '.join(format_fields)
828
  else:
829
    format = separator.replace("%", "%%").join(format_fields)
830

    
831
  for row in data:
832
    for idx, val in enumerate(row):
833
      if unitfields.Matches(fields[idx]):
834
        try:
835
          val = int(val)
836
        except ValueError:
837
          pass
838
        else:
839
          val = row[idx] = utils.FormatUnit(val, units)
840
      val = row[idx] = str(val)
841
      if separator is None:
842
        mlens[idx] = max(mlens[idx], len(val))
843

    
844
  result = []
845
  if headers:
846
    args = []
847
    for idx, name in enumerate(fields):
848
      hdr = headers[name]
849
      if separator is None:
850
        mlens[idx] = max(mlens[idx], len(hdr))
851
        args.append(mlens[idx])
852
      args.append(hdr)
853
    result.append(format % tuple(args))
854

    
855
  for line in data:
856
    args = []
857
    for idx in xrange(len(fields)):
858
      if separator is None:
859
        args.append(mlens[idx])
860
      args.append(line[idx])
861
    result.append(format % tuple(args))
862

    
863
  return result
864

    
865

    
866
def FormatTimestamp(ts):
867
  """Formats a given timestamp.
868

869
  @type ts: timestamp
870
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
871

872
  @rtype: string
873
  @returns: a string with the formatted timestamp
874

875
  """
876
  if not isinstance (ts, (tuple, list)) or len(ts) != 2:
877
    return '?'
878
  sec, usec = ts
879
  return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
880

    
881

    
882
def ParseTimespec(value):
883
  """Parse a time specification.
884

885
  The following suffixed will be recognized:
886

887
    - s: seconds
888
    - m: minutes
889
    - h: hours
890
    - d: day
891
    - w: weeks
892

893
  Without any suffix, the value will be taken to be in seconds.
894

895
  """
896
  value = str(value)
897
  if not value:
898
    raise errors.OpPrereqError("Empty time specification passed")
899
  suffix_map = {
900
    's': 1,
901
    'm': 60,
902
    'h': 3600,
903
    'd': 86400,
904
    'w': 604800,
905
    }
906
  if value[-1] not in suffix_map:
907
    try:
908
      value = int(value)
909
    except ValueError:
910
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
911
  else:
912
    multiplier = suffix_map[value[-1]]
913
    value = value[:-1]
914
    if not value: # no data left after stripping the suffix
915
      raise errors.OpPrereqError("Invalid time specification (only"
916
                                 " suffix passed)")
917
    try:
918
      value = int(value) * multiplier
919
    except ValueError:
920
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
921
  return value
922

    
923

    
924
def GetOnlineNodes(nodes, cl=None, nowarn=False):
925
  """Returns the names of online nodes.
926

927
  This function will also log a warning on stderr with the names of
928
  the online nodes.
929

930
  @param nodes: if not empty, use only this subset of nodes (minus the
931
      offline ones)
932
  @param cl: if not None, luxi client to use
933
  @type nowarn: boolean
934
  @param nowarn: by default, this function will output a note with the
935
      offline nodes that are skipped; if this parameter is True the
936
      note is not displayed
937

938
  """
939
  if cl is None:
940
    cl = GetClient()
941

    
942
  op = opcodes.OpQueryNodes(output_fields=["name", "offline"],
943
                            names=nodes)
944
  result = SubmitOpCode(op, cl=cl)
945
  offline = [row[0] for row in result if row[1]]
946
  if offline and not nowarn:
947
    ToStderr("Note: skipping offline node(s): %s" % ", ".join(offline))
948
  return [row[0] for row in result if not row[1]]
949

    
950

    
951
def _ToStream(stream, txt, *args):
952
  """Write a message to a stream, bypassing the logging system
953

954
  @type stream: file object
955
  @param stream: the file to which we should write
956
  @type txt: str
957
  @param txt: the message
958

959
  """
960
  if args:
961
    args = tuple(args)
962
    stream.write(txt % args)
963
  else:
964
    stream.write(txt)
965
  stream.write('\n')
966
  stream.flush()
967

    
968

    
969
def ToStdout(txt, *args):
970
  """Write a message to stdout only, bypassing the logging system
971

972
  This is just a wrapper over _ToStream.
973

974
  @type txt: str
975
  @param txt: the message
976

977
  """
978
  _ToStream(sys.stdout, txt, *args)
979

    
980

    
981
def ToStderr(txt, *args):
982
  """Write a message to stderr only, bypassing the logging system
983

984
  This is just a wrapper over _ToStream.
985

986
  @type txt: str
987
  @param txt: the message
988

989
  """
990
  _ToStream(sys.stderr, txt, *args)
991

    
992

    
993
class JobExecutor(object):
994
  """Class which manages the submission and execution of multiple jobs.
995

996
  Note that instances of this class should not be reused between
997
  GetResults() calls.
998

999
  """
1000
  def __init__(self, cl=None, verbose=True):
1001
    self.queue = []
1002
    if cl is None:
1003
      cl = GetClient()
1004
    self.cl = cl
1005
    self.verbose = verbose
1006

    
1007
  def QueueJob(self, name, *ops):
1008
    """Submit a job for execution.
1009

1010
    @type name: string
1011
    @param name: a description of the job, will be used in WaitJobSet
1012
    """
1013
    job_id = SendJob(ops, cl=self.cl)
1014
    self.queue.append((job_id, name))
1015

    
1016
  def GetResults(self):
1017
    """Wait for and return the results of all jobs.
1018

1019
    @rtype: list
1020
    @return: list of tuples (success, job results), in the same order
1021
        as the submitted jobs; if a job has failed, instead of the result
1022
        there will be the error message
1023

1024
    """
1025
    results = []
1026
    if self.verbose:
1027
      ToStdout("Submitted jobs %s", ", ".join(row[0] for row in self.queue))
1028
    for jid, name in self.queue:
1029
      if self.verbose:
1030
        ToStdout("Waiting for job %s for %s...", jid, name)
1031
      try:
1032
        job_result = PollJob(jid, cl=self.cl)
1033
        success = True
1034
      except (errors.GenericError, luxi.ProtocolError), err:
1035
        _, job_result = FormatError(err)
1036
        success = False
1037
        # the error message will always be shown, verbose or not
1038
        ToStderr("Job %s for %s has failed: %s", jid, name, job_result)
1039

    
1040
      results.append((success, job_result))
1041
    return results
1042

    
1043
  def WaitOrShow(self, wait):
1044
    """Wait for job results or only print the job IDs.
1045

1046
    @type wait: boolean
1047
    @param wait: whether to wait or not
1048

1049
    """
1050
    if wait:
1051
      return self.GetResults()
1052
    else:
1053
      for jid, name in self.queue:
1054
        ToStdout("%s: %s", jid, name)