Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ f961e2ba

History | View | Annotate | Download (73.3 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 cea881e5 Michael Hanselmann
from ganeti import compat
41 a8083063 Iustin Pop
42 c38c44ad Michael Hanselmann
from optparse import (OptionParser, TitledHelpFormatter,
43 38206f3c Iustin Pop
                      Option, OptionValueError)
44 a8083063 Iustin Pop
45 03298ebe Michael Hanselmann
46 4abc4f1e Iustin Pop
__all__ = [
47 4abc4f1e Iustin Pop
  # Command line options
48 fdad8c4d Balazs Lecz
  "ADD_UIDS_OPT",
49 e7e09483 Iustin Pop
  "ALLOCATABLE_OPT",
50 2d5e7ae1 Iustin Pop
  "ALL_OPT",
51 4c61d894 Iustin Pop
  "AUTO_PROMOTE_OPT",
52 e00f7a05 Iustin Pop
  "AUTO_REPLACE_OPT",
53 087ed2ed Iustin Pop
  "BACKEND_OPT",
54 baef337d Iustin Pop
  "CLEANUP_OPT",
55 4abc4f1e Iustin Pop
  "CONFIRM_OPT",
56 e32df528 Iustin Pop
  "CP_SIZE_OPT",
57 4abc4f1e Iustin Pop
  "DEBUG_OPT",
58 a0c9776a Iustin Pop
  "DEBUG_SIMERR_OPT",
59 4b038a1e Iustin Pop
  "DISKIDX_OPT",
60 e3876ccb Iustin Pop
  "DISK_OPT",
61 4b038a1e Iustin Pop
  "DISK_TEMPLATE_OPT",
62 771734c9 Iustin Pop
  "DRAINED_OPT",
63 7ea7bcf6 Iustin Pop
  "EARLY_RELEASE_OPT",
64 383a3591 Iustin Pop
  "ENABLED_HV_OPT",
65 14e9e7f3 Iustin Pop
  "ERROR_CODES_OPT",
66 4abc4f1e Iustin Pop
  "FIELDS_OPT",
67 4a25828c Iustin Pop
  "FILESTORE_DIR_OPT",
68 0f87c43e Iustin Pop
  "FILESTORE_DRIVER_OPT",
69 06073e85 Guido Trotter
  "FORCE_OPT",
70 06073e85 Guido Trotter
  "FORCE_VARIANT_OPT",
71 29392516 Iustin Pop
  "GLOBAL_FILEDIR_OPT",
72 073271f6 Iustin Pop
  "HVLIST_OPT",
73 48f212d7 Iustin Pop
  "HVOPTS_OPT",
74 236fd9c4 Iustin Pop
  "HYPERVISOR_OPT",
75 4eb62659 Iustin Pop
  "IALLOCATOR_OPT",
76 e588764d Iustin Pop
  "IDENTIFY_DEFAULTS_OPT",
77 82a786d5 Iustin Pop
  "IGNORE_CONSIST_OPT",
78 b6e841a8 Iustin Pop
  "IGNORE_FAILURES_OPT",
79 ee3f9578 Iustin Pop
  "IGNORE_SECONDARIES_OPT",
80 05586c90 Iustin Pop
  "IGNORE_SIZE_OPT",
81 e3646f22 Iustin Pop
  "MAC_PREFIX_OPT",
82 3953242f Iustin Pop
  "MAINTAIN_NODE_HEALTH_OPT",
83 29392516 Iustin Pop
  "MASTER_NETDEV_OPT",
84 771734c9 Iustin Pop
  "MC_OPT",
85 7d3a9fab Iustin Pop
  "NET_OPT",
86 6d4a1656 Michael Hanselmann
  "NEW_CLUSTER_CERT_OPT",
87 6b7d5878 Michael Hanselmann
  "NEW_CONFD_HMAC_KEY_OPT",
88 6d4a1656 Michael Hanselmann
  "NEW_RAPI_CERT_OPT",
89 a14db5ff Iustin Pop
  "NEW_SECONDARY_OPT",
90 4fbc93dd Iustin Pop
  "NIC_PARAMS_OPT",
91 7edc4637 Iustin Pop
  "NODE_LIST_OPT",
92 990b7886 Iustin Pop
  "NODE_PLACEMENT_OPT",
93 4abc4f1e Iustin Pop
  "NOHDR_OPT",
94 91e0748c Iustin Pop
  "NOIPCHECK_OPT",
95 25a8792c Iustin Pop
  "NO_INSTALL_OPT",
96 460d22be Iustin Pop
  "NONAMECHECK_OPT",
97 831040bf Iustin Pop
  "NOLVM_STORAGE_OPT",
98 29392516 Iustin Pop
  "NOMODIFY_ETCHOSTS_OPT",
99 b989b9d9 Ken Wehr
  "NOMODIFY_SSH_SETUP_OPT",
100 26023ecd Iustin Pop
  "NONICS_OPT",
101 f2a0828c Iustin Pop
  "NONLIVE_OPT",
102 14e9e7f3 Iustin Pop
  "NONPLUS1_OPT",
103 44c44832 Iustin Pop
  "NOSHUTDOWN_OPT",
104 edeb878a Iustin Pop
  "NOSTART_OPT",
105 fcdde7f2 Iustin Pop
  "NOSSH_KEYCHECK_OPT",
106 58371861 Iustin Pop
  "NOVOTING_OPT",
107 3f75b4f3 Iustin Pop
  "NWSYNC_OPT",
108 a72d0a79 Iustin Pop
  "ON_PRIMARY_OPT",
109 feb09e6a Iustin Pop
  "ON_SECONDARY_OPT",
110 771734c9 Iustin Pop
  "OFFLINE_OPT",
111 d3ed23ff Iustin Pop
  "OS_OPT",
112 ff00c1a7 Iustin Pop
  "OS_SIZE_OPT",
113 6d4a1656 Michael Hanselmann
  "RAPI_CERT_OPT",
114 b8d0f938 Iustin Pop
  "READD_OPT",
115 12054861 Iustin Pop
  "REBOOT_TYPE_OPT",
116 fdad8c4d Balazs Lecz
  "REMOVE_UIDS_OPT",
117 8d823629 Iustin Pop
  "SECONDARY_IP_OPT",
118 67840b40 Iustin Pop
  "SELECT_OS_OPT",
119 4abc4f1e Iustin Pop
  "SEP_OPT",
120 fdcf4d84 Iustin Pop
  "SHOWCMD_OPT",
121 7e5eaaa8 Guido Trotter
  "SHUTDOWN_TIMEOUT_OPT",
122 f36d7d81 Iustin Pop
  "SINGLE_NODE_OPT",
123 df62e5db Iustin Pop
  "SRC_DIR_OPT",
124 df62e5db Iustin Pop
  "SRC_NODE_OPT",
125 4abc4f1e Iustin Pop
  "SUBMIT_OPT",
126 99a8c799 Iustin Pop
  "STATIC_OPT",
127 4abc4f1e Iustin Pop
  "SYNC_OPT",
128 4abc4f1e Iustin Pop
  "TAG_SRC_OPT",
129 b5762e2a Guido Trotter
  "TIMEOUT_OPT",
130 1338f2b4 Balazs Lecz
  "UIDPOOL_OPT",
131 4abc4f1e Iustin Pop
  "USEUNITS_OPT",
132 74adc100 Iustin Pop
  "USE_REPL_NET_OPT",
133 9cdb9578 Iustin Pop
  "VERBOSE_OPT",
134 b58726e8 Iustin Pop
  "VG_NAME_OPT",
135 1f587d3d Iustin Pop
  "YES_DOIT_OPT",
136 4abc4f1e Iustin Pop
  # Generic functions for CLI programs
137 4abc4f1e Iustin Pop
  "GenericMain",
138 d77490c5 Iustin Pop
  "GenericInstanceCreate",
139 4abc4f1e Iustin Pop
  "GetClient",
140 4abc4f1e Iustin Pop
  "GetOnlineNodes",
141 4abc4f1e Iustin Pop
  "JobExecutor",
142 4abc4f1e Iustin Pop
  "JobSubmittedException",
143 4abc4f1e Iustin Pop
  "ParseTimespec",
144 7e49b6ce Michael Hanselmann
  "RunWhileClusterStopped",
145 4abc4f1e Iustin Pop
  "SubmitOpCode",
146 4abc4f1e Iustin Pop
  "SubmitOrSend",
147 4abc4f1e Iustin Pop
  "UsesRPC",
148 4abc4f1e Iustin Pop
  # Formatting functions
149 4abc4f1e Iustin Pop
  "ToStderr", "ToStdout",
150 4abc4f1e Iustin Pop
  "FormatError",
151 4abc4f1e Iustin Pop
  "GenerateTable",
152 4abc4f1e Iustin Pop
  "AskUser",
153 4abc4f1e Iustin Pop
  "FormatTimestamp",
154 4abc4f1e Iustin Pop
  # Tags functions
155 4abc4f1e Iustin Pop
  "ListTags",
156 4abc4f1e Iustin Pop
  "AddTags",
157 4abc4f1e Iustin Pop
  "RemoveTags",
158 4abc4f1e Iustin Pop
  # command line options support infrastructure
159 4abc4f1e Iustin Pop
  "ARGS_MANY_INSTANCES",
160 4abc4f1e Iustin Pop
  "ARGS_MANY_NODES",
161 4abc4f1e Iustin Pop
  "ARGS_NONE",
162 4abc4f1e Iustin Pop
  "ARGS_ONE_INSTANCE",
163 4abc4f1e Iustin Pop
  "ARGS_ONE_NODE",
164 f9faf9c3 René Nussbaumer
  "ARGS_ONE_OS",
165 4abc4f1e Iustin Pop
  "ArgChoice",
166 4abc4f1e Iustin Pop
  "ArgCommand",
167 4abc4f1e Iustin Pop
  "ArgFile",
168 4abc4f1e Iustin Pop
  "ArgHost",
169 4abc4f1e Iustin Pop
  "ArgInstance",
170 4abc4f1e Iustin Pop
  "ArgJobId",
171 4abc4f1e Iustin Pop
  "ArgNode",
172 f9faf9c3 René Nussbaumer
  "ArgOs",
173 4abc4f1e Iustin Pop
  "ArgSuggest",
174 4abc4f1e Iustin Pop
  "ArgUnknown",
175 4abc4f1e Iustin Pop
  "OPT_COMPL_INST_ADD_NODES",
176 4abc4f1e Iustin Pop
  "OPT_COMPL_MANY_NODES",
177 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_IALLOCATOR",
178 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_INSTANCE",
179 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_NODE",
180 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_OS",
181 4abc4f1e Iustin Pop
  "cli_option",
182 4abc4f1e Iustin Pop
  "SplitNodeOption",
183 07150497 Guido Trotter
  "CalculateOSNames",
184 4abc4f1e Iustin Pop
  ]
185 846baef9 Iustin Pop
186 8b46606c Guido Trotter
NO_PREFIX = "no_"
187 8b46606c Guido Trotter
UN_PREFIX = "-"
188 846baef9 Iustin Pop
189 03298ebe Michael Hanselmann
190 863d7f46 Michael Hanselmann
class _Argument:
191 7260cfbe Iustin Pop
  def __init__(self, min=0, max=None): # pylint: disable-msg=W0622
192 863d7f46 Michael Hanselmann
    self.min = min
193 863d7f46 Michael Hanselmann
    self.max = max
194 863d7f46 Michael Hanselmann
195 863d7f46 Michael Hanselmann
  def __repr__(self):
196 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s>" %
197 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max))
198 863d7f46 Michael Hanselmann
199 863d7f46 Michael Hanselmann
200 863d7f46 Michael Hanselmann
class ArgSuggest(_Argument):
201 863d7f46 Michael Hanselmann
  """Suggesting argument.
202 863d7f46 Michael Hanselmann

203 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
204 863d7f46 Michael Hanselmann

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

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

222 863d7f46 Michael Hanselmann
  """
