Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 5b349fd1

History | View | Annotate | Download (68.2 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Module dealing with command line parsing"""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
25 a8083063 Iustin Pop
import sys
26 a8083063 Iustin Pop
import textwrap
27 a8083063 Iustin Pop
import os.path
28 685ee993 Iustin Pop
import time
29 46fbdd04 Iustin Pop
import logging
30 73702ee7 Iustin Pop
from cStringIO import StringIO
31 a8083063 Iustin Pop
32 a8083063 Iustin Pop
from ganeti import utils
33 a8083063 Iustin Pop
from ganeti import errors
34 a8083063 Iustin Pop
from ganeti import constants
35 846baef9 Iustin Pop
from ganeti import opcodes
36 ceab32dd Iustin Pop
from ganeti import luxi
37 b33e986b Iustin Pop
from ganeti import ssconf
38 4331f6cd Michael Hanselmann
from ganeti import rpc
39 7e49b6ce Michael Hanselmann
from ganeti import ssh
40 a8083063 Iustin Pop
41 c38c44ad Michael Hanselmann
from optparse import (OptionParser, TitledHelpFormatter,
42 38206f3c Iustin Pop
                      Option, OptionValueError)
43 a8083063 Iustin Pop
44 03298ebe Michael Hanselmann
45 4abc4f1e Iustin Pop
__all__ = [
46 4abc4f1e Iustin Pop
  # Command line options
47 e7e09483 Iustin Pop
  "ALLOCATABLE_OPT",
48 2d5e7ae1 Iustin Pop
  "ALL_OPT",
49 4c61d894 Iustin Pop
  "AUTO_PROMOTE_OPT",
50 e00f7a05 Iustin Pop
  "AUTO_REPLACE_OPT",
51 087ed2ed Iustin Pop
  "BACKEND_OPT",
52 baef337d Iustin Pop
  "CLEANUP_OPT",
53 4abc4f1e Iustin Pop
  "CONFIRM_OPT",
54 e32df528 Iustin Pop
  "CP_SIZE_OPT",
55 4abc4f1e Iustin Pop
  "DEBUG_OPT",
56 a0c9776a Iustin Pop
  "DEBUG_SIMERR_OPT",
57 4b038a1e Iustin Pop
  "DISKIDX_OPT",
58 e3876ccb Iustin Pop
  "DISK_OPT",
59 4b038a1e Iustin Pop
  "DISK_TEMPLATE_OPT",
60 771734c9 Iustin Pop
  "DRAINED_OPT",
61 7ea7bcf6 Iustin Pop
  "EARLY_RELEASE_OPT",
62 383a3591 Iustin Pop
  "ENABLED_HV_OPT",
63 14e9e7f3 Iustin Pop
  "ERROR_CODES_OPT",
64 4abc4f1e Iustin Pop
  "FIELDS_OPT",
65 4a25828c Iustin Pop
  "FILESTORE_DIR_OPT",
66 0f87c43e Iustin Pop
  "FILESTORE_DRIVER_OPT",
67 06073e85 Guido Trotter
  "FORCE_OPT",
68 06073e85 Guido Trotter
  "FORCE_VARIANT_OPT",
69 29392516 Iustin Pop
  "GLOBAL_FILEDIR_OPT",
70 073271f6 Iustin Pop
  "HVLIST_OPT",
71 48f212d7 Iustin Pop
  "HVOPTS_OPT",
72 236fd9c4 Iustin Pop
  "HYPERVISOR_OPT",
73 4eb62659 Iustin Pop
  "IALLOCATOR_OPT",
74 82a786d5 Iustin Pop
  "IGNORE_CONSIST_OPT",
75 b6e841a8 Iustin Pop
  "IGNORE_FAILURES_OPT",
76 ee3f9578 Iustin Pop
  "IGNORE_SECONDARIES_OPT",
77 05586c90 Iustin Pop
  "IGNORE_SIZE_OPT",
78 e3646f22 Iustin Pop
  "MAC_PREFIX_OPT",
79 29392516 Iustin Pop
  "MASTER_NETDEV_OPT",
80 771734c9 Iustin Pop
  "MC_OPT",
81 7d3a9fab Iustin Pop
  "NET_OPT",
82 6d4a1656 Michael Hanselmann
  "NEW_CLUSTER_CERT_OPT",
83 6b7d5878 Michael Hanselmann
  "NEW_CONFD_HMAC_KEY_OPT",
84 6d4a1656 Michael Hanselmann
  "NEW_RAPI_CERT_OPT",
85 a14db5ff Iustin Pop
  "NEW_SECONDARY_OPT",
86 4fbc93dd Iustin Pop
  "NIC_PARAMS_OPT",
87 7edc4637 Iustin Pop
  "NODE_LIST_OPT",
88 990b7886 Iustin Pop
  "NODE_PLACEMENT_OPT",
89 4abc4f1e Iustin Pop
  "NOHDR_OPT",
90 91e0748c Iustin Pop
  "NOIPCHECK_OPT",
91 25a8792c Iustin Pop
  "NO_INSTALL_OPT",
92 460d22be Iustin Pop
  "NONAMECHECK_OPT",
93 831040bf Iustin Pop
  "NOLVM_STORAGE_OPT",
94 29392516 Iustin Pop
  "NOMODIFY_ETCHOSTS_OPT",
95 b989b9d9 Ken Wehr
  "NOMODIFY_SSH_SETUP_OPT",
96 26023ecd Iustin Pop
  "NONICS_OPT",
97 f2a0828c Iustin Pop
  "NONLIVE_OPT",
98 14e9e7f3 Iustin Pop
  "NONPLUS1_OPT",
99 44c44832 Iustin Pop
  "NOSHUTDOWN_OPT",
100 edeb878a Iustin Pop
  "NOSTART_OPT",
101 fcdde7f2 Iustin Pop
  "NOSSH_KEYCHECK_OPT",
102 58371861 Iustin Pop
  "NOVOTING_OPT",
103 3f75b4f3 Iustin Pop
  "NWSYNC_OPT",
104 a72d0a79 Iustin Pop
  "ON_PRIMARY_OPT",
105 feb09e6a Iustin Pop
  "ON_SECONDARY_OPT",
106 771734c9 Iustin Pop
  "OFFLINE_OPT",
107 d3ed23ff Iustin Pop
  "OS_OPT",
108 ff00c1a7 Iustin Pop
  "OS_SIZE_OPT",
109 6d4a1656 Michael Hanselmann
  "RAPI_CERT_OPT",
110 b8d0f938 Iustin Pop
  "READD_OPT",
111 12054861 Iustin Pop
  "REBOOT_TYPE_OPT",
112 8d823629 Iustin Pop
  "SECONDARY_IP_OPT",
113 67840b40 Iustin Pop
  "SELECT_OS_OPT",
114 4abc4f1e Iustin Pop
  "SEP_OPT",
115 fdcf4d84 Iustin Pop
  "SHOWCMD_OPT",
116 7e5eaaa8 Guido Trotter
  "SHUTDOWN_TIMEOUT_OPT",
117 f36d7d81 Iustin Pop
  "SINGLE_NODE_OPT",
118 df62e5db Iustin Pop
  "SRC_DIR_OPT",
119 df62e5db Iustin Pop
  "SRC_NODE_OPT",
120 4abc4f1e Iustin Pop
  "SUBMIT_OPT",
121 99a8c799 Iustin Pop
  "STATIC_OPT",
122 4abc4f1e Iustin Pop
  "SYNC_OPT",
123 4abc4f1e Iustin Pop
  "TAG_SRC_OPT",
124 b5762e2a Guido Trotter
  "TIMEOUT_OPT",
125 4abc4f1e Iustin Pop
  "USEUNITS_OPT",
126 74adc100 Iustin Pop
  "USE_REPL_NET_OPT",
127 9cdb9578 Iustin Pop
  "VERBOSE_OPT",
128 b58726e8 Iustin Pop
  "VG_NAME_OPT",
129 1f587d3d Iustin Pop
  "YES_DOIT_OPT",
130 4abc4f1e Iustin Pop
  # Generic functions for CLI programs
131 4abc4f1e Iustin Pop
  "GenericMain",
132 d77490c5 Iustin Pop
  "GenericInstanceCreate",
133 4abc4f1e Iustin Pop
  "GetClient",
134 4abc4f1e Iustin Pop
  "GetOnlineNodes",
135 4abc4f1e Iustin Pop
  "JobExecutor",
136 4abc4f1e Iustin Pop
  "JobSubmittedException",
137 4abc4f1e Iustin Pop
  "ParseTimespec",
138 7e49b6ce Michael Hanselmann
  "RunWhileClusterStopped",
139 4abc4f1e Iustin Pop
  "SubmitOpCode",
140 4abc4f1e Iustin Pop
  "SubmitOrSend",
141 4abc4f1e Iustin Pop
  "UsesRPC",
142 4abc4f1e Iustin Pop
  # Formatting functions
143 4abc4f1e Iustin Pop
  "ToStderr", "ToStdout",
144 4abc4f1e Iustin Pop
  "FormatError",
145 4abc4f1e Iustin Pop
  "GenerateTable",
146 4abc4f1e Iustin Pop
  "AskUser",
147 4abc4f1e Iustin Pop
  "FormatTimestamp",
148 4abc4f1e Iustin Pop
  # Tags functions
149 4abc4f1e Iustin Pop
  "ListTags",
150 4abc4f1e Iustin Pop
  "AddTags",
151 4abc4f1e Iustin Pop
  "RemoveTags",
152 4abc4f1e Iustin Pop
  # command line options support infrastructure
153 4abc4f1e Iustin Pop
  "ARGS_MANY_INSTANCES",
154 4abc4f1e Iustin Pop
  "ARGS_MANY_NODES",
155 4abc4f1e Iustin Pop
  "ARGS_NONE",
156 4abc4f1e Iustin Pop
  "ARGS_ONE_INSTANCE",
157 4abc4f1e Iustin Pop
  "ARGS_ONE_NODE",
158 f9faf9c3 Renรฉ Nussbaumer
  "ARGS_ONE_OS",
159 4abc4f1e Iustin Pop
  "ArgChoice",
160 4abc4f1e Iustin Pop
  "ArgCommand",
161 4abc4f1e Iustin Pop
  "ArgFile",
162 4abc4f1e Iustin Pop
  "ArgHost",
163 4abc4f1e Iustin Pop
  "ArgInstance",
164 4abc4f1e Iustin Pop
  "ArgJobId",
165 4abc4f1e Iustin Pop
  "ArgNode",
166 f9faf9c3 Renรฉ Nussbaumer
  "ArgOs",
167 4abc4f1e Iustin Pop
  "ArgSuggest",
168 4abc4f1e Iustin Pop
  "ArgUnknown",
169 4abc4f1e Iustin Pop
  "OPT_COMPL_INST_ADD_NODES",
170 4abc4f1e Iustin Pop
  "OPT_COMPL_MANY_NODES",
171 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_IALLOCATOR",
172 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_INSTANCE",
173 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_NODE",
174 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_OS",
175 4abc4f1e Iustin Pop
  "cli_option",
176 4abc4f1e Iustin Pop
  "SplitNodeOption",
177 07150497 Guido Trotter
  "CalculateOSNames",
178 4abc4f1e Iustin Pop
  ]
179 846baef9 Iustin Pop
180 8b46606c Guido Trotter
NO_PREFIX = "no_"
181 8b46606c Guido Trotter
UN_PREFIX = "-"
182 846baef9 Iustin Pop
183 03298ebe Michael Hanselmann
184 863d7f46 Michael Hanselmann
class _Argument:
185 7260cfbe Iustin Pop
  def __init__(self, min=0, max=None): # pylint: disable-msg=W0622
186 863d7f46 Michael Hanselmann
    self.min = min
187 863d7f46 Michael Hanselmann
    self.max = max
188 863d7f46 Michael Hanselmann
189 863d7f46 Michael Hanselmann
  def __repr__(self):
190 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s>" %
191 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max))
192 863d7f46 Michael Hanselmann
193 863d7f46 Michael Hanselmann
194 863d7f46 Michael Hanselmann
class ArgSuggest(_Argument):
195 863d7f46 Michael Hanselmann
  """Suggesting argument.
196 863d7f46 Michael Hanselmann

197 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
198 863d7f46 Michael Hanselmann

199 863d7f46 Michael Hanselmann
  """
200 7260cfbe Iustin Pop
  # pylint: disable-msg=W0622
201 863d7f46 Michael Hanselmann
  def __init__(self, min=0, max=None, choices=None):
202 863d7f46 Michael Hanselmann
    _Argument.__init__(self, min=min, max=max)
203 863d7f46 Michael Hanselmann
    self.choices = choices
204 863d7f46 Michael Hanselmann
205 863d7f46 Michael Hanselmann
  def __repr__(self):
206 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s choices=%r>" %
207 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max, self.choices))
208 863d7f46 Michael Hanselmann
209 863d7f46 Michael Hanselmann
210 863d7f46 Michael Hanselmann
class ArgChoice(ArgSuggest):
211 863d7f46 Michael Hanselmann
  """Choice argument.
212 863d7f46 Michael Hanselmann

213 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor. Like L{ArgSuggest},
214 863d7f46 Michael Hanselmann
  but value must be one of the choices.
215 863d7f46 Michael Hanselmann

216 863d7f46 Michael Hanselmann
  """
217 863d7f46 Michael Hanselmann
218 863d7f46 Michael Hanselmann
219 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
220 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
221 863d7f46 Michael Hanselmann

222 863d7f46 Michael Hanselmann
  """
223 863d7f46 Michael Hanselmann
224 863d7f46 Michael Hanselmann
225 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
226 863d7f46 Michael Hanselmann
  """Instances argument.
227 863d7f46 Michael Hanselmann

228 863d7f46 Michael Hanselmann
  """
229 863d7f46 Michael Hanselmann
230 863d7f46 Michael Hanselmann
231 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
232 863d7f46 Michael Hanselmann
  """Node argument.
233 863d7f46 Michael Hanselmann

234 863d7f46 Michael Hanselmann
  """
235 863d7f46 Michael Hanselmann
236 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
237 863d7f46 Michael Hanselmann
  """Job ID argument.
238 863d7f46 Michael Hanselmann

239 863d7f46 Michael Hanselmann
  """
240 863d7f46 Michael Hanselmann
241 863d7f46 Michael Hanselmann
242 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
243 863d7f46 Michael Hanselmann
  """File path argument.
244 863d7f46 Michael Hanselmann

245 863d7f46 Michael Hanselmann
  """
246 863d7f46 Michael Hanselmann
247 863d7f46 Michael Hanselmann
248 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
249 863d7f46 Michael Hanselmann
  """Command argument.
250 863d7f46 Michael Hanselmann

251 863d7f46 Michael Hanselmann
  """
252 863d7f46 Michael Hanselmann
253 863d7f46 Michael Hanselmann
254 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
255 83ec7961 Michael Hanselmann
  """Host argument.
256 83ec7961 Michael Hanselmann

257 83ec7961 Michael Hanselmann
  """
258 83ec7961 Michael Hanselmann
259 83ec7961 Michael Hanselmann
260 f9faf9c3 Renรฉ Nussbaumer
class ArgOs(_Argument):
261 f9faf9c3 Renรฉ Nussbaumer
  """OS argument.
262 f9faf9c3 Renรฉ Nussbaumer

263 f9faf9c3 Renรฉ Nussbaumer
  """
264 f9faf9c3 Renรฉ Nussbaumer
265 f9faf9c3 Renรฉ Nussbaumer
266 4a265c08 Michael Hanselmann
ARGS_NONE = []
267 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
268 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
269 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
270 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
271 f9faf9c3 Renรฉ Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
272 4a265c08 Michael Hanselmann
273 4a265c08 Michael Hanselmann
274 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
275 846baef9 Iustin Pop
  """Extract the tag type object.
276 846baef9 Iustin Pop

277 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
278 846baef9 Iustin Pop

279 846baef9 Iustin Pop
  """
280 846baef9 Iustin Pop
  if not hasattr(opts, "tag_type"):
281 846baef9 Iustin Pop
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
282 846baef9 Iustin Pop
  kind = opts.tag_type
283 846baef9 Iustin Pop
  if kind == constants.TAG_CLUSTER:
284 846baef9 Iustin Pop
    retval = kind, kind
285 846baef9 Iustin Pop
  elif kind == constants.TAG_NODE or kind == constants.TAG_INSTANCE:
286 846baef9 Iustin Pop
    if not args:
287 0c434948 Iustin Pop
      raise errors.OpPrereqError("no arguments passed to the command")
288 846baef9 Iustin Pop
    name = args.pop(0)
289 846baef9 Iustin Pop
    retval = kind, name
290 846baef9 Iustin Pop
  else:
291 846baef9 Iustin Pop
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
292 846baef9 Iustin Pop
  return retval
293 846baef9 Iustin Pop
294 846baef9 Iustin Pop
295 810c50b7 Iustin Pop
def _ExtendTags(opts, args):
296 810c50b7 Iustin Pop
  """Extend the args if a source file has been given.
297 810c50b7 Iustin Pop

298 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
299 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
300 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
301 810c50b7 Iustin Pop

302 810c50b7 Iustin Pop
  """
303 810c50b7 Iustin Pop
  fname = opts.tags_source
304 810c50b7 Iustin Pop
  if fname is None:
305 810c50b7 Iustin Pop
    return
306 810c50b7 Iustin Pop
  if fname == "-":
307 810c50b7 Iustin Pop
    new_fh = sys.stdin
308 810c50b7 Iustin Pop
  else:
309 810c50b7 Iustin Pop
    new_fh = open(fname, "r")
310 810c50b7 Iustin Pop
  new_data = []
311 810c50b7 Iustin Pop
  try:
312 810c50b7 Iustin Pop
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
313 810c50b7 Iustin Pop
    # because of python bug 1633941
314 810c50b7 Iustin Pop
    while True:
315 810c50b7 Iustin Pop
      line = new_fh.readline()
316 810c50b7 Iustin Pop
      if not line:
317 810c50b7 Iustin Pop
        break
318 810c50b7 Iustin Pop
      new_data.append(line.strip())
319 810c50b7 Iustin Pop
  finally:
320 810c50b7 Iustin Pop
    new_fh.close()
321 810c50b7 Iustin Pop
  args.extend(new_data)
322 810c50b7 Iustin Pop
323 810c50b7 Iustin Pop
324 846baef9 Iustin Pop
def ListTags(opts, args):
325 846baef9 Iustin Pop
  """List the tags on a given object.
326 846baef9 Iustin Pop

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

332 846baef9 Iustin Pop
  """
333 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
334 7699c3af Iustin Pop
  cl = GetClient()
335 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
336 846baef9 Iustin Pop
  result = list(result)
337 846baef9 Iustin Pop
  result.sort()
338 846baef9 Iustin Pop
  for tag in result:
339 03298ebe Michael Hanselmann
    ToStdout(tag)
340 846baef9 Iustin Pop
341 846baef9 Iustin Pop
342 846baef9 Iustin Pop
def AddTags(opts, args):
343 846baef9 Iustin Pop
  """Add tags on a given object.
344 846baef9 Iustin Pop

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

350 846baef9 Iustin Pop
  """
351 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
352 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
353 846baef9 Iustin Pop
  if not args:
354 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be added")
355 846baef9 Iustin Pop
  op = opcodes.OpAddTags(kind=kind, name=name, tags=args)
356 846baef9 Iustin Pop
  SubmitOpCode(op)
357 846baef9 Iustin Pop
358 846baef9 Iustin Pop
359 846baef9 Iustin Pop
def RemoveTags(opts, args):
360 846baef9 Iustin Pop
  """Remove tags from a given object.
361 846baef9 Iustin Pop

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

367 846baef9 Iustin Pop
  """
368 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
369 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
370 846baef9 Iustin Pop
  if not args:
371 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be removed")
372 846baef9 Iustin Pop
  op = opcodes.OpDelTags(kind=kind, name=name, tags=args)
373 846baef9 Iustin Pop
  SubmitOpCode(op)
374 846baef9 Iustin Pop
375 a8083063 Iustin Pop
376 8929d28c Iustin Pop
def check_unit(option, opt, value): # pylint: disable-msg=W0613
377 65fe4693 Iustin Pop
  """OptParsers custom converter for units.
378 65fe4693 Iustin Pop

379 65fe4693 Iustin Pop
  """
380 a8083063 Iustin Pop
  try:
381 a8083063 Iustin Pop
    return utils.ParseUnit(value)
382 a8083063 Iustin Pop
  except errors.UnitParseError, err:
383 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
384 a8083063 Iustin Pop
385 a8083063 Iustin Pop
386 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
387 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
388 a8469393 Iustin Pop

389 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
390 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
391 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
392 a8469393 Iustin Pop
  have value=True.
393 a8469393 Iustin Pop

394 a8469393 Iustin Pop
  @type opt: string
395 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
396 a8469393 Iustin Pop
      data, used in building error messages
397 a8469393 Iustin Pop
  @type data: string
398 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
399 a8469393 Iustin Pop
  @rtype: dict
400 a8469393 Iustin Pop
  @return: {key=val, key=val}
401 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
402 a8469393 Iustin Pop

403 a8469393 Iustin Pop
  """
404 a8469393 Iustin Pop
  kv_dict = {}
405 4f31882e Guido Trotter
  if data:
406 1b3a7656 Iustin Pop
    for elem in utils.UnescapeAndSplit(data, sep=","):
407 4f31882e Guido Trotter
      if "=" in elem:
408 4f31882e Guido Trotter
        key, val = elem.split("=", 1)
409 a8469393 Iustin Pop
      else:
410 4f31882e Guido Trotter
        if elem.startswith(NO_PREFIX):
411 4f31882e Guido Trotter
          key, val = elem[len(NO_PREFIX):], False
412 4f31882e Guido Trotter
        elif elem.startswith(UN_PREFIX):
413 4f31882e Guido Trotter
          key, val = elem[len(UN_PREFIX):], None
414 4f31882e Guido Trotter
        else:
415 4f31882e Guido Trotter
          key, val = elem, True
416 4f31882e Guido Trotter
      if key in kv_dict:
417 4f31882e Guido Trotter
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
418 4f31882e Guido Trotter
                                    (key, opt))
419 4f31882e Guido Trotter
      kv_dict[key] = val
420 a8469393 Iustin Pop
  return kv_dict
421 a8469393 Iustin Pop
422 a8469393 Iustin Pop
423 8929d28c Iustin Pop
def check_ident_key_val(option, opt, value):  # pylint: disable-msg=W0613
424 552c8dff Michael Hanselmann
  """Custom parser for ident:key=val,key=val options.
425 552c8dff Michael Hanselmann

426 552c8dff Michael Hanselmann
  This will store the parsed values as a tuple (ident, {key: val}). As such,
427 552c8dff Michael Hanselmann
  multiple uses of this option via action=append is possible.
428 a8469393 Iustin Pop

429 a8469393 Iustin Pop
  """
430 a8469393 Iustin Pop
  if ":" not in value:
431 8b46606c Guido Trotter
    ident, rest = value, ''
432 a8469393 Iustin Pop
  else:
433 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
434 8b46606c Guido Trotter
435 8b46606c Guido Trotter
  if ident.startswith(NO_PREFIX):
436 8b46606c Guido Trotter
    if rest:
437 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
438 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
439 8b46606c Guido Trotter
    retval = (ident[len(NO_PREFIX):], False)
440 8b46606c Guido Trotter
  elif ident.startswith(UN_PREFIX):
441 8b46606c Guido Trotter
    if rest:
442 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
443 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
444 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
445 8b46606c Guido Trotter
  else:
446 a8469393 Iustin Pop
    kv_dict = _SplitKeyVal(opt, rest)
447 a8469393 Iustin Pop
    retval = (ident, kv_dict)
448 a8469393 Iustin Pop
  return retval
449 a8469393 Iustin Pop
450 a8469393 Iustin Pop
451 8929d28c Iustin Pop
def check_key_val(option, opt, value):  # pylint: disable-msg=W0613
452 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
453 552c8dff Michael Hanselmann

454 552c8dff Michael Hanselmann
  This will store the parsed values as a dict {key: val}.
455 a8469393 Iustin Pop

456 a8469393 Iustin Pop
  """
457 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
458 a8469393 Iustin Pop
459 a8469393 Iustin Pop
460 e7b61bb0 Iustin Pop
def check_bool(option, opt, value): # pylint: disable-msg=W0613
461 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
462 e7b61bb0 Iustin Pop

463 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
464 e7b61bb0 Iustin Pop

465 e7b61bb0 Iustin Pop
  """
466 e7b61bb0 Iustin Pop
  value = value.lower()
467 e7b61bb0 Iustin Pop
  if value == constants.VALUE_FALSE or value == "no":
468 e7b61bb0 Iustin Pop
    return False
469 e7b61bb0 Iustin Pop
  elif value == constants.VALUE_TRUE or value == "yes":
470 e7b61bb0 Iustin Pop
    return True
471 e7b61bb0 Iustin Pop
  else:
472 e7b61bb0 Iustin Pop
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
473 e7b61bb0 Iustin Pop
474 e7b61bb0 Iustin Pop
475 63d44c55 Michael Hanselmann
# completion_suggestion is normally a list. Using numeric values not evaluating
476 63d44c55 Michael Hanselmann
# to False for dynamic completion.
477 63d44c55 Michael Hanselmann
(OPT_COMPL_MANY_NODES,
478 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_NODE,
479 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_INSTANCE,
480 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_OS,
481 2d3ed64b Michael Hanselmann
 OPT_COMPL_ONE_IALLOCATOR,
482 2d3ed64b Michael Hanselmann
 OPT_COMPL_INST_ADD_NODES) = range(100, 106)
483 63d44c55 Michael Hanselmann
484 63d44c55 Michael Hanselmann
OPT_COMPL_ALL = frozenset([
485 63d44c55 Michael Hanselmann
  OPT_COMPL_MANY_NODES,
486 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_NODE,
487 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_INSTANCE,
488 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_OS,
489 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_IALLOCATOR,
490 2d3ed64b Michael Hanselmann
  OPT_COMPL_INST_ADD_NODES,
491 63d44c55 Michael Hanselmann
  ])
492 63d44c55 Michael Hanselmann
493 63d44c55 Michael Hanselmann
494 552c8dff Michael Hanselmann
class CliOption(Option):
495 552c8dff Michael Hanselmann
  """Custom option class for optparse.
496 a8469393 Iustin Pop

497 a8469393 Iustin Pop
  """
498 863d7f46 Michael Hanselmann
  ATTRS = Option.ATTRS + [
499 863d7f46 Michael Hanselmann
    "completion_suggest",
500 863d7f46 Michael Hanselmann
    ]
501 552c8dff Michael Hanselmann
  TYPES = Option.TYPES + (
502 552c8dff Michael Hanselmann
    "identkeyval",
503 552c8dff Michael Hanselmann
    "keyval",
504 552c8dff Michael Hanselmann
    "unit",
505 e7b61bb0 Iustin Pop
    "bool",
506 552c8dff Michael Hanselmann
    )
507 552c8dff Michael Hanselmann
  TYPE_CHECKER = Option.TYPE_CHECKER.copy()
508 552c8dff Michael Hanselmann
  TYPE_CHECKER["identkeyval"] = check_ident_key_val
509 a8469393 Iustin Pop
  TYPE_CHECKER["keyval"] = check_key_val
510 552c8dff Michael Hanselmann
  TYPE_CHECKER["unit"] = check_unit
511 e7b61bb0 Iustin Pop
  TYPE_CHECKER["bool"] = check_bool
512 a8469393 Iustin Pop
513 a8469393 Iustin Pop
514 a8083063 Iustin Pop
# optparse.py sets make_option, so we do it for our own option class, too
515 a8083063 Iustin Pop
cli_option = CliOption
516 a8083063 Iustin Pop
517 a8083063 Iustin Pop
518 771734c9 Iustin Pop
_YORNO = "yes|no"
519 771734c9 Iustin Pop
520 ea34193f Iustin Pop
DEBUG_OPT = cli_option("-d", "--debug", default=0, action="count",
521 ea34193f Iustin Pop
                       help="Increase debugging level")
522 c38c44ad Michael Hanselmann
523 c38c44ad Michael Hanselmann
NOHDR_OPT = cli_option("--no-headers", default=False,
524 c38c44ad Michael Hanselmann
                       action="store_true", dest="no_headers",
525 c38c44ad Michael Hanselmann
                       help="Don't display column headers")
526 c38c44ad Michael Hanselmann
527 c38c44ad Michael Hanselmann
SEP_OPT = cli_option("--separator", default=None,
528 c38c44ad Michael Hanselmann
                     action="store", dest="separator",
529 c38c44ad Michael Hanselmann
                     help=("Separator between output fields"
530 c38c44ad Michael Hanselmann
                           " (defaults to one space)"))
531 c38c44ad Michael Hanselmann
532 c38c44ad Michael Hanselmann
USEUNITS_OPT = cli_option("--units", default=None,
533 c38c44ad Michael Hanselmann
                          dest="units", choices=('h', 'm', 'g', 't'),
534 c38c44ad Michael Hanselmann
                          help="Specify units for output (one of hmgt)")
535 c38c44ad Michael Hanselmann
536 c38c44ad Michael Hanselmann
FIELDS_OPT = cli_option("-o", "--output", dest="output", action="store",
537 c38c44ad Michael Hanselmann
                        type="string", metavar="FIELDS",
538 c38c44ad Michael Hanselmann
                        help="Comma separated list of output fields")
539 c38c44ad Michael Hanselmann
540 c38c44ad Michael Hanselmann
FORCE_OPT = cli_option("-f", "--force", dest="force", action="store_true",
541 c38c44ad Michael Hanselmann
                       default=False, help="Force the operation")
542 c38c44ad Michael Hanselmann
543 c38c44ad Michael Hanselmann
CONFIRM_OPT = cli_option("--yes", dest="confirm", action="store_true",
544 c38c44ad Michael Hanselmann
                         default=False, help="Do not require confirmation")
545 c38c44ad Michael Hanselmann
546 c38c44ad Michael Hanselmann
TAG_SRC_OPT = cli_option("--from", dest="tags_source",
547 c38c44ad Michael Hanselmann
                         default=None, help="File with tag names")
548 c38c44ad Michael Hanselmann
549 c38c44ad Michael Hanselmann
SUBMIT_OPT = cli_option("--submit", dest="submit_only",
550 c38c44ad Michael Hanselmann
                        default=False, action="store_true",
551 c38c44ad Michael Hanselmann
                        help=("Submit the job and return the job ID, but"
552 c38c44ad Michael Hanselmann
                              " don't wait for the job to finish"))
553 c38c44ad Michael Hanselmann
554 c38c44ad Michael Hanselmann
SYNC_OPT = cli_option("--sync", dest="do_locking",
555 c38c44ad Michael Hanselmann
                      default=False, action="store_true",
556 c38c44ad Michael Hanselmann
                      help=("Grab locks while doing the queries"
557 c38c44ad Michael Hanselmann
                            " in order to ensure more consistent results"))
558 c38c44ad Michael Hanselmann
559 c38c44ad Michael Hanselmann
_DRY_RUN_OPT = cli_option("--dry-run", default=False,
560 c38c44ad Michael Hanselmann
                          action="store_true",
561 c38c44ad Michael Hanselmann
                          help=("Do not execute the operation, just run the"
562 c38c44ad Michael Hanselmann
                                " check steps and verify it it could be"
563 c38c44ad Michael Hanselmann
                                " executed"))
564 c38c44ad Michael Hanselmann
565 9cdb9578 Iustin Pop
VERBOSE_OPT = cli_option("-v", "--verbose", default=False,
566 9cdb9578 Iustin Pop
                         action="store_true",
567 9cdb9578 Iustin Pop
                         help="Increase the verbosity of the operation")
568 9cdb9578 Iustin Pop
569 a0c9776a Iustin Pop
DEBUG_SIMERR_OPT = cli_option("--debug-simulate-errors", default=False,
570 a0c9776a Iustin Pop
                              action="store_true", dest="simulate_errors",
571 a0c9776a Iustin Pop
                              help="Debugging option that makes the operation"
572 a0c9776a Iustin Pop
                              " treat most runtime checks as failed")
573 a0c9776a Iustin Pop
574 3f75b4f3 Iustin Pop
NWSYNC_OPT = cli_option("--no-wait-for-sync", dest="wait_for_sync",
575 3f75b4f3 Iustin Pop
                        default=True, action="store_false",
576 3f75b4f3 Iustin Pop
                        help="Don't wait for sync (DANGEROUS!)")
577 3f75b4f3 Iustin Pop
578 4f365444 Iustin Pop
DISK_TEMPLATE_OPT = cli_option("-t", "--disk-template", dest="disk_template",
579 4f365444 Iustin Pop
                               help="Custom disk setup (diskless, file,"
580 4f365444 Iustin Pop
                               " plain or drbd)",
581 4f365444 Iustin Pop
                               default=None, metavar="TEMPL",
582 4f365444 Iustin Pop
                               choices=list(constants.DISK_TEMPLATES))
583 4f365444 Iustin Pop
584 26023ecd Iustin Pop
NONICS_OPT = cli_option("--no-nics", default=False, action="store_true",
585 26023ecd Iustin Pop
                        help="Do not create any network cards for"
586 26023ecd Iustin Pop
                        " the instance")
587 26023ecd Iustin Pop
588 4a25828c Iustin Pop
FILESTORE_DIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
589 4a25828c Iustin Pop
                               help="Relative path under default cluster-wide"
590 4a25828c Iustin Pop
                               " file storage dir to store file-based disks",
591 4a25828c Iustin Pop
                               default=None, metavar="<DIR>")
592 4a25828c Iustin Pop
593 0f87c43e Iustin Pop
FILESTORE_DRIVER_OPT = cli_option("--file-driver", dest="file_driver",
594 0f87c43e Iustin Pop
                                  help="Driver to use for image files",
595 0f87c43e Iustin Pop
                                  default="loop", metavar="<DRIVER>",
596 0f87c43e Iustin Pop
                                  choices=list(constants.FILE_DRIVER))
597 0f87c43e Iustin Pop
598 4eb62659 Iustin Pop
IALLOCATOR_OPT = cli_option("-I", "--iallocator", metavar="<NAME>",
599 4eb62659 Iustin Pop
                            help="Select nodes for the instance automatically"
600 4eb62659 Iustin Pop
                            " using the <NAME> iallocator plugin",
601 4eb62659 Iustin Pop
                            default=None, type="string",
602 4eb62659 Iustin Pop
                            completion_suggest=OPT_COMPL_ONE_IALLOCATOR)
603 4eb62659 Iustin Pop
604 d3ed23ff Iustin Pop
OS_OPT = cli_option("-o", "--os-type", dest="os", help="What OS to run",
605 d3ed23ff Iustin Pop
                    metavar="<os>",
606 d3ed23ff Iustin Pop
                    completion_suggest=OPT_COMPL_ONE_OS)
607 d3ed23ff Iustin Pop
608 06073e85 Guido Trotter
FORCE_VARIANT_OPT = cli_option("--force-variant", dest="force_variant",
609 06073e85 Guido Trotter
                               action="store_true", default=False,
610 06073e85 Guido Trotter
                               help="Force an unknown variant")
611 06073e85 Guido Trotter
612 25a8792c Iustin Pop
NO_INSTALL_OPT = cli_option("--no-install", dest="no_install",
613 25a8792c Iustin Pop
                            action="store_true", default=False,
614 25a8792c Iustin Pop
                            help="Do not install the OS (will"
615 25a8792c Iustin Pop
                            " enable no-start)")
616 25a8792c Iustin Pop
617 087ed2ed Iustin Pop
BACKEND_OPT = cli_option("-B", "--backend-parameters", dest="beparams",
618 087ed2ed Iustin Pop
                         type="keyval", default={},
619 087ed2ed Iustin Pop
                         help="Backend parameters")
620 48f212d7 Iustin Pop
621 48f212d7 Iustin Pop
HVOPTS_OPT =  cli_option("-H", "--hypervisor-parameters", type="keyval",
622 48f212d7 Iustin Pop
                         default={}, dest="hvparams",
623 48f212d7 Iustin Pop
                         help="Hypervisor parameters")
624 087ed2ed Iustin Pop
625 236fd9c4 Iustin Pop
HYPERVISOR_OPT = cli_option("-H", "--hypervisor-parameters", dest="hypervisor",
626 236fd9c4 Iustin Pop
                            help="Hypervisor and hypervisor options, in the"
627 236fd9c4 Iustin Pop
                            " format hypervisor:option=value,option=value,...",
628 236fd9c4 Iustin Pop
                            default=None, type="identkeyval")
629 073271f6 Iustin Pop
630 073271f6 Iustin Pop
HVLIST_OPT = cli_option("-H", "--hypervisor-parameters", dest="hvparams",
631 073271f6 Iustin Pop
                        help="Hypervisor and hypervisor options, in the"
632 073271f6 Iustin Pop
                        " format hypervisor:option=value,option=value,...",
633 073271f6 Iustin Pop
                        default=[], action="append", type="identkeyval")
634 236fd9c4 Iustin Pop
635 91e0748c Iustin Pop
NOIPCHECK_OPT = cli_option("--no-ip-check", dest="ip_check", default=True,
636 91e0748c Iustin Pop
                           action="store_false",
637 91e0748c Iustin Pop
                           help="Don't check that the instance's IP"
638 91e0748c Iustin Pop
                           " is alive")
639 91e0748c Iustin Pop
640 460d22be Iustin Pop
NONAMECHECK_OPT = cli_option("--no-name-check", dest="name_check",
641 460d22be Iustin Pop
                             default=True, action="store_false",
642 460d22be Iustin Pop
                             help="Don't check that the instance's name"
643 460d22be Iustin Pop
                             " is resolvable")
644 460d22be Iustin Pop
645 7d3a9fab Iustin Pop
NET_OPT = cli_option("--net",
646 7d3a9fab Iustin Pop
                     help="NIC parameters", default=[],
647 7d3a9fab Iustin Pop
                     dest="nics", action="append", type="identkeyval")
648 e3876ccb Iustin Pop
649 e3876ccb Iustin Pop
DISK_OPT = cli_option("--disk", help="Disk parameters", default=[],
650 e3876ccb Iustin Pop
                      dest="disks", action="append", type="identkeyval")
651 91e0748c Iustin Pop
652 4b038a1e Iustin Pop
DISKIDX_OPT = cli_option("--disks", dest="disks", default=None,
653 4b038a1e Iustin Pop
                         help="Comma-separated list of disks"
654 4b038a1e Iustin Pop
                         " indices to act on (e.g. 0,2) (optional,"
655 4b038a1e Iustin Pop
                         " defaults to all disks)")
656 4b038a1e Iustin Pop
657 ff00c1a7 Iustin Pop
OS_SIZE_OPT = cli_option("-s", "--os-size", dest="sd_size",
658 ff00c1a7 Iustin Pop
                         help="Enforces a single-disk configuration using the"
659 ff00c1a7 Iustin Pop
                         " given disk size, in MiB unless a suffix is used",
660 ff00c1a7 Iustin Pop
                         default=None, type="unit", metavar="<size>")
661 ff00c1a7 Iustin Pop
662 82a786d5 Iustin Pop
IGNORE_CONSIST_OPT = cli_option("--ignore-consistency",
663 82a786d5 Iustin Pop
                                dest="ignore_consistency",
664 82a786d5 Iustin Pop
                                action="store_true", default=False,
665 82a786d5 Iustin Pop
                                help="Ignore the consistency of the disks on"
666 82a786d5 Iustin Pop
                                " the secondary")
667 82a786d5 Iustin Pop
668 f2a0828c Iustin Pop
NONLIVE_OPT = cli_option("--non-live", dest="live",
669 f2a0828c Iustin Pop
                         default=True, action="store_false",
670 f2a0828c Iustin Pop
                         help="Do a non-live migration (this usually means"
671 f2a0828c Iustin Pop
                         " freeze the instance, save the state, transfer and"
672 f2a0828c Iustin Pop
                         " only then resume running on the secondary node)")
673 f2a0828c Iustin Pop
674 990b7886 Iustin Pop
NODE_PLACEMENT_OPT = cli_option("-n", "--node", dest="node",
675 990b7886 Iustin Pop
                                help="Target node and optional secondary node",
676 990b7886 Iustin Pop
                                metavar="<pnode>[:<snode>]",
677 990b7886 Iustin Pop
                                completion_suggest=OPT_COMPL_INST_ADD_NODES)
678 990b7886 Iustin Pop
679 7edc4637 Iustin Pop
NODE_LIST_OPT = cli_option("-n", "--node", dest="nodes", default=[],
680 7edc4637 Iustin Pop
                           action="append", metavar="<node>",
681 7edc4637 Iustin Pop
                           help="Use only this node (can be used multiple"
682 7edc4637 Iustin Pop
                           " times, if not given defaults to all nodes)",
683 7edc4637 Iustin Pop
                           completion_suggest=OPT_COMPL_ONE_NODE)
684 f36d7d81 Iustin Pop
685 f36d7d81 Iustin Pop
SINGLE_NODE_OPT = cli_option("-n", "--node", dest="node", help="Target node",
686 f36d7d81 Iustin Pop
                             metavar="<node>",
687 f36d7d81 Iustin Pop
                             completion_suggest=OPT_COMPL_ONE_NODE)
688 7edc4637 Iustin Pop
689 edeb878a Iustin Pop
NOSTART_OPT = cli_option("--no-start", dest="start", default=True,
690 edeb878a Iustin Pop
                         action="store_false",
691 edeb878a Iustin Pop
                         help="Don't start the instance after creation")
692 edeb878a Iustin Pop
693 fdcf4d84 Iustin Pop
SHOWCMD_OPT = cli_option("--show-cmd", dest="show_command",
694 fdcf4d84 Iustin Pop
                         action="store_true", default=False,
695 fdcf4d84 Iustin Pop
                         help="Show command instead of executing it")
696 fdcf4d84 Iustin Pop
697 baef337d Iustin Pop
CLEANUP_OPT = cli_option("--cleanup", dest="cleanup",
698 baef337d Iustin Pop
                         default=False, action="store_true",
699 baef337d Iustin Pop
                         help="Instead of performing the migration, try to"
700 baef337d Iustin Pop
                         " recover from a failed cleanup. This is safe"
701 baef337d Iustin Pop
                         " to run even if the instance is healthy, but it"
702 baef337d Iustin Pop
                         " will create extra replication traffic and "
703 baef337d Iustin Pop
                         " disrupt briefly the replication (like during the"
704 baef337d Iustin Pop
                         " migration")
705 baef337d Iustin Pop
706 99a8c799 Iustin Pop
STATIC_OPT = cli_option("-s", "--static", dest="static",
707 99a8c799 Iustin Pop
                        action="store_true", default=False,
708 99a8c799 Iustin Pop
                        help="Only show configuration data, not runtime data")
709 99a8c799 Iustin Pop
710 2d5e7ae1 Iustin Pop
ALL_OPT = cli_option("--all", dest="show_all",
711 2d5e7ae1 Iustin Pop
                     default=False, action="store_true",
712 2d5e7ae1 Iustin Pop
                     help="Show info on all instances on the cluster."
713 2d5e7ae1 Iustin Pop
                     " This can take a long time to run, use wisely")
714 2d5e7ae1 Iustin Pop
715 67840b40 Iustin Pop
SELECT_OS_OPT = cli_option("--select-os", dest="select_os",
716 67840b40 Iustin Pop
                           action="store_true", default=False,
717 67840b40 Iustin Pop
                           help="Interactive OS reinstall, lists available"
718 67840b40 Iustin Pop
                           " OS templates for selection")
719 2d5e7ae1 Iustin Pop
720 b6e841a8 Iustin Pop
IGNORE_FAILURES_OPT = cli_option("--ignore-failures", dest="ignore_failures",
721 b6e841a8 Iustin Pop
                                 action="store_true", default=False,
722 b6e841a8 Iustin Pop
                                 help="Remove the instance from the cluster"
723 b6e841a8 Iustin Pop
                                 " configuration even if there are failures"
724 b6e841a8 Iustin Pop
                                 " during the removal process")
725 b6e841a8 Iustin Pop
726 a14db5ff Iustin Pop
NEW_SECONDARY_OPT = cli_option("-n", "--new-secondary", dest="dst_node",
727 a14db5ff Iustin Pop
                               help="Specifies the new secondary node",
728 a14db5ff Iustin Pop
                               metavar="NODE", default=None,
729 a14db5ff Iustin Pop
                               completion_suggest=OPT_COMPL_ONE_NODE)
730 a14db5ff Iustin Pop
731 a72d0a79 Iustin Pop
ON_PRIMARY_OPT = cli_option("-p", "--on-primary", dest="on_primary",
732 a72d0a79 Iustin Pop
                            default=False, action="store_true",
733 a72d0a79 Iustin Pop
                            help="Replace the disk(s) on the primary"
734 a72d0a79 Iustin Pop
                            " node (only for the drbd template)")
735 feb09e6a Iustin Pop
736 feb09e6a Iustin Pop
ON_SECONDARY_OPT = cli_option("-s", "--on-secondary", dest="on_secondary",
737 feb09e6a Iustin Pop
                              default=False, action="store_true",
738 feb09e6a Iustin Pop
                              help="Replace the disk(s) on the secondary"
739 feb09e6a Iustin Pop
                              " node (only for the drbd template)")
740 e00f7a05 Iustin Pop
741 4c61d894 Iustin Pop
AUTO_PROMOTE_OPT = cli_option("--auto-promote", dest="auto_promote",
742 4c61d894 Iustin Pop
                              default=False, action="store_true",
743 4c61d894 Iustin Pop
                              help="Lock all nodes and auto-promote as needed"
744 4c61d894 Iustin Pop
                              " to MC status")
745 4c61d894 Iustin Pop
746 e00f7a05 Iustin Pop
AUTO_REPLACE_OPT = cli_option("-a", "--auto", dest="auto",
747 e00f7a05 Iustin Pop
                              default=False, action="store_true",
748 e00f7a05 Iustin Pop
                              help="Automatically replace faulty disks"
749 e00f7a05 Iustin Pop
                              " (only for the drbd template)")
750 a72d0a79 Iustin Pop
751 05586c90 Iustin Pop
IGNORE_SIZE_OPT = cli_option("--ignore-size", dest="ignore_size",
752 05586c90 Iustin Pop
                             default=False, action="store_true",
753 05586c90 Iustin Pop
                             help="Ignore current recorded size"
754 05586c90 Iustin Pop
                             " (useful for forcing activation when"
755 05586c90 Iustin Pop
                             " the recorded size is wrong)")
756 05586c90 Iustin Pop
757 df62e5db Iustin Pop
SRC_NODE_OPT = cli_option("--src-node", dest="src_node", help="Source node",
758 df62e5db Iustin Pop
                          metavar="<node>",
759 df62e5db Iustin Pop
                          completion_suggest=OPT_COMPL_ONE_NODE)
760 df62e5db Iustin Pop
761 df62e5db Iustin Pop
SRC_DIR_OPT = cli_option("--src-dir", dest="src_dir", help="Source directory",
762 df62e5db Iustin Pop
                         metavar="<dir>")
763 df62e5db Iustin Pop
764 8d823629 Iustin Pop
SECONDARY_IP_OPT = cli_option("-s", "--secondary-ip", dest="secondary_ip",
765 8d823629 Iustin Pop
                              help="Specify the secondary ip for the node",
766 8d823629 Iustin Pop
                              metavar="ADDRESS", default=None)
767 8d823629 Iustin Pop
768 b8d0f938 Iustin Pop
READD_OPT = cli_option("--readd", dest="readd",
769 b8d0f938 Iustin Pop
                       default=False, action="store_true",
770 b8d0f938 Iustin Pop
                       help="Readd old node after replacing it")
771 b8d0f938 Iustin Pop
772 fcdde7f2 Iustin Pop
NOSSH_KEYCHECK_OPT = cli_option("--no-ssh-key-check", dest="ssh_key_check",
773 fcdde7f2 Iustin Pop
                                default=True, action="store_false",
774 fcdde7f2 Iustin Pop
                                help="Disable SSH key fingerprint checking")
775 fcdde7f2 Iustin Pop
776 c38c44ad Michael Hanselmann
777 771734c9 Iustin Pop
MC_OPT = cli_option("-C", "--master-candidate", dest="master_candidate",
778 e7b61bb0 Iustin Pop
                    type="bool", default=None, metavar=_YORNO,
779 771734c9 Iustin Pop
                    help="Set the master_candidate flag on the node")
780 771734c9 Iustin Pop
781 771734c9 Iustin Pop
OFFLINE_OPT = cli_option("-O", "--offline", dest="offline", metavar=_YORNO,
782 e7b61bb0 Iustin Pop
                         type="bool", default=None,
783 771734c9 Iustin Pop
                         help="Set the offline flag on the node")
784 771734c9 Iustin Pop
785 771734c9 Iustin Pop
DRAINED_OPT = cli_option("-D", "--drained", dest="drained", metavar=_YORNO,
786 e7b61bb0 Iustin Pop
                         type="bool", default=None,
787 771734c9 Iustin Pop
                         help="Set the drained flag on the node")
788 771734c9 Iustin Pop
789 e7e09483 Iustin Pop
ALLOCATABLE_OPT = cli_option("--allocatable", dest="allocatable",
790 e7b61bb0 Iustin Pop
                             type="bool", default=None, metavar=_YORNO,
791 e7e09483 Iustin Pop
                             help="Set the allocatable flag on a volume")
792 e7e09483 Iustin Pop
793 831040bf Iustin Pop
NOLVM_STORAGE_OPT = cli_option("--no-lvm-storage", dest="lvm_storage",
794 831040bf Iustin Pop
                               help="Disable support for lvm based instances"
795 831040bf Iustin Pop
                               " (cluster-wide)",
796 831040bf Iustin Pop
                               action="store_false", default=True)
797 831040bf Iustin Pop
798 383a3591 Iustin Pop
ENABLED_HV_OPT = cli_option("--enabled-hypervisors",
799 383a3591 Iustin Pop
                            dest="enabled_hypervisors",
800 383a3591 Iustin Pop
                            help="Comma-separated list of hypervisors",
801 383a3591 Iustin Pop
                            type="string", default=None)
802 383a3591 Iustin Pop
803 4fbc93dd Iustin Pop
NIC_PARAMS_OPT = cli_option("-N", "--nic-parameters", dest="nicparams",
804 4fbc93dd Iustin Pop
                            type="keyval", default={},
805 4fbc93dd Iustin Pop
                            help="NIC parameters")
806 4fbc93dd Iustin Pop
807 e32df528 Iustin Pop
CP_SIZE_OPT = cli_option("-C", "--candidate-pool-size", default=None,
808 e32df528 Iustin Pop
                         dest="candidate_pool_size", type="int",
809 e32df528 Iustin Pop
                         help="Set the candidate pool size")
810 e32df528 Iustin Pop
811 b58726e8 Iustin Pop
VG_NAME_OPT = cli_option("-g", "--vg-name", dest="vg_name",
812 b58726e8 Iustin Pop
                         help="Enables LVM and specifies the volume group"
813 b58726e8 Iustin Pop
                         " name (cluster-wide) for disk allocation [xenvg]",
814 b58726e8 Iustin Pop
                         metavar="VG", default=None)
815 b58726e8 Iustin Pop
816 1f587d3d Iustin Pop
YES_DOIT_OPT = cli_option("--yes-do-it", dest="yes_do_it",
817 1f587d3d Iustin Pop
                          help="Destroy cluster", action="store_true")
818 b58726e8 Iustin Pop
819 58371861 Iustin Pop
NOVOTING_OPT = cli_option("--no-voting", dest="no_voting",
820 58371861 Iustin Pop
                          help="Skip node agreement check (dangerous)",
821 58371861 Iustin Pop
                          action="store_true", default=False)
822 58371861 Iustin Pop
823 e3646f22 Iustin Pop
MAC_PREFIX_OPT = cli_option("-m", "--mac-prefix", dest="mac_prefix",
824 e3646f22 Iustin Pop
                            help="Specify the mac prefix for the instance IP"
825 e3646f22 Iustin Pop
                            " addresses, in the format XX:XX:XX",
826 e3646f22 Iustin Pop
                            metavar="PREFIX",
827 e3646f22 Iustin Pop
                            default=None)
828 e3646f22 Iustin Pop
829 29392516 Iustin Pop
MASTER_NETDEV_OPT = cli_option("--master-netdev", dest="master_netdev",
830 29392516 Iustin Pop
                               help="Specify the node interface (cluster-wide)"
831 29392516 Iustin Pop
                               " on which the master IP address will be added "
832 29392516 Iustin Pop
                               " [%s]" % constants.DEFAULT_BRIDGE,
833 29392516 Iustin Pop
                               metavar="NETDEV",
834 29392516 Iustin Pop
                               default=constants.DEFAULT_BRIDGE)
835 29392516 Iustin Pop
836 29392516 Iustin Pop
837 29392516 Iustin Pop
GLOBAL_FILEDIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
838 29392516 Iustin Pop
                                help="Specify the default directory (cluster-"
839 29392516 Iustin Pop
                                "wide) for storing the file-based disks [%s]" %
840 29392516 Iustin Pop
                                constants.DEFAULT_FILE_STORAGE_DIR,
841 29392516 Iustin Pop
                                metavar="DIR",
842 29392516 Iustin Pop
                                default=constants.DEFAULT_FILE_STORAGE_DIR)
843 29392516 Iustin Pop
844 29392516 Iustin Pop
NOMODIFY_ETCHOSTS_OPT = cli_option("--no-etc-hosts", dest="modify_etc_hosts",
845 29392516 Iustin Pop
                                   help="Don't modify /etc/hosts",
846 29392516 Iustin Pop
                                   action="store_false", default=True)
847 29392516 Iustin Pop
848 b989b9d9 Ken Wehr
NOMODIFY_SSH_SETUP_OPT = cli_option("--no-ssh-init", dest="modify_ssh_setup",
849 b989b9d9 Ken Wehr
                                    help="Don't initialize SSH keys",
850 b989b9d9 Ken Wehr
                                    action="store_false", default=True)
851 b989b9d9 Ken Wehr
852 14e9e7f3 Iustin Pop
ERROR_CODES_OPT = cli_option("--error-codes", dest="error_codes",
853 14e9e7f3 Iustin Pop
                             help="Enable parseable error messages",
854 14e9e7f3 Iustin Pop
                             action="store_true", default=False)
855 14e9e7f3 Iustin Pop
856 14e9e7f3 Iustin Pop
NONPLUS1_OPT = cli_option("--no-nplus1-mem", dest="skip_nplusone_mem",
857 14e9e7f3 Iustin Pop
                          help="Skip N+1 memory redundancy tests",
858 14e9e7f3 Iustin Pop
                          action="store_true", default=False)
859 14e9e7f3 Iustin Pop
860 12054861 Iustin Pop
REBOOT_TYPE_OPT = cli_option("-t", "--type", dest="reboot_type",
861 12054861 Iustin Pop
                             help="Type of reboot: soft/hard/full",
862 12054861 Iustin Pop
                             default=constants.INSTANCE_REBOOT_HARD,
863 12054861 Iustin Pop
                             metavar="<REBOOT>",
864 12054861 Iustin Pop
                             choices=list(constants.REBOOT_TYPES))
865 12054861 Iustin Pop
866 ee3f9578 Iustin Pop
IGNORE_SECONDARIES_OPT = cli_option("--ignore-secondaries",
867 ee3f9578 Iustin Pop
                                    dest="ignore_secondaries",
868 ee3f9578 Iustin Pop
                                    default=False, action="store_true",
869 ee3f9578 Iustin Pop
                                    help="Ignore errors from secondaries")
870 ee3f9578 Iustin Pop
871 69b99987 Michael Hanselmann
NOSHUTDOWN_OPT = cli_option("--noshutdown", dest="shutdown",
872 44c44832 Iustin Pop
                            action="store_false", default=True,
873 44c44832 Iustin Pop
                            help="Don't shutdown the instance (unsafe)")
874 44c44832 Iustin Pop
875 b5762e2a Guido Trotter
TIMEOUT_OPT = cli_option("--timeout", dest="timeout", type="int",
876 b5762e2a Guido Trotter
                         default=constants.DEFAULT_SHUTDOWN_TIMEOUT,
877 b5762e2a Guido Trotter
                         help="Maximum time to wait")
878 44c44832 Iustin Pop
879 4d98c565 Guido Trotter
SHUTDOWN_TIMEOUT_OPT = cli_option("--shutdown-timeout",
880 4d98c565 Guido Trotter
                         dest="shutdown_timeout", type="int",
881 7e5eaaa8 Guido Trotter
                         default=constants.DEFAULT_SHUTDOWN_TIMEOUT,
882 7e5eaaa8 Guido Trotter
                         help="Maximum time to wait for instance shutdown")
883 7e5eaaa8 Guido Trotter
884 7ea7bcf6 Iustin Pop
EARLY_RELEASE_OPT = cli_option("--early-release",
885 7ea7bcf6 Iustin Pop
                               dest="early_release", default=False,
886 7ea7bcf6 Iustin Pop
                               action="store_true",
887 7ea7bcf6 Iustin Pop
                               help="Release the locks on the secondary"
888 7ea7bcf6 Iustin Pop
                               " node(s) early")
889 7ea7bcf6 Iustin Pop
890 6d4a1656 Michael Hanselmann
NEW_CLUSTER_CERT_OPT = cli_option("--new-cluster-certificate",
891 6d4a1656 Michael Hanselmann
                                  dest="new_cluster_cert",
892 6d4a1656 Michael Hanselmann
                                  default=False, action="store_true",
893 6d4a1656 Michael Hanselmann
                                  help="Generate a new cluster certificate")
894 6d4a1656 Michael Hanselmann
895 6d4a1656 Michael Hanselmann
RAPI_CERT_OPT = cli_option("--rapi-certificate", dest="rapi_cert",
896 6d4a1656 Michael Hanselmann
                           default=None,
897 6d4a1656 Michael Hanselmann
                           help="File containing new RAPI certificate")
898 6d4a1656 Michael Hanselmann
899 6d4a1656 Michael Hanselmann
NEW_RAPI_CERT_OPT = cli_option("--new-rapi-certificate", dest="new_rapi_cert",
900 6d4a1656 Michael Hanselmann
                               default=None, action="store_true",
901 6d4a1656 Michael Hanselmann
                               help=("Generate a new self-signed RAPI"
902 6d4a1656 Michael Hanselmann
                                     " certificate"))
903 6d4a1656 Michael Hanselmann
904 6b7d5878 Michael Hanselmann
NEW_CONFD_HMAC_KEY_OPT = cli_option("--new-confd-hmac-key",
905 6b7d5878 Michael Hanselmann
                                    dest="new_confd_hmac_key",
906 6b7d5878 Michael Hanselmann
                                    default=False, action="store_true",
907 6b7d5878 Michael Hanselmann
                                    help=("Create a new HMAC key for %s" %
908 6b7d5878 Michael Hanselmann
                                          constants.CONFD))
909 6d4a1656 Michael Hanselmann
910 74adc100 Iustin Pop
USE_REPL_NET_OPT = cli_option("--use-replication-network",
911 74adc100 Iustin Pop
                              dest="use_replication_network",
912 74adc100 Iustin Pop
                              help="Whether to use the replication network"
913 74adc100 Iustin Pop
                              " for talking to the nodes",
914 74adc100 Iustin Pop
                              action="store_true", default=False)
915 74adc100 Iustin Pop
916 771734c9 Iustin Pop
917 de47cf8f Guido Trotter
def _ParseArgs(argv, commands, aliases):
918 c41eea6e Iustin Pop
  """Parser for the command line arguments.
919 a8083063 Iustin Pop

920 5bbd3f7f Michael Hanselmann
  This function parses the arguments and returns the function which
921 c41eea6e Iustin Pop
  must be executed together with its (modified) arguments.
922 a8083063 Iustin Pop

923 c41eea6e Iustin Pop
  @param argv: the command line
924 c41eea6e Iustin Pop
  @param commands: dictionary with special contents, see the design
925 c41eea6e Iustin Pop
      doc for cmdline handling
926 c41eea6e Iustin Pop
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
927 098c0958 Michael Hanselmann

928 a8083063 Iustin Pop
  """
929 a8083063 Iustin Pop
  if len(argv) == 0:
930 a8083063 Iustin Pop
    binary = "<command>"
931 a8083063 Iustin Pop
  else:
932 a8083063 Iustin Pop
    binary = argv[0].split("/")[-1]
933 a8083063 Iustin Pop
934 a8083063 Iustin Pop
  if len(argv) > 1 and argv[1] == "--version":
935 03298ebe Michael Hanselmann
    ToStdout("%s (ganeti) %s", binary, constants.RELEASE_VERSION)
936 a8083063 Iustin Pop
    # Quit right away. That way we don't have to care about this special
937 a8083063 Iustin Pop
    # argument. optparse.py does it the same.
938 a8083063 Iustin Pop
    sys.exit(0)
939 a8083063 Iustin Pop
940 de47cf8f Guido Trotter
  if len(argv) < 2 or not (argv[1] in commands or
941 70a35b6f Guido Trotter
                           argv[1] in aliases):
942 a8083063 Iustin Pop
    # let's do a nice thing
943 a8083063 Iustin Pop
    sortedcmds = commands.keys()
944 a8083063 Iustin Pop
    sortedcmds.sort()
945 03298ebe Michael Hanselmann
946 03298ebe Michael Hanselmann
    ToStdout("Usage: %s {command} [options...] [argument...]", binary)
947 03298ebe Michael Hanselmann
    ToStdout("%s <command> --help to see details, or man %s", binary, binary)
948 03298ebe Michael Hanselmann
    ToStdout("")
949 03298ebe Michael Hanselmann
950 a8083063 Iustin Pop
    # compute the max line length for cmd + usage
951 4e713df6 Iustin Pop
    mlen = max([len(" %s" % cmd) for cmd in commands])
952 a8083063 Iustin Pop
    mlen = min(60, mlen) # should not get here...
953 03298ebe Michael Hanselmann
954 a8083063 Iustin Pop
    # and format a nice command list
955 03298ebe Michael Hanselmann
    ToStdout("Commands:")
956 a8083063 Iustin Pop
    for cmd in sortedcmds:
957 4e713df6 Iustin Pop
      cmdstr = " %s" % (cmd,)
958 9a033156 Iustin Pop
      help_text = commands[cmd][4]
959 03298ebe Michael Hanselmann
      help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
960 03298ebe Michael Hanselmann
      ToStdout("%-*s - %s", mlen, cmdstr, help_lines.pop(0))
961 a8083063 Iustin Pop
      for line in help_lines:
962 03298ebe Michael Hanselmann
        ToStdout("%-*s   %s", mlen, "", line)
963 03298ebe Michael Hanselmann
964 03298ebe Michael Hanselmann
    ToStdout("")
965 03298ebe Michael Hanselmann
966 a8083063 Iustin Pop
    return None, None, None
967 de47cf8f Guido Trotter
968 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
969 a8083063 Iustin Pop
  cmd = argv.pop(1)
970 de47cf8f Guido Trotter
  if cmd in aliases:
971 de47cf8f Guido Trotter
    if cmd in commands:
972 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' overrides an existing"
973 de47cf8f Guido Trotter
                                   " command" % cmd)
974 de47cf8f Guido Trotter
975 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
976 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
977 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
978 de47cf8f Guido Trotter
979 de47cf8f Guido Trotter
    cmd = aliases[cmd]
980 de47cf8f Guido Trotter
981 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
982 064c21f8 Iustin Pop
  parser = OptionParser(option_list=parser_opts + [_DRY_RUN_OPT, DEBUG_OPT],
983 a8083063 Iustin Pop
                        description=description,
984 a8083063 Iustin Pop
                        formatter=TitledHelpFormatter(),
985 a8083063 Iustin Pop
                        usage="%%prog %s %s" % (cmd, usage))
986 a8083063 Iustin Pop
  parser.disable_interspersed_args()
987 a8083063 Iustin Pop
  options, args = parser.parse_args()
988 a8005e17 Michael Hanselmann
989 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
990 a8083063 Iustin Pop
    return None, None, None
991 a8083063 Iustin Pop
992 a8083063 Iustin Pop
  return func, options, args
993 a8083063 Iustin Pop
994 a8083063 Iustin Pop
995 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
996 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
997 a8005e17 Michael Hanselmann

998 a8005e17 Michael Hanselmann
  Algorithm:
999 a8005e17 Michael Hanselmann

1000 a8005e17 Michael Hanselmann
    1. Abort with error if values specified by user but none expected.
1001 a8005e17 Michael Hanselmann

1002 a8005e17 Michael Hanselmann
    1. For each argument in definition
1003 a8005e17 Michael Hanselmann

1004 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1005 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1006 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1007 a8005e17 Michael Hanselmann

1008 a8005e17 Michael Hanselmann
        1. Abort with error if it's not the last argument in the definition
1009 a8005e17 Michael Hanselmann

1010 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1011 a8005e17 Michael Hanselmann

1012 a8005e17 Michael Hanselmann
      1. Abort with error if number of values doesn't match or is too large
1013 a8005e17 Michael Hanselmann

1014 a8005e17 Michael Hanselmann
    1. Abort with error if user didn't pass enough values (min_count)
1015 a8005e17 Michael Hanselmann

1016 a8005e17 Michael Hanselmann
  """
1017 a8005e17 Michael Hanselmann
  if args and not args_def:
1018 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1019 a8005e17 Michael Hanselmann
    return False
1020 a8005e17 Michael Hanselmann
1021 a8005e17 Michael Hanselmann
  min_count = None
1022 a8005e17 Michael Hanselmann
  max_count = None
1023 a8005e17 Michael Hanselmann
  check_max = None
1024 a8005e17 Michael Hanselmann
1025 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1026 a8005e17 Michael Hanselmann
1027 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1028 a8005e17 Michael Hanselmann
    if min_count is None:
1029 a8005e17 Michael Hanselmann
      min_count = arg.min
1030 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1031 a8005e17 Michael Hanselmann
      min_count += arg.min
1032 a8005e17 Michael Hanselmann
1033 a8005e17 Michael Hanselmann
    if max_count is None:
1034 a8005e17 Michael Hanselmann
      max_count = arg.max
1035 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1036 a8005e17 Michael Hanselmann
      max_count += arg.max
1037 a8005e17 Michael Hanselmann
1038 a8005e17 Michael Hanselmann
    if idx == last_idx:
1039 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1040 a8005e17 Michael Hanselmann
1041 a8005e17 Michael Hanselmann
    elif arg.max is None:
1042 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1043 a8005e17 Michael Hanselmann
1044 a8005e17 Michael Hanselmann
  if check_max:
1045 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1046 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1047 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1048 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1049 a8005e17 Michael Hanselmann
      return False
1050 a8005e17 Michael Hanselmann
1051 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1052 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1053 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1054 a8005e17 Michael Hanselmann
               cmd, max_count)
1055 a8005e17 Michael Hanselmann
      return False
1056 a8005e17 Michael Hanselmann
1057 a8005e17 Michael Hanselmann
  # Command with some required arguments
1058 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1059 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1060 a8005e17 Michael Hanselmann
             cmd, min_count)
1061 a8005e17 Michael Hanselmann
    return False
1062 a8005e17 Michael Hanselmann
1063 a8005e17 Michael Hanselmann
  return True
1064 a8005e17 Michael Hanselmann
1065 a8005e17 Michael Hanselmann
1066 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1067 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1068 60d49723 Michael Hanselmann

1069 60d49723 Michael Hanselmann
  """
1070 60d49723 Michael Hanselmann
  if value and ':' in value:
1071 60d49723 Michael Hanselmann
    return value.split(':', 1)
1072 60d49723 Michael Hanselmann
  else:
1073 60d49723 Michael Hanselmann
    return (value, None)
1074 60d49723 Michael Hanselmann
1075 60d49723 Michael Hanselmann
1076 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1077 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1078 07150497 Guido Trotter

1079 07150497 Guido Trotter
  @type os_name: string
1080 07150497 Guido Trotter
  @param os_name: base name of the os
1081 07150497 Guido Trotter
  @type os_variants: list or None
1082 07150497 Guido Trotter
  @param os_variants: list of supported variants
1083 07150497 Guido Trotter
  @rtype: list
1084 07150497 Guido Trotter
  @return: list of valid names
1085 07150497 Guido Trotter

1086 07150497 Guido Trotter
  """