223 863d7f46 Michael Hanselmann
224 863d7f46 Michael Hanselmann
225 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
226 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
227 863d7f46 Michael Hanselmann

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

234 863d7f46 Michael Hanselmann
  """
235 863d7f46 Michael Hanselmann
236 863d7f46 Michael Hanselmann
237 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
238 863d7f46 Michael Hanselmann
  """Node argument.
239 863d7f46 Michael Hanselmann

240 863d7f46 Michael Hanselmann
  """
241 863d7f46 Michael Hanselmann
242 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
243 863d7f46 Michael Hanselmann
  """Job ID argument.
244 863d7f46 Michael Hanselmann

245 863d7f46 Michael Hanselmann
  """
246 863d7f46 Michael Hanselmann
247 863d7f46 Michael Hanselmann
248 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
249 863d7f46 Michael Hanselmann
  """File path argument.
250 863d7f46 Michael Hanselmann

251 863d7f46 Michael Hanselmann
  """
252 863d7f46 Michael Hanselmann
253 863d7f46 Michael Hanselmann
254 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
255 863d7f46 Michael Hanselmann
  """Command argument.
256 863d7f46 Michael Hanselmann

257 863d7f46 Michael Hanselmann
  """
258 863d7f46 Michael Hanselmann
259 863d7f46 Michael Hanselmann
260 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
261 83ec7961 Michael Hanselmann
  """Host argument.
262 83ec7961 Michael Hanselmann

263 83ec7961 Michael Hanselmann
  """
264 83ec7961 Michael Hanselmann
265 83ec7961 Michael Hanselmann
266 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
267 f9faf9c3 René Nussbaumer
  """OS argument.
268 f9faf9c3 René Nussbaumer

269 f9faf9c3 René Nussbaumer
  """
270 f9faf9c3 René Nussbaumer
271 f9faf9c3 René Nussbaumer
272 4a265c08 Michael Hanselmann
ARGS_NONE = []
273 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
274 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
275 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
276 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
277 f9faf9c3 René Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
278 4a265c08 Michael Hanselmann
279 4a265c08 Michael Hanselmann
280 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
281 846baef9 Iustin Pop
  """Extract the tag type object.
282 846baef9 Iustin Pop

283 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
284 846baef9 Iustin Pop

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

304 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
305 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
306 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
307 810c50b7 Iustin Pop

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

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

338 846baef9 Iustin Pop
  """
339 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
340 7699c3af Iustin Pop
  cl = GetClient()
341 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
342 846baef9 Iustin Pop
  result = list(result)
343 846baef9 Iustin Pop
  result.sort()
344 846baef9 Iustin Pop
  for tag in result:
345 03298ebe Michael Hanselmann
    ToStdout(tag)
346 846baef9 Iustin Pop
347 846baef9 Iustin Pop
348 846baef9 Iustin Pop
def AddTags(opts, args):
349 846baef9 Iustin Pop
  """Add tags on a given object.
350 846baef9 Iustin Pop

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

356 846baef9 Iustin Pop
  """
357 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
358 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
359 846baef9 Iustin Pop
  if not args:
360 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be added")
361 846baef9 Iustin Pop
  op = opcodes.OpAddTags(kind=kind, name=name, tags=args)
362 846baef9 Iustin Pop
  SubmitOpCode(op)
363 846baef9 Iustin Pop
364 846baef9 Iustin Pop
365 846baef9 Iustin Pop
def RemoveTags(opts, args):
366 846baef9 Iustin Pop
  """Remove tags from a given object.
367 846baef9 Iustin Pop

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

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

385 65fe4693 Iustin Pop
  """
386 a8083063 Iustin Pop
  try:
387 a8083063 Iustin Pop
    return utils.ParseUnit(value)
388 a8083063 Iustin Pop
  except errors.UnitParseError, err:
389 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
390 a8083063 Iustin Pop
391 a8083063 Iustin Pop
392 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
393 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
394 a8469393 Iustin Pop

395 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
396 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
397 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
398 a8469393 Iustin Pop
  have value=True.
399 a8469393 Iustin Pop

400 a8469393 Iustin Pop
  @type opt: string
401 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
402 a8469393 Iustin Pop
      data, used in building error messages
403 a8469393 Iustin Pop
  @type data: string
404 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
405 a8469393 Iustin Pop
  @rtype: dict
406 a8469393 Iustin Pop
  @return: {key=val, key=val}
407 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
408 a8469393 Iustin Pop

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

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

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

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

462 a8469393 Iustin Pop
  """
463 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
464 a8469393 Iustin Pop
465 a8469393 Iustin Pop
466 e7b61bb0 Iustin Pop
def check_bool(option, opt, value): # pylint: disable-msg=W0613
467 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
468 e7b61bb0 Iustin Pop

469 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
470 e7b61bb0 Iustin Pop

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

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

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

960 c41eea6e Iustin Pop
  @param argv: the command line
961 c41eea6e Iustin Pop
  @param commands: dictionary with special contents, see the design
962 c41eea6e Iustin Pop
      doc for cmdline handling
963 c41eea6e Iustin Pop
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
964 098c0958 Michael Hanselmann

965 a8083063 Iustin Pop
  """
966 a8083063 Iustin Pop
  if len(argv) == 0:
967 a8083063 Iustin Pop
    binary = "<command>"
968 a8083063 Iustin Pop
  else:
969 a8083063 Iustin Pop
    binary = argv[0].split("/")[-1]
970 a8083063 Iustin Pop
971 a8083063 Iustin Pop
  if len(argv) > 1 and argv[1] == "--version":
972 03298ebe Michael Hanselmann
    ToStdout("%s (ganeti) %s", binary, constants.RELEASE_VERSION)
973 a8083063 Iustin Pop
    # Quit right away. That way we don't have to care about this special
974 a8083063 Iustin Pop
    # argument. optparse.py does it the same.
975 a8083063 Iustin Pop
    sys.exit(0)
976 a8083063 Iustin Pop
977 de47cf8f Guido Trotter
  if len(argv) < 2 or not (argv[1] in commands or
978 70a35b6f Guido Trotter
                           argv[1] in aliases):
979 a8083063 Iustin Pop
    # let's do a nice thing
980 a8083063 Iustin Pop
    sortedcmds = commands.keys()
981 a8083063 Iustin Pop
    sortedcmds.sort()
982 03298ebe Michael Hanselmann
983 03298ebe Michael Hanselmann
    ToStdout("Usage: %s {command} [options...] [argument...]", binary)
984 03298ebe Michael Hanselmann
    ToStdout("%s <command> --help to see details, or man %s", binary, binary)
985 03298ebe Michael Hanselmann
    ToStdout("")
986 03298ebe Michael Hanselmann
987 a8083063 Iustin Pop
    # compute the max line length for cmd + usage
988 4e713df6 Iustin Pop
    mlen = max([len(" %s" % cmd) for cmd in commands])
989 a8083063 Iustin Pop
    mlen = min(60, mlen) # should not get here...
990 03298ebe Michael Hanselmann
991 a8083063 Iustin Pop
    # and format a nice command list
992 03298ebe Michael Hanselmann
    ToStdout("Commands:")
993 a8083063 Iustin Pop
    for cmd in sortedcmds:
994 4e713df6 Iustin Pop
      cmdstr = " %s" % (cmd,)
995 9a033156 Iustin Pop
      help_text = commands[cmd][4]
996 03298ebe Michael Hanselmann
      help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
997 03298ebe Michael Hanselmann
      ToStdout("%-*s - %s", mlen, cmdstr, help_lines.pop(0))
998 a8083063 Iustin Pop
      for line in help_lines:
999 03298ebe Michael Hanselmann
        ToStdout("%-*s   %s", mlen, "", line)
1000 03298ebe Michael Hanselmann
1001 03298ebe Michael Hanselmann
    ToStdout("")
1002 03298ebe Michael Hanselmann
1003 a8083063 Iustin Pop
    return None, None, None
1004 de47cf8f Guido Trotter
1005 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1006 a8083063 Iustin Pop
  cmd = argv.pop(1)
1007 de47cf8f Guido Trotter
  if cmd in aliases:
1008 de47cf8f Guido Trotter
    if cmd in commands:
1009 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' overrides an existing"
1010 de47cf8f Guido Trotter
                                   " command" % cmd)
1011 de47cf8f Guido Trotter
1012 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1013 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1014 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1015 de47cf8f Guido Trotter
1016 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1017 de47cf8f Guido Trotter
1018 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1019 064c21f8 Iustin Pop
  parser = OptionParser(option_list=parser_opts + [_DRY_RUN_OPT, DEBUG_OPT],
1020 a8083063 Iustin Pop
                        description=description,
1021 a8083063 Iustin Pop
                        formatter=TitledHelpFormatter(),
1022 a8083063 Iustin Pop
                        usage="%%prog %s %s" % (cmd, usage))
1023 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1024 a8083063 Iustin Pop
  options, args = parser.parse_args()
1025 a8005e17 Michael Hanselmann
1026 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1027 a8083063 Iustin Pop
    return None, None, None
1028 a8083063 Iustin Pop
1029 a8083063 Iustin Pop
  return func, options, args
1030 a8083063 Iustin Pop
1031 a8083063 Iustin Pop
1032 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1033 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1034 a8005e17 Michael Hanselmann

1035 a8005e17 Michael Hanselmann
  Algorithm:
1036 a8005e17 Michael Hanselmann

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

1039 a8005e17 Michael Hanselmann
    1. For each argument in definition
1040 a8005e17 Michael Hanselmann

1041 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1042 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1043 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1044 a8005e17 Michael Hanselmann

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

1047 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1048 a8005e17 Michael Hanselmann

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

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

1053 a8005e17 Michael Hanselmann
  """