1087 07150497 Guido Trotter
  if os_variants:
1088 07150497 Guido Trotter
    return ['%s+%s' % (os_name, v) for v in os_variants]
1089 07150497 Guido Trotter
  else:
1090 07150497 Guido Trotter
    return [os_name]
1091 07150497 Guido Trotter
1092 07150497 Guido Trotter
1093 4331f6cd Michael Hanselmann
def UsesRPC(fn):
1094 4331f6cd Michael Hanselmann
  def wrapper(*args, **kwargs):
1095 4331f6cd Michael Hanselmann
    rpc.Init()
1096 4331f6cd Michael Hanselmann
    try:
1097 4331f6cd Michael Hanselmann
      return fn(*args, **kwargs)
1098 4331f6cd Michael Hanselmann
    finally:
1099 4331f6cd Michael Hanselmann
      rpc.Shutdown()
1100 4331f6cd Michael Hanselmann
  return wrapper
1101 4331f6cd Michael Hanselmann
1102 4331f6cd Michael Hanselmann
1103 47988778 Iustin Pop
def AskUser(text, choices=None):
1104 47988778 Iustin Pop
  """Ask the user a question.
1105 a8083063 Iustin Pop

1106 c41eea6e Iustin Pop
  @param text: the question to ask
1107 a8083063 Iustin Pop

1108 c41eea6e Iustin Pop
  @param choices: list with elements tuples (input_char, return_value,
1109 c41eea6e Iustin Pop
      description); if not given, it will default to: [('y', True,
1110 c41eea6e Iustin Pop
      'Perform the operation'), ('n', False, 'Do no do the operation')];
1111 c41eea6e Iustin Pop
      note that the '?' char is reserved for help
1112 47988778 Iustin Pop

1113 c41eea6e Iustin Pop
  @return: one of the return values from the choices list; if input is
1114 c41eea6e Iustin Pop
      not possible (i.e. not running with a tty, we return the last
1115 c41eea6e Iustin Pop
      entry from the list
1116 a8083063 Iustin Pop

1117 a8083063 Iustin Pop
  """
1118 47988778 Iustin Pop
  if choices is None:
1119 47988778 Iustin Pop
    choices = [('y', True, 'Perform the operation'),
1120 47988778 Iustin Pop
               ('n', False, 'Do not perform the operation')]
1121 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1122 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1123 47988778 Iustin Pop
  for entry in choices:
1124 47988778 Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == '?':
1125 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1126 47988778 Iustin Pop
1127 47988778 Iustin Pop
  answer = choices[-1][1]
1128 47988778 Iustin Pop
  new_text = []
1129 47988778 Iustin Pop
  for line in text.splitlines():
1130 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1131 47988778 Iustin Pop
  text = "\n".join(new_text)
1132 a8083063 Iustin Pop
  try:
1133 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1134 a8083063 Iustin Pop
  except IOError:
1135 47988778 Iustin Pop
    return answer
1136 a8083063 Iustin Pop
  try:
1137 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1138 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1139 47988778 Iustin Pop
    chars.append('?')
1140 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1141 47988778 Iustin Pop
    while True:
1142 47988778 Iustin Pop
      f.write(text)
1143 47988778 Iustin Pop
      f.write('\n')
1144 47988778 Iustin Pop
      f.write("/".join(chars))
1145 47988778 Iustin Pop
      f.write(": ")
1146 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1147 47988778 Iustin Pop
      if line in maps:
1148 47988778 Iustin Pop
        answer = maps[line]
1149 47988778 Iustin Pop
        break
1150 47988778 Iustin Pop
      elif line == '?':
1151 47988778 Iustin Pop
        for entry in choices:
1152 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1153 47988778 Iustin Pop
        f.write("\n")
1154 47988778 Iustin Pop
        continue
1155 a8083063 Iustin Pop
  finally:
1156 a8083063 Iustin Pop
    f.close()
1157 a8083063 Iustin Pop
  return answer
1158 a8083063 Iustin Pop
1159 a8083063 Iustin Pop
1160 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1161 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1162 e9d741b6 Iustin Pop

1163 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1164 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1165 e9d741b6 Iustin Pop

1166 e9d741b6 Iustin Pop
  This is not an error, just a structured way to exit from clients.
1167 e9d741b6 Iustin Pop

1168 e9d741b6 Iustin Pop
  """
1169 e9d741b6 Iustin Pop
1170 e9d741b6 Iustin Pop
1171 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1172 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1173 a8083063 Iustin Pop

1174 0a1e74d9 Iustin Pop
  @type ops: list
1175 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1176 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1177 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1178 0a1e74d9 Iustin Pop
             if None, a new client will be created
1179 a8083063 Iustin Pop

1180 a8083063 Iustin Pop
  """
1181 e2212007 Iustin Pop
  if cl is None:
1182 b33e986b Iustin Pop
    cl = GetClient()
1183 685ee993 Iustin Pop
1184 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1185 0a1e74d9 Iustin Pop
1186 0a1e74d9 Iustin Pop
  return job_id