1054 a8005e17 Michael Hanselmann
  if args and not args_def:
1055 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1056 a8005e17 Michael Hanselmann
    return False
1057 a8005e17 Michael Hanselmann
1058 a8005e17 Michael Hanselmann
  min_count = None
1059 a8005e17 Michael Hanselmann
  max_count = None
1060 a8005e17 Michael Hanselmann
  check_max = None
1061 a8005e17 Michael Hanselmann
1062 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1063 a8005e17 Michael Hanselmann
1064 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1065 a8005e17 Michael Hanselmann
    if min_count is None:
1066 a8005e17 Michael Hanselmann
      min_count = arg.min
1067 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1068 a8005e17 Michael Hanselmann
      min_count += arg.min
1069 a8005e17 Michael Hanselmann
1070 a8005e17 Michael Hanselmann
    if max_count is None:
1071 a8005e17 Michael Hanselmann
      max_count = arg.max
1072 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1073 a8005e17 Michael Hanselmann
      max_count += arg.max
1074 a8005e17 Michael Hanselmann
1075 a8005e17 Michael Hanselmann
    if idx == last_idx:
1076 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1077 a8005e17 Michael Hanselmann
1078 a8005e17 Michael Hanselmann
    elif arg.max is None:
1079 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1080 a8005e17 Michael Hanselmann
1081 a8005e17 Michael Hanselmann
  if check_max:
1082 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1083 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1084 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1085 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1086 a8005e17 Michael Hanselmann
      return False
1087 a8005e17 Michael Hanselmann
1088 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1089 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1090 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1091 a8005e17 Michael Hanselmann
               cmd, max_count)
1092 a8005e17 Michael Hanselmann
      return False
1093 a8005e17 Michael Hanselmann
1094 a8005e17 Michael Hanselmann
  # Command with some required arguments
1095 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1096 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1097 a8005e17 Michael Hanselmann
             cmd, min_count)
1098 a8005e17 Michael Hanselmann
    return False
1099 a8005e17 Michael Hanselmann
1100 a8005e17 Michael Hanselmann
  return True
1101 a8005e17 Michael Hanselmann
1102 a8005e17 Michael Hanselmann
1103 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1104 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1105 60d49723 Michael Hanselmann

1106 60d49723 Michael Hanselmann
  """
1107 60d49723 Michael Hanselmann
  if value and ':' in value:
1108 60d49723 Michael Hanselmann
    return value.split(':', 1)
1109 60d49723 Michael Hanselmann
  else:
1110 60d49723 Michael Hanselmann
    return (value, None)
1111 60d49723 Michael Hanselmann
1112 60d49723 Michael Hanselmann
1113 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1114 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1115 07150497 Guido Trotter

1116 07150497 Guido Trotter
  @type os_name: string
1117 07150497 Guido Trotter
  @param os_name: base name of the os
1118 07150497 Guido Trotter
  @type os_variants: list or None
1119 07150497 Guido Trotter
  @param os_variants: list of supported variants
1120 07150497 Guido Trotter
  @rtype: list
1121 07150497 Guido Trotter
  @return: list of valid names
1122 07150497 Guido Trotter

1123 07150497 Guido Trotter
  """
1124 07150497 Guido Trotter
  if os_variants:
1125 07150497 Guido Trotter
    return ['%s+%s' % (os_name, v) for v in os_variants]
1126 07150497 Guido Trotter
  else:
1127 07150497 Guido Trotter
    return [os_name]
1128 07150497 Guido Trotter
1129 07150497 Guido Trotter
1130 4331f6cd Michael Hanselmann
def UsesRPC(fn):
1131 4331f6cd Michael Hanselmann
  def wrapper(*args, **kwargs):
1132 4331f6cd Michael Hanselmann
    rpc.Init()
1133 4331f6cd Michael Hanselmann
    try:
1134 4331f6cd Michael Hanselmann
      return fn(*args, **kwargs)
1135 4331f6cd Michael Hanselmann
    finally:
1136 4331f6cd Michael Hanselmann
      rpc.Shutdown()
1137 4331f6cd Michael Hanselmann
  return wrapper
1138 4331f6cd Michael Hanselmann
1139 4331f6cd Michael Hanselmann
1140 47988778 Iustin Pop
def AskUser(text, choices=None):
1141 47988778 Iustin Pop
  """Ask the user a question.
1142 a8083063 Iustin Pop

1143 c41eea6e Iustin Pop
  @param text: the question to ask
1144 a8083063 Iustin Pop

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

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

1154 a8083063 Iustin Pop
  """
1155 47988778 Iustin Pop
  if choices is None:
1156 47988778 Iustin Pop
    choices = [('y', True, 'Perform the operation'),
1157 47988778 Iustin Pop
               ('n', False, 'Do not perform the operation')]
1158 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1159 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1160 47988778 Iustin Pop
  for entry in choices:
1161 47988778 Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == '?':
1162 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1163 47988778 Iustin Pop
1164 47988778 Iustin Pop
  answer = choices[-1][1]
1165 47988778 Iustin Pop
  new_text = []
1166 47988778 Iustin Pop
  for line in text.splitlines():
1167 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1168 47988778 Iustin Pop
  text = "\n".join(new_text)
1169 a8083063 Iustin Pop
  try:
1170 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1171 a8083063 Iustin Pop
  except IOError:
1172 47988778 Iustin Pop
    return answer
1173 a8083063 Iustin Pop
  try:
1174 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1175 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1176 47988778 Iustin Pop
    chars.append('?')
1177 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1178 47988778 Iustin Pop
    while True:
1179 47988778 Iustin Pop
      f.write(text)
1180 47988778 Iustin Pop
      f.write('\n')
1181 47988778 Iustin Pop
      f.write("/".join(chars))
1182 47988778 Iustin Pop
      f.write(": ")
1183 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1184 47988778 Iustin Pop
      if line in maps:
1185 47988778 Iustin Pop
        answer = maps[line]
1186 47988778 Iustin Pop
        break
1187 47988778 Iustin Pop
      elif line == '?':
1188 47988778 Iustin Pop
        for entry in choices:
1189 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1190 47988778 Iustin Pop
        f.write("\n")
1191 47988778 Iustin Pop
        continue
1192 a8083063 Iustin Pop
  finally:
1193 a8083063 Iustin Pop
    f.close()
1194 a8083063 Iustin Pop
  return answer
1195 a8083063 Iustin Pop
1196 a8083063 Iustin Pop
1197 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1198 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1199 e9d741b6 Iustin Pop

1200 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1201 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1202 e9d741b6 Iustin Pop

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

1205 e9d741b6 Iustin Pop
  """
1206 e9d741b6 Iustin Pop
1207 e9d741b6 Iustin Pop
1208 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1209 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1210 a8083063 Iustin Pop

1211 0a1e74d9 Iustin Pop
  @type ops: list
1212 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1213 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1214 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1215 0a1e74d9 Iustin Pop
             if None, a new client will be created
1216 a8083063 Iustin Pop

1217 a8083063 Iustin Pop
  """
1218 e2212007 Iustin Pop
  if cl is None:
1219 b33e986b Iustin Pop
    cl = GetClient()
1220 685ee993 Iustin Pop
1221 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1222 0a1e74d9 Iustin Pop
1223 0a1e74d9 Iustin Pop
  return job_id