1187 0a1e74d9 Iustin Pop
1188 0a1e74d9 Iustin Pop
1189 281606c1 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None):
1190 0a1e74d9 Iustin Pop
  """Function to poll for the result of a job.
1191 0a1e74d9 Iustin Pop

1192 0a1e74d9 Iustin Pop
  @type job_id: job identified
1193 0a1e74d9 Iustin Pop
  @param job_id: the job to poll for results
1194 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1195 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1196 0a1e74d9 Iustin Pop
             if None, a new client will be created
1197 0a1e74d9 Iustin Pop

1198 0a1e74d9 Iustin Pop
  """
1199 0a1e74d9 Iustin Pop
  if cl is None:
1200 0a1e74d9 Iustin Pop
    cl = GetClient()
1201 685ee993 Iustin Pop
1202 6c5a7090 Michael Hanselmann
  prev_job_info = None
1203 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1204 6c5a7090 Michael Hanselmann
1205 f4484122 Michael Hanselmann
  status = None
1206 f4484122 Michael Hanselmann
1207 f4484122 Michael Hanselmann
  notified_queued = False
1208 f4484122 Michael Hanselmann
  notified_waitlock = False
1209 f4484122 Michael Hanselmann
1210 685ee993 Iustin Pop
  while True:
1211 f4484122 Michael Hanselmann
    result = cl.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1212 f4484122 Michael Hanselmann
                                     prev_logmsg_serial)
1213 6c5a7090 Michael Hanselmann
    if not result:
1214 685ee993 Iustin Pop
      # job not found, go away!
1215 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1216 f4484122 Michael Hanselmann
    elif result == constants.JOB_NOTCHANGED:
1217 f4484122 Michael Hanselmann
      if status is not None and not callable(feedback_fn):
1218 f4484122 Michael Hanselmann
        if status == constants.JOB_STATUS_QUEUED and not notified_queued:
1219 f4484122 Michael Hanselmann
          ToStderr("Job %s is waiting in queue", job_id)
1220 f4484122 Michael Hanselmann
          notified_queued = True
1221 f4484122 Michael Hanselmann
        elif status == constants.JOB_STATUS_WAITLOCK and not notified_waitlock:
1222 f4484122 Michael Hanselmann
          ToStderr("Job %s is trying to acquire all necessary locks", job_id)
1223 f4484122 Michael Hanselmann
          notified_waitlock = True
1224 f4484122 Michael Hanselmann
1225 f4484122 Michael Hanselmann
      # Wait again
1226 f4484122 Michael Hanselmann
      continue
1227 685ee993 Iustin Pop
1228 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1229 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1230 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1231 6c5a7090 Michael Hanselmann
1232 6c5a7090 Michael Hanselmann
    if log_entries:
1233 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1234 6c5a7090 Michael Hanselmann
        (serial, timestamp, _, message) = log_entry
1235 6c5a7090 Michael Hanselmann
        if callable(feedback_fn):
1236 6c5a7090 Michael Hanselmann
          feedback_fn(log_entry[1:])
1237 6c5a7090 Michael Hanselmann
        else:
1238 26f15862 Iustin Pop
          encoded = utils.SafeEncode(message)
1239 03298ebe Michael Hanselmann
          ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)), encoded)
1240 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1241 6c5a7090 Michael Hanselmann
1242 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1243 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1244 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1245 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1246 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1247 685ee993 Iustin Pop
      break
1248 6c5a7090 Michael Hanselmann
1249 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1250 685ee993 Iustin Pop
1251 0e050889 Iustin Pop
  jobs = cl.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1252 0bbe448c Michael Hanselmann
  if not jobs:
1253 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1254 685ee993 Iustin Pop
1255 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1256 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1257 53c04d04 Iustin Pop
    return result
1258 fbf0262f Michael Hanselmann
  elif status in (constants.JOB_STATUS_CANCELING,
1259 fbf0262f Michael Hanselmann
                  constants.JOB_STATUS_CANCELED):
1260 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1261 0bbe448c Michael Hanselmann
  else:
1262 0e050889 Iustin Pop
    has_ok = False
1263 0e050889 Iustin Pop
    for idx, (status, msg) in enumerate(zip(opstatus, result)):
1264 0e050889 Iustin Pop
      if status == constants.OP_STATUS_SUCCESS:
1265 0e050889 Iustin Pop
        has_ok = True
1266 0e050889 Iustin Pop
      elif status == constants.OP_STATUS_ERROR:
1267 bcb66fca Iustin Pop
        errors.MaybeRaise(msg)
1268 0e050889 Iustin Pop
        if has_ok:
1269 0e050889 Iustin Pop
          raise errors.OpExecError("partial failure (opcode %d): %s" %
1270 0e050889 Iustin Pop
                                   (idx, msg))
1271 0e050889 Iustin Pop
        else:
1272 0e050889 Iustin Pop
          raise errors.OpExecError(str(msg))
1273 0e050889 Iustin Pop
    # default failure mode
1274 0bbe448c Michael Hanselmann
    raise errors.OpExecError(result)
1275 ceab32dd Iustin Pop
1276 ceab32dd Iustin Pop
1277 293ba2d8 Iustin Pop
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None):
1278 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
1279 0a1e74d9 Iustin Pop

1280 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
1281 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
1282 0a1e74d9 Iustin Pop
  interaction functions.
1283 0a1e74d9 Iustin Pop

1284 0a1e74d9 Iustin Pop
  """
1285 0a1e74d9 Iustin Pop
  if cl is None:
1286 0a1e74d9 Iustin Pop
    cl = GetClient()
1287 0a1e74d9 Iustin Pop
1288 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
1289 293ba2d8 Iustin Pop
1290 0a1e74d9 Iustin Pop
  job_id = SendJob([op], cl)
1291 0a1e74d9 Iustin Pop
1292 53c04d04 Iustin Pop
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn)
1293 53c04d04 Iustin Pop
1294 53c04d04 Iustin Pop
  return op_results[0]
1295 0a1e74d9 Iustin Pop
1296 0a1e74d9 Iustin Pop
1297 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
1298 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
1299 94428652 Iustin Pop

1300 94428652 Iustin Pop
  This function will decide, based on the 'opts' parameter, whether to
1301 94428652 Iustin Pop
  submit and wait for the result of the opcode (and return it), or
1302 94428652 Iustin Pop
  whether to just send the job and print its identifier. It is used in
1303 94428652 Iustin Pop
  order to simplify the implementation of the '--submit' option.
1304 94428652 Iustin Pop

1305 293ba2d8 Iustin Pop
  It will also process the opcodes if we're sending the via SendJob
1306 293ba2d8 Iustin Pop
  (otherwise SubmitOpCode does it).
1307 64c65a2a Iustin Pop

1308 94428652 Iustin Pop
  """
1309 94428652 Iustin Pop
  if opts and opts.submit_only:
1310 293ba2d8 Iustin Pop
    job = [op]
1311 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
1312 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
1313 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
1314 94428652 Iustin Pop
  else:
1315 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
1316 293ba2d8 Iustin Pop
1317 293ba2d8 Iustin Pop
1318 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
1319 293ba2d8 Iustin Pop
  """Processor for generic options.
1320 293ba2d8 Iustin Pop

1321 293ba2d8 Iustin Pop
  This function updates the given opcodes based on generic command
1322 293ba2d8 Iustin Pop
  line options (like debug, dry-run, etc.).
1323 293ba2d8 Iustin Pop

1324 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
1325 293ba2d8 Iustin Pop
  @param options: command line options or None
1326 293ba2d8 Iustin Pop
  @return: None (in-place modification)
1327 293ba2d8 Iustin Pop

1328 293ba2d8 Iustin Pop
  """
1329 293ba2d8 Iustin Pop
  if not options:
1330 293ba2d8 Iustin Pop
    return
1331 293ba2d8 Iustin Pop
  for op in opcode_list:
1332 293ba2d8 Iustin Pop
    op.dry_run = options.dry_run
1333 293ba2d8 Iustin Pop
    op.debug_level = options.debug
1334 94428652 Iustin Pop
1335 94428652 Iustin Pop
1336 af30b2fd Michael Hanselmann
def GetClient():
1337 af30b2fd Michael Hanselmann
  # TODO: Cache object?
1338 b33e986b Iustin Pop
  try:
1339 b33e986b Iustin Pop
    client = luxi.Client()
1340 b33e986b Iustin Pop
  except luxi.NoMasterError:
1341 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
1342 d9a51679 Michael Hanselmann
1343 d9a51679 Michael Hanselmann
    # Try to read ssconf file
1344 d9a51679 Michael Hanselmann
    try:
1345 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
1346 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
1347 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
1348 d9a51679 Michael Hanselmann
                                 " not part of a cluster")
1349 d9a51679 Michael Hanselmann
1350 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
1351 b33e986b Iustin Pop
    if master != myself:
1352 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
1353 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
1354 b33e986b Iustin Pop
                                 master)
1355 d9a51679 Michael Hanselmann
    raise
1356 b33e986b Iustin Pop
  return client
1357 af30b2fd Michael Hanselmann
1358 af30b2fd Michael Hanselmann
1359 73702ee7 Iustin Pop
def FormatError(err):
1360 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
1361 73702ee7 Iustin Pop

1362 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
1363 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
1364 73702ee7 Iustin Pop
  second, a string describing the error message (not
1365 73702ee7 Iustin Pop
  newline-terminated).
1366 73702ee7 Iustin Pop

1367 73702ee7 Iustin Pop
  """
1368 73702ee7 Iustin Pop
  retcode = 1
1369 73702ee7 Iustin Pop
  obuf = StringIO()
1370 e2e521d0 Iustin Pop
  msg = str(err)
1371 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
1372 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
1373 46fbdd04 Iustin Pop
    logging.error(txt)
1374 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
1375 73702ee7 Iustin Pop
    obuf.write("Aborting.")
1376 73702ee7 Iustin Pop
    retcode = 2
1377 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
1378 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
1379 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
1380 73702ee7 Iustin Pop
      if out:
1381 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
1382 73702ee7 Iustin Pop
                   (node, script, out))
1383 73702ee7 Iustin Pop
      else:
1384 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
1385 73702ee7 Iustin Pop
                   (node, script))
1386 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
1387 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
1388 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
1389 73702ee7 Iustin Pop
    this_host = utils.HostInfo.SysName()
1390 73702ee7 Iustin Pop
    if err.args[0] == this_host:
1391 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
1392 73702ee7 Iustin Pop
    else:
1393 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
1394 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
1395 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
1396 5c983ee5 Iustin Pop
    if len(err.args) == 2:
1397 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1398 5c983ee5 Iustin Pop
               " operation:\nerror type: %s, error details:\n%s" %
1399 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
1400 5c983ee5 Iustin Pop
    else:
1401 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1402 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
1403 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
1404 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
1405 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
1406 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
1407 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
1408 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
1409 686d7433 Iustin Pop
               " accept new requests\n")
1410 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
1411 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
1412 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
1413 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
1414 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
1415 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
1416 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
1417 73702ee7 Iustin Pop
  elif isinstance(err, errors.GenericError):
1418 e2e521d0 Iustin Pop
    obuf.write("Unhandled Ganeti error: %s" % msg)
1419 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
1420 03a8dbdc Iustin Pop
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
1421 082c5adb Michael Hanselmann
               " and listening for connections?")
1422 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
1423 03a8dbdc Iustin Pop
    obuf.write("Timeout while talking to the master daemon. Error:\n"
1424 03a8dbdc Iustin Pop
               "%s" % msg)
1425 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
1426 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
1427 03a8dbdc Iustin Pop
               "%s" % msg)
1428 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
1429 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
1430 e9d741b6 Iustin Pop
    retcode = 0
1431 73702ee7 Iustin Pop
  else:
1432 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
1433 73702ee7 Iustin Pop
  return retcode, obuf.getvalue().rstrip('\n')
1434 73702ee7 Iustin Pop
1435 73702ee7 Iustin Pop
1436 de47cf8f Guido Trotter
def GenericMain(commands, override=None, aliases=None):
1437 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
1438 a8083063 Iustin Pop

1439 334d1483 Iustin Pop
  Arguments:
1440 334d1483 Iustin Pop
    - commands: a dictionary with a special structure, see the design doc
1441 334d1483 Iustin Pop
                for command line handling.
1442 334d1483 Iustin Pop
    - override: if not None, we expect a dictionary with keys that will
1443 334d1483 Iustin Pop
                override command line options; this can be used to pass
1444 334d1483 Iustin Pop
                options from the scripts to generic functions
1445 de47cf8f Guido Trotter
    - aliases: dictionary with command aliases {'alias': 'target, ...}
1446 a8083063 Iustin Pop

1447 a8083063 Iustin Pop
  """
1448 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
1449 a8083063 Iustin Pop
  if sys.argv:
1450 a8083063 Iustin Pop
    binary = os.path.basename(sys.argv[0]) or sys.argv[0]
1451 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
1452 a8083063 Iustin Pop
      binary += " " + sys.argv[1]
1453 a8083063 Iustin Pop
      old_cmdline = " ".join(sys.argv[2:])
1454 a8083063 Iustin Pop
    else:
1455 a8083063 Iustin Pop
      old_cmdline = ""
1456 a8083063 Iustin Pop
  else:
1457 a8083063 Iustin Pop
    binary = "<unknown program>"
1458 a8083063 Iustin Pop
    old_cmdline = ""
1459 a8083063 Iustin Pop
1460 de47cf8f Guido Trotter
  if aliases is None:
1461 de47cf8f Guido Trotter
    aliases = {}
1462 de47cf8f Guido Trotter
1463 3126878d Guido Trotter
  try:
1464 3126878d Guido Trotter
    func, options, args = _ParseArgs(sys.argv, commands, aliases)
1465 3126878d Guido Trotter
  except errors.ParameterError, err:
1466 3126878d Guido Trotter
    result, err_msg = FormatError(err)
1467 3126878d Guido Trotter
    ToStderr(err_msg)
1468 3126878d Guido Trotter
    return 1
1469 3126878d Guido Trotter
1470 a8083063 Iustin Pop
  if func is None: # parse error
1471 a8083063 Iustin Pop
    return 1
1472 a8083063 Iustin Pop
1473 334d1483 Iustin Pop
  if override is not None:
1474 334d1483 Iustin Pop
    for key, val in override.iteritems():
1475 334d1483 Iustin Pop
      setattr(options, key, val)
1476 334d1483 Iustin Pop
1477 82d9caef Iustin Pop
  utils.SetupLogging(constants.LOG_COMMANDS, debug=options.debug,
1478 82d9caef Iustin Pop
                     stderr_logging=True, program=binary)
1479 a8083063 Iustin Pop
1480 a8083063 Iustin Pop
  if old_cmdline:
1481 46fbdd04 Iustin Pop
    logging.info("run with arguments '%s'", old_cmdline)
1482 a8083063 Iustin Pop
  else:
1483 46fbdd04 Iustin Pop
    logging.info("run with no arguments")
1484 a8083063 Iustin Pop
1485 a8083063 Iustin Pop
  try:
1486 a4af651e Iustin Pop
    result = func(options, args)