1224 0a1e74d9 Iustin Pop
1225 0a1e74d9 Iustin Pop
1226 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1227 4e338533 Michael Hanselmann
  """Generic job-polling function.
1228 0a1e74d9 Iustin Pop

1229 4e338533 Michael Hanselmann
  @type job_id: number
1230 4e338533 Michael Hanselmann
  @param job_id: Job ID
1231 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1232 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1233 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1234 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1235 0a1e74d9 Iustin Pop

1236 0a1e74d9 Iustin Pop
  """
1237 6c5a7090 Michael Hanselmann
  prev_job_info = None
1238 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1239 6c5a7090 Michael Hanselmann
1240 f4484122 Michael Hanselmann
  status = None
1241 f4484122 Michael Hanselmann
1242 685ee993 Iustin Pop
  while True:
1243 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1244 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
1245 6c5a7090 Michael Hanselmann
    if not result:
1246 685ee993 Iustin Pop
      # job not found, go away!
1247 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1248 4e338533 Michael Hanselmann
1249 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
1250 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
1251 f4484122 Michael Hanselmann
1252 f4484122 Michael Hanselmann
      # Wait again
1253 f4484122 Michael Hanselmann
      continue
1254 685ee993 Iustin Pop
1255 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1256 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1257 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1258 6c5a7090 Michael Hanselmann
1259 6c5a7090 Michael Hanselmann
    if log_entries:
1260 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1261 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
1262 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
1263 4e338533 Michael Hanselmann
                                    log_type, message)
1264 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1265 6c5a7090 Michael Hanselmann
1266 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1267 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1268 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1269 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1270 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1271 685ee993 Iustin Pop
      break
1272 6c5a7090 Michael Hanselmann
1273 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1274 685ee993 Iustin Pop
1275 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1276 0bbe448c Michael Hanselmann
  if not jobs:
1277 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1278 685ee993 Iustin Pop
1279 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1280 4e338533 Michael Hanselmann
1281 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1282 53c04d04 Iustin Pop
    return result
1283 4e338533 Michael Hanselmann
1284 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
1285 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1286 4e338533 Michael Hanselmann
1287 4e338533 Michael Hanselmann
  has_ok = False
1288 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
1289 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
1290 4e338533 Michael Hanselmann
      has_ok = True
1291 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
1292 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
1293 4e338533 Michael Hanselmann
1294 4e338533 Michael Hanselmann
      if has_ok:
1295 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
1296 4e338533 Michael Hanselmann
                                 (idx, msg))
1297 4e338533 Michael Hanselmann
1298 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
1299 4e338533 Michael Hanselmann
1300 4e338533 Michael Hanselmann
  # default failure mode
1301 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
1302 4e338533 Michael Hanselmann
1303 4e338533 Michael Hanselmann
1304 4e338533 Michael Hanselmann
class JobPollCbBase:
1305 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
1306 4e338533 Michael Hanselmann

1307 4e338533 Michael Hanselmann
  """
1308 4e338533 Michael Hanselmann
  def __init__(self):
1309 4e338533 Michael Hanselmann
    """Initializes this class.
1310 4e338533 Michael Hanselmann

1311 4e338533 Michael Hanselmann
    """
1312 4e338533 Michael Hanselmann
1313 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1314 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1315 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1316 4e338533 Michael Hanselmann

1317 4e338533 Michael Hanselmann
    """
1318 4e338533 Michael Hanselmann
    raise NotImplementedError()
1319 4e338533 Michael Hanselmann
1320 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1321 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1322 4e338533 Michael Hanselmann

1323 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
1324 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
1325 4e338533 Michael Hanselmann
    @type fields: list of strings
1326 4e338533 Michael Hanselmann
    @param fields: Fields
1327 4e338533 Michael Hanselmann

1328 4e338533 Michael Hanselmann
    """
1329 4e338533 Michael Hanselmann
    raise NotImplementedError()
1330 4e338533 Michael Hanselmann
1331 4e338533 Michael Hanselmann
1332 4e338533 Michael Hanselmann
class JobPollReportCbBase:
1333 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
1334 4e338533 Michael Hanselmann

1335 4e338533 Michael Hanselmann
  """
1336 4e338533 Michael Hanselmann
  def __init__(self):
1337 4e338533 Michael Hanselmann
    """Initializes this class.
1338 4e338533 Michael Hanselmann

1339 4e338533 Michael Hanselmann
    """
1340 4e338533 Michael Hanselmann
1341 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1342 4e338533 Michael Hanselmann
    """Handles a log message.
1343 4e338533 Michael Hanselmann

1344 4e338533 Michael Hanselmann
    """
1345 4e338533 Michael Hanselmann
    raise NotImplementedError()
1346 4e338533 Michael Hanselmann
1347 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1348 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
1349 4e338533 Michael Hanselmann

1350 4e338533 Michael Hanselmann
    @type job_id: number
1351 4e338533 Michael Hanselmann
    @param job_id: Job ID
1352 4e338533 Michael Hanselmann
    @type status: string or None
1353 4e338533 Michael Hanselmann
    @param status: Job status if available
1354 4e338533 Michael Hanselmann

1355 4e338533 Michael Hanselmann
    """
1356 4e338533 Michael Hanselmann
    raise NotImplementedError()
1357 4e338533 Michael Hanselmann
1358 4e338533 Michael Hanselmann
1359 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
1360 4e338533 Michael Hanselmann
  def __init__(self, cl):
1361 4e338533 Michael Hanselmann
    """Initializes this class.
1362 4e338533 Michael Hanselmann

1363 4e338533 Michael Hanselmann
    """
1364 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
1365 4e338533 Michael Hanselmann
    self.cl = cl
1366 4e338533 Michael Hanselmann
1367 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1368 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1369 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1370 4e338533 Michael Hanselmann

1371 4e338533 Michael Hanselmann
    """
1372 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
1373 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
1374 4e338533 Michael Hanselmann
1375 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1376 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1377 4e338533 Michael Hanselmann

1378 4e338533 Michael Hanselmann
    """
1379 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
1380 4e338533 Michael Hanselmann
1381 4e338533 Michael Hanselmann
1382 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
1383 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
1384 4e338533 Michael Hanselmann
    """Initializes this class.
1385 4e338533 Michael Hanselmann

1386 4e338533 Michael Hanselmann
    """
1387 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1388 4e338533 Michael Hanselmann
1389 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
1390 4e338533 Michael Hanselmann
1391 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
1392 4e338533 Michael Hanselmann
1393 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1394 4e338533 Michael Hanselmann
    """Handles a log message.
1395 4e338533 Michael Hanselmann

1396 4e338533 Michael Hanselmann
    """
1397 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
1398 4e338533 Michael Hanselmann
1399 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1400 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1401 4e338533 Michael Hanselmann

1402 4e338533 Michael Hanselmann
    """
1403 4e338533 Michael Hanselmann
    # Ignore
1404 4e338533 Michael Hanselmann
1405 4e338533 Michael Hanselmann
1406 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
1407 4e338533 Michael Hanselmann
  def __init__(self):
1408 4e338533 Michael Hanselmann
    """Initializes this class.
1409 4e338533 Michael Hanselmann

1410 4e338533 Michael Hanselmann
    """
1411 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1412 4e338533 Michael Hanselmann
1413 4e338533 Michael Hanselmann
    self.notified_queued = False
1414 4e338533 Michael Hanselmann
    self.notified_waitlock = False
1415 4e338533 Michael Hanselmann
1416 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1417 4e338533 Michael Hanselmann
    """Handles a log message.
1418 4e338533 Michael Hanselmann

1419 4e338533 Michael Hanselmann
    """
1420 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
1421 4e338533 Michael Hanselmann
             utils.SafeEncode(log_msg))
1422 4e338533 Michael Hanselmann
1423 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1424 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1425 4e338533 Michael Hanselmann

1426 4e338533 Michael Hanselmann
    """
1427 4e338533 Michael Hanselmann
    if status is None:
1428 4e338533 Michael Hanselmann
      return
1429 4e338533 Michael Hanselmann
1430 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
1431 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
1432 4e338533 Michael Hanselmann
      self.notified_queued = True
1433 4e338533 Michael Hanselmann
1434 4e338533 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITLOCK and not self.notified_waitlock:
1435 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
1436 4e338533 Michael Hanselmann
      self.notified_waitlock = True
1437 4e338533 Michael Hanselmann
1438 4e338533 Michael Hanselmann
1439 4e338533 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None):
1440 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
1441 4e338533 Michael Hanselmann

1442 4e338533 Michael Hanselmann
  @type job_id: job identified
1443 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
1444 4e338533 Michael Hanselmann
  @type cl: luxi.Client
1445 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
1446 4e338533 Michael Hanselmann
             if None, a new client will be created
1447 4e338533 Michael Hanselmann

1448 4e338533 Michael Hanselmann
  """
1449 4e338533 Michael Hanselmann
  if cl is None:
1450 4e338533 Michael Hanselmann
    cl = GetClient()
1451 4e338533 Michael Hanselmann
1452 4e338533 Michael Hanselmann
  if feedback_fn:
1453 4e338533 Michael Hanselmann
    reporter = FeedbackFnJobPollReportCb(feedback_fn)
1454 0bbe448c Michael Hanselmann
  else:
1455 4e338533 Michael Hanselmann
    reporter = StdioJobPollReportCb()
1456 4e338533 Michael Hanselmann
1457 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
1458 ceab32dd Iustin Pop
1459 ceab32dd Iustin Pop
1460 293ba2d8 Iustin Pop
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None):
1461 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
1462 0a1e74d9 Iustin Pop

1463 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
1464 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
1465 0a1e74d9 Iustin Pop
  interaction functions.
1466 0a1e74d9 Iustin Pop