1487 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
1488 d8353c3a Iustin Pop
          JobSubmittedException), err:
1489 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
1490 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
1491 46fbdd04 Iustin Pop
    ToStderr(err_msg)
1492 a8083063 Iustin Pop
1493 a8083063 Iustin Pop
  return result
1494 137161c9 Michael Hanselmann
1495 137161c9 Michael Hanselmann
1496 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
1497 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
1498 d77490c5 Iustin Pop

1499 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
1500 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
1501 d77490c5 Iustin Pop
  @type args: list
1502 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
1503 d77490c5 Iustin Pop
  @rtype: int
1504 d77490c5 Iustin Pop
  @return: the desired exit code
1505 d77490c5 Iustin Pop

1506 d77490c5 Iustin Pop
  """
1507 d77490c5 Iustin Pop
  instance = args[0]
1508 d77490c5 Iustin Pop
1509 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
1510 d77490c5 Iustin Pop
1511 d77490c5 Iustin Pop
  hypervisor = None
1512 d77490c5 Iustin Pop
  hvparams = {}
1513 d77490c5 Iustin Pop
  if opts.hypervisor:
1514 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
1515 d77490c5 Iustin Pop
1516 d77490c5 Iustin Pop
  if opts.nics:
1517 d77490c5 Iustin Pop
    try:
1518 21bcb9aa Michael Hanselmann
      nic_max = max(int(nidx[0]) + 1 for nidx in opts.nics)
1519 d77490c5 Iustin Pop
    except ValueError, err:
1520 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
1521 d77490c5 Iustin Pop
    nics = [{}] * nic_max
1522 d77490c5 Iustin Pop
    for nidx, ndict in opts.nics:
1523 d77490c5 Iustin Pop
      nidx = int(nidx)
1524 d77490c5 Iustin Pop
      if not isinstance(ndict, dict):
1525 d77490c5 Iustin Pop
        msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
1526 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
1527 d77490c5 Iustin Pop
      nics[nidx] = ndict
1528 d77490c5 Iustin Pop
  elif opts.no_nics:
1529 d77490c5 Iustin Pop
    # no nics
1530 d77490c5 Iustin Pop
    nics = []
1531 d77490c5 Iustin Pop
  else:
1532 d77490c5 Iustin Pop
    # default of one nic, all auto
1533 d77490c5 Iustin Pop
    nics = [{}]
1534 d77490c5 Iustin Pop
1535 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
1536 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
1537 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
1538 d77490c5 Iustin Pop
                                 " information passed")
1539 d77490c5 Iustin Pop
    disks = []
1540 d77490c5 Iustin Pop
  else:
1541 d77490c5 Iustin Pop
    if not opts.disks and not opts.sd_size:
1542 d77490c5 Iustin Pop
      raise errors.OpPrereqError("No disk information specified")
1543 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
1544 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
1545 d77490c5 Iustin Pop
                                 " '-s' option")
1546 d77490c5 Iustin Pop
    if opts.sd_size is not None:
1547 d77490c5 Iustin Pop
      opts.disks = [(0, {"size": opts.sd_size})]
1548 d77490c5 Iustin Pop
    try:
1549 21bcb9aa Michael Hanselmann
      disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
1550 d77490c5 Iustin Pop
    except ValueError, err:
1551 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
1552 d77490c5 Iustin Pop
    disks = [{}] * disk_max
1553 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
1554 d77490c5 Iustin Pop
      didx = int(didx)
1555 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
1556 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
1557 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
1558 5029db65 Iustin Pop
      elif "size" in ddict:
1559 5029db65 Iustin Pop
        if "adopt" in ddict:
1560 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
1561 5029db65 Iustin Pop
                                     " (disk %d)" % didx)
1562 5029db65 Iustin Pop
        try:
1563 5029db65 Iustin Pop
          ddict["size"] = utils.ParseUnit(ddict["size"])
1564 5029db65 Iustin Pop
        except ValueError, err:
1565 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
1566 5029db65 Iustin Pop
                                     (didx, err))
1567 5029db65 Iustin Pop
      elif "adopt" in ddict:
1568 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
1569 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
1570 5029db65 Iustin Pop
                                     " import")
1571 5029db65 Iustin Pop
        ddict["size"] = 0
1572 5029db65 Iustin Pop
      else:
1573 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
1574 5029db65 Iustin Pop
                                   " disk %d" % didx)
1575 d77490c5 Iustin Pop
      disks[didx] = ddict
1576 d77490c5 Iustin Pop
1577 d77490c5 Iustin Pop
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
1578 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
1579 d77490c5 Iustin Pop
1580 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
1581 d77490c5 Iustin Pop
    start = opts.start
1582 d77490c5 Iustin Pop
    os_type = opts.os
1583 d77490c5 Iustin Pop
    src_node = None
1584 d77490c5 Iustin Pop
    src_path = None
1585 25a8792c Iustin Pop
    no_install = opts.no_install
1586 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
1587 d77490c5 Iustin Pop
    start = False
1588 d77490c5 Iustin Pop
    os_type = None
1589 d77490c5 Iustin Pop
    src_node = opts.src_node
1590 d77490c5 Iustin Pop
    src_path = opts.src_dir
1591 25a8792c Iustin Pop
    no_install = None
1592 d77490c5 Iustin Pop
  else:
1593 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
1594 d77490c5 Iustin Pop
1595 d77490c5 Iustin Pop
  op = opcodes.OpCreateInstance(instance_name=instance,
1596 d77490c5 Iustin Pop
                                disks=disks,
1597 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
1598 d77490c5 Iustin Pop
                                nics=nics,
1599 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
1600 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
1601 460d22be Iustin Pop
                                name_check=opts.name_check,
1602 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
1603 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
1604 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
1605 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
1606 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
1607 d77490c5 Iustin Pop
                                hvparams=hvparams,
1608 d77490c5 Iustin Pop
                                beparams=opts.beparams,
1609 d77490c5 Iustin Pop
                                mode=mode,
1610 d77490c5 Iustin Pop
                                start=start,
1611 d77490c5 Iustin Pop
                                os_type=os_type,
1612 d77490c5 Iustin Pop
                                src_node=src_node,
1613 25a8792c Iustin Pop
                                src_path=src_path,
1614 25a8792c Iustin Pop
                                no_install=no_install)
1615 d77490c5 Iustin Pop
1616 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
1617 d77490c5 Iustin Pop
  return 0
1618 d77490c5 Iustin Pop
1619 d77490c5 Iustin Pop
1620 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
1621 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
1622 7e49b6ce Michael Hanselmann

1623 7e49b6ce Michael Hanselmann
  """
1624 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
1625 7e49b6ce Michael Hanselmann
    """Initializes this class.
1626 7e49b6ce Michael Hanselmann

1627 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
1628 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
1629 7e49b6ce Michael Hanselmann
    @type cluster_name: string
1630 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
1631 7e49b6ce Michael Hanselmann
    @type master_node: string
1632 7e49b6ce Michael Hanselmann
    @param master_node Master node name
1633 7e49b6ce Michael Hanselmann
    @type online_nodes: list
1634 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
1635 7e49b6ce Michael Hanselmann

1636 7e49b6ce Michael Hanselmann
    """
1637 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
1638 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
1639 7e49b6ce Michael Hanselmann
    self.master_node = master_node
1640 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
1641 7e49b6ce Michael Hanselmann
1642 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
1643 7e49b6ce Michael Hanselmann
1644 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
1645 7e49b6ce Michael Hanselmann
                            if name != master_node]
1646 7e49b6ce Michael Hanselmann
1647 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
1648 7e49b6ce Michael Hanselmann
1649 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
1650 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
1651 7e49b6ce Michael Hanselmann

1652 7e49b6ce Michael Hanselmann
    @type node_name: string
1653 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
1654 7e49b6ce Michael Hanselmann
    @type cmd: list
1655 7e49b6ce Michael Hanselmann
    @param cmd: Command
1656 7e49b6ce Michael Hanselmann

1657 7e49b6ce Michael Hanselmann
    """
1658 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
1659 7e49b6ce Michael Hanselmann
      # No need to use SSH
1660 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
1661 7e49b6ce Michael Hanselmann
    else:
1662 7e49b6ce Michael Hanselmann
      result = self.ssh.Run(node_name, "root", utils.ShellQuoteArgs(cmd))
1663 7e49b6ce Michael Hanselmann
1664 7e49b6ce Michael Hanselmann
    if result.failed:
1665 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
1666 7e49b6ce Michael Hanselmann
      if node_name:
1667 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
1668 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
1669 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
1670 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
1671 7e49b6ce Michael Hanselmann
1672 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
1673 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
1674 7e49b6ce Michael Hanselmann

1675 7e49b6ce Michael Hanselmann
    @type fn: callable
1676 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
1677 7e49b6ce Michael Hanselmann

1678 7e49b6ce Michael Hanselmann
    """
1679 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
1680 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
1681 7e49b6ce Michael Hanselmann
    watcher_block = utils.FileLock.Open(constants.WATCHER_STATEFILE)
1682 7e49b6ce Michael Hanselmann
    try:
1683 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
1684 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
1685 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
1686 7e49b6ce Michael Hanselmann
1687 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
1688 7e49b6ce Michael Hanselmann
      # ones are finished
1689 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
1690 7e49b6ce Michael Hanselmann
      self._RunCmd(None, [constants.DAEMON_UTIL, "stop-master"])
1691 7e49b6ce Michael Hanselmann
      try:
1692 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
1693 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
1694 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
1695 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "stop-all"])
1696 7e49b6ce Michael Hanselmann
1697 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
1698 7e49b6ce Michael Hanselmann
        try:
1699 7e49b6ce Michael Hanselmann
          return fn(self, *args)
1700 d512e84b Michael Hanselmann
        except Exception, err:
1701 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
1702 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
1703 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
1704 7e49b6ce Michael Hanselmann
          raise
1705 7e49b6ce Michael Hanselmann
      finally:
1706 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
1707 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
1708 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
1709 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "start-all"])
1710 7e49b6ce Michael Hanselmann
    finally:
1711 7e49b6ce Michael Hanselmann
      # Resume watcher
1712 7e49b6ce Michael Hanselmann
      watcher_block.Close()
1713 7e49b6ce Michael Hanselmann
1714 7e49b6ce Michael Hanselmann
1715 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
1716 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
1717 7e49b6ce Michael Hanselmann

1718 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
1719 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
1720 7e49b6ce Michael Hanselmann
  @type fn: callable
1721 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
1722 7e49b6ce Michael Hanselmann

1723 7e49b6ce Michael Hanselmann
  """
1724 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
1725 7e49b6ce Michael Hanselmann
1726 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
1727 7e49b6ce Michael Hanselmann
  cl = GetClient()
1728 7e49b6ce Michael Hanselmann
1729 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
1730 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
1731 7e49b6ce Michael Hanselmann
1732 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
1733 7e49b6ce Michael Hanselmann
1734 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
1735 7e49b6ce Michael Hanselmann
  del cl
1736 7e49b6ce Michael Hanselmann
1737 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
1738 7e49b6ce Michael Hanselmann
1739 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
1740 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
1741 7e49b6ce Michael Hanselmann
1742 7e49b6ce Michael Hanselmann
1743 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
1744 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
1745 9fbfbb7b Iustin Pop
                  units=None):
1746 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
1747 137161c9 Michael Hanselmann

1748 9fbfbb7b Iustin Pop
  @type headers: dict
1749 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
1750 9fbfbb7b Iustin Pop
      the table
1751 9fbfbb7b Iustin Pop
  @type fields: list
1752 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
1753 9fbfbb7b Iustin Pop
      the data field
1754 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
1755 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
1756 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
1757 9fbfbb7b Iustin Pop
      each field
1758 9fbfbb7b Iustin Pop
  @type data: list
1759 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
1760 9fbfbb7b Iustin Pop
  @type numfields: list
1761 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
1762 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
1763 9fbfbb7b Iustin Pop
  @type unitfields: list
1764 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
1765 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
1766 9fbfbb7b Iustin Pop
  @type units: string or None
1767 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
1768 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
1769 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
1770 137161c9 Michael Hanselmann

1771 137161c9 Michael Hanselmann
  """
1772 9fbfbb7b Iustin Pop
  if units is None:
1773 9fbfbb7b Iustin Pop
    if separator:
1774 9fbfbb7b Iustin Pop
      units = "m"
1775 9fbfbb7b Iustin Pop
    else:
1776 9fbfbb7b Iustin Pop
      units = "h"
1777 9fbfbb7b Iustin Pop
1778 137161c9 Michael Hanselmann
  if numfields is None:
1779 137161c9 Michael Hanselmann
    numfields = []
1780 137161c9 Michael Hanselmann
  if unitfields is None:
1781 137161c9 Michael Hanselmann
    unitfields = []
1782 137161c9 Michael Hanselmann
1783 fe267188 Iustin Pop
  numfields = utils.FieldSet(*numfields)   # pylint: disable-msg=W0142
1784 fe267188 Iustin Pop
  unitfields = utils.FieldSet(*unitfields) # pylint: disable-msg=W0142
1785 00430f8e Iustin Pop
1786 137161c9 Michael Hanselmann
  format_fields = []
1787 137161c9 Michael Hanselmann
  for field in fields:
1788 01ca31ae Iustin Pop
    if headers and field not in headers:
1789 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
1790 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
1791 71c1af58 Iustin Pop
      # variable fields)
1792 71c1af58 Iustin Pop
      headers[field] = field
1793 137161c9 Michael Hanselmann
    if separator is not None:
1794 137161c9 Michael Hanselmann
      format_fields.append("%s")
1795 00430f8e Iustin Pop
    elif numfields.Matches(field):
1796 137161c9 Michael Hanselmann
      format_fields.append("%*s")
1797 137161c9 Michael Hanselmann
    else:
1798 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
1799 137161c9 Michael Hanselmann
1800 137161c9 Michael Hanselmann
  if separator is None:
1801 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
1802 137161c9 Michael Hanselmann
    format = ' '.join(format_fields)
1803 137161c9 Michael Hanselmann
  else:
1804 137161c9 Michael Hanselmann
    format = separator.replace("%", "%%").join(format_fields)
1805 137161c9 Michael Hanselmann
1806 137161c9 Michael Hanselmann
  for row in data:
1807 dcbd6288 Guido Trotter
    if row is None:
1808 dcbd6288 Guido Trotter
      continue
1809 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
1810 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
1811 137161c9 Michael Hanselmann
        try:
1812 137161c9 Michael Hanselmann
          val = int(val)
1813 691744c4 Iustin Pop
        except (TypeError, ValueError):
1814 137161c9 Michael Hanselmann
          pass
1815 137161c9 Michael Hanselmann
        else:
1816 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
1817 01ca31ae Iustin Pop
      val = row[idx] = str(val)
1818 137161c9 Michael Hanselmann
      if separator is None:
1819 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
1820 137161c9 Michael Hanselmann
1821 16be8703 Iustin Pop
  result = []