1467 0a1e74d9 Iustin Pop
  """
1468 0a1e74d9 Iustin Pop
  if cl is None:
1469 0a1e74d9 Iustin Pop
    cl = GetClient()
1470 0a1e74d9 Iustin Pop
1471 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
1472 293ba2d8 Iustin Pop
1473 0a1e74d9 Iustin Pop
  job_id = SendJob([op], cl)
1474 0a1e74d9 Iustin Pop
1475 53c04d04 Iustin Pop
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn)
1476 53c04d04 Iustin Pop
1477 53c04d04 Iustin Pop
  return op_results[0]
1478 0a1e74d9 Iustin Pop
1479 0a1e74d9 Iustin Pop
1480 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
1481 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
1482 94428652 Iustin Pop

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

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

1491 94428652 Iustin Pop
  """
1492 94428652 Iustin Pop
  if opts and opts.submit_only:
1493 293ba2d8 Iustin Pop
    job = [op]
1494 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
1495 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
1496 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
1497 94428652 Iustin Pop
  else:
1498 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
1499 293ba2d8 Iustin Pop
1500 293ba2d8 Iustin Pop
1501 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
1502 293ba2d8 Iustin Pop
  """Processor for generic options.
1503 293ba2d8 Iustin Pop

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

1507 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
1508 293ba2d8 Iustin Pop
  @param options: command line options or None
1509 293ba2d8 Iustin Pop
  @return: None (in-place modification)
1510 293ba2d8 Iustin Pop

1511 293ba2d8 Iustin Pop
  """
1512 293ba2d8 Iustin Pop
  if not options:
1513 293ba2d8 Iustin Pop
    return
1514 293ba2d8 Iustin Pop
  for op in opcode_list:
1515 293ba2d8 Iustin Pop
    op.dry_run = options.dry_run
1516 293ba2d8 Iustin Pop
    op.debug_level = options.debug
1517 94428652 Iustin Pop
1518 94428652 Iustin Pop
1519 af30b2fd Michael Hanselmann
def GetClient():
1520 af30b2fd Michael Hanselmann
  # TODO: Cache object?
1521 b33e986b Iustin Pop
  try:
1522 b33e986b Iustin Pop
    client = luxi.Client()
1523 b33e986b Iustin Pop
  except luxi.NoMasterError:
1524 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
1525 d9a51679 Michael Hanselmann
1526 d9a51679 Michael Hanselmann
    # Try to read ssconf file
1527 d9a51679 Michael Hanselmann
    try:
1528 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
1529 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
1530 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
1531 d9a51679 Michael Hanselmann
                                 " not part of a cluster")
1532 d9a51679 Michael Hanselmann
1533 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
1534 b33e986b Iustin Pop
    if master != myself:
1535 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
1536 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
1537 b33e986b Iustin Pop
                                 master)
1538 d9a51679 Michael Hanselmann
    raise
1539 b33e986b Iustin Pop
  return client
1540 af30b2fd Michael Hanselmann
1541 af30b2fd Michael Hanselmann
1542 73702ee7 Iustin Pop
def FormatError(err):
1543 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
1544 73702ee7 Iustin Pop

1545 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
1546 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
1547 73702ee7 Iustin Pop
  second, a string describing the error message (not
1548 73702ee7 Iustin Pop
  newline-terminated).
1549 73702ee7 Iustin Pop

1550 73702ee7 Iustin Pop
  """
1551 73702ee7 Iustin Pop
  retcode = 1
1552 73702ee7 Iustin Pop
  obuf = StringIO()
1553 e2e521d0 Iustin Pop
  msg = str(err)
1554 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
1555 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
1556 46fbdd04 Iustin Pop
    logging.error(txt)
1557 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
1558 73702ee7 Iustin Pop
    obuf.write("Aborting.")
1559 73702ee7 Iustin Pop
    retcode = 2
1560 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
1561 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
1562 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
1563 73702ee7 Iustin Pop
      if out:
1564 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
1565 73702ee7 Iustin Pop
                   (node, script, out))
1566 73702ee7 Iustin Pop
      else:
1567 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
1568 73702ee7 Iustin Pop
                   (node, script))
1569 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
1570 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
1571 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
1572 73702ee7 Iustin Pop
    this_host = utils.HostInfo.SysName()
1573 73702ee7 Iustin Pop
    if err.args[0] == this_host:
1574 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
1575 73702ee7 Iustin Pop
    else:
1576 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
1577 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
1578 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
1579 5c983ee5 Iustin Pop
    if len(err.args) == 2:
1580 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1581 5c983ee5 Iustin Pop
               " operation:\nerror type: %s, error details:\n%s" %
1582 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
1583 5c983ee5 Iustin Pop
    else:
1584 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1585 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
1586 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
1587 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
1588 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
1589 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
1590 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
1591 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
1592 686d7433 Iustin Pop
               " accept new requests\n")
1593 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
1594 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
1595 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
1596 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
1597 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
1598 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
1599 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
1600 73702ee7 Iustin Pop
  elif isinstance(err, errors.GenericError):
1601 e2e521d0 Iustin Pop
    obuf.write("Unhandled Ganeti error: %s" % msg)
1602 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
1603 03a8dbdc Iustin Pop
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
1604 082c5adb Michael Hanselmann
               " and listening for connections?")
1605 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
1606 03a8dbdc Iustin Pop
    obuf.write("Timeout while talking to the master daemon. Error:\n"
1607 03a8dbdc Iustin Pop
               "%s" % msg)
1608 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
1609 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
1610 03a8dbdc Iustin Pop
               "%s" % msg)
1611 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
1612 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
1613 e9d741b6 Iustin Pop
    retcode = 0
1614 73702ee7 Iustin Pop
  else:
1615 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
1616 73702ee7 Iustin Pop
  return retcode, obuf.getvalue().rstrip('\n')
1617 73702ee7 Iustin Pop
1618 73702ee7 Iustin Pop
1619 de47cf8f Guido Trotter
def GenericMain(commands, override=None, aliases=None):
1620 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
1621 a8083063 Iustin Pop

1622 334d1483 Iustin Pop
  Arguments:
1623 334d1483 Iustin Pop
    - commands: a dictionary with a special structure, see the design doc
1624 334d1483 Iustin Pop
                for command line handling.
1625 334d1483 Iustin Pop
    - override: if not None, we expect a dictionary with keys that will
1626 334d1483 Iustin Pop
                override command line options; this can be used to pass
1627 334d1483 Iustin Pop
                options from the scripts to generic functions
1628 de47cf8f Guido Trotter
    - aliases: dictionary with command aliases {'alias': 'target, ...}
1629 a8083063 Iustin Pop

1630 a8083063 Iustin Pop
  """
1631 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
1632 a8083063 Iustin Pop
  if sys.argv:
1633 a8083063 Iustin Pop
    binary = os.path.basename(sys.argv[0]) or sys.argv[0]
1634 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
1635 a8083063 Iustin Pop
      binary += " " + sys.argv[1]
1636 a8083063 Iustin Pop
      old_cmdline = " ".join(sys.argv[2:])
1637 a8083063 Iustin Pop
    else:
1638 a8083063 Iustin Pop
      old_cmdline = ""
1639 a8083063 Iustin Pop
  else:
1640 a8083063 Iustin Pop
    binary = "<unknown program>"
1641 a8083063 Iustin Pop
    old_cmdline = ""
1642 a8083063 Iustin Pop
1643 de47cf8f Guido Trotter
  if aliases is None:
1644 de47cf8f Guido Trotter
    aliases = {}
1645 de47cf8f Guido Trotter
1646 3126878d Guido Trotter
  try:
1647 3126878d Guido Trotter
    func, options, args = _ParseArgs(sys.argv, commands, aliases)
1648 3126878d Guido Trotter
  except errors.ParameterError, err:
1649 3126878d Guido Trotter
    result, err_msg = FormatError(err)
1650 3126878d Guido Trotter
    ToStderr(err_msg)
1651 3126878d Guido Trotter
    return 1
1652 3126878d Guido Trotter
1653 a8083063 Iustin Pop
  if func is None: # parse error
1654 a8083063 Iustin Pop
    return 1
1655 a8083063 Iustin Pop
1656 334d1483 Iustin Pop
  if override is not None:
1657 334d1483 Iustin Pop
    for key, val in override.iteritems():
1658 334d1483 Iustin Pop
      setattr(options, key, val)
1659 334d1483 Iustin Pop
1660 82d9caef Iustin Pop
  utils.SetupLogging(constants.LOG_COMMANDS, debug=options.debug,
1661 82d9caef Iustin Pop
                     stderr_logging=True, program=binary)
1662 a8083063 Iustin Pop
1663 a8083063 Iustin Pop
  if old_cmdline:
1664 46fbdd04 Iustin Pop
    logging.info("run with arguments '%s'", old_cmdline)
1665 a8083063 Iustin Pop
  else:
1666 46fbdd04 Iustin Pop
    logging.info("run with no arguments")
1667 a8083063 Iustin Pop
1668 a8083063 Iustin Pop
  try:
1669 a4af651e Iustin Pop
    result = func(options, args)
1670 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
1671 d8353c3a Iustin Pop
          JobSubmittedException), err:
1672 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
1673 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
1674 46fbdd04 Iustin Pop
    ToStderr(err_msg)
1675 a8083063 Iustin Pop
1676 a8083063 Iustin Pop
  return result
1677 137161c9 Michael Hanselmann
1678 137161c9 Michael Hanselmann
1679 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
1680 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
1681 d77490c5 Iustin Pop

1682 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
1683 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
1684 d77490c5 Iustin Pop
  @type args: list
1685 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
1686 d77490c5 Iustin Pop
  @rtype: int
1687 d77490c5 Iustin Pop
  @return: the desired exit code
1688 d77490c5 Iustin Pop