1822 137161c9 Michael Hanselmann
  if headers:
1823 137161c9 Michael Hanselmann
    args = []
1824 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
1825 137161c9 Michael Hanselmann
      hdr = headers[name]
1826 137161c9 Michael Hanselmann
      if separator is None:
1827 ec39d63c Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
1828 137161c9 Michael Hanselmann
        args.append(mlens[idx])
1829 137161c9 Michael Hanselmann
      args.append(hdr)
1830 16be8703 Iustin Pop
    result.append(format % tuple(args))
1831 137161c9 Michael Hanselmann
1832 ec39d63c Michael Hanselmann
  if separator is None:
1833 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
1834 ec39d63c Michael Hanselmann
1835 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
1836 ec39d63c Michael Hanselmann
      mlens[-1] = 0
1837 ec39d63c Michael Hanselmann
1838 137161c9 Michael Hanselmann
  for line in data:
1839 137161c9 Michael Hanselmann
    args = []
1840 dcbd6288 Guido Trotter
    if line is None:
1841 dcbd6288 Guido Trotter
      line = ['-' for _ in fields]
1842 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
1843 137161c9 Michael Hanselmann
      if separator is None:
1844 137161c9 Michael Hanselmann
        args.append(mlens[idx])
1845 137161c9 Michael Hanselmann
      args.append(line[idx])
1846 16be8703 Iustin Pop
    result.append(format % tuple(args))
1847 16be8703 Iustin Pop
1848 16be8703 Iustin Pop
  return result
1849 3386e7a9 Iustin Pop
1850 3386e7a9 Iustin Pop
1851 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
1852 3386e7a9 Iustin Pop
  """Formats a given timestamp.
1853 3386e7a9 Iustin Pop

1854 3386e7a9 Iustin Pop
  @type ts: timestamp
1855 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
1856 3386e7a9 Iustin Pop

1857 3386e7a9 Iustin Pop
  @rtype: string
1858 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
1859 3386e7a9 Iustin Pop

1860 3386e7a9 Iustin Pop
  """
1861 e0ec0ff6 Iustin Pop
  if not isinstance (ts, (tuple, list)) or len(ts) != 2:
1862 e0ec0ff6 Iustin Pop
    return '?'
1863 3386e7a9 Iustin Pop
  sec, usec = ts
1864 3386e7a9 Iustin Pop
  return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
1865 2241e2b9 Iustin Pop
1866 2241e2b9 Iustin Pop
1867 2241e2b9 Iustin Pop
def ParseTimespec(value):
1868 2241e2b9 Iustin Pop
  """Parse a time specification.
1869 2241e2b9 Iustin Pop

1870 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
1871 2241e2b9 Iustin Pop

1872 2241e2b9 Iustin Pop
    - s: seconds
1873 2241e2b9 Iustin Pop
    - m: minutes
1874 2241e2b9 Iustin Pop
    - h: hours
1875 2241e2b9 Iustin Pop
    - d: day
1876 2241e2b9 Iustin Pop
    - w: weeks
1877 2241e2b9 Iustin Pop

1878 2241e2b9 Iustin Pop
  Without any suffix, the value will be taken to be in seconds.
1879 2241e2b9 Iustin Pop

1880 2241e2b9 Iustin Pop
  """
1881 2241e2b9 Iustin Pop
  value = str(value)
1882 2241e2b9 Iustin Pop
  if not value:
1883 2241e2b9 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed")
1884 2241e2b9 Iustin Pop
  suffix_map = {
1885 2241e2b9 Iustin Pop
    's': 1,
1886 2241e2b9 Iustin Pop
    'm': 60,
1887 2241e2b9 Iustin Pop
    'h': 3600,
1888 2241e2b9 Iustin Pop
    'd': 86400,
1889 2241e2b9 Iustin Pop
    'w': 604800,
1890 2241e2b9 Iustin Pop
    }
1891 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
1892 2241e2b9 Iustin Pop
    try:
1893 2241e2b9 Iustin Pop
      value = int(value)
1894 691744c4 Iustin Pop
    except (TypeError, ValueError):
1895 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
1896 2241e2b9 Iustin Pop
  else:
1897 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
1898 2241e2b9 Iustin Pop
    value = value[:-1]
1899 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
1900 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
1901 2241e2b9 Iustin Pop
                                 " suffix passed)")
1902 2241e2b9 Iustin Pop
    try:
1903 2241e2b9 Iustin Pop
      value = int(value) * multiplier
1904 691744c4 Iustin Pop
    except (TypeError, ValueError):
1905 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
1906 2241e2b9 Iustin Pop
  return value
1907 46fbdd04 Iustin Pop
1908 46fbdd04 Iustin Pop
1909 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
1910 e9e26bb3 Iustin Pop
                   filter_master=False):
1911 4040a784 Iustin Pop
  """Returns the names of online nodes.
1912 4040a784 Iustin Pop

1913 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
1914 4040a784 Iustin Pop
  the online nodes.
1915 4040a784 Iustin Pop

1916 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
1917 4040a784 Iustin Pop
      offline ones)
1918 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
1919 4040a784 Iustin Pop
  @type nowarn: boolean
1920 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
1921 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
1922 4040a784 Iustin Pop
      note is not displayed
1923 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
1924 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
1925 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
1926 e9e26bb3 Iustin Pop
      (if any)
1927 e9e26bb3 Iustin Pop
  @type filter_master: boolean
1928 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
1929 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
1930 e9e26bb3 Iustin Pop
      node name against the list)
1931 4040a784 Iustin Pop

1932 4040a784 Iustin Pop
  """
1933 4040a784 Iustin Pop
  if cl is None:
1934 4040a784 Iustin Pop
    cl = GetClient()
1935 4040a784 Iustin Pop
1936 e9e26bb3 Iustin Pop
  if secondary_ips:
1937 e9e26bb3 Iustin Pop
    name_idx = 2
1938 e9e26bb3 Iustin Pop
  else:
1939 e9e26bb3 Iustin Pop
    name_idx = 0
1940 e9e26bb3 Iustin Pop
1941 e9e26bb3 Iustin Pop
  if filter_master:
1942 e9e26bb3 Iustin Pop
    master_node = cl.QueryConfigValues(["master_node"])[0]
1943 e9e26bb3 Iustin Pop
    filter_fn = lambda x: x != master_node
1944 e9e26bb3 Iustin Pop
  else:
1945 e9e26bb3 Iustin Pop
    filter_fn = lambda _: True
1946 e9e26bb3 Iustin Pop
1947 e9e26bb3 Iustin Pop
  result = cl.QueryNodes(names=nodes, fields=["name", "offline", "sip"],
1948 2e7b8369 Iustin Pop
                         use_locking=False)
1949 4040a784 Iustin Pop
  offline = [row[0] for row in result if row[1]]
1950 4040a784 Iustin Pop
  if offline and not nowarn:
1951 1f864b60 Iustin Pop
    ToStderr("Note: skipping offline node(s): %s" % utils.CommaJoin(offline))
1952 e9e26bb3 Iustin Pop
  return [row[name_idx] for row in result if not row[1] and filter_fn(row[0])]
1953 4040a784 Iustin Pop
1954 4040a784 Iustin Pop
1955 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
1956 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
1957 46fbdd04 Iustin Pop

1958 46fbdd04 Iustin Pop
  @type stream: file object
1959 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
1960 46fbdd04 Iustin Pop
  @type txt: str
1961 46fbdd04 Iustin Pop
  @param txt: the message
1962 46fbdd04 Iustin Pop

1963 46fbdd04 Iustin Pop
  """
1964 46fbdd04 Iustin Pop
  if args:
1965 46fbdd04 Iustin Pop
    args = tuple(args)
1966 46fbdd04 Iustin Pop
    stream.write(txt % args)
1967 46fbdd04 Iustin Pop
  else:
1968 46fbdd04 Iustin Pop
    stream.write(txt)
1969 46fbdd04 Iustin Pop
  stream.write('\n')
1970 46fbdd04 Iustin Pop
  stream.flush()
1971 46fbdd04 Iustin Pop
1972 46fbdd04 Iustin Pop
1973 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
1974 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
1975 46fbdd04 Iustin Pop

1976 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
1977 46fbdd04 Iustin Pop

1978 46fbdd04 Iustin Pop
  @type txt: str
1979 46fbdd04 Iustin Pop
  @param txt: the message
1980 46fbdd04 Iustin Pop

1981 46fbdd04 Iustin Pop
  """
1982 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
1983 46fbdd04 Iustin Pop
1984 46fbdd04 Iustin Pop
1985 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
1986 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
1987 46fbdd04 Iustin Pop

1988 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
1989 46fbdd04 Iustin Pop

1990 46fbdd04 Iustin Pop
  @type txt: str
1991 46fbdd04 Iustin Pop
  @param txt: the message
1992 46fbdd04 Iustin Pop

1993 46fbdd04 Iustin Pop
  """
1994 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
1995 479636a3 Iustin Pop
1996 479636a3 Iustin Pop
1997 479636a3 Iustin Pop
class JobExecutor(object):
1998 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
1999 479636a3 Iustin Pop

2000 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
2001 479636a3 Iustin Pop
  GetResults() calls.
2002 479636a3 Iustin Pop

2003 479636a3 Iustin Pop
  """
2004 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
2005 479636a3 Iustin Pop
    self.queue = []
2006 479636a3 Iustin Pop
    if cl is None:
2007 479636a3 Iustin Pop
      cl = GetClient()
2008 479636a3 Iustin Pop
    self.cl = cl
2009 479636a3 Iustin Pop
    self.verbose = verbose
2010 23b4b983 Iustin Pop
    self.jobs = []
2011 cff5fa7f Iustin Pop
    self.opts = opts
2012 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
2013 479636a3 Iustin Pop
2014 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
2015 23b4b983 Iustin Pop
    """Record a job for later submit.
2016 479636a3 Iustin Pop

2017 479636a3 Iustin Pop
    @type name: string
2018 479636a3 Iustin Pop
    @param name: a description of the job, will be used in WaitJobSet
2019 479636a3 Iustin Pop
    """
2020 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
2021 23b4b983 Iustin Pop
    self.queue.append((name, ops))
2022 23b4b983 Iustin Pop
2023 23b4b983 Iustin Pop
  def SubmitPending(self):
2024 23b4b983 Iustin Pop
    """Submit all pending jobs.
2025 23b4b983 Iustin Pop

2026 23b4b983 Iustin Pop
    """
2027 23b4b983 Iustin Pop
    results = self.cl.SubmitManyJobs([row[1] for row in self.queue])
2028 5299e61f Iustin Pop
    for (idx, ((status, data), (name, _))) in enumerate(zip(results,
2029 5299e61f Iustin Pop
                                                            self.queue)):
2030 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
2031 5299e61f Iustin Pop
2032 5299e61f Iustin Pop
  def _ChooseJob(self):
2033 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
2034 5299e61f Iustin Pop

2035 5299e61f Iustin Pop
    """
2036 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
2037 5299e61f Iustin Pop
2038 5299e61f Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs], ["status"])
2039 5299e61f Iustin Pop
    assert result
2040 5299e61f Iustin Pop
2041 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
2042 5299e61f Iustin Pop
      if status[0] in (constants.JOB_STATUS_QUEUED,
2043 5299e61f Iustin Pop
                    constants.JOB_STATUS_WAITLOCK,
2044 5299e61f Iustin Pop
                    constants.JOB_STATUS_CANCELING):
2045 5299e61f Iustin Pop
        # job is still waiting
2046 5299e61f Iustin Pop
        continue
2047 5299e61f Iustin Pop
      # good candidate found
2048 5299e61f Iustin Pop
      self.jobs.remove(job_data)
2049 5299e61f Iustin Pop
      return job_data
2050 5299e61f Iustin Pop
2051 5299e61f Iustin Pop
    # no job found
2052 5299e61f Iustin Pop
    return self.jobs.pop(0)
2053 479636a3 Iustin Pop
2054 479636a3 Iustin Pop
  def GetResults(self):
2055 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
2056 479636a3 Iustin Pop

2057 479636a3 Iustin Pop
    @rtype: list
2058 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
2059 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
2060 479636a3 Iustin Pop
        there will be the error message
2061 479636a3 Iustin Pop

2062 479636a3 Iustin Pop
    """
2063 23b4b983 Iustin Pop
    if not self.jobs:
2064 23b4b983 Iustin Pop
      self.SubmitPending()
2065 479636a3 Iustin Pop
    results = []
2066 479636a3 Iustin Pop
    if self.verbose:
2067 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
2068 23b4b983 Iustin Pop
      if ok_jobs:
2069 1f864b60 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
2070 5299e61f Iustin Pop
2071 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
2072 5299e61f Iustin Pop
    self.jobs, failures = utils.partition(self.jobs, lambda x: x[1])
2073 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
2074 c63355f2 Iustin Pop
      ToStderr("Failed to submit job for %s: %s", name, jid)
2075 c63355f2 Iustin Pop
      results.append((idx, False, jid))
2076 5299e61f Iustin Pop
2077 5299e61f Iustin Pop
    while self.jobs:
2078 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
2079 5299e61f Iustin Pop
      ToStdout("Waiting for job %s for %s...", jid, name)
2080 479636a3 Iustin Pop
      try:
2081 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
2082 479636a3 Iustin Pop
        success = True
2083 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
2084 479636a3 Iustin Pop
        _, job_result = FormatError(err)
2085 479636a3 Iustin Pop
        success = False
2086 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
2087 479636a3 Iustin Pop
        ToStderr("Job %s for %s has failed: %s", jid, name, job_result)
2088 479636a3 Iustin Pop
2089 5299e61f Iustin Pop
      results.append((idx, success, job_result))
2090 5299e61f Iustin Pop
2091 5299e61f Iustin Pop
    # sort based on the index, then drop it
2092 5299e61f Iustin Pop
    results.sort()
2093 5299e61f Iustin Pop
    results = [i[1:] for i in results]
2094 5299e61f Iustin Pop
2095 479636a3 Iustin Pop
    return results
2096 479636a3 Iustin Pop
2097 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
2098 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
2099 479636a3 Iustin Pop

2100 479636a3 Iustin Pop
    @type wait: boolean
2101 479636a3 Iustin Pop
    @param wait: whether to wait or not
2102 479636a3 Iustin Pop

2103 479636a3 Iustin Pop
    """
2104 479636a3 Iustin Pop
    if wait:
2105 479636a3 Iustin Pop
      return self.GetResults()
2106 479636a3 Iustin Pop
    else:
2107 23b4b983 Iustin Pop
      if not self.jobs:
2108 23b4b983 Iustin Pop
        self.SubmitPending()
2109 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
2110 23b4b983 Iustin Pop
        if status:
2111 23b4b983 Iustin Pop
          ToStdout("%s: %s", result, name)
2112 23b4b983 Iustin Pop
        else:
2113 23b4b983 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)