1689 d77490c5 Iustin Pop
  """
1690 d77490c5 Iustin Pop
  instance = args[0]
1691 d77490c5 Iustin Pop
1692 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
1693 d77490c5 Iustin Pop
1694 d77490c5 Iustin Pop
  hypervisor = None
1695 d77490c5 Iustin Pop
  hvparams = {}
1696 d77490c5 Iustin Pop
  if opts.hypervisor:
1697 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
1698 d77490c5 Iustin Pop
1699 d77490c5 Iustin Pop
  if opts.nics:
1700 d77490c5 Iustin Pop
    try:
1701 21bcb9aa Michael Hanselmann
      nic_max = max(int(nidx[0]) + 1 for nidx in opts.nics)
1702 d77490c5 Iustin Pop
    except ValueError, err:
1703 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
1704 d77490c5 Iustin Pop
    nics = [{}] * nic_max
1705 d77490c5 Iustin Pop
    for nidx, ndict in opts.nics:
1706 d77490c5 Iustin Pop
      nidx = int(nidx)
1707 d77490c5 Iustin Pop
      if not isinstance(ndict, dict):
1708 d77490c5 Iustin Pop
        msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
1709 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
1710 d77490c5 Iustin Pop
      nics[nidx] = ndict
1711 d77490c5 Iustin Pop
  elif opts.no_nics:
1712 d77490c5 Iustin Pop
    # no nics
1713 d77490c5 Iustin Pop
    nics = []
1714 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
1715 d77490c5 Iustin Pop
    # default of one nic, all auto
1716 d77490c5 Iustin Pop
    nics = [{}]
1717 0af0f641 Iustin Pop
  else:
1718 0af0f641 Iustin Pop
    # mode == import
1719 0af0f641 Iustin Pop
    nics = []
1720 d77490c5 Iustin Pop
1721 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
1722 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
1723 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
1724 d77490c5 Iustin Pop
                                 " information passed")
1725 d77490c5 Iustin Pop
    disks = []
1726 d77490c5 Iustin Pop
  else:
1727 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
1728 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
1729 d77490c5 Iustin Pop
      raise errors.OpPrereqError("No disk information specified")
1730 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
1731 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
1732 d77490c5 Iustin Pop
                                 " '-s' option")
1733 d77490c5 Iustin Pop
    if opts.sd_size is not None:
1734 d77490c5 Iustin Pop
      opts.disks = [(0, {"size": opts.sd_size})]
1735 9b12ed0f Iustin Pop
1736 9b12ed0f Iustin Pop
    if opts.disks:
1737 9b12ed0f Iustin Pop
      try:
1738 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
1739 9b12ed0f Iustin Pop
      except ValueError, err:
1740 9b12ed0f Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
1741 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
1742 9b12ed0f Iustin Pop
    else:
1743 9b12ed0f Iustin Pop
      disks = []
1744 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
1745 d77490c5 Iustin Pop
      didx = int(didx)
1746 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
1747 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
1748 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
1749 5029db65 Iustin Pop
      elif "size" in ddict:
1750 5029db65 Iustin Pop
        if "adopt" in ddict:
1751 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
1752 5029db65 Iustin Pop
                                     " (disk %d)" % didx)
1753 5029db65 Iustin Pop
        try:
1754 5029db65 Iustin Pop
          ddict["size"] = utils.ParseUnit(ddict["size"])
1755 5029db65 Iustin Pop
        except ValueError, err:
1756 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
1757 5029db65 Iustin Pop
                                     (didx, err))
1758 5029db65 Iustin Pop
      elif "adopt" in ddict:
1759 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
1760 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
1761 5029db65 Iustin Pop
                                     " import")
1762 5029db65 Iustin Pop
        ddict["size"] = 0
1763 5029db65 Iustin Pop
      else:
1764 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
1765 5029db65 Iustin Pop
                                   " disk %d" % didx)
1766 d77490c5 Iustin Pop
      disks[didx] = ddict
1767 d77490c5 Iustin Pop
1768 d77490c5 Iustin Pop
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
1769 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
1770 d77490c5 Iustin Pop
1771 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
1772 d77490c5 Iustin Pop
    start = opts.start
1773 d77490c5 Iustin Pop
    os_type = opts.os
1774 d77490c5 Iustin Pop
    src_node = None
1775 d77490c5 Iustin Pop
    src_path = None
1776 25a8792c Iustin Pop
    no_install = opts.no_install
1777 e588764d Iustin Pop
    identify_defaults = False
1778 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
1779 d77490c5 Iustin Pop
    start = False
1780 d77490c5 Iustin Pop
    os_type = None
1781 d77490c5 Iustin Pop
    src_node = opts.src_node
1782 d77490c5 Iustin Pop
    src_path = opts.src_dir
1783 25a8792c Iustin Pop
    no_install = None
1784 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
1785 d77490c5 Iustin Pop
  else:
1786 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
1787 d77490c5 Iustin Pop
1788 d77490c5 Iustin Pop
  op = opcodes.OpCreateInstance(instance_name=instance,
1789 d77490c5 Iustin Pop
                                disks=disks,
1790 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
1791 d77490c5 Iustin Pop
                                nics=nics,
1792 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
1793 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
1794 460d22be Iustin Pop
                                name_check=opts.name_check,
1795 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
1796 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
1797 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
1798 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
1799 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
1800 d77490c5 Iustin Pop
                                hvparams=hvparams,
1801 d77490c5 Iustin Pop
                                beparams=opts.beparams,
1802 d77490c5 Iustin Pop
                                mode=mode,
1803 d77490c5 Iustin Pop
                                start=start,
1804 d77490c5 Iustin Pop
                                os_type=os_type,
1805 d77490c5 Iustin Pop
                                src_node=src_node,
1806 25a8792c Iustin Pop
                                src_path=src_path,
1807 e588764d Iustin Pop
                                no_install=no_install,
1808 e588764d Iustin Pop
                                identify_defaults=identify_defaults)
1809 d77490c5 Iustin Pop
1810 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
1811 d77490c5 Iustin Pop
  return 0
1812 d77490c5 Iustin Pop
1813 d77490c5 Iustin Pop
1814 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
1815 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
1816 7e49b6ce Michael Hanselmann

1817 7e49b6ce Michael Hanselmann
  """
1818 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
1819 7e49b6ce Michael Hanselmann
    """Initializes this class.
1820 7e49b6ce Michael Hanselmann

1821 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
1822 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
1823 7e49b6ce Michael Hanselmann
    @type cluster_name: string
1824 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
1825 7e49b6ce Michael Hanselmann
    @type master_node: string
1826 7e49b6ce Michael Hanselmann
    @param master_node Master node name
1827 7e49b6ce Michael Hanselmann
    @type online_nodes: list
1828 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
1829 7e49b6ce Michael Hanselmann

1830 7e49b6ce Michael Hanselmann
    """
1831 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
1832 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
1833 7e49b6ce Michael Hanselmann
    self.master_node = master_node
1834 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
1835 7e49b6ce Michael Hanselmann
1836 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
1837 7e49b6ce Michael Hanselmann
1838 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
1839 7e49b6ce Michael Hanselmann
                            if name != master_node]
1840 7e49b6ce Michael Hanselmann
1841 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
1842 7e49b6ce Michael Hanselmann
1843 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
1844 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
1845 7e49b6ce Michael Hanselmann

1846 7e49b6ce Michael Hanselmann
    @type node_name: string
1847 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
1848 7e49b6ce Michael Hanselmann
    @type cmd: list
1849 7e49b6ce Michael Hanselmann
    @param cmd: Command
1850 7e49b6ce Michael Hanselmann

1851 7e49b6ce Michael Hanselmann
    """
1852 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
1853 7e49b6ce Michael Hanselmann
      # No need to use SSH
1854 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
1855 7e49b6ce Michael Hanselmann
    else:
1856 7e49b6ce Michael Hanselmann
      result = self.ssh.Run(node_name, "root", utils.ShellQuoteArgs(cmd))
1857 7e49b6ce Michael Hanselmann
1858 7e49b6ce Michael Hanselmann
    if result.failed:
1859 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
1860 7e49b6ce Michael Hanselmann
      if node_name:
1861 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
1862 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
1863 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
1864 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
1865 7e49b6ce Michael Hanselmann
1866 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
1867 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
1868 7e49b6ce Michael Hanselmann

1869 7e49b6ce Michael Hanselmann
    @type fn: callable
1870 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
1871 7e49b6ce Michael Hanselmann

1872 7e49b6ce Michael Hanselmann
    """
1873 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
1874 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
1875 7e49b6ce Michael Hanselmann
    watcher_block = utils.FileLock.Open(constants.WATCHER_STATEFILE)
1876 7e49b6ce Michael Hanselmann
    try:
1877 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
1878 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
1879 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
1880 7e49b6ce Michael Hanselmann
1881 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
1882 7e49b6ce Michael Hanselmann
      # ones are finished
1883 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
1884 7e49b6ce Michael Hanselmann
      self._RunCmd(None, [constants.DAEMON_UTIL, "stop-master"])
1885 7e49b6ce Michael Hanselmann
      try:
1886 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
1887 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
1888 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
1889 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "stop-all"])
1890 7e49b6ce Michael Hanselmann
1891 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
1892 7e49b6ce Michael Hanselmann
        try:
1893 7e49b6ce Michael Hanselmann
          return fn(self, *args)
1894 d512e84b Michael Hanselmann
        except Exception, err:
1895 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
1896 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
1897 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
1898 7e49b6ce Michael Hanselmann
          raise
1899 7e49b6ce Michael Hanselmann
      finally:
1900 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
1901 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
1902 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
1903 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "start-all"])
1904 7e49b6ce Michael Hanselmann
    finally:
1905 7e49b6ce Michael Hanselmann
      # Resume watcher
1906 7e49b6ce Michael Hanselmann
      watcher_block.Close()
1907 7e49b6ce Michael Hanselmann
1908 7e49b6ce Michael Hanselmann
1909 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
1910 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
1911 7e49b6ce Michael Hanselmann

1912 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
1913 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
1914 7e49b6ce Michael Hanselmann
  @type fn: callable
1915 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
1916 7e49b6ce Michael Hanselmann

1917 7e49b6ce Michael Hanselmann
  """
1918 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
1919 7e49b6ce Michael Hanselmann
1920 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
1921 7e49b6ce Michael Hanselmann
  cl = GetClient()
1922 7e49b6ce Michael Hanselmann
1923 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
1924 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
1925 7e49b6ce Michael Hanselmann
1926 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
1927 7e49b6ce Michael Hanselmann
1928 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
1929 7e49b6ce Michael Hanselmann
  del cl
1930 7e49b6ce Michael Hanselmann
1931 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
1932 7e49b6ce Michael Hanselmann
1933 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
1934 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
1935 7e49b6ce Michael Hanselmann
1936 7e49b6ce Michael Hanselmann
1937 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
1938 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
1939 9fbfbb7b Iustin Pop
                  units=None):
1940 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
1941 137161c9 Michael Hanselmann

1942 9fbfbb7b Iustin Pop
  @type headers: dict
1943 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
1944 9fbfbb7b Iustin Pop
      the table
1945 9fbfbb7b Iustin Pop
  @type fields: list
1946 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
1947 9fbfbb7b Iustin Pop
      the data field
1948 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
1949 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
1950 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
1951 9fbfbb7b Iustin Pop
      each field
1952 9fbfbb7b Iustin Pop
  @type data: list
1953 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
1954 9fbfbb7b Iustin Pop
  @type numfields: list
1955 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
1956 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
1957 9fbfbb7b Iustin Pop
  @type unitfields: list
1958 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
1959 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
1960 9fbfbb7b Iustin Pop
  @type units: string or None
1961 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
1962 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
1963 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
1964 137161c9 Michael Hanselmann

1965 137161c9 Michael Hanselmann
  """
1966 9fbfbb7b Iustin Pop
  if units is None:
1967 9fbfbb7b Iustin Pop
    if separator:
1968 9fbfbb7b Iustin Pop
      units = "m"
1969 9fbfbb7b Iustin Pop
    else:
1970 9fbfbb7b Iustin Pop
      units = "h"
1971 9fbfbb7b Iustin Pop
1972 137161c9 Michael Hanselmann
  if numfields is None:
1973 137161c9 Michael Hanselmann
    numfields = []
1974 137161c9 Michael Hanselmann
  if unitfields is None:
1975 137161c9 Michael Hanselmann
    unitfields = []
1976 137161c9 Michael Hanselmann
1977 fe267188 Iustin Pop
  numfields = utils.FieldSet(*numfields)   # pylint: disable-msg=W0142
1978 fe267188 Iustin Pop
  unitfields = utils.FieldSet(*unitfields) # pylint: disable-msg=W0142
1979 00430f8e Iustin Pop
1980 137161c9 Michael Hanselmann
  format_fields = []
1981 137161c9 Michael Hanselmann
  for field in fields:
1982 01ca31ae Iustin Pop
    if headers and field not in headers:
1983 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
1984 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
1985 71c1af58 Iustin Pop
      # variable fields)
1986 71c1af58 Iustin Pop
      headers[field] = field
1987 137161c9 Michael Hanselmann
    if separator is not None:
1988 137161c9 Michael Hanselmann
      format_fields.append("%s")
1989 00430f8e Iustin Pop
    elif numfields.Matches(field):
1990 137161c9 Michael Hanselmann
      format_fields.append("%*s")
1991 137161c9 Michael Hanselmann
    else:
1992 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
1993 137161c9 Michael Hanselmann
1994 137161c9 Michael Hanselmann
  if separator is None:
1995 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
1996 137161c9 Michael Hanselmann
    format = ' '.join(format_fields)
1997 137161c9 Michael Hanselmann
  else:
1998 137161c9 Michael Hanselmann
    format = separator.replace("%", "%%").join(format_fields)
1999 137161c9 Michael Hanselmann
2000 137161c9 Michael Hanselmann
  for row in data:
2001 dcbd6288 Guido Trotter
    if row is None:
2002 dcbd6288 Guido Trotter
      continue
2003 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2004 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2005 137161c9 Michael Hanselmann
        try:
2006 137161c9 Michael Hanselmann
          val = int(val)
2007 691744c4 Iustin Pop
        except (TypeError, ValueError):
2008 137161c9 Michael Hanselmann
          pass
2009 137161c9 Michael Hanselmann
        else:
2010 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2011 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2012 137161c9 Michael Hanselmann
      if separator is None:
2013 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2014 137161c9 Michael Hanselmann
2015 16be8703 Iustin Pop
  result = []
2016 137161c9 Michael Hanselmann
  if headers:
2017 137161c9 Michael Hanselmann
    args = []
2018 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2019 137161c9 Michael Hanselmann
      hdr = headers[name]
2020 137161c9 Michael Hanselmann
      if separator is None:
2021 ec39d63c Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2022 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2023 137161c9 Michael Hanselmann
      args.append(hdr)
2024 16be8703 Iustin Pop
    result.append(format % tuple(args))
2025 137161c9 Michael Hanselmann
2026 ec39d63c Michael Hanselmann
  if separator is None:
2027 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2028 ec39d63c Michael Hanselmann
2029 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2030 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2031 ec39d63c Michael Hanselmann
2032 137161c9 Michael Hanselmann
  for line in data:
2033 137161c9 Michael Hanselmann
    args = []
2034 dcbd6288 Guido Trotter
    if line is None:
2035 dcbd6288 Guido Trotter
      line = ['-' for _ in fields]
2036 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2037 137161c9 Michael Hanselmann
      if separator is None:
2038 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2039 137161c9 Michael Hanselmann
      args.append(line[idx])
2040 16be8703 Iustin Pop
    result.append(format % tuple(args))
2041 16be8703 Iustin Pop
2042 16be8703 Iustin Pop
  return result
2043 3386e7a9 Iustin Pop
2044 3386e7a9 Iustin Pop
2045 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
2046 3386e7a9 Iustin Pop
  """Formats a given timestamp.
2047 3386e7a9 Iustin Pop

2048 3386e7a9 Iustin Pop
  @type ts: timestamp
2049 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
2050 3386e7a9 Iustin Pop

2051 3386e7a9 Iustin Pop
  @rtype: string
2052 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
2053 3386e7a9 Iustin Pop

2054 3386e7a9 Iustin Pop
  """
2055 e0ec0ff6 Iustin Pop
  if not isinstance (ts, (tuple, list)) or len(ts) != 2:
2056 e0ec0ff6 Iustin Pop
    return '?'
2057 3386e7a9 Iustin Pop
  sec, usec = ts
2058 3386e7a9 Iustin Pop
  return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
2059 2241e2b9 Iustin Pop
2060 2241e2b9 Iustin Pop
2061 2241e2b9 Iustin Pop
def ParseTimespec(value):
2062 2241e2b9 Iustin Pop
  """Parse a time specification.
2063 2241e2b9 Iustin Pop

2064 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
2065 2241e2b9 Iustin Pop

2066 2241e2b9 Iustin Pop
    - s: seconds
2067 2241e2b9 Iustin Pop
    - m: minutes
2068 2241e2b9 Iustin Pop
    - h: hours
2069 2241e2b9 Iustin Pop
    - d: day
2070 2241e2b9 Iustin Pop
    - w: weeks
2071 2241e2b9 Iustin Pop

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

2074 2241e2b9 Iustin Pop
  """
2075 2241e2b9 Iustin Pop
  value = str(value)
2076 2241e2b9 Iustin Pop
  if not value:
2077 2241e2b9 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed")
2078 2241e2b9 Iustin Pop
  suffix_map = {
2079 2241e2b9 Iustin Pop
    's': 1,
2080 2241e2b9 Iustin Pop
    'm': 60,
2081 2241e2b9 Iustin Pop
    'h': 3600,
2082 2241e2b9 Iustin Pop
    'd': 86400,
2083 2241e2b9 Iustin Pop
    'w': 604800,
2084 2241e2b9 Iustin Pop
    }
2085 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
2086 2241e2b9 Iustin Pop
    try:
2087 2241e2b9 Iustin Pop
      value = int(value)
2088 691744c4 Iustin Pop
    except (TypeError, ValueError):
2089 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2090 2241e2b9 Iustin Pop
  else:
2091 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
2092 2241e2b9 Iustin Pop
    value = value[:-1]
2093 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
2094 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
2095 2241e2b9 Iustin Pop
                                 " suffix passed)")
2096 2241e2b9 Iustin Pop
    try:
2097 2241e2b9 Iustin Pop
      value = int(value) * multiplier
2098 691744c4 Iustin Pop
    except (TypeError, ValueError):
2099 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2100 2241e2b9 Iustin Pop
  return value
2101 46fbdd04 Iustin Pop
2102 46fbdd04 Iustin Pop
2103 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
2104 e9e26bb3 Iustin Pop
                   filter_master=False):
2105 4040a784 Iustin Pop
  """Returns the names of online nodes.
2106 4040a784 Iustin Pop

2107 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
2108 4040a784 Iustin Pop
  the online nodes.
2109 4040a784 Iustin Pop

2110 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
2111 4040a784 Iustin Pop
      offline ones)
2112 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
2113 4040a784 Iustin Pop
  @type nowarn: boolean
2114 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
2115 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
2116 4040a784 Iustin Pop
      note is not displayed
2117 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
2118 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
2119 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
2120 e9e26bb3 Iustin Pop
      (if any)
2121 e9e26bb3 Iustin Pop
  @type filter_master: boolean
2122 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
2123 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
2124 e9e26bb3 Iustin Pop
      node name against the list)
2125 4040a784 Iustin Pop

2126 4040a784 Iustin Pop
  """
2127 4040a784 Iustin Pop
  if cl is None:
2128 4040a784 Iustin Pop
    cl = GetClient()
2129 4040a784 Iustin Pop
2130 e9e26bb3 Iustin Pop
  if secondary_ips:
2131 e9e26bb3 Iustin Pop
    name_idx = 2
2132 e9e26bb3 Iustin Pop
  else:
2133 e9e26bb3 Iustin Pop
    name_idx = 0
2134 e9e26bb3 Iustin Pop
2135 e9e26bb3 Iustin Pop
  if filter_master:
2136 e9e26bb3 Iustin Pop
    master_node = cl.QueryConfigValues(["master_node"])[0]
2137 e9e26bb3 Iustin Pop
    filter_fn = lambda x: x != master_node
2138 e9e26bb3 Iustin Pop
  else:
2139 e9e26bb3 Iustin Pop
    filter_fn = lambda _: True
2140 e9e26bb3 Iustin Pop
2141 e9e26bb3 Iustin Pop
  result = cl.QueryNodes(names=nodes, fields=["name", "offline", "sip"],
2142 2e7b8369 Iustin Pop
                         use_locking=False)
2143 4040a784 Iustin Pop
  offline = [row[0] for row in result if row[1]]
2144 4040a784 Iustin Pop
  if offline and not nowarn:
2145 1f864b60 Iustin Pop
    ToStderr("Note: skipping offline node(s): %s" % utils.CommaJoin(offline))
2146 e9e26bb3 Iustin Pop
  return [row[name_idx] for row in result if not row[1] and filter_fn(row[0])]
2147 4040a784 Iustin Pop
2148 4040a784 Iustin Pop
2149 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
2150 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
2151 46fbdd04 Iustin Pop

2152 46fbdd04 Iustin Pop
  @type stream: file object
2153 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
2154 46fbdd04 Iustin Pop
  @type txt: str
2155 46fbdd04 Iustin Pop
  @param txt: the message
2156 46fbdd04 Iustin Pop

2157 46fbdd04 Iustin Pop
  """
2158 46fbdd04 Iustin Pop
  if args:
2159 46fbdd04 Iustin Pop
    args = tuple(args)
2160 46fbdd04 Iustin Pop
    stream.write(txt % args)
2161 46fbdd04 Iustin Pop
  else:
2162 46fbdd04 Iustin Pop
    stream.write(txt)
2163 46fbdd04 Iustin Pop
  stream.write('\n')
2164 46fbdd04 Iustin Pop
  stream.flush()
2165 46fbdd04 Iustin Pop
2166 46fbdd04 Iustin Pop
2167 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
2168 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
2169 46fbdd04 Iustin Pop

2170 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
2171 46fbdd04 Iustin Pop

2172 46fbdd04 Iustin Pop
  @type txt: str
2173 46fbdd04 Iustin Pop
  @param txt: the message
2174 46fbdd04 Iustin Pop

2175 46fbdd04 Iustin Pop
  """
2176 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
2177 46fbdd04 Iustin Pop
2178 46fbdd04 Iustin Pop
2179 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
2180 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
2181 46fbdd04 Iustin Pop

2182 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
2183 46fbdd04 Iustin Pop

2184 46fbdd04 Iustin Pop
  @type txt: str
2185 46fbdd04 Iustin Pop
  @param txt: the message
2186 46fbdd04 Iustin Pop

2187 46fbdd04 Iustin Pop
  """
2188 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
2189 479636a3 Iustin Pop
2190 479636a3 Iustin Pop
2191 479636a3 Iustin Pop
class JobExecutor(object):
2192 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
2193 479636a3 Iustin Pop

2194 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
2195 479636a3 Iustin Pop
  GetResults() calls.
2196 479636a3 Iustin Pop

2197 479636a3 Iustin Pop
  """
2198 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
2199 479636a3 Iustin Pop
    self.queue = []
2200 479636a3 Iustin Pop
    if cl is None:
2201 479636a3 Iustin Pop
      cl = GetClient()
2202 479636a3 Iustin Pop
    self.cl = cl
2203 479636a3 Iustin Pop
    self.verbose = verbose
2204 23b4b983 Iustin Pop
    self.jobs = []
2205 cff5fa7f Iustin Pop
    self.opts = opts
2206 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
2207 479636a3 Iustin Pop
2208 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
2209 23b4b983 Iustin Pop
    """Record a job for later submit.
2210 479636a3 Iustin Pop

2211 479636a3 Iustin Pop
    @type name: string
2212 479636a3 Iustin Pop
    @param name: a description of the job, will be used in WaitJobSet
2213 479636a3 Iustin Pop
    """
2214 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
2215 23b4b983 Iustin Pop
    self.queue.append((name, ops))
2216 23b4b983 Iustin Pop
2217 23b4b983 Iustin Pop
  def SubmitPending(self):
2218 23b4b983 Iustin Pop
    """Submit all pending jobs.
2219 23b4b983 Iustin Pop

2220 23b4b983 Iustin Pop
    """
2221 23b4b983 Iustin Pop
    results = self.cl.SubmitManyJobs([row[1] for row in self.queue])
2222 5299e61f Iustin Pop
    for (idx, ((status, data), (name, _))) in enumerate(zip(results,
2223 5299e61f Iustin Pop
                                                            self.queue)):
2224 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
2225 5299e61f Iustin Pop
2226 5299e61f Iustin Pop
  def _ChooseJob(self):
2227 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
2228 5299e61f Iustin Pop

2229 5299e61f Iustin Pop
    """
2230 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
2231 5299e61f Iustin Pop
2232 5299e61f Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs], ["status"])
2233 5299e61f Iustin Pop
    assert result
2234 5299e61f Iustin Pop
2235 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
2236 5299e61f Iustin Pop
      if status[0] in (constants.JOB_STATUS_QUEUED,
2237 5299e61f Iustin Pop
                    constants.JOB_STATUS_WAITLOCK,
2238 5299e61f Iustin Pop
                    constants.JOB_STATUS_CANCELING):
2239 5299e61f Iustin Pop
        # job is still waiting
2240 5299e61f Iustin Pop
        continue
2241 5299e61f Iustin Pop
      # good candidate found
2242 5299e61f Iustin Pop
      self.jobs.remove(job_data)
2243 5299e61f Iustin Pop
      return job_data
2244 5299e61f Iustin Pop
2245 5299e61f Iustin Pop
    # no job found
2246 5299e61f Iustin Pop
    return self.jobs.pop(0)
2247 479636a3 Iustin Pop
2248 479636a3 Iustin Pop
  def GetResults(self):
2249 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
2250 479636a3 Iustin Pop

2251 479636a3 Iustin Pop
    @rtype: list
2252 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
2253 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
2254 479636a3 Iustin Pop
        there will be the error message
2255 479636a3 Iustin Pop

2256 479636a3 Iustin Pop
    """
2257 23b4b983 Iustin Pop
    if not self.jobs:
2258 23b4b983 Iustin Pop
      self.SubmitPending()
2259 479636a3 Iustin Pop
    results = []
2260 479636a3 Iustin Pop
    if self.verbose:
2261 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
2262 23b4b983 Iustin Pop
      if ok_jobs:
2263 1f864b60 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
2264 5299e61f Iustin Pop
2265 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
2266 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
2267 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
2268 c63355f2 Iustin Pop
      ToStderr("Failed to submit job for %s: %s", name, jid)
2269 c63355f2 Iustin Pop
      results.append((idx, False, jid))
2270 5299e61f Iustin Pop
2271 5299e61f Iustin Pop
    while self.jobs:
2272 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
2273 5299e61f Iustin Pop
      ToStdout("Waiting for job %s for %s...", jid, name)
2274 479636a3 Iustin Pop
      try:
2275 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
2276 479636a3 Iustin Pop
        success = True
2277 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
2278 479636a3 Iustin Pop
        _, job_result = FormatError(err)
2279 479636a3 Iustin Pop
        success = False
2280 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
2281 479636a3 Iustin Pop
        ToStderr("Job %s for %s has failed: %s", jid, name, job_result)
2282 479636a3 Iustin Pop
2283 5299e61f Iustin Pop
      results.append((idx, success, job_result))
2284 5299e61f Iustin Pop
2285 5299e61f Iustin Pop
    # sort based on the index, then drop it
2286 5299e61f Iustin Pop
    results.sort()
2287 5299e61f Iustin Pop
    results = [i[1:] for i in results]
2288 5299e61f Iustin Pop
2289 479636a3 Iustin Pop
    return results
2290 479636a3 Iustin Pop
2291 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
2292 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
2293 479636a3 Iustin Pop

2294 479636a3 Iustin Pop
    @type wait: boolean
2295 479636a3 Iustin Pop
    @param wait: whether to wait or not
2296 479636a3 Iustin Pop

2297 479636a3 Iustin Pop
    """
2298 479636a3 Iustin Pop
    if wait:
2299 479636a3 Iustin Pop
      return self.GetResults()
2300 479636a3 Iustin Pop
    else:
2301 23b4b983 Iustin Pop
      if not self.jobs:
2302 23b4b983 Iustin Pop
        self.SubmitPending()
2303 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
2304 23b4b983 Iustin Pop
        if status:
2305 23b4b983 Iustin Pop
          ToStdout("%s: %s", result, name)
2306 23b4b983 Iustin Pop
        else:
2307 23b4b983 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)