Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 82599b3e

History | View | Annotate | Download (93.9 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 18009c1e Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 a744b676 Manuel Franceschini
from ganeti import netutils
42 ee3aedff Michael Hanselmann
from ganeti import qlang
43 a8083063 Iustin Pop
44 c38c44ad Michael Hanselmann
from optparse import (OptionParser, TitledHelpFormatter,
45 38206f3c Iustin Pop
                      Option, OptionValueError)
46 a8083063 Iustin Pop
47 03298ebe Michael Hanselmann
48 4abc4f1e Iustin Pop
__all__ = [
49 4abc4f1e Iustin Pop
  # Command line options
50 fdad8c4d Balazs Lecz
  "ADD_UIDS_OPT",
51 e7e09483 Iustin Pop
  "ALLOCATABLE_OPT",
52 90e99856 Adeodato Simo
  "ALLOC_POLICY_OPT",
53 2d5e7ae1 Iustin Pop
  "ALL_OPT",
54 4c61d894 Iustin Pop
  "AUTO_PROMOTE_OPT",
55 e00f7a05 Iustin Pop
  "AUTO_REPLACE_OPT",
56 087ed2ed Iustin Pop
  "BACKEND_OPT",
57 61a14bb3 Iustin Pop
  "BLK_OS_OPT",
58 f91e255a Iustin Pop
  "CAPAB_MASTER_OPT",
59 53919782 Iustin Pop
  "CAPAB_VM_OPT",
60 baef337d Iustin Pop
  "CLEANUP_OPT",
61 3db3eb2a Michael Hanselmann
  "CLUSTER_DOMAIN_SECRET_OPT",
62 4abc4f1e Iustin Pop
  "CONFIRM_OPT",
63 e32df528 Iustin Pop
  "CP_SIZE_OPT",
64 4abc4f1e Iustin Pop
  "DEBUG_OPT",
65 a0c9776a Iustin Pop
  "DEBUG_SIMERR_OPT",
66 4b038a1e Iustin Pop
  "DISKIDX_OPT",
67 e3876ccb Iustin Pop
  "DISK_OPT",
68 4b038a1e Iustin Pop
  "DISK_TEMPLATE_OPT",
69 771734c9 Iustin Pop
  "DRAINED_OPT",
70 a0a6ff34 Iustin Pop
  "DRY_RUN_OPT",
71 26591bfd Luca Bigliardi
  "DRBD_HELPER_OPT",
72 7ea7bcf6 Iustin Pop
  "EARLY_RELEASE_OPT",
73 383a3591 Iustin Pop
  "ENABLED_HV_OPT",
74 14e9e7f3 Iustin Pop
  "ERROR_CODES_OPT",
75 4abc4f1e Iustin Pop
  "FIELDS_OPT",
76 4a25828c Iustin Pop
  "FILESTORE_DIR_OPT",
77 0f87c43e Iustin Pop
  "FILESTORE_DRIVER_OPT",
78 06073e85 Guido Trotter
  "FORCE_OPT",
79 06073e85 Guido Trotter
  "FORCE_VARIANT_OPT",
80 29392516 Iustin Pop
  "GLOBAL_FILEDIR_OPT",
81 61a14bb3 Iustin Pop
  "HID_OS_OPT",
82 073271f6 Iustin Pop
  "HVLIST_OPT",
83 48f212d7 Iustin Pop
  "HVOPTS_OPT",
84 236fd9c4 Iustin Pop
  "HYPERVISOR_OPT",
85 4eb62659 Iustin Pop
  "IALLOCATOR_OPT",
86 bf4af505 Apollon Oikonomopoulos
  "DEFAULT_IALLOCATOR_OPT",
87 e588764d Iustin Pop
  "IDENTIFY_DEFAULTS_OPT",
88 82a786d5 Iustin Pop
  "IGNORE_CONSIST_OPT",
89 b6e841a8 Iustin Pop
  "IGNORE_FAILURES_OPT",
90 b44bd844 Michael Hanselmann
  "IGNORE_OFFLINE_OPT",
91 8d8d650c Michael Hanselmann
  "IGNORE_REMOVE_FAILURES_OPT",
92 ee3f9578 Iustin Pop
  "IGNORE_SECONDARIES_OPT",
93 05586c90 Iustin Pop
  "IGNORE_SIZE_OPT",
94 19b9ba9a Michael Hanselmann
  "INTERVAL_OPT",
95 e3646f22 Iustin Pop
  "MAC_PREFIX_OPT",
96 3953242f Iustin Pop
  "MAINTAIN_NODE_HEALTH_OPT",
97 29392516 Iustin Pop
  "MASTER_NETDEV_OPT",
98 771734c9 Iustin Pop
  "MC_OPT",
99 783a6c0b Iustin Pop
  "MIGRATION_MODE_OPT",
100 7d3a9fab Iustin Pop
  "NET_OPT",
101 6d4a1656 Michael Hanselmann
  "NEW_CLUSTER_CERT_OPT",
102 3db3eb2a Michael Hanselmann
  "NEW_CLUSTER_DOMAIN_SECRET_OPT",
103 6b7d5878 Michael Hanselmann
  "NEW_CONFD_HMAC_KEY_OPT",
104 6d4a1656 Michael Hanselmann
  "NEW_RAPI_CERT_OPT",
105 a14db5ff Iustin Pop
  "NEW_SECONDARY_OPT",
106 4fbc93dd Iustin Pop
  "NIC_PARAMS_OPT",
107 7edc4637 Iustin Pop
  "NODE_LIST_OPT",
108 990b7886 Iustin Pop
  "NODE_PLACEMENT_OPT",
109 5fbbd028 Guido Trotter
  "NODEGROUP_OPT",
110 a535cef7 René Nussbaumer
  "NODE_PARAMS_OPT",
111 dd94e9f6 René Nussbaumer
  "NODE_POWERED_OPT",
112 26591bfd Luca Bigliardi
  "NODRBD_STORAGE_OPT",
113 4abc4f1e Iustin Pop
  "NOHDR_OPT",
114 91e0748c Iustin Pop
  "NOIPCHECK_OPT",
115 25a8792c Iustin Pop
  "NO_INSTALL_OPT",
116 460d22be Iustin Pop
  "NONAMECHECK_OPT",
117 831040bf Iustin Pop
  "NOLVM_STORAGE_OPT",
118 29392516 Iustin Pop
  "NOMODIFY_ETCHOSTS_OPT",
119 b989b9d9 Ken Wehr
  "NOMODIFY_SSH_SETUP_OPT",
120 26023ecd Iustin Pop
  "NONICS_OPT",
121 f2a0828c Iustin Pop
  "NONLIVE_OPT",
122 14e9e7f3 Iustin Pop
  "NONPLUS1_OPT",
123 44c44832 Iustin Pop
  "NOSHUTDOWN_OPT",
124 edeb878a Iustin Pop
  "NOSTART_OPT",
125 fcdde7f2 Iustin Pop
  "NOSSH_KEYCHECK_OPT",
126 58371861 Iustin Pop
  "NOVOTING_OPT",
127 3f75b4f3 Iustin Pop
  "NWSYNC_OPT",
128 a72d0a79 Iustin Pop
  "ON_PRIMARY_OPT",
129 feb09e6a Iustin Pop
  "ON_SECONDARY_OPT",
130 771734c9 Iustin Pop
  "OFFLINE_OPT",
131 062a7100 Iustin Pop
  "OSPARAMS_OPT",
132 d3ed23ff Iustin Pop
  "OS_OPT",
133 ff00c1a7 Iustin Pop
  "OS_SIZE_OPT",
134 b883637f René Nussbaumer
  "PREALLOC_WIPE_DISKS_OPT",
135 e7323b5e Manuel Franceschini
  "PRIMARY_IP_VERSION_OPT",
136 84a5b33c Michael Hanselmann
  "PRIORITY_OPT",
137 6d4a1656 Michael Hanselmann
  "RAPI_CERT_OPT",
138 b8d0f938 Iustin Pop
  "READD_OPT",
139 12054861 Iustin Pop
  "REBOOT_TYPE_OPT",
140 8d8d650c Michael Hanselmann
  "REMOVE_INSTANCE_OPT",
141 fdad8c4d Balazs Lecz
  "REMOVE_UIDS_OPT",
142 f38ea602 Iustin Pop
  "RESERVED_LVS_OPT",
143 31d97b2a Guido Trotter
  "ROMAN_OPT",
144 8d823629 Iustin Pop
  "SECONDARY_IP_OPT",
145 67840b40 Iustin Pop
  "SELECT_OS_OPT",
146 4abc4f1e Iustin Pop
  "SEP_OPT",
147 fdcf4d84 Iustin Pop
  "SHOWCMD_OPT",
148 7e5eaaa8 Guido Trotter
  "SHUTDOWN_TIMEOUT_OPT",
149 f36d7d81 Iustin Pop
  "SINGLE_NODE_OPT",
150 df62e5db Iustin Pop
  "SRC_DIR_OPT",
151 df62e5db Iustin Pop
  "SRC_NODE_OPT",
152 4abc4f1e Iustin Pop
  "SUBMIT_OPT",
153 99a8c799 Iustin Pop
  "STATIC_OPT",
154 4abc4f1e Iustin Pop
  "SYNC_OPT",
155 4abc4f1e Iustin Pop
  "TAG_SRC_OPT",
156 b5762e2a Guido Trotter
  "TIMEOUT_OPT",
157 1338f2b4 Balazs Lecz
  "UIDPOOL_OPT",
158 4abc4f1e Iustin Pop
  "USEUNITS_OPT",
159 74adc100 Iustin Pop
  "USE_REPL_NET_OPT",
160 9cdb9578 Iustin Pop
  "VERBOSE_OPT",
161 b58726e8 Iustin Pop
  "VG_NAME_OPT",
162 1f587d3d Iustin Pop
  "YES_DOIT_OPT",
163 4abc4f1e Iustin Pop
  # Generic functions for CLI programs
164 4abc4f1e Iustin Pop
  "GenericMain",
165 d77490c5 Iustin Pop
  "GenericInstanceCreate",
166 ee3aedff Michael Hanselmann
  "GenericList",
167 ee3aedff Michael Hanselmann
  "GenericListFields",
168 4abc4f1e Iustin Pop
  "GetClient",
169 4abc4f1e Iustin Pop
  "GetOnlineNodes",
170 4abc4f1e Iustin Pop
  "JobExecutor",
171 4abc4f1e Iustin Pop
  "JobSubmittedException",
172 4abc4f1e Iustin Pop
  "ParseTimespec",
173 7e49b6ce Michael Hanselmann
  "RunWhileClusterStopped",
174 4abc4f1e Iustin Pop
  "SubmitOpCode",
175 4abc4f1e Iustin Pop
  "SubmitOrSend",
176 4abc4f1e Iustin Pop
  "UsesRPC",
177 4abc4f1e Iustin Pop
  # Formatting functions
178 4abc4f1e Iustin Pop
  "ToStderr", "ToStdout",
179 4abc4f1e Iustin Pop
  "FormatError",
180 ee3aedff Michael Hanselmann
  "FormatQueryResult",
181 acd19189 René Nussbaumer
  "FormatParameterDict",
182 4abc4f1e Iustin Pop
  "GenerateTable",
183 4abc4f1e Iustin Pop
  "AskUser",
184 4abc4f1e Iustin Pop
  "FormatTimestamp",
185 8a7f1c61 Michael Hanselmann
  "FormatLogMessage",
186 4abc4f1e Iustin Pop
  # Tags functions
187 4abc4f1e Iustin Pop
  "ListTags",
188 4abc4f1e Iustin Pop
  "AddTags",
189 4abc4f1e Iustin Pop
  "RemoveTags",
190 4abc4f1e Iustin Pop
  # command line options support infrastructure
191 4abc4f1e Iustin Pop
  "ARGS_MANY_INSTANCES",
192 4abc4f1e Iustin Pop
  "ARGS_MANY_NODES",
193 667dbd6b Adeodato Simo
  "ARGS_MANY_GROUPS",
194 4abc4f1e Iustin Pop
  "ARGS_NONE",
195 4abc4f1e Iustin Pop
  "ARGS_ONE_INSTANCE",
196 4abc4f1e Iustin Pop
  "ARGS_ONE_NODE",
197 667dbd6b Adeodato Simo
  "ARGS_ONE_GROUP",
198 f9faf9c3 René Nussbaumer
  "ARGS_ONE_OS",
199 4abc4f1e Iustin Pop
  "ArgChoice",
200 4abc4f1e Iustin Pop
  "ArgCommand",
201 4abc4f1e Iustin Pop
  "ArgFile",
202 667dbd6b Adeodato Simo
  "ArgGroup",
203 4abc4f1e Iustin Pop
  "ArgHost",
204 4abc4f1e Iustin Pop
  "ArgInstance",
205 4abc4f1e Iustin Pop
  "ArgJobId",
206 4abc4f1e Iustin Pop
  "ArgNode",
207 f9faf9c3 René Nussbaumer
  "ArgOs",
208 4abc4f1e Iustin Pop
  "ArgSuggest",
209 4abc4f1e Iustin Pop
  "ArgUnknown",
210 4abc4f1e Iustin Pop
  "OPT_COMPL_INST_ADD_NODES",
211 4abc4f1e Iustin Pop
  "OPT_COMPL_MANY_NODES",
212 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_IALLOCATOR",
213 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_INSTANCE",
214 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_NODE",
215 36e247e1 Guido Trotter
  "OPT_COMPL_ONE_NODEGROUP",
216 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_OS",
217 4abc4f1e Iustin Pop
  "cli_option",
218 4abc4f1e Iustin Pop
  "SplitNodeOption",
219 07150497 Guido Trotter
  "CalculateOSNames",
220 a4ebd726 Michael Hanselmann
  "ParseFields",
221 eb28ecf6 Guido Trotter
  "COMMON_CREATE_OPTS",
222 4abc4f1e Iustin Pop
  ]
223 846baef9 Iustin Pop
224 8b46606c Guido Trotter
NO_PREFIX = "no_"
225 8b46606c Guido Trotter
UN_PREFIX = "-"
226 846baef9 Iustin Pop
227 84a5b33c Michael Hanselmann
#: Priorities (sorted)
228 84a5b33c Michael Hanselmann
_PRIORITY_NAMES = [
229 84a5b33c Michael Hanselmann
  ("low", constants.OP_PRIO_LOW),
230 84a5b33c Michael Hanselmann
  ("normal", constants.OP_PRIO_NORMAL),
231 84a5b33c Michael Hanselmann
  ("high", constants.OP_PRIO_HIGH),
232 84a5b33c Michael Hanselmann
  ]
233 84a5b33c Michael Hanselmann
234 84a5b33c Michael Hanselmann
#: Priority dictionary for easier lookup
235 84a5b33c Michael Hanselmann
# TODO: Replace this and _PRIORITY_NAMES with a single sorted dictionary once
236 84a5b33c Michael Hanselmann
# we migrate to Python 2.6
237 84a5b33c Michael Hanselmann
_PRIONAME_TO_VALUE = dict(_PRIORITY_NAMES)
238 84a5b33c Michael Hanselmann
239 ee3aedff Michael Hanselmann
# Query result status for clients
240 ee3aedff Michael Hanselmann
(QR_NORMAL,
241 ee3aedff Michael Hanselmann
 QR_UNKNOWN,
242 ee3aedff Michael Hanselmann
 QR_INCOMPLETE) = range(3)
243 ee3aedff Michael Hanselmann
244 03298ebe Michael Hanselmann
245 863d7f46 Michael Hanselmann
class _Argument:
246 7260cfbe Iustin Pop
  def __init__(self, min=0, max=None): # pylint: disable-msg=W0622
247 863d7f46 Michael Hanselmann
    self.min = min
248 863d7f46 Michael Hanselmann
    self.max = max
249 863d7f46 Michael Hanselmann
250 863d7f46 Michael Hanselmann
  def __repr__(self):
251 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s>" %
252 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max))
253 863d7f46 Michael Hanselmann
254 863d7f46 Michael Hanselmann
255 863d7f46 Michael Hanselmann
class ArgSuggest(_Argument):
256 863d7f46 Michael Hanselmann
  """Suggesting argument.
257 863d7f46 Michael Hanselmann

258 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
259 863d7f46 Michael Hanselmann

260 863d7f46 Michael Hanselmann
  """
261 7260cfbe Iustin Pop
  # pylint: disable-msg=W0622
262 863d7f46 Michael Hanselmann
  def __init__(self, min=0, max=None, choices=None):
263 863d7f46 Michael Hanselmann
    _Argument.__init__(self, min=min, max=max)
264 863d7f46 Michael Hanselmann
    self.choices = choices
265 863d7f46 Michael Hanselmann
266 863d7f46 Michael Hanselmann
  def __repr__(self):
267 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s choices=%r>" %
268 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max, self.choices))
269 863d7f46 Michael Hanselmann
270 863d7f46 Michael Hanselmann
271 863d7f46 Michael Hanselmann
class ArgChoice(ArgSuggest):
272 863d7f46 Michael Hanselmann
  """Choice argument.
273 863d7f46 Michael Hanselmann

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

277 863d7f46 Michael Hanselmann
  """
278 863d7f46 Michael Hanselmann
279 863d7f46 Michael Hanselmann
280 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
281 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
282 863d7f46 Michael Hanselmann

283 863d7f46 Michael Hanselmann
  """
284 863d7f46 Michael Hanselmann
285 863d7f46 Michael Hanselmann
286 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
287 863d7f46 Michael Hanselmann
  """Instances argument.
288 863d7f46 Michael Hanselmann

289 863d7f46 Michael Hanselmann
  """
290 863d7f46 Michael Hanselmann
291 863d7f46 Michael Hanselmann
292 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
293 863d7f46 Michael Hanselmann
  """Node argument.
294 863d7f46 Michael Hanselmann

295 863d7f46 Michael Hanselmann
  """
296 863d7f46 Michael Hanselmann
297 667dbd6b Adeodato Simo
298 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
299 667dbd6b Adeodato Simo
  """Node group argument.
300 667dbd6b Adeodato Simo

301 667dbd6b Adeodato Simo
  """
302 667dbd6b Adeodato Simo
303 667dbd6b Adeodato Simo
304 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
305 863d7f46 Michael Hanselmann
  """Job ID argument.
306 863d7f46 Michael Hanselmann

307 863d7f46 Michael Hanselmann
  """
308 863d7f46 Michael Hanselmann
309 863d7f46 Michael Hanselmann
310 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
311 863d7f46 Michael Hanselmann
  """File path argument.
312 863d7f46 Michael Hanselmann

313 863d7f46 Michael Hanselmann
  """
314 863d7f46 Michael Hanselmann
315 863d7f46 Michael Hanselmann
316 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
317 863d7f46 Michael Hanselmann
  """Command argument.
318 863d7f46 Michael Hanselmann

319 863d7f46 Michael Hanselmann
  """
320 863d7f46 Michael Hanselmann
321 863d7f46 Michael Hanselmann
322 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
323 83ec7961 Michael Hanselmann
  """Host argument.
324 83ec7961 Michael Hanselmann

325 83ec7961 Michael Hanselmann
  """
326 83ec7961 Michael Hanselmann
327 83ec7961 Michael Hanselmann
328 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
329 f9faf9c3 René Nussbaumer
  """OS argument.
330 f9faf9c3 René Nussbaumer

331 f9faf9c3 René Nussbaumer
  """
332 f9faf9c3 René Nussbaumer
333 f9faf9c3 René Nussbaumer
334 4a265c08 Michael Hanselmann
ARGS_NONE = []
335 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
336 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
337 667dbd6b Adeodato Simo
ARGS_MANY_GROUPS = [ArgGroup()]
338 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
339 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
340 667dbd6b Adeodato Simo
ARGS_ONE_GROUP = [ArgInstance(min=1, max=1)]
341 f9faf9c3 René Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
342 4a265c08 Michael Hanselmann
343 4a265c08 Michael Hanselmann
344 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
345 846baef9 Iustin Pop
  """Extract the tag type object.
346 846baef9 Iustin Pop

347 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
348 846baef9 Iustin Pop

349 846baef9 Iustin Pop
  """
350 846baef9 Iustin Pop
  if not hasattr(opts, "tag_type"):
351 846baef9 Iustin Pop
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
352 846baef9 Iustin Pop
  kind = opts.tag_type
353 846baef9 Iustin Pop
  if kind == constants.TAG_CLUSTER:
354 846baef9 Iustin Pop
    retval = kind, kind
355 846baef9 Iustin Pop
  elif kind == constants.TAG_NODE or kind == constants.TAG_INSTANCE:
356 846baef9 Iustin Pop
    if not args:
357 0c434948 Iustin Pop
      raise errors.OpPrereqError("no arguments passed to the command")
358 846baef9 Iustin Pop
    name = args.pop(0)
359 846baef9 Iustin Pop
    retval = kind, name
360 846baef9 Iustin Pop
  else:
361 846baef9 Iustin Pop
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
362 846baef9 Iustin Pop
  return retval
363 846baef9 Iustin Pop
364 846baef9 Iustin Pop
365 810c50b7 Iustin Pop
def _ExtendTags(opts, args):
366 810c50b7 Iustin Pop
  """Extend the args if a source file has been given.
367 810c50b7 Iustin Pop

368 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
369 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
370 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
371 810c50b7 Iustin Pop

372 810c50b7 Iustin Pop
  """
373 810c50b7 Iustin Pop
  fname = opts.tags_source
374 810c50b7 Iustin Pop
  if fname is None:
375 810c50b7 Iustin Pop
    return
376 810c50b7 Iustin Pop
  if fname == "-":
377 810c50b7 Iustin Pop
    new_fh = sys.stdin
378 810c50b7 Iustin Pop
  else:
379 810c50b7 Iustin Pop
    new_fh = open(fname, "r")
380 810c50b7 Iustin Pop
  new_data = []
381 810c50b7 Iustin Pop
  try:
382 810c50b7 Iustin Pop
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
383 810c50b7 Iustin Pop
    # because of python bug 1633941
384 810c50b7 Iustin Pop
    while True:
385 810c50b7 Iustin Pop
      line = new_fh.readline()
386 810c50b7 Iustin Pop
      if not line:
387 810c50b7 Iustin Pop
        break
388 810c50b7 Iustin Pop
      new_data.append(line.strip())
389 810c50b7 Iustin Pop
  finally:
390 810c50b7 Iustin Pop
    new_fh.close()
391 810c50b7 Iustin Pop
  args.extend(new_data)
392 810c50b7 Iustin Pop
393 810c50b7 Iustin Pop
394 846baef9 Iustin Pop
def ListTags(opts, args):
395 846baef9 Iustin Pop
  """List the tags on a given object.
396 846baef9 Iustin Pop

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

402 846baef9 Iustin Pop
  """
403 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
404 7699c3af Iustin Pop
  cl = GetClient()
405 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
406 846baef9 Iustin Pop
  result = list(result)
407 846baef9 Iustin Pop
  result.sort()
408 846baef9 Iustin Pop
  for tag in result:
409 03298ebe Michael Hanselmann
    ToStdout(tag)
410 846baef9 Iustin Pop
411 846baef9 Iustin Pop
412 846baef9 Iustin Pop
def AddTags(opts, args):
413 846baef9 Iustin Pop
  """Add tags on a given object.
414 846baef9 Iustin Pop

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

420 846baef9 Iustin Pop
  """
421 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
422 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
423 846baef9 Iustin Pop
  if not args:
424 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be added")
425 d1602edc Iustin Pop
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
426 af1a81d1 Michael Hanselmann
  SubmitOpCode(op, opts=opts)
427 846baef9 Iustin Pop
428 846baef9 Iustin Pop
429 846baef9 Iustin Pop
def RemoveTags(opts, args):
430 846baef9 Iustin Pop
  """Remove tags from a given object.
431 846baef9 Iustin Pop

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

437 846baef9 Iustin Pop
  """
438 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
439 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
440 846baef9 Iustin Pop
  if not args:
441 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be removed")
442 3f0ab95f Iustin Pop
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
443 af1a81d1 Michael Hanselmann
  SubmitOpCode(op, opts=opts)
444 846baef9 Iustin Pop
445 a8083063 Iustin Pop
446 8929d28c Iustin Pop
def check_unit(option, opt, value): # pylint: disable-msg=W0613
447 65fe4693 Iustin Pop
  """OptParsers custom converter for units.
448 65fe4693 Iustin Pop

449 65fe4693 Iustin Pop
  """
450 a8083063 Iustin Pop
  try:
451 a8083063 Iustin Pop
    return utils.ParseUnit(value)
452 a8083063 Iustin Pop
  except errors.UnitParseError, err:
453 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
454 a8083063 Iustin Pop
455 a8083063 Iustin Pop
456 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
457 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
458 a8469393 Iustin Pop

459 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
460 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
461 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
462 a8469393 Iustin Pop
  have value=True.
463 a8469393 Iustin Pop

464 a8469393 Iustin Pop
  @type opt: string
465 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
466 a8469393 Iustin Pop
      data, used in building error messages
467 a8469393 Iustin Pop
  @type data: string
468 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
469 a8469393 Iustin Pop
  @rtype: dict
470 a8469393 Iustin Pop
  @return: {key=val, key=val}
471 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
472 a8469393 Iustin Pop

473 a8469393 Iustin Pop
  """
474 a8469393 Iustin Pop
  kv_dict = {}
475 4f31882e Guido Trotter
  if data:
476 1b3a7656 Iustin Pop
    for elem in utils.UnescapeAndSplit(data, sep=","):
477 4f31882e Guido Trotter
      if "=" in elem:
478 4f31882e Guido Trotter
        key, val = elem.split("=", 1)
479 a8469393 Iustin Pop
      else:
480 4f31882e Guido Trotter
        if elem.startswith(NO_PREFIX):
481 4f31882e Guido Trotter
          key, val = elem[len(NO_PREFIX):], False
482 4f31882e Guido Trotter
        elif elem.startswith(UN_PREFIX):
483 4f31882e Guido Trotter
          key, val = elem[len(UN_PREFIX):], None
484 4f31882e Guido Trotter
        else:
485 4f31882e Guido Trotter
          key, val = elem, True
486 4f31882e Guido Trotter
      if key in kv_dict:
487 4f31882e Guido Trotter
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
488 4f31882e Guido Trotter
                                    (key, opt))
489 4f31882e Guido Trotter
      kv_dict[key] = val
490 a8469393 Iustin Pop
  return kv_dict
491 a8469393 Iustin Pop
492 a8469393 Iustin Pop
493 8929d28c Iustin Pop
def check_ident_key_val(option, opt, value):  # pylint: disable-msg=W0613
494 552c8dff Michael Hanselmann
  """Custom parser for ident:key=val,key=val options.
495 552c8dff Michael Hanselmann

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

499 a8469393 Iustin Pop
  """
500 a8469393 Iustin Pop
  if ":" not in value:
501 8b46606c Guido Trotter
    ident, rest = value, ''
502 a8469393 Iustin Pop
  else:
503 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
504 8b46606c Guido Trotter
505 8b46606c Guido Trotter
  if ident.startswith(NO_PREFIX):
506 8b46606c Guido Trotter
    if rest:
507 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
508 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
509 8b46606c Guido Trotter
    retval = (ident[len(NO_PREFIX):], False)
510 8b46606c Guido Trotter
  elif ident.startswith(UN_PREFIX):
511 8b46606c Guido Trotter
    if rest:
512 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
513 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
514 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
515 8b46606c Guido Trotter
  else:
516 a8469393 Iustin Pop
    kv_dict = _SplitKeyVal(opt, rest)
517 a8469393 Iustin Pop
    retval = (ident, kv_dict)
518 a8469393 Iustin Pop
  return retval
519 a8469393 Iustin Pop
520 a8469393 Iustin Pop
521 8929d28c Iustin Pop
def check_key_val(option, opt, value):  # pylint: disable-msg=W0613
522 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
523 552c8dff Michael Hanselmann

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

526 a8469393 Iustin Pop
  """
527 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
528 a8469393 Iustin Pop
529 a8469393 Iustin Pop
530 e7b61bb0 Iustin Pop
def check_bool(option, opt, value): # pylint: disable-msg=W0613
531 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
532 e7b61bb0 Iustin Pop

533 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
534 e7b61bb0 Iustin Pop

535 e7b61bb0 Iustin Pop
  """
536 e7b61bb0 Iustin Pop
  value = value.lower()
537 e7b61bb0 Iustin Pop
  if value == constants.VALUE_FALSE or value == "no":
538 e7b61bb0 Iustin Pop
    return False
539 e7b61bb0 Iustin Pop
  elif value == constants.VALUE_TRUE or value == "yes":
540 e7b61bb0 Iustin Pop
    return True
541 e7b61bb0 Iustin Pop
  else:
542 e7b61bb0 Iustin Pop
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
543 e7b61bb0 Iustin Pop
544 e7b61bb0 Iustin Pop
545 63d44c55 Michael Hanselmann
# completion_suggestion is normally a list. Using numeric values not evaluating
546 63d44c55 Michael Hanselmann
# to False for dynamic completion.
547 63d44c55 Michael Hanselmann
(OPT_COMPL_MANY_NODES,
548 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_NODE,
549 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_INSTANCE,
550 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_OS,
551 2d3ed64b Michael Hanselmann
 OPT_COMPL_ONE_IALLOCATOR,
552 36e247e1 Guido Trotter
 OPT_COMPL_INST_ADD_NODES,
553 36e247e1 Guido Trotter
 OPT_COMPL_ONE_NODEGROUP) = range(100, 107)
554 63d44c55 Michael Hanselmann
555 63d44c55 Michael Hanselmann
OPT_COMPL_ALL = frozenset([
556 63d44c55 Michael Hanselmann
  OPT_COMPL_MANY_NODES,
557 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_NODE,
558 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_INSTANCE,
559 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_OS,
560 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_IALLOCATOR,
561 2d3ed64b Michael Hanselmann
  OPT_COMPL_INST_ADD_NODES,
562 36e247e1 Guido Trotter
  OPT_COMPL_ONE_NODEGROUP,
563 63d44c55 Michael Hanselmann
  ])
564 63d44c55 Michael Hanselmann
565 63d44c55 Michael Hanselmann
566 552c8dff Michael Hanselmann
class CliOption(Option):
567 552c8dff Michael Hanselmann
  """Custom option class for optparse.
568 a8469393 Iustin Pop

569 a8469393 Iustin Pop
  """
570 863d7f46 Michael Hanselmann
  ATTRS = Option.ATTRS + [
571 863d7f46 Michael Hanselmann
    "completion_suggest",
572 863d7f46 Michael Hanselmann
    ]
573 552c8dff Michael Hanselmann
  TYPES = Option.TYPES + (
574 552c8dff Michael Hanselmann
    "identkeyval",
575 552c8dff Michael Hanselmann
    "keyval",
576 552c8dff Michael Hanselmann
    "unit",
577 e7b61bb0 Iustin Pop
    "bool",
578 552c8dff Michael Hanselmann
    )
579 552c8dff Michael Hanselmann
  TYPE_CHECKER = Option.TYPE_CHECKER.copy()
580 552c8dff Michael Hanselmann
  TYPE_CHECKER["identkeyval"] = check_ident_key_val
581 a8469393 Iustin Pop
  TYPE_CHECKER["keyval"] = check_key_val
582 552c8dff Michael Hanselmann
  TYPE_CHECKER["unit"] = check_unit
583 e7b61bb0 Iustin Pop
  TYPE_CHECKER["bool"] = check_bool
584 a8469393 Iustin Pop
585 a8469393 Iustin Pop
586 a8083063 Iustin Pop
# optparse.py sets make_option, so we do it for our own option class, too
587 a8083063 Iustin Pop
cli_option = CliOption
588 a8083063 Iustin Pop
589 a8083063 Iustin Pop
590 771734c9 Iustin Pop
_YORNO = "yes|no"
591 771734c9 Iustin Pop
592 ea34193f Iustin Pop
DEBUG_OPT = cli_option("-d", "--debug", default=0, action="count",
593 ea34193f Iustin Pop
                       help="Increase debugging level")
594 c38c44ad Michael Hanselmann
595 c38c44ad Michael Hanselmann
NOHDR_OPT = cli_option("--no-headers", default=False,
596 c38c44ad Michael Hanselmann
                       action="store_true", dest="no_headers",
597 c38c44ad Michael Hanselmann
                       help="Don't display column headers")
598 c38c44ad Michael Hanselmann
599 c38c44ad Michael Hanselmann
SEP_OPT = cli_option("--separator", default=None,
600 c38c44ad Michael Hanselmann
                     action="store", dest="separator",
601 c38c44ad Michael Hanselmann
                     help=("Separator between output fields"
602 c38c44ad Michael Hanselmann
                           " (defaults to one space)"))
603 c38c44ad Michael Hanselmann
604 c38c44ad Michael Hanselmann
USEUNITS_OPT = cli_option("--units", default=None,
605 c38c44ad Michael Hanselmann
                          dest="units", choices=('h', 'm', 'g', 't'),
606 b714765a Adeodato Simo
                          help="Specify units for output (one of h/m/g/t)")
607 c38c44ad Michael Hanselmann
608 c38c44ad Michael Hanselmann
FIELDS_OPT = cli_option("-o", "--output", dest="output", action="store",
609 c38c44ad Michael Hanselmann
                        type="string", metavar="FIELDS",
610 c38c44ad Michael Hanselmann
                        help="Comma separated list of output fields")
611 c38c44ad Michael Hanselmann
612 c38c44ad Michael Hanselmann
FORCE_OPT = cli_option("-f", "--force", dest="force", action="store_true",
613 c38c44ad Michael Hanselmann
                       default=False, help="Force the operation")
614 c38c44ad Michael Hanselmann
615 c38c44ad Michael Hanselmann
CONFIRM_OPT = cli_option("--yes", dest="confirm", action="store_true",
616 c38c44ad Michael Hanselmann
                         default=False, help="Do not require confirmation")
617 c38c44ad Michael Hanselmann
618 b44bd844 Michael Hanselmann
IGNORE_OFFLINE_OPT = cli_option("--ignore-offline", dest="ignore_offline",
619 b44bd844 Michael Hanselmann
                                  action="store_true", default=False,
620 b44bd844 Michael Hanselmann
                                  help=("Ignore offline nodes and do as much"
621 b44bd844 Michael Hanselmann
                                        " as possible"))
622 b44bd844 Michael Hanselmann
623 c38c44ad Michael Hanselmann
TAG_SRC_OPT = cli_option("--from", dest="tags_source",
624 c38c44ad Michael Hanselmann
                         default=None, help="File with tag names")
625 c38c44ad Michael Hanselmann
626 c38c44ad Michael Hanselmann
SUBMIT_OPT = cli_option("--submit", dest="submit_only",
627 c38c44ad Michael Hanselmann
                        default=False, action="store_true",
628 c38c44ad Michael Hanselmann
                        help=("Submit the job and return the job ID, but"
629 c38c44ad Michael Hanselmann
                              " don't wait for the job to finish"))
630 c38c44ad Michael Hanselmann
631 c38c44ad Michael Hanselmann
SYNC_OPT = cli_option("--sync", dest="do_locking",
632 c38c44ad Michael Hanselmann
                      default=False, action="store_true",
633 c38c44ad Michael Hanselmann
                      help=("Grab locks while doing the queries"
634 c38c44ad Michael Hanselmann
                            " in order to ensure more consistent results"))
635 c38c44ad Michael Hanselmann
636 a0a6ff34 Iustin Pop
DRY_RUN_OPT = cli_option("--dry-run", default=False,
637 a0a6ff34 Iustin Pop
                         action="store_true",
638 a0a6ff34 Iustin Pop
                         help=("Do not execute the operation, just run the"
639 a0a6ff34 Iustin Pop
                               " check steps and verify it it could be"
640 a0a6ff34 Iustin Pop
                               " executed"))
641 c38c44ad Michael Hanselmann
642 9cdb9578 Iustin Pop
VERBOSE_OPT = cli_option("-v", "--verbose", default=False,
643 9cdb9578 Iustin Pop
                         action="store_true",
644 9cdb9578 Iustin Pop
                         help="Increase the verbosity of the operation")
645 9cdb9578 Iustin Pop
646 a0c9776a Iustin Pop
DEBUG_SIMERR_OPT = cli_option("--debug-simulate-errors", default=False,
647 a0c9776a Iustin Pop
                              action="store_true", dest="simulate_errors",
648 a0c9776a Iustin Pop
                              help="Debugging option that makes the operation"
649 a0c9776a Iustin Pop
                              " treat most runtime checks as failed")
650 a0c9776a Iustin Pop
651 3f75b4f3 Iustin Pop
NWSYNC_OPT = cli_option("--no-wait-for-sync", dest="wait_for_sync",
652 3f75b4f3 Iustin Pop
                        default=True, action="store_false",
653 3f75b4f3 Iustin Pop
                        help="Don't wait for sync (DANGEROUS!)")
654 3f75b4f3 Iustin Pop
655 4f365444 Iustin Pop
DISK_TEMPLATE_OPT = cli_option("-t", "--disk-template", dest="disk_template",
656 4f365444 Iustin Pop
                               help="Custom disk setup (diskless, file,"
657 4f365444 Iustin Pop
                               " plain or drbd)",
658 4f365444 Iustin Pop
                               default=None, metavar="TEMPL",
659 4f365444 Iustin Pop
                               choices=list(constants.DISK_TEMPLATES))
660 4f365444 Iustin Pop
661 26023ecd Iustin Pop
NONICS_OPT = cli_option("--no-nics", default=False, action="store_true",
662 26023ecd Iustin Pop
                        help="Do not create any network cards for"
663 26023ecd Iustin Pop
                        " the instance")
664 26023ecd Iustin Pop
665 4a25828c Iustin Pop
FILESTORE_DIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
666 4a25828c Iustin Pop
                               help="Relative path under default cluster-wide"
667 4a25828c Iustin Pop
                               " file storage dir to store file-based disks",
668 4a25828c Iustin Pop
                               default=None, metavar="<DIR>")
669 4a25828c Iustin Pop
670 0f87c43e Iustin Pop
FILESTORE_DRIVER_OPT = cli_option("--file-driver", dest="file_driver",
671 0f87c43e Iustin Pop
                                  help="Driver to use for image files",
672 0f87c43e Iustin Pop
                                  default="loop", metavar="<DRIVER>",
673 0f87c43e Iustin Pop
                                  choices=list(constants.FILE_DRIVER))
674 0f87c43e Iustin Pop
675 4eb62659 Iustin Pop
IALLOCATOR_OPT = cli_option("-I", "--iallocator", metavar="<NAME>",
676 4eb62659 Iustin Pop
                            help="Select nodes for the instance automatically"
677 4eb62659 Iustin Pop
                            " using the <NAME> iallocator plugin",
678 4eb62659 Iustin Pop
                            default=None, type="string",
679 4eb62659 Iustin Pop
                            completion_suggest=OPT_COMPL_ONE_IALLOCATOR)
680 4eb62659 Iustin Pop
681 bf4af505 Apollon Oikonomopoulos
DEFAULT_IALLOCATOR_OPT = cli_option("-I", "--default-iallocator",
682 bf4af505 Apollon Oikonomopoulos
                            metavar="<NAME>",
683 bf4af505 Apollon Oikonomopoulos
                            help="Set the default instance allocator plugin",
684 bf4af505 Apollon Oikonomopoulos
                            default=None, type="string",
685 bf4af505 Apollon Oikonomopoulos
                            completion_suggest=OPT_COMPL_ONE_IALLOCATOR)
686 bf4af505 Apollon Oikonomopoulos
687 d3ed23ff Iustin Pop
OS_OPT = cli_option("-o", "--os-type", dest="os", help="What OS to run",
688 d3ed23ff Iustin Pop
                    metavar="<os>",
689 d3ed23ff Iustin Pop
                    completion_suggest=OPT_COMPL_ONE_OS)
690 d3ed23ff Iustin Pop
691 062a7100 Iustin Pop
OSPARAMS_OPT = cli_option("-O", "--os-parameters", dest="osparams",
692 062a7100 Iustin Pop
                         type="keyval", default={},
693 062a7100 Iustin Pop
                         help="OS parameters")
694 062a7100 Iustin Pop
695 06073e85 Guido Trotter
FORCE_VARIANT_OPT = cli_option("--force-variant", dest="force_variant",
696 06073e85 Guido Trotter
                               action="store_true", default=False,
697 06073e85 Guido Trotter
                               help="Force an unknown variant")
698 06073e85 Guido Trotter
699 25a8792c Iustin Pop
NO_INSTALL_OPT = cli_option("--no-install", dest="no_install",
700 25a8792c Iustin Pop
                            action="store_true", default=False,
701 25a8792c Iustin Pop
                            help="Do not install the OS (will"
702 25a8792c Iustin Pop
                            " enable no-start)")
703 25a8792c Iustin Pop
704 087ed2ed Iustin Pop
BACKEND_OPT = cli_option("-B", "--backend-parameters", dest="beparams",
705 087ed2ed Iustin Pop
                         type="keyval", default={},
706 087ed2ed Iustin Pop
                         help="Backend parameters")
707 48f212d7 Iustin Pop
708 48f212d7 Iustin Pop
HVOPTS_OPT =  cli_option("-H", "--hypervisor-parameters", type="keyval",
709 48f212d7 Iustin Pop
                         default={}, dest="hvparams",
710 48f212d7 Iustin Pop
                         help="Hypervisor parameters")
711 087ed2ed Iustin Pop
712 236fd9c4 Iustin Pop
HYPERVISOR_OPT = cli_option("-H", "--hypervisor-parameters", dest="hypervisor",
713 236fd9c4 Iustin Pop
                            help="Hypervisor and hypervisor options, in the"
714 236fd9c4 Iustin Pop
                            " format hypervisor:option=value,option=value,...",
715 236fd9c4 Iustin Pop
                            default=None, type="identkeyval")
716 073271f6 Iustin Pop
717 073271f6 Iustin Pop
HVLIST_OPT = cli_option("-H", "--hypervisor-parameters", dest="hvparams",
718 073271f6 Iustin Pop
                        help="Hypervisor and hypervisor options, in the"
719 073271f6 Iustin Pop
                        " format hypervisor:option=value,option=value,...",
720 073271f6 Iustin Pop
                        default=[], action="append", type="identkeyval")
721 236fd9c4 Iustin Pop
722 91e0748c Iustin Pop
NOIPCHECK_OPT = cli_option("--no-ip-check", dest="ip_check", default=True,
723 91e0748c Iustin Pop
                           action="store_false",
724 91e0748c Iustin Pop
                           help="Don't check that the instance's IP"
725 91e0748c Iustin Pop
                           " is alive")
726 91e0748c Iustin Pop
727 460d22be Iustin Pop
NONAMECHECK_OPT = cli_option("--no-name-check", dest="name_check",
728 460d22be Iustin Pop
                             default=True, action="store_false",
729 460d22be Iustin Pop
                             help="Don't check that the instance's name"
730 460d22be Iustin Pop
                             " is resolvable")
731 460d22be Iustin Pop
732 7d3a9fab Iustin Pop
NET_OPT = cli_option("--net",
733 7d3a9fab Iustin Pop
                     help="NIC parameters", default=[],
734 7d3a9fab Iustin Pop
                     dest="nics", action="append", type="identkeyval")
735 e3876ccb Iustin Pop
736 e3876ccb Iustin Pop
DISK_OPT = cli_option("--disk", help="Disk parameters", default=[],
737 e3876ccb Iustin Pop
                      dest="disks", action="append", type="identkeyval")
738 91e0748c Iustin Pop
739 4b038a1e Iustin Pop
DISKIDX_OPT = cli_option("--disks", dest="disks", default=None,
740 4b038a1e Iustin Pop
                         help="Comma-separated list of disks"
741 4b038a1e Iustin Pop
                         " indices to act on (e.g. 0,2) (optional,"
742 4b038a1e Iustin Pop
                         " defaults to all disks)")
743 4b038a1e Iustin Pop
744 ff00c1a7 Iustin Pop
OS_SIZE_OPT = cli_option("-s", "--os-size", dest="sd_size",
745 ff00c1a7 Iustin Pop
                         help="Enforces a single-disk configuration using the"
746 ff00c1a7 Iustin Pop
                         " given disk size, in MiB unless a suffix is used",
747 ff00c1a7 Iustin Pop
                         default=None, type="unit", metavar="<size>")
748 ff00c1a7 Iustin Pop
749 82a786d5 Iustin Pop
IGNORE_CONSIST_OPT = cli_option("--ignore-consistency",
750 82a786d5 Iustin Pop
                                dest="ignore_consistency",
751 82a786d5 Iustin Pop
                                action="store_true", default=False,
752 82a786d5 Iustin Pop
                                help="Ignore the consistency of the disks on"
753 82a786d5 Iustin Pop
                                " the secondary")
754 82a786d5 Iustin Pop
755 f2a0828c Iustin Pop
NONLIVE_OPT = cli_option("--non-live", dest="live",
756 f2a0828c Iustin Pop
                         default=True, action="store_false",
757 f2a0828c Iustin Pop
                         help="Do a non-live migration (this usually means"
758 f2a0828c Iustin Pop
                         " freeze the instance, save the state, transfer and"
759 f2a0828c Iustin Pop
                         " only then resume running on the secondary node)")
760 f2a0828c Iustin Pop
761 783a6c0b Iustin Pop
MIGRATION_MODE_OPT = cli_option("--migration-mode", dest="migration_mode",
762 e71b9ef4 Iustin Pop
                                default=None,
763 783a6c0b Iustin Pop
                                choices=list(constants.HT_MIGRATION_MODES),
764 783a6c0b Iustin Pop
                                help="Override default migration mode (choose"
765 e71b9ef4 Iustin Pop
                                " either live or non-live")
766 e71b9ef4 Iustin Pop
767 990b7886 Iustin Pop
NODE_PLACEMENT_OPT = cli_option("-n", "--node", dest="node",
768 990b7886 Iustin Pop
                                help="Target node and optional secondary node",
769 990b7886 Iustin Pop
                                metavar="<pnode>[:<snode>]",
770 990b7886 Iustin Pop
                                completion_suggest=OPT_COMPL_INST_ADD_NODES)
771 990b7886 Iustin Pop
772 7edc4637 Iustin Pop
NODE_LIST_OPT = cli_option("-n", "--node", dest="nodes", default=[],
773 7edc4637 Iustin Pop
                           action="append", metavar="<node>",
774 7edc4637 Iustin Pop
                           help="Use only this node (can be used multiple"
775 7edc4637 Iustin Pop
                           " times, if not given defaults to all nodes)",
776 7edc4637 Iustin Pop
                           completion_suggest=OPT_COMPL_ONE_NODE)
777 f36d7d81 Iustin Pop
778 a285fcfd Iustin Pop
NODEGROUP_OPT = cli_option("-g", "--node-group",
779 5fbbd028 Guido Trotter
                           dest="nodegroup",
780 5fbbd028 Guido Trotter
                           help="Node group (name or uuid)",
781 5fbbd028 Guido Trotter
                           metavar="<nodegroup>",
782 5fbbd028 Guido Trotter
                           default=None, type="string",
783 5fbbd028 Guido Trotter
                           completion_suggest=OPT_COMPL_ONE_NODEGROUP)
784 5fbbd028 Guido Trotter
785 f36d7d81 Iustin Pop
SINGLE_NODE_OPT = cli_option("-n", "--node", dest="node", help="Target node",
786 f36d7d81 Iustin Pop
                             metavar="<node>",
787 f36d7d81 Iustin Pop
                             completion_suggest=OPT_COMPL_ONE_NODE)
788 7edc4637 Iustin Pop
789 edeb878a Iustin Pop
NOSTART_OPT = cli_option("--no-start", dest="start", default=True,
790 edeb878a Iustin Pop
                         action="store_false",
791 edeb878a Iustin Pop
                         help="Don't start the instance after creation")
792 edeb878a Iustin Pop
793 fdcf4d84 Iustin Pop
SHOWCMD_OPT = cli_option("--show-cmd", dest="show_command",
794 fdcf4d84 Iustin Pop
                         action="store_true", default=False,
795 fdcf4d84 Iustin Pop
                         help="Show command instead of executing it")
796 fdcf4d84 Iustin Pop
797 baef337d Iustin Pop
CLEANUP_OPT = cli_option("--cleanup", dest="cleanup",
798 baef337d Iustin Pop
                         default=False, action="store_true",
799 baef337d Iustin Pop
                         help="Instead of performing the migration, try to"
800 baef337d Iustin Pop
                         " recover from a failed cleanup. This is safe"
801 baef337d Iustin Pop
                         " to run even if the instance is healthy, but it"
802 baef337d Iustin Pop
                         " will create extra replication traffic and "
803 baef337d Iustin Pop
                         " disrupt briefly the replication (like during the"
804 baef337d Iustin Pop
                         " migration")
805 baef337d Iustin Pop
806 99a8c799 Iustin Pop
STATIC_OPT = cli_option("-s", "--static", dest="static",
807 99a8c799 Iustin Pop
                        action="store_true", default=False,
808 99a8c799 Iustin Pop
                        help="Only show configuration data, not runtime data")
809 99a8c799 Iustin Pop
810 2d5e7ae1 Iustin Pop
ALL_OPT = cli_option("--all", dest="show_all",
811 2d5e7ae1 Iustin Pop
                     default=False, action="store_true",
812 2d5e7ae1 Iustin Pop
                     help="Show info on all instances on the cluster."
813 2d5e7ae1 Iustin Pop
                     " This can take a long time to run, use wisely")
814 2d5e7ae1 Iustin Pop
815 67840b40 Iustin Pop
SELECT_OS_OPT = cli_option("--select-os", dest="select_os",
816 67840b40 Iustin Pop
                           action="store_true", default=False,
817 67840b40 Iustin Pop
                           help="Interactive OS reinstall, lists available"
818 67840b40 Iustin Pop
                           " OS templates for selection")
819 2d5e7ae1 Iustin Pop
820 b6e841a8 Iustin Pop
IGNORE_FAILURES_OPT = cli_option("--ignore-failures", dest="ignore_failures",
821 b6e841a8 Iustin Pop
                                 action="store_true", default=False,
822 b6e841a8 Iustin Pop
                                 help="Remove the instance from the cluster"
823 b6e841a8 Iustin Pop
                                 " configuration even if there are failures"
824 b6e841a8 Iustin Pop
                                 " during the removal process")
825 b6e841a8 Iustin Pop
826 8d8d650c Michael Hanselmann
IGNORE_REMOVE_FAILURES_OPT = cli_option("--ignore-remove-failures",
827 8d8d650c Michael Hanselmann
                                        dest="ignore_remove_failures",
828 8d8d650c Michael Hanselmann
                                        action="store_true", default=False,
829 8d8d650c Michael Hanselmann
                                        help="Remove the instance from the"
830 8d8d650c Michael Hanselmann
                                        " cluster configuration even if there"
831 8d8d650c Michael Hanselmann
                                        " are failures during the removal"
832 8d8d650c Michael Hanselmann
                                        " process")
833 8d8d650c Michael Hanselmann
834 8d8d650c Michael Hanselmann
REMOVE_INSTANCE_OPT = cli_option("--remove-instance", dest="remove_instance",
835 8d8d650c Michael Hanselmann
                                 action="store_true", default=False,
836 8d8d650c Michael Hanselmann
                                 help="Remove the instance from the cluster")
837 8d8d650c Michael Hanselmann
838 a14db5ff Iustin Pop
NEW_SECONDARY_OPT = cli_option("-n", "--new-secondary", dest="dst_node",
839 a14db5ff Iustin Pop
                               help="Specifies the new secondary node",
840 a14db5ff Iustin Pop
                               metavar="NODE", default=None,
841 a14db5ff Iustin Pop
                               completion_suggest=OPT_COMPL_ONE_NODE)
842 a14db5ff Iustin Pop
843 a72d0a79 Iustin Pop
ON_PRIMARY_OPT = cli_option("-p", "--on-primary", dest="on_primary",
844 a72d0a79 Iustin Pop
                            default=False, action="store_true",
845 a72d0a79 Iustin Pop
                            help="Replace the disk(s) on the primary"
846 a72d0a79 Iustin Pop
                            " node (only for the drbd template)")
847 feb09e6a Iustin Pop
848 feb09e6a Iustin Pop
ON_SECONDARY_OPT = cli_option("-s", "--on-secondary", dest="on_secondary",
849 feb09e6a Iustin Pop
                              default=False, action="store_true",
850 feb09e6a Iustin Pop
                              help="Replace the disk(s) on the secondary"
851 feb09e6a Iustin Pop
                              " node (only for the drbd template)")
852 e00f7a05 Iustin Pop
853 4c61d894 Iustin Pop
AUTO_PROMOTE_OPT = cli_option("--auto-promote", dest="auto_promote",
854 4c61d894 Iustin Pop
                              default=False, action="store_true",
855 4c61d894 Iustin Pop
                              help="Lock all nodes and auto-promote as needed"
856 4c61d894 Iustin Pop
                              " to MC status")
857 4c61d894 Iustin Pop
858 e00f7a05 Iustin Pop
AUTO_REPLACE_OPT = cli_option("-a", "--auto", dest="auto",
859 e00f7a05 Iustin Pop
                              default=False, action="store_true",
860 e00f7a05 Iustin Pop
                              help="Automatically replace faulty disks"
861 e00f7a05 Iustin Pop
                              " (only for the drbd template)")
862 a72d0a79 Iustin Pop
863 05586c90 Iustin Pop
IGNORE_SIZE_OPT = cli_option("--ignore-size", dest="ignore_size",
864 05586c90 Iustin Pop
                             default=False, action="store_true",
865 05586c90 Iustin Pop
                             help="Ignore current recorded size"
866 05586c90 Iustin Pop
                             " (useful for forcing activation when"
867 05586c90 Iustin Pop
                             " the recorded size is wrong)")
868 05586c90 Iustin Pop
869 df62e5db Iustin Pop
SRC_NODE_OPT = cli_option("--src-node", dest="src_node", help="Source node",
870 df62e5db Iustin Pop
                          metavar="<node>",
871 df62e5db Iustin Pop
                          completion_suggest=OPT_COMPL_ONE_NODE)
872 df62e5db Iustin Pop
873 df62e5db Iustin Pop
SRC_DIR_OPT = cli_option("--src-dir", dest="src_dir", help="Source directory",
874 df62e5db Iustin Pop
                         metavar="<dir>")
875 df62e5db Iustin Pop
876 8d823629 Iustin Pop
SECONDARY_IP_OPT = cli_option("-s", "--secondary-ip", dest="secondary_ip",
877 8d823629 Iustin Pop
                              help="Specify the secondary ip for the node",
878 8d823629 Iustin Pop
                              metavar="ADDRESS", default=None)
879 8d823629 Iustin Pop
880 b8d0f938 Iustin Pop
READD_OPT = cli_option("--readd", dest="readd",
881 b8d0f938 Iustin Pop
                       default=False, action="store_true",
882 b8d0f938 Iustin Pop
                       help="Readd old node after replacing it")
883 b8d0f938 Iustin Pop
884 fcdde7f2 Iustin Pop
NOSSH_KEYCHECK_OPT = cli_option("--no-ssh-key-check", dest="ssh_key_check",
885 fcdde7f2 Iustin Pop
                                default=True, action="store_false",
886 fcdde7f2 Iustin Pop
                                help="Disable SSH key fingerprint checking")
887 fcdde7f2 Iustin Pop
888 c38c44ad Michael Hanselmann
889 771734c9 Iustin Pop
MC_OPT = cli_option("-C", "--master-candidate", dest="master_candidate",
890 e7b61bb0 Iustin Pop
                    type="bool", default=None, metavar=_YORNO,
891 771734c9 Iustin Pop
                    help="Set the master_candidate flag on the node")
892 771734c9 Iustin Pop
893 771734c9 Iustin Pop
OFFLINE_OPT = cli_option("-O", "--offline", dest="offline", metavar=_YORNO,
894 e7b61bb0 Iustin Pop
                         type="bool", default=None,
895 771734c9 Iustin Pop
                         help="Set the offline flag on the node")
896 771734c9 Iustin Pop
897 771734c9 Iustin Pop
DRAINED_OPT = cli_option("-D", "--drained", dest="drained", metavar=_YORNO,
898 e7b61bb0 Iustin Pop
                         type="bool", default=None,
899 771734c9 Iustin Pop
                         help="Set the drained flag on the node")
900 771734c9 Iustin Pop
901 f91e255a Iustin Pop
CAPAB_MASTER_OPT = cli_option("--master-capable", dest="master_capable",
902 f91e255a Iustin Pop
                    type="bool", default=None, metavar=_YORNO,
903 f91e255a Iustin Pop
                    help="Set the master_capable flag on the node")
904 f91e255a Iustin Pop
905 53919782 Iustin Pop
CAPAB_VM_OPT = cli_option("--vm-capable", dest="vm_capable",
906 53919782 Iustin Pop
                    type="bool", default=None, metavar=_YORNO,
907 53919782 Iustin Pop
                    help="Set the vm_capable flag on the node")
908 53919782 Iustin Pop
909 e7e09483 Iustin Pop
ALLOCATABLE_OPT = cli_option("--allocatable", dest="allocatable",
910 e7b61bb0 Iustin Pop
                             type="bool", default=None, metavar=_YORNO,
911 e7e09483 Iustin Pop
                             help="Set the allocatable flag on a volume")
912 e7e09483 Iustin Pop
913 831040bf Iustin Pop
NOLVM_STORAGE_OPT = cli_option("--no-lvm-storage", dest="lvm_storage",
914 831040bf Iustin Pop
                               help="Disable support for lvm based instances"
915 831040bf Iustin Pop
                               " (cluster-wide)",
916 831040bf Iustin Pop
                               action="store_false", default=True)
917 831040bf Iustin Pop
918 383a3591 Iustin Pop
ENABLED_HV_OPT = cli_option("--enabled-hypervisors",
919 383a3591 Iustin Pop
                            dest="enabled_hypervisors",
920 383a3591 Iustin Pop
                            help="Comma-separated list of hypervisors",
921 383a3591 Iustin Pop
                            type="string", default=None)
922 383a3591 Iustin Pop
923 4fbc93dd Iustin Pop
NIC_PARAMS_OPT = cli_option("-N", "--nic-parameters", dest="nicparams",
924 4fbc93dd Iustin Pop
                            type="keyval", default={},
925 4fbc93dd Iustin Pop
                            help="NIC parameters")
926 4fbc93dd Iustin Pop
927 e32df528 Iustin Pop
CP_SIZE_OPT = cli_option("-C", "--candidate-pool-size", default=None,
928 e32df528 Iustin Pop
                         dest="candidate_pool_size", type="int",
929 e32df528 Iustin Pop
                         help="Set the candidate pool size")
930 e32df528 Iustin Pop
931 04367e70 Guido Trotter
VG_NAME_OPT = cli_option("--vg-name", dest="vg_name",
932 b58726e8 Iustin Pop
                         help="Enables LVM and specifies the volume group"
933 b58726e8 Iustin Pop
                         " name (cluster-wide) for disk allocation [xenvg]",
934 b58726e8 Iustin Pop
                         metavar="VG", default=None)
935 b58726e8 Iustin Pop
936 1f587d3d Iustin Pop
YES_DOIT_OPT = cli_option("--yes-do-it", dest="yes_do_it",
937 1f587d3d Iustin Pop
                          help="Destroy cluster", action="store_true")
938 b58726e8 Iustin Pop
939 58371861 Iustin Pop
NOVOTING_OPT = cli_option("--no-voting", dest="no_voting",
940 58371861 Iustin Pop
                          help="Skip node agreement check (dangerous)",
941 58371861 Iustin Pop
                          action="store_true", default=False)
942 58371861 Iustin Pop
943 e3646f22 Iustin Pop
MAC_PREFIX_OPT = cli_option("-m", "--mac-prefix", dest="mac_prefix",
944 e3646f22 Iustin Pop
                            help="Specify the mac prefix for the instance IP"
945 e3646f22 Iustin Pop
                            " addresses, in the format XX:XX:XX",
946 e3646f22 Iustin Pop
                            metavar="PREFIX",
947 e3646f22 Iustin Pop
                            default=None)
948 e3646f22 Iustin Pop
949 29392516 Iustin Pop
MASTER_NETDEV_OPT = cli_option("--master-netdev", dest="master_netdev",
950 29392516 Iustin Pop
                               help="Specify the node interface (cluster-wide)"
951 25be0c75 Guido Trotter
                               " on which the master IP address will be added"
952 25be0c75 Guido Trotter
                               " (cluster init default: %s)" %
953 25be0c75 Guido Trotter
                               constants.DEFAULT_BRIDGE,
954 29392516 Iustin Pop
                               metavar="NETDEV",
955 25be0c75 Guido Trotter
                               default=None)
956 29392516 Iustin Pop
957 29392516 Iustin Pop
GLOBAL_FILEDIR_OPT = cli_option("--file-storage-dir", dest="file_storage_dir",
958 29392516 Iustin Pop
                                help="Specify the default directory (cluster-"
959 29392516 Iustin Pop
                                "wide) for storing the file-based disks [%s]" %
960 29392516 Iustin Pop
                                constants.DEFAULT_FILE_STORAGE_DIR,
961 29392516 Iustin Pop
                                metavar="DIR",
962 29392516 Iustin Pop
                                default=constants.DEFAULT_FILE_STORAGE_DIR)
963 29392516 Iustin Pop
964 29392516 Iustin Pop
NOMODIFY_ETCHOSTS_OPT = cli_option("--no-etc-hosts", dest="modify_etc_hosts",
965 29392516 Iustin Pop
                                   help="Don't modify /etc/hosts",
966 29392516 Iustin Pop
                                   action="store_false", default=True)
967 29392516 Iustin Pop
968 b989b9d9 Ken Wehr
NOMODIFY_SSH_SETUP_OPT = cli_option("--no-ssh-init", dest="modify_ssh_setup",
969 b989b9d9 Ken Wehr
                                    help="Don't initialize SSH keys",
970 b989b9d9 Ken Wehr
                                    action="store_false", default=True)
971 b989b9d9 Ken Wehr
972 14e9e7f3 Iustin Pop
ERROR_CODES_OPT = cli_option("--error-codes", dest="error_codes",
973 14e9e7f3 Iustin Pop
                             help="Enable parseable error messages",
974 14e9e7f3 Iustin Pop
                             action="store_true", default=False)
975 14e9e7f3 Iustin Pop
976 14e9e7f3 Iustin Pop
NONPLUS1_OPT = cli_option("--no-nplus1-mem", dest="skip_nplusone_mem",
977 14e9e7f3 Iustin Pop
                          help="Skip N+1 memory redundancy tests",
978 14e9e7f3 Iustin Pop
                          action="store_true", default=False)
979 14e9e7f3 Iustin Pop
980 12054861 Iustin Pop
REBOOT_TYPE_OPT = cli_option("-t", "--type", dest="reboot_type",
981 12054861 Iustin Pop
                             help="Type of reboot: soft/hard/full",
982 12054861 Iustin Pop
                             default=constants.INSTANCE_REBOOT_HARD,
983 12054861 Iustin Pop
                             metavar="<REBOOT>",
984 12054861 Iustin Pop
                             choices=list(constants.REBOOT_TYPES))
985 12054861 Iustin Pop
986 ee3f9578 Iustin Pop
IGNORE_SECONDARIES_OPT = cli_option("--ignore-secondaries",
987 ee3f9578 Iustin Pop
                                    dest="ignore_secondaries",
988 ee3f9578 Iustin Pop
                                    default=False, action="store_true",
989 ee3f9578 Iustin Pop
                                    help="Ignore errors from secondaries")
990 ee3f9578 Iustin Pop
991 69b99987 Michael Hanselmann
NOSHUTDOWN_OPT = cli_option("--noshutdown", dest="shutdown",
992 44c44832 Iustin Pop
                            action="store_false", default=True,
993 44c44832 Iustin Pop
                            help="Don't shutdown the instance (unsafe)")
994 44c44832 Iustin Pop
995 b5762e2a Guido Trotter
TIMEOUT_OPT = cli_option("--timeout", dest="timeout", type="int",
996 b5762e2a Guido Trotter
                         default=constants.DEFAULT_SHUTDOWN_TIMEOUT,
997 b5762e2a Guido Trotter
                         help="Maximum time to wait")
998 44c44832 Iustin Pop
999 4d98c565 Guido Trotter
SHUTDOWN_TIMEOUT_OPT = cli_option("--shutdown-timeout",
1000 4d98c565 Guido Trotter
                         dest="shutdown_timeout", type="int",
1001 7e5eaaa8 Guido Trotter
                         default=constants.DEFAULT_SHUTDOWN_TIMEOUT,
1002 7e5eaaa8 Guido Trotter
                         help="Maximum time to wait for instance shutdown")
1003 7e5eaaa8 Guido Trotter
1004 19b9ba9a Michael Hanselmann
INTERVAL_OPT = cli_option("--interval", dest="interval", type="int",
1005 19b9ba9a Michael Hanselmann
                          default=None,
1006 19b9ba9a Michael Hanselmann
                          help=("Number of seconds between repetions of the"
1007 19b9ba9a Michael Hanselmann
                                " command"))
1008 19b9ba9a Michael Hanselmann
1009 7ea7bcf6 Iustin Pop
EARLY_RELEASE_OPT = cli_option("--early-release",
1010 7ea7bcf6 Iustin Pop
                               dest="early_release", default=False,
1011 7ea7bcf6 Iustin Pop
                               action="store_true",
1012 7ea7bcf6 Iustin Pop
                               help="Release the locks on the secondary"
1013 7ea7bcf6 Iustin Pop
                               " node(s) early")
1014 7ea7bcf6 Iustin Pop
1015 6d4a1656 Michael Hanselmann
NEW_CLUSTER_CERT_OPT = cli_option("--new-cluster-certificate",
1016 6d4a1656 Michael Hanselmann
                                  dest="new_cluster_cert",
1017 6d4a1656 Michael Hanselmann
                                  default=False, action="store_true",
1018 6d4a1656 Michael Hanselmann
                                  help="Generate a new cluster certificate")
1019 6d4a1656 Michael Hanselmann
1020 6d4a1656 Michael Hanselmann
RAPI_CERT_OPT = cli_option("--rapi-certificate", dest="rapi_cert",
1021 6d4a1656 Michael Hanselmann
                           default=None,
1022 6d4a1656 Michael Hanselmann
                           help="File containing new RAPI certificate")
1023 6d4a1656 Michael Hanselmann
1024 6d4a1656 Michael Hanselmann
NEW_RAPI_CERT_OPT = cli_option("--new-rapi-certificate", dest="new_rapi_cert",
1025 6d4a1656 Michael Hanselmann
                               default=None, action="store_true",
1026 6d4a1656 Michael Hanselmann
                               help=("Generate a new self-signed RAPI"
1027 6d4a1656 Michael Hanselmann
                                     " certificate"))
1028 6d4a1656 Michael Hanselmann
1029 6b7d5878 Michael Hanselmann
NEW_CONFD_HMAC_KEY_OPT = cli_option("--new-confd-hmac-key",
1030 6b7d5878 Michael Hanselmann
                                    dest="new_confd_hmac_key",
1031 6b7d5878 Michael Hanselmann
                                    default=False, action="store_true",
1032 6b7d5878 Michael Hanselmann
                                    help=("Create a new HMAC key for %s" %
1033 6b7d5878 Michael Hanselmann
                                          constants.CONFD))
1034 6d4a1656 Michael Hanselmann
1035 3db3eb2a Michael Hanselmann
CLUSTER_DOMAIN_SECRET_OPT = cli_option("--cluster-domain-secret",
1036 3db3eb2a Michael Hanselmann
                                       dest="cluster_domain_secret",
1037 3db3eb2a Michael Hanselmann
                                       default=None,
1038 3db3eb2a Michael Hanselmann
                                       help=("Load new new cluster domain"
1039 3db3eb2a Michael Hanselmann
                                             " secret from file"))
1040 3db3eb2a Michael Hanselmann
1041 3db3eb2a Michael Hanselmann
NEW_CLUSTER_DOMAIN_SECRET_OPT = cli_option("--new-cluster-domain-secret",
1042 3db3eb2a Michael Hanselmann
                                           dest="new_cluster_domain_secret",
1043 3db3eb2a Michael Hanselmann
                                           default=False, action="store_true",
1044 3db3eb2a Michael Hanselmann
                                           help=("Create a new cluster domain"
1045 3db3eb2a Michael Hanselmann
                                                 " secret"))
1046 3db3eb2a Michael Hanselmann
1047 74adc100 Iustin Pop
USE_REPL_NET_OPT = cli_option("--use-replication-network",
1048 74adc100 Iustin Pop
                              dest="use_replication_network",
1049 74adc100 Iustin Pop
                              help="Whether to use the replication network"
1050 74adc100 Iustin Pop
                              " for talking to the nodes",
1051 74adc100 Iustin Pop
                              action="store_true", default=False)
1052 74adc100 Iustin Pop
1053 3953242f Iustin Pop
MAINTAIN_NODE_HEALTH_OPT = \
1054 3953242f Iustin Pop
    cli_option("--maintain-node-health", dest="maintain_node_health",
1055 3953242f Iustin Pop
               metavar=_YORNO, default=None, type="bool",
1056 3953242f Iustin Pop
               help="Configure the cluster to automatically maintain node"
1057 3953242f Iustin Pop
               " health, by shutting down unknown instances, shutting down"
1058 3953242f Iustin Pop
               " unknown DRBD devices, etc.")
1059 3953242f Iustin Pop
1060 e588764d Iustin Pop
IDENTIFY_DEFAULTS_OPT = \
1061 e588764d Iustin Pop
    cli_option("--identify-defaults", dest="identify_defaults",
1062 e588764d Iustin Pop
               default=False, action="store_true",
1063 e588764d Iustin Pop
               help="Identify which saved instance parameters are equal to"
1064 e588764d Iustin Pop
               " the current cluster defaults and set them as such, instead"
1065 e588764d Iustin Pop
               " of marking them as overridden")
1066 e588764d Iustin Pop
1067 1338f2b4 Balazs Lecz
UIDPOOL_OPT = cli_option("--uid-pool", default=None,
1068 1338f2b4 Balazs Lecz
                         action="store", dest="uid_pool",
1069 1338f2b4 Balazs Lecz
                         help=("A list of user-ids or user-id"
1070 1338f2b4 Balazs Lecz
                               " ranges separated by commas"))
1071 1338f2b4 Balazs Lecz
1072 fdad8c4d Balazs Lecz
ADD_UIDS_OPT = cli_option("--add-uids", default=None,
1073 fdad8c4d Balazs Lecz
                          action="store", dest="add_uids",
1074 fdad8c4d Balazs Lecz
                          help=("A list of user-ids or user-id"
1075 fdad8c4d Balazs Lecz
                                " ranges separated by commas, to be"
1076 fdad8c4d Balazs Lecz
                                " added to the user-id pool"))
1077 fdad8c4d Balazs Lecz
1078 fdad8c4d Balazs Lecz
REMOVE_UIDS_OPT = cli_option("--remove-uids", default=None,
1079 fdad8c4d Balazs Lecz
                             action="store", dest="remove_uids",
1080 fdad8c4d Balazs Lecz
                             help=("A list of user-ids or user-id"
1081 fdad8c4d Balazs Lecz
                                   " ranges separated by commas, to be"
1082 fdad8c4d Balazs Lecz
                                   " removed from the user-id pool"))
1083 fdad8c4d Balazs Lecz
1084 f38ea602 Iustin Pop
RESERVED_LVS_OPT = cli_option("--reserved-lvs", default=None,
1085 f38ea602 Iustin Pop
                             action="store", dest="reserved_lvs",
1086 f38ea602 Iustin Pop
                             help=("A comma-separated list of reserved"
1087 f38ea602 Iustin Pop
                                   " logical volumes names, that will be"
1088 f38ea602 Iustin Pop
                                   " ignored by cluster verify"))
1089 f38ea602 Iustin Pop
1090 31d97b2a Guido Trotter
ROMAN_OPT = cli_option("--roman",
1091 31d97b2a Guido Trotter
                       dest="roman_integers", default=False,
1092 31d97b2a Guido Trotter
                       action="store_true",
1093 31d97b2a Guido Trotter
                       help="Use roman numbers for positive integers")
1094 31d97b2a Guido Trotter
1095 26591bfd Luca Bigliardi
DRBD_HELPER_OPT = cli_option("--drbd-usermode-helper", dest="drbd_helper",
1096 26591bfd Luca Bigliardi
                             action="store", default=None,
1097 26591bfd Luca Bigliardi
                             help="Specifies usermode helper for DRBD")
1098 26591bfd Luca Bigliardi
1099 26591bfd Luca Bigliardi
NODRBD_STORAGE_OPT = cli_option("--no-drbd-storage", dest="drbd_storage",
1100 26591bfd Luca Bigliardi
                                action="store_false", default=True,
1101 26591bfd Luca Bigliardi
                                help="Disable support for DRBD")
1102 31d97b2a Guido Trotter
1103 e7323b5e Manuel Franceschini
PRIMARY_IP_VERSION_OPT = \
1104 e7323b5e Manuel Franceschini
    cli_option("--primary-ip-version", default=constants.IP4_VERSION,
1105 e7323b5e Manuel Franceschini
               action="store", dest="primary_ip_version",
1106 e7323b5e Manuel Franceschini
               metavar="%d|%d" % (constants.IP4_VERSION,
1107 e7323b5e Manuel Franceschini
                                  constants.IP6_VERSION),
1108 e7323b5e Manuel Franceschini
               help="Cluster-wide IP version for primary IP")
1109 e7323b5e Manuel Franceschini
1110 84a5b33c Michael Hanselmann
PRIORITY_OPT = cli_option("--priority", default=None, dest="priority",
1111 84a5b33c Michael Hanselmann
                          metavar="|".join(name for name, _ in _PRIORITY_NAMES),
1112 84a5b33c Michael Hanselmann
                          choices=_PRIONAME_TO_VALUE.keys(),
1113 aa06f8c6 Michael Hanselmann
                          help="Priority for opcode processing")
1114 84a5b33c Michael Hanselmann
1115 61a14bb3 Iustin Pop
HID_OS_OPT = cli_option("--hidden", dest="hidden",
1116 61a14bb3 Iustin Pop
                        type="bool", default=None, metavar=_YORNO,
1117 61a14bb3 Iustin Pop
                        help="Sets the hidden flag on the OS")
1118 61a14bb3 Iustin Pop
1119 61a14bb3 Iustin Pop
BLK_OS_OPT = cli_option("--blacklisted", dest="blacklisted",
1120 61a14bb3 Iustin Pop
                        type="bool", default=None, metavar=_YORNO,
1121 61a14bb3 Iustin Pop
                        help="Sets the blacklisted flag on the OS")
1122 61a14bb3 Iustin Pop
1123 b883637f René Nussbaumer
PREALLOC_WIPE_DISKS_OPT = cli_option("--prealloc-wipe-disks", default=None,
1124 b883637f René Nussbaumer
                                     type="bool", metavar=_YORNO,
1125 b883637f René Nussbaumer
                                     dest="prealloc_wipe_disks",
1126 b883637f René Nussbaumer
                                     help=("Wipe disks prior to instance"
1127 b883637f René Nussbaumer
                                           " creation"))
1128 b883637f René Nussbaumer
1129 a535cef7 René Nussbaumer
NODE_PARAMS_OPT = cli_option("--node-parameters", dest="ndparams",
1130 3c2b6a98 René Nussbaumer
                             type="keyval", default=None,
1131 a535cef7 René Nussbaumer
                             help="Node parameters")
1132 a535cef7 René Nussbaumer
1133 90e99856 Adeodato Simo
ALLOC_POLICY_OPT = cli_option("--alloc-policy", dest="alloc_policy",
1134 90e99856 Adeodato Simo
                              action="store", metavar="POLICY", default=None,
1135 90e99856 Adeodato Simo
                              help="Allocation policy for the node group")
1136 90e99856 Adeodato Simo
1137 d2881c71 René Nussbaumer
NODE_POWERED_OPT = cli_option("--node-powered", default=None,
1138 d2881c71 René Nussbaumer
                              type="bool", metavar=_YORNO,
1139 d2881c71 René Nussbaumer
                              dest="node_powered",
1140 d2881c71 René Nussbaumer
                              help="Specify if the SoR for node is powered")
1141 d2881c71 René Nussbaumer
1142 61a14bb3 Iustin Pop
1143 5786c087 Michael Hanselmann
#: Options provided by all commands
1144 5786c087 Michael Hanselmann
COMMON_OPTS = [DEBUG_OPT]
1145 5786c087 Michael Hanselmann
1146 eb28ecf6 Guido Trotter
# common options for creating instances. add and import then add their own
1147 eb28ecf6 Guido Trotter
# specific ones.
1148 eb28ecf6 Guido Trotter
COMMON_CREATE_OPTS = [
1149 eb28ecf6 Guido Trotter
  BACKEND_OPT,
1150 eb28ecf6 Guido Trotter
  DISK_OPT,
1151 eb28ecf6 Guido Trotter
  DISK_TEMPLATE_OPT,
1152 eb28ecf6 Guido Trotter
  FILESTORE_DIR_OPT,
1153 eb28ecf6 Guido Trotter
  FILESTORE_DRIVER_OPT,
1154 eb28ecf6 Guido Trotter
  HYPERVISOR_OPT,
1155 eb28ecf6 Guido Trotter
  IALLOCATOR_OPT,
1156 eb28ecf6 Guido Trotter
  NET_OPT,
1157 eb28ecf6 Guido Trotter
  NODE_PLACEMENT_OPT,
1158 eb28ecf6 Guido Trotter
  NOIPCHECK_OPT,
1159 eb28ecf6 Guido Trotter
  NONAMECHECK_OPT,
1160 eb28ecf6 Guido Trotter
  NONICS_OPT,
1161 eb28ecf6 Guido Trotter
  NWSYNC_OPT,
1162 eb28ecf6 Guido Trotter
  OSPARAMS_OPT,
1163 eb28ecf6 Guido Trotter
  OS_SIZE_OPT,
1164 eb28ecf6 Guido Trotter
  SUBMIT_OPT,
1165 eb28ecf6 Guido Trotter
  DRY_RUN_OPT,
1166 eb28ecf6 Guido Trotter
  PRIORITY_OPT,
1167 eb28ecf6 Guido Trotter
  ]
1168 eb28ecf6 Guido Trotter
1169 771734c9 Iustin Pop
1170 de47cf8f Guido Trotter
def _ParseArgs(argv, commands, aliases):
1171 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1172 a8083063 Iustin Pop

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

1176 c41eea6e Iustin Pop
  @param argv: the command line
1177 c41eea6e Iustin Pop
  @param commands: dictionary with special contents, see the design
1178 c41eea6e Iustin Pop
      doc for cmdline handling
1179 c41eea6e Iustin Pop
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
1180 098c0958 Michael Hanselmann

1181 a8083063 Iustin Pop
  """
1182 a8083063 Iustin Pop
  if len(argv) == 0:
1183 a8083063 Iustin Pop
    binary = "<command>"
1184 a8083063 Iustin Pop
  else:
1185 a8083063 Iustin Pop
    binary = argv[0].split("/")[-1]
1186 a8083063 Iustin Pop
1187 a8083063 Iustin Pop
  if len(argv) > 1 and argv[1] == "--version":
1188 84a12e40 Iustin Pop
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
1189 84a12e40 Iustin Pop
             constants.RELEASE_VERSION)
1190 a8083063 Iustin Pop
    # Quit right away. That way we don't have to care about this special
1191 a8083063 Iustin Pop
    # argument. optparse.py does it the same.
1192 a8083063 Iustin Pop
    sys.exit(0)
1193 a8083063 Iustin Pop
1194 de47cf8f Guido Trotter
  if len(argv) < 2 or not (argv[1] in commands or
1195 70a35b6f Guido Trotter
                           argv[1] in aliases):
1196 a8083063 Iustin Pop
    # let's do a nice thing
1197 a8083063 Iustin Pop
    sortedcmds = commands.keys()
1198 a8083063 Iustin Pop
    sortedcmds.sort()
1199 03298ebe Michael Hanselmann
1200 03298ebe Michael Hanselmann
    ToStdout("Usage: %s {command} [options...] [argument...]", binary)
1201 03298ebe Michael Hanselmann
    ToStdout("%s <command> --help to see details, or man %s", binary, binary)
1202 03298ebe Michael Hanselmann
    ToStdout("")
1203 03298ebe Michael Hanselmann
1204 a8083063 Iustin Pop
    # compute the max line length for cmd + usage
1205 4e713df6 Iustin Pop
    mlen = max([len(" %s" % cmd) for cmd in commands])
1206 a8083063 Iustin Pop
    mlen = min(60, mlen) # should not get here...
1207 03298ebe Michael Hanselmann
1208 a8083063 Iustin Pop
    # and format a nice command list
1209 03298ebe Michael Hanselmann
    ToStdout("Commands:")
1210 a8083063 Iustin Pop
    for cmd in sortedcmds:
1211 4e713df6 Iustin Pop
      cmdstr = " %s" % (cmd,)
1212 9a033156 Iustin Pop
      help_text = commands[cmd][4]
1213 03298ebe Michael Hanselmann
      help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1214 03298ebe Michael Hanselmann
      ToStdout("%-*s - %s", mlen, cmdstr, help_lines.pop(0))
1215 a8083063 Iustin Pop
      for line in help_lines:
1216 03298ebe Michael Hanselmann
        ToStdout("%-*s   %s", mlen, "", line)
1217 03298ebe Michael Hanselmann
1218 03298ebe Michael Hanselmann
    ToStdout("")
1219 03298ebe Michael Hanselmann
1220 a8083063 Iustin Pop
    return None, None, None
1221 de47cf8f Guido Trotter
1222 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1223 a8083063 Iustin Pop
  cmd = argv.pop(1)
1224 de47cf8f Guido Trotter
  if cmd in aliases:
1225 de47cf8f Guido Trotter
    if cmd in commands:
1226 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' overrides an existing"
1227 de47cf8f Guido Trotter
                                   " command" % cmd)
1228 de47cf8f Guido Trotter
1229 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1230 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1231 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1232 de47cf8f Guido Trotter
1233 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1234 de47cf8f Guido Trotter
1235 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1236 5786c087 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1237 a8083063 Iustin Pop
                        description=description,
1238 a8083063 Iustin Pop
                        formatter=TitledHelpFormatter(),
1239 a8083063 Iustin Pop
                        usage="%%prog %s %s" % (cmd, usage))
1240 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1241 a8083063 Iustin Pop
  options, args = parser.parse_args()
1242 a8005e17 Michael Hanselmann
1243 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1244 a8083063 Iustin Pop
    return None, None, None
1245 a8083063 Iustin Pop
1246 a8083063 Iustin Pop
  return func, options, args
1247 a8083063 Iustin Pop
1248 a8083063 Iustin Pop
1249 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1250 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1251 a8005e17 Michael Hanselmann

1252 a8005e17 Michael Hanselmann
  Algorithm:
1253 a8005e17 Michael Hanselmann

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

1256 a8005e17 Michael Hanselmann
    1. For each argument in definition
1257 a8005e17 Michael Hanselmann

1258 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1259 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1260 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1261 a8005e17 Michael Hanselmann

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

1264 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1265 a8005e17 Michael Hanselmann

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

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

1270 a8005e17 Michael Hanselmann
  """
1271 a8005e17 Michael Hanselmann
  if args and not args_def:
1272 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1273 a8005e17 Michael Hanselmann
    return False
1274 a8005e17 Michael Hanselmann
1275 a8005e17 Michael Hanselmann
  min_count = None
1276 a8005e17 Michael Hanselmann
  max_count = None
1277 a8005e17 Michael Hanselmann
  check_max = None
1278 a8005e17 Michael Hanselmann
1279 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1280 a8005e17 Michael Hanselmann
1281 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1282 a8005e17 Michael Hanselmann
    if min_count is None:
1283 a8005e17 Michael Hanselmann
      min_count = arg.min
1284 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1285 a8005e17 Michael Hanselmann
      min_count += arg.min
1286 a8005e17 Michael Hanselmann
1287 a8005e17 Michael Hanselmann
    if max_count is None:
1288 a8005e17 Michael Hanselmann
      max_count = arg.max
1289 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1290 a8005e17 Michael Hanselmann
      max_count += arg.max
1291 a8005e17 Michael Hanselmann
1292 a8005e17 Michael Hanselmann
    if idx == last_idx:
1293 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1294 a8005e17 Michael Hanselmann
1295 a8005e17 Michael Hanselmann
    elif arg.max is None:
1296 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1297 a8005e17 Michael Hanselmann
1298 a8005e17 Michael Hanselmann
  if check_max:
1299 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1300 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1301 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1302 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1303 a8005e17 Michael Hanselmann
      return False
1304 a8005e17 Michael Hanselmann
1305 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1306 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1307 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1308 a8005e17 Michael Hanselmann
               cmd, max_count)
1309 a8005e17 Michael Hanselmann
      return False
1310 a8005e17 Michael Hanselmann
1311 a8005e17 Michael Hanselmann
  # Command with some required arguments
1312 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1313 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1314 a8005e17 Michael Hanselmann
             cmd, min_count)
1315 a8005e17 Michael Hanselmann
    return False
1316 a8005e17 Michael Hanselmann
1317 a8005e17 Michael Hanselmann
  return True
1318 a8005e17 Michael Hanselmann
1319 a8005e17 Michael Hanselmann
1320 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1321 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1322 60d49723 Michael Hanselmann

1323 60d49723 Michael Hanselmann
  """
1324 60d49723 Michael Hanselmann
  if value and ':' in value:
1325 60d49723 Michael Hanselmann
    return value.split(':', 1)
1326 60d49723 Michael Hanselmann
  else:
1327 60d49723 Michael Hanselmann
    return (value, None)
1328 60d49723 Michael Hanselmann
1329 60d49723 Michael Hanselmann
1330 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1331 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1332 07150497 Guido Trotter

1333 07150497 Guido Trotter
  @type os_name: string
1334 07150497 Guido Trotter
  @param os_name: base name of the os
1335 07150497 Guido Trotter
  @type os_variants: list or None
1336 07150497 Guido Trotter
  @param os_variants: list of supported variants
1337 07150497 Guido Trotter
  @rtype: list
1338 07150497 Guido Trotter
  @return: list of valid names
1339 07150497 Guido Trotter

1340 07150497 Guido Trotter
  """
1341 07150497 Guido Trotter
  if os_variants:
1342 07150497 Guido Trotter
    return ['%s+%s' % (os_name, v) for v in os_variants]
1343 07150497 Guido Trotter
  else:
1344 07150497 Guido Trotter
    return [os_name]
1345 07150497 Guido Trotter
1346 07150497 Guido Trotter
1347 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1348 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1349 a4ebd726 Michael Hanselmann

1350 a4ebd726 Michael Hanselmann
  @type selected: string or None
1351 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1352 a4ebd726 Michael Hanselmann
  @type default: list
1353 a4ebd726 Michael Hanselmann
  @param default: Default fields
1354 a4ebd726 Michael Hanselmann

1355 a4ebd726 Michael Hanselmann
  """
1356 a4ebd726 Michael Hanselmann
  if selected is None:
1357 a4ebd726 Michael Hanselmann
    return default
1358 a4ebd726 Michael Hanselmann
1359 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1360 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1361 a4ebd726 Michael Hanselmann
1362 a4ebd726 Michael Hanselmann
  return selected.split(",")
1363 a4ebd726 Michael Hanselmann
1364 a4ebd726 Michael Hanselmann
1365 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1366 4331f6cd Michael Hanselmann
1367 4331f6cd Michael Hanselmann
1368 47988778 Iustin Pop
def AskUser(text, choices=None):
1369 47988778 Iustin Pop
  """Ask the user a question.
1370 a8083063 Iustin Pop

1371 c41eea6e Iustin Pop
  @param text: the question to ask
1372 a8083063 Iustin Pop

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

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

1382 a8083063 Iustin Pop
  """
1383 47988778 Iustin Pop
  if choices is None:
1384 47988778 Iustin Pop
    choices = [('y', True, 'Perform the operation'),
1385 47988778 Iustin Pop
               ('n', False, 'Do not perform the operation')]
1386 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1387 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1388 47988778 Iustin Pop
  for entry in choices:
1389 47988778 Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == '?':
1390 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1391 47988778 Iustin Pop
1392 47988778 Iustin Pop
  answer = choices[-1][1]
1393 47988778 Iustin Pop
  new_text = []
1394 47988778 Iustin Pop
  for line in text.splitlines():
1395 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1396 47988778 Iustin Pop
  text = "\n".join(new_text)
1397 a8083063 Iustin Pop
  try:
1398 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1399 a8083063 Iustin Pop
  except IOError:
1400 47988778 Iustin Pop
    return answer
1401 a8083063 Iustin Pop
  try:
1402 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1403 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1404 47988778 Iustin Pop
    chars.append('?')
1405 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1406 47988778 Iustin Pop
    while True:
1407 47988778 Iustin Pop
      f.write(text)
1408 47988778 Iustin Pop
      f.write('\n')
1409 47988778 Iustin Pop
      f.write("/".join(chars))
1410 47988778 Iustin Pop
      f.write(": ")
1411 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1412 47988778 Iustin Pop
      if line in maps:
1413 47988778 Iustin Pop
        answer = maps[line]
1414 47988778 Iustin Pop
        break
1415 47988778 Iustin Pop
      elif line == '?':
1416 47988778 Iustin Pop
        for entry in choices:
1417 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1418 47988778 Iustin Pop
        f.write("\n")
1419 47988778 Iustin Pop
        continue
1420 a8083063 Iustin Pop
  finally:
1421 a8083063 Iustin Pop
    f.close()
1422 a8083063 Iustin Pop
  return answer
1423 a8083063 Iustin Pop
1424 a8083063 Iustin Pop
1425 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1426 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1427 e9d741b6 Iustin Pop

1428 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1429 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1430 e9d741b6 Iustin Pop

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

1433 e9d741b6 Iustin Pop
  """
1434 e9d741b6 Iustin Pop
1435 e9d741b6 Iustin Pop
1436 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1437 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1438 a8083063 Iustin Pop

1439 0a1e74d9 Iustin Pop
  @type ops: list
1440 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1441 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1442 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1443 0a1e74d9 Iustin Pop
             if None, a new client will be created
1444 a8083063 Iustin Pop

1445 a8083063 Iustin Pop
  """
1446 e2212007 Iustin Pop
  if cl is None:
1447 b33e986b Iustin Pop
    cl = GetClient()
1448 685ee993 Iustin Pop
1449 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1450 0a1e74d9 Iustin Pop
1451 0a1e74d9 Iustin Pop
  return job_id
1452 0a1e74d9 Iustin Pop
1453 0a1e74d9 Iustin Pop
1454 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1455 4e338533 Michael Hanselmann
  """Generic job-polling function.
1456 0a1e74d9 Iustin Pop

1457 4e338533 Michael Hanselmann
  @type job_id: number
1458 4e338533 Michael Hanselmann
  @param job_id: Job ID
1459 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1460 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1461 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1462 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1463 0a1e74d9 Iustin Pop

1464 0a1e74d9 Iustin Pop
  """
1465 6c5a7090 Michael Hanselmann
  prev_job_info = None
1466 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1467 6c5a7090 Michael Hanselmann
1468 f4484122 Michael Hanselmann
  status = None
1469 f4484122 Michael Hanselmann
1470 685ee993 Iustin Pop
  while True:
1471 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1472 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
1473 6c5a7090 Michael Hanselmann
    if not result:
1474 685ee993 Iustin Pop
      # job not found, go away!
1475 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1476 4e338533 Michael Hanselmann
1477 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
1478 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
1479 f4484122 Michael Hanselmann
1480 f4484122 Michael Hanselmann
      # Wait again
1481 f4484122 Michael Hanselmann
      continue
1482 685ee993 Iustin Pop
1483 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1484 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1485 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1486 6c5a7090 Michael Hanselmann
1487 6c5a7090 Michael Hanselmann
    if log_entries:
1488 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1489 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
1490 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
1491 4e338533 Michael Hanselmann
                                    log_type, message)
1492 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1493 6c5a7090 Michael Hanselmann
1494 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1495 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1496 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1497 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1498 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1499 685ee993 Iustin Pop
      break
1500 6c5a7090 Michael Hanselmann
1501 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1502 685ee993 Iustin Pop
1503 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1504 0bbe448c Michael Hanselmann
  if not jobs:
1505 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1506 685ee993 Iustin Pop
1507 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1508 4e338533 Michael Hanselmann
1509 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1510 53c04d04 Iustin Pop
    return result
1511 4e338533 Michael Hanselmann
1512 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
1513 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1514 4e338533 Michael Hanselmann
1515 4e338533 Michael Hanselmann
  has_ok = False
1516 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
1517 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
1518 4e338533 Michael Hanselmann
      has_ok = True
1519 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
1520 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
1521 4e338533 Michael Hanselmann
1522 4e338533 Michael Hanselmann
      if has_ok:
1523 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
1524 4e338533 Michael Hanselmann
                                 (idx, msg))
1525 4e338533 Michael Hanselmann
1526 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
1527 4e338533 Michael Hanselmann
1528 4e338533 Michael Hanselmann
  # default failure mode
1529 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
1530 4e338533 Michael Hanselmann
1531 4e338533 Michael Hanselmann
1532 4e338533 Michael Hanselmann
class JobPollCbBase:
1533 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
1534 4e338533 Michael Hanselmann

1535 4e338533 Michael Hanselmann
  """
1536 4e338533 Michael Hanselmann
  def __init__(self):
1537 4e338533 Michael Hanselmann
    """Initializes this class.
1538 4e338533 Michael Hanselmann

1539 4e338533 Michael Hanselmann
    """
1540 4e338533 Michael Hanselmann
1541 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1542 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1543 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1544 4e338533 Michael Hanselmann

1545 4e338533 Michael Hanselmann
    """
1546 4e338533 Michael Hanselmann
    raise NotImplementedError()
1547 4e338533 Michael Hanselmann
1548 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1549 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1550 4e338533 Michael Hanselmann

1551 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
1552 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
1553 4e338533 Michael Hanselmann
    @type fields: list of strings
1554 4e338533 Michael Hanselmann
    @param fields: Fields
1555 4e338533 Michael Hanselmann

1556 4e338533 Michael Hanselmann
    """
1557 4e338533 Michael Hanselmann
    raise NotImplementedError()
1558 4e338533 Michael Hanselmann
1559 4e338533 Michael Hanselmann
1560 4e338533 Michael Hanselmann
class JobPollReportCbBase:
1561 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
1562 4e338533 Michael Hanselmann

1563 4e338533 Michael Hanselmann
  """
1564 4e338533 Michael Hanselmann
  def __init__(self):
1565 4e338533 Michael Hanselmann
    """Initializes this class.
1566 4e338533 Michael Hanselmann

1567 4e338533 Michael Hanselmann
    """
1568 4e338533 Michael Hanselmann
1569 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1570 4e338533 Michael Hanselmann
    """Handles a log message.
1571 4e338533 Michael Hanselmann

1572 4e338533 Michael Hanselmann
    """
1573 4e338533 Michael Hanselmann
    raise NotImplementedError()
1574 4e338533 Michael Hanselmann
1575 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1576 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
1577 4e338533 Michael Hanselmann

1578 4e338533 Michael Hanselmann
    @type job_id: number
1579 4e338533 Michael Hanselmann
    @param job_id: Job ID
1580 4e338533 Michael Hanselmann
    @type status: string or None
1581 4e338533 Michael Hanselmann
    @param status: Job status if available
1582 4e338533 Michael Hanselmann

1583 4e338533 Michael Hanselmann
    """
1584 4e338533 Michael Hanselmann
    raise NotImplementedError()
1585 4e338533 Michael Hanselmann
1586 4e338533 Michael Hanselmann
1587 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
1588 4e338533 Michael Hanselmann
  def __init__(self, cl):
1589 4e338533 Michael Hanselmann
    """Initializes this class.
1590 4e338533 Michael Hanselmann

1591 4e338533 Michael Hanselmann
    """
1592 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
1593 4e338533 Michael Hanselmann
    self.cl = cl
1594 4e338533 Michael Hanselmann
1595 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1596 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1597 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1598 4e338533 Michael Hanselmann

1599 4e338533 Michael Hanselmann
    """
1600 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
1601 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
1602 4e338533 Michael Hanselmann
1603 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1604 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1605 4e338533 Michael Hanselmann

1606 4e338533 Michael Hanselmann
    """
1607 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
1608 4e338533 Michael Hanselmann
1609 4e338533 Michael Hanselmann
1610 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
1611 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
1612 4e338533 Michael Hanselmann
    """Initializes this class.
1613 4e338533 Michael Hanselmann

1614 4e338533 Michael Hanselmann
    """
1615 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1616 4e338533 Michael Hanselmann
1617 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
1618 4e338533 Michael Hanselmann
1619 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
1620 4e338533 Michael Hanselmann
1621 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1622 4e338533 Michael Hanselmann
    """Handles a log message.
1623 4e338533 Michael Hanselmann

1624 4e338533 Michael Hanselmann
    """
1625 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
1626 4e338533 Michael Hanselmann
1627 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1628 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1629 4e338533 Michael Hanselmann

1630 4e338533 Michael Hanselmann
    """
1631 4e338533 Michael Hanselmann
    # Ignore
1632 4e338533 Michael Hanselmann
1633 4e338533 Michael Hanselmann
1634 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
1635 4e338533 Michael Hanselmann
  def __init__(self):
1636 4e338533 Michael Hanselmann
    """Initializes this class.
1637 4e338533 Michael Hanselmann

1638 4e338533 Michael Hanselmann
    """
1639 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1640 4e338533 Michael Hanselmann
1641 4e338533 Michael Hanselmann
    self.notified_queued = False
1642 4e338533 Michael Hanselmann
    self.notified_waitlock = False
1643 4e338533 Michael Hanselmann
1644 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1645 4e338533 Michael Hanselmann
    """Handles a log message.
1646 4e338533 Michael Hanselmann

1647 4e338533 Michael Hanselmann
    """
1648 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
1649 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
1650 4e338533 Michael Hanselmann
1651 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1652 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1653 4e338533 Michael Hanselmann

1654 4e338533 Michael Hanselmann
    """
1655 4e338533 Michael Hanselmann
    if status is None:
1656 4e338533 Michael Hanselmann
      return
1657 4e338533 Michael Hanselmann
1658 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
1659 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
1660 4e338533 Michael Hanselmann
      self.notified_queued = True
1661 4e338533 Michael Hanselmann
1662 4e338533 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITLOCK and not self.notified_waitlock:
1663 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
1664 4e338533 Michael Hanselmann
      self.notified_waitlock = True
1665 4e338533 Michael Hanselmann
1666 4e338533 Michael Hanselmann
1667 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
1668 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
1669 8a7f1c61 Michael Hanselmann

1670 8a7f1c61 Michael Hanselmann
  """
1671 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
1672 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
1673 8a7f1c61 Michael Hanselmann
1674 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
1675 8a7f1c61 Michael Hanselmann
1676 8a7f1c61 Michael Hanselmann
1677 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
1678 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
1679 4e338533 Michael Hanselmann

1680 4e338533 Michael Hanselmann
  @type job_id: job identified
1681 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
1682 4e338533 Michael Hanselmann
  @type cl: luxi.Client
1683 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
1684 4e338533 Michael Hanselmann
             if None, a new client will be created
1685 4e338533 Michael Hanselmann

1686 4e338533 Michael Hanselmann
  """
1687 4e338533 Michael Hanselmann
  if cl is None:
1688 4e338533 Michael Hanselmann
    cl = GetClient()
1689 4e338533 Michael Hanselmann
1690 583163a6 Michael Hanselmann
  if reporter is None:
1691 583163a6 Michael Hanselmann
    if feedback_fn:
1692 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
1693 583163a6 Michael Hanselmann
    else:
1694 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
1695 583163a6 Michael Hanselmann
  elif feedback_fn:
1696 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
1697 4e338533 Michael Hanselmann
1698 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
1699 ceab32dd Iustin Pop
1700 ceab32dd Iustin Pop
1701 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
1702 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
1703 0a1e74d9 Iustin Pop

1704 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
1705 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
1706 0a1e74d9 Iustin Pop
  interaction functions.
1707 0a1e74d9 Iustin Pop

1708 0a1e74d9 Iustin Pop
  """
1709 0a1e74d9 Iustin Pop
  if cl is None:
1710 0a1e74d9 Iustin Pop
    cl = GetClient()
1711 0a1e74d9 Iustin Pop
1712 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
1713 293ba2d8 Iustin Pop
1714 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
1715 0a1e74d9 Iustin Pop
1716 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
1717 583163a6 Michael Hanselmann
                       reporter=reporter)
1718 53c04d04 Iustin Pop
1719 53c04d04 Iustin Pop
  return op_results[0]
1720 0a1e74d9 Iustin Pop
1721 0a1e74d9 Iustin Pop
1722 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
1723 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
1724 94428652 Iustin Pop

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

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

1733 94428652 Iustin Pop
  """
1734 94428652 Iustin Pop
  if opts and opts.submit_only:
1735 293ba2d8 Iustin Pop
    job = [op]
1736 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
1737 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
1738 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
1739 94428652 Iustin Pop
  else:
1740 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
1741 293ba2d8 Iustin Pop
1742 293ba2d8 Iustin Pop
1743 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
1744 293ba2d8 Iustin Pop
  """Processor for generic options.
1745 293ba2d8 Iustin Pop

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

1749 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
1750 293ba2d8 Iustin Pop
  @param options: command line options or None
1751 293ba2d8 Iustin Pop
  @return: None (in-place modification)
1752 293ba2d8 Iustin Pop

1753 293ba2d8 Iustin Pop
  """
1754 293ba2d8 Iustin Pop
  if not options:
1755 293ba2d8 Iustin Pop
    return
1756 293ba2d8 Iustin Pop
  for op in opcode_list:
1757 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
1758 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
1759 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
1760 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
1761 aa06f8c6 Michael Hanselmann
      op.priority = _PRIONAME_TO_VALUE[options.priority]
1762 94428652 Iustin Pop
1763 94428652 Iustin Pop
1764 af30b2fd Michael Hanselmann
def GetClient():
1765 af30b2fd Michael Hanselmann
  # TODO: Cache object?
1766 b33e986b Iustin Pop
  try:
1767 b33e986b Iustin Pop
    client = luxi.Client()
1768 b33e986b Iustin Pop
  except luxi.NoMasterError:
1769 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
1770 d9a51679 Michael Hanselmann
1771 d9a51679 Michael Hanselmann
    # Try to read ssconf file
1772 d9a51679 Michael Hanselmann
    try:
1773 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
1774 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
1775 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
1776 d9a51679 Michael Hanselmann
                                 " not part of a cluster")
1777 d9a51679 Michael Hanselmann
1778 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
1779 b33e986b Iustin Pop
    if master != myself:
1780 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
1781 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
1782 b33e986b Iustin Pop
                                 master)
1783 d9a51679 Michael Hanselmann
    raise
1784 b33e986b Iustin Pop
  return client
1785 af30b2fd Michael Hanselmann
1786 af30b2fd Michael Hanselmann
1787 73702ee7 Iustin Pop
def FormatError(err):
1788 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
1789 73702ee7 Iustin Pop

1790 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
1791 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
1792 73702ee7 Iustin Pop
  second, a string describing the error message (not
1793 73702ee7 Iustin Pop
  newline-terminated).
1794 73702ee7 Iustin Pop

1795 73702ee7 Iustin Pop
  """
1796 73702ee7 Iustin Pop
  retcode = 1
1797 73702ee7 Iustin Pop
  obuf = StringIO()
1798 e2e521d0 Iustin Pop
  msg = str(err)
1799 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
1800 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
1801 46fbdd04 Iustin Pop
    logging.error(txt)
1802 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
1803 73702ee7 Iustin Pop
    obuf.write("Aborting.")
1804 73702ee7 Iustin Pop
    retcode = 2
1805 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
1806 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
1807 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
1808 73702ee7 Iustin Pop
      if out:
1809 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
1810 73702ee7 Iustin Pop
                   (node, script, out))
1811 73702ee7 Iustin Pop
      else:
1812 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
1813 73702ee7 Iustin Pop
                   (node, script))
1814 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
1815 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
1816 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
1817 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
1818 73702ee7 Iustin Pop
    if err.args[0] == this_host:
1819 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
1820 73702ee7 Iustin Pop
    else:
1821 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
1822 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
1823 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
1824 5c983ee5 Iustin Pop
    if len(err.args) == 2:
1825 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1826 5c983ee5 Iustin Pop
               " operation:\nerror type: %s, error details:\n%s" %
1827 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
1828 5c983ee5 Iustin Pop
    else:
1829 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1830 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
1831 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
1832 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
1833 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
1834 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
1835 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
1836 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
1837 686d7433 Iustin Pop
               " accept new requests\n")
1838 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
1839 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
1840 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
1841 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
1842 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
1843 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
1844 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
1845 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
1846 03a8dbdc Iustin Pop
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
1847 082c5adb Michael Hanselmann
               " and listening for connections?")
1848 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
1849 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
1850 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
1851 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
1852 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
1853 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
1854 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
1855 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
1856 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
1857 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
1858 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
1859 03a8dbdc Iustin Pop
               "%s" % msg)
1860 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
1861 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
1862 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
1863 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
1864 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
1865 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
1866 e9d741b6 Iustin Pop
    retcode = 0
1867 73702ee7 Iustin Pop
  else:
1868 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
1869 73702ee7 Iustin Pop
  return retcode, obuf.getvalue().rstrip('\n')
1870 73702ee7 Iustin Pop
1871 73702ee7 Iustin Pop
1872 de47cf8f Guido Trotter
def GenericMain(commands, override=None, aliases=None):
1873 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
1874 a8083063 Iustin Pop

1875 334d1483 Iustin Pop
  Arguments:
1876 334d1483 Iustin Pop
    - commands: a dictionary with a special structure, see the design doc
1877 334d1483 Iustin Pop
                for command line handling.
1878 334d1483 Iustin Pop
    - override: if not None, we expect a dictionary with keys that will
1879 334d1483 Iustin Pop
                override command line options; this can be used to pass
1880 334d1483 Iustin Pop
                options from the scripts to generic functions
1881 de47cf8f Guido Trotter
    - aliases: dictionary with command aliases {'alias': 'target, ...}
1882 a8083063 Iustin Pop

1883 a8083063 Iustin Pop
  """
1884 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
1885 a8083063 Iustin Pop
  if sys.argv:
1886 a8083063 Iustin Pop
    binary = os.path.basename(sys.argv[0]) or sys.argv[0]
1887 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
1888 a8083063 Iustin Pop
      binary += " " + sys.argv[1]
1889 a8083063 Iustin Pop
      old_cmdline = " ".join(sys.argv[2:])
1890 a8083063 Iustin Pop
    else:
1891 a8083063 Iustin Pop
      old_cmdline = ""
1892 a8083063 Iustin Pop
  else:
1893 a8083063 Iustin Pop
    binary = "<unknown program>"
1894 a8083063 Iustin Pop
    old_cmdline = ""
1895 a8083063 Iustin Pop
1896 de47cf8f Guido Trotter
  if aliases is None:
1897 de47cf8f Guido Trotter
    aliases = {}
1898 de47cf8f Guido Trotter
1899 3126878d Guido Trotter
  try:
1900 3126878d Guido Trotter
    func, options, args = _ParseArgs(sys.argv, commands, aliases)
1901 3126878d Guido Trotter
  except errors.ParameterError, err:
1902 3126878d Guido Trotter
    result, err_msg = FormatError(err)
1903 3126878d Guido Trotter
    ToStderr(err_msg)
1904 3126878d Guido Trotter
    return 1
1905 3126878d Guido Trotter
1906 a8083063 Iustin Pop
  if func is None: # parse error
1907 a8083063 Iustin Pop
    return 1
1908 a8083063 Iustin Pop
1909 334d1483 Iustin Pop
  if override is not None:
1910 334d1483 Iustin Pop
    for key, val in override.iteritems():
1911 334d1483 Iustin Pop
      setattr(options, key, val)
1912 334d1483 Iustin Pop
1913 82d9caef Iustin Pop
  utils.SetupLogging(constants.LOG_COMMANDS, debug=options.debug,
1914 82d9caef Iustin Pop
                     stderr_logging=True, program=binary)
1915 a8083063 Iustin Pop
1916 a8083063 Iustin Pop
  if old_cmdline:
1917 46fbdd04 Iustin Pop
    logging.info("run with arguments '%s'", old_cmdline)
1918 a8083063 Iustin Pop
  else:
1919 46fbdd04 Iustin Pop
    logging.info("run with no arguments")
1920 a8083063 Iustin Pop
1921 a8083063 Iustin Pop
  try:
1922 a4af651e Iustin Pop
    result = func(options, args)
1923 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
1924 d8353c3a Iustin Pop
          JobSubmittedException), err:
1925 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
1926 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
1927 46fbdd04 Iustin Pop
    ToStderr(err_msg)
1928 a8083063 Iustin Pop
1929 a8083063 Iustin Pop
  return result
1930 137161c9 Michael Hanselmann
1931 137161c9 Michael Hanselmann
1932 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
1933 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
1934 845c79d8 Michael Hanselmann

1935 845c79d8 Michael Hanselmann
  """
1936 845c79d8 Michael Hanselmann
  try:
1937 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
1938 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
1939 845c79d8 Michael Hanselmann
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
1940 845c79d8 Michael Hanselmann
1941 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
1942 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
1943 845c79d8 Michael Hanselmann
    nidx = int(nidx)
1944 845c79d8 Michael Hanselmann
1945 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
1946 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
1947 845c79d8 Michael Hanselmann
                                 " got %s" % (nidx, ndict))
1948 845c79d8 Michael Hanselmann
1949 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
1950 845c79d8 Michael Hanselmann
1951 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
1952 845c79d8 Michael Hanselmann
1953 845c79d8 Michael Hanselmann
  return nics
1954 845c79d8 Michael Hanselmann
1955 845c79d8 Michael Hanselmann
1956 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
1957 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
1958 d77490c5 Iustin Pop

1959 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
1960 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
1961 d77490c5 Iustin Pop
  @type args: list
1962 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
1963 d77490c5 Iustin Pop
  @rtype: int
1964 d77490c5 Iustin Pop
  @return: the desired exit code
1965 d77490c5 Iustin Pop

1966 d77490c5 Iustin Pop
  """
1967 d77490c5 Iustin Pop
  instance = args[0]
1968 d77490c5 Iustin Pop
1969 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
1970 d77490c5 Iustin Pop
1971 d77490c5 Iustin Pop
  hypervisor = None
1972 d77490c5 Iustin Pop
  hvparams = {}
1973 d77490c5 Iustin Pop
  if opts.hypervisor:
1974 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
1975 d77490c5 Iustin Pop
1976 d77490c5 Iustin Pop
  if opts.nics:
1977 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
1978 d77490c5 Iustin Pop
  elif opts.no_nics:
1979 d77490c5 Iustin Pop
    # no nics
1980 d77490c5 Iustin Pop
    nics = []
1981 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
1982 d77490c5 Iustin Pop
    # default of one nic, all auto
1983 d77490c5 Iustin Pop
    nics = [{}]
1984 0af0f641 Iustin Pop
  else:
1985 0af0f641 Iustin Pop
    # mode == import
1986 0af0f641 Iustin Pop
    nics = []
1987 d77490c5 Iustin Pop
1988 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
1989 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
1990 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
1991 d77490c5 Iustin Pop
                                 " information passed")
1992 d77490c5 Iustin Pop
    disks = []
1993 d77490c5 Iustin Pop
  else:
1994 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
1995 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
1996 d77490c5 Iustin Pop
      raise errors.OpPrereqError("No disk information specified")
1997 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
1998 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
1999 d77490c5 Iustin Pop
                                 " '-s' option")
2000 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2001 d77490c5 Iustin Pop
      opts.disks = [(0, {"size": opts.sd_size})]
2002 9b12ed0f Iustin Pop
2003 9b12ed0f Iustin Pop
    if opts.disks:
2004 9b12ed0f Iustin Pop
      try:
2005 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2006 9b12ed0f Iustin Pop
      except ValueError, err:
2007 9b12ed0f Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
2008 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2009 9b12ed0f Iustin Pop
    else:
2010 9b12ed0f Iustin Pop
      disks = []
2011 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2012 d77490c5 Iustin Pop
      didx = int(didx)
2013 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2014 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2015 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
2016 5029db65 Iustin Pop
      elif "size" in ddict:
2017 5029db65 Iustin Pop
        if "adopt" in ddict:
2018 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2019 5029db65 Iustin Pop
                                     " (disk %d)" % didx)
2020 5029db65 Iustin Pop
        try:
2021 5029db65 Iustin Pop
          ddict["size"] = utils.ParseUnit(ddict["size"])
2022 5029db65 Iustin Pop
        except ValueError, err:
2023 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2024 5029db65 Iustin Pop
                                     (didx, err))
2025 5029db65 Iustin Pop
      elif "adopt" in ddict:
2026 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2027 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2028 5029db65 Iustin Pop
                                     " import")
2029 5029db65 Iustin Pop
        ddict["size"] = 0
2030 5029db65 Iustin Pop
      else:
2031 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2032 5029db65 Iustin Pop
                                   " disk %d" % didx)
2033 d77490c5 Iustin Pop
      disks[didx] = ddict
2034 d77490c5 Iustin Pop
2035 d77490c5 Iustin Pop
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
2036 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2037 d77490c5 Iustin Pop
2038 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2039 d77490c5 Iustin Pop
    start = opts.start
2040 d77490c5 Iustin Pop
    os_type = opts.os
2041 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2042 d77490c5 Iustin Pop
    src_node = None
2043 d77490c5 Iustin Pop
    src_path = None
2044 25a8792c Iustin Pop
    no_install = opts.no_install
2045 e588764d Iustin Pop
    identify_defaults = False
2046 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2047 d77490c5 Iustin Pop
    start = False
2048 d77490c5 Iustin Pop
    os_type = None
2049 1ee8e01a Guido Trotter
    force_variant = False
2050 d77490c5 Iustin Pop
    src_node = opts.src_node
2051 d77490c5 Iustin Pop
    src_path = opts.src_dir
2052 25a8792c Iustin Pop
    no_install = None
2053 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2054 d77490c5 Iustin Pop
  else:
2055 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2056 d77490c5 Iustin Pop
2057 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2058 d77490c5 Iustin Pop
                                disks=disks,
2059 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2060 d77490c5 Iustin Pop
                                nics=nics,
2061 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2062 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2063 460d22be Iustin Pop
                                name_check=opts.name_check,
2064 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2065 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2066 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2067 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2068 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2069 d77490c5 Iustin Pop
                                hvparams=hvparams,
2070 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2071 062a7100 Iustin Pop
                                osparams=opts.osparams,
2072 d77490c5 Iustin Pop
                                mode=mode,
2073 d77490c5 Iustin Pop
                                start=start,
2074 d77490c5 Iustin Pop
                                os_type=os_type,
2075 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2076 d77490c5 Iustin Pop
                                src_node=src_node,
2077 25a8792c Iustin Pop
                                src_path=src_path,
2078 e588764d Iustin Pop
                                no_install=no_install,
2079 e588764d Iustin Pop
                                identify_defaults=identify_defaults)
2080 d77490c5 Iustin Pop
2081 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2082 d77490c5 Iustin Pop
  return 0
2083 d77490c5 Iustin Pop
2084 d77490c5 Iustin Pop
2085 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2086 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2087 7e49b6ce Michael Hanselmann

2088 7e49b6ce Michael Hanselmann
  """
2089 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2090 7e49b6ce Michael Hanselmann
    """Initializes this class.
2091 7e49b6ce Michael Hanselmann

2092 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2093 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2094 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2095 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2096 7e49b6ce Michael Hanselmann
    @type master_node: string
2097 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2098 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2099 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2100 7e49b6ce Michael Hanselmann

2101 7e49b6ce Michael Hanselmann
    """
2102 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2103 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2104 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2105 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2106 7e49b6ce Michael Hanselmann
2107 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2108 7e49b6ce Michael Hanselmann
2109 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2110 7e49b6ce Michael Hanselmann
                            if name != master_node]
2111 7e49b6ce Michael Hanselmann
2112 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2113 7e49b6ce Michael Hanselmann
2114 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2115 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2116 7e49b6ce Michael Hanselmann

2117 7e49b6ce Michael Hanselmann
    @type node_name: string
2118 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2119 7e49b6ce Michael Hanselmann
    @type cmd: list
2120 7e49b6ce Michael Hanselmann
    @param cmd: Command
2121 7e49b6ce Michael Hanselmann

2122 7e49b6ce Michael Hanselmann
    """
2123 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2124 7e49b6ce Michael Hanselmann
      # No need to use SSH
2125 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2126 7e49b6ce Michael Hanselmann
    else:
2127 7e49b6ce Michael Hanselmann
      result = self.ssh.Run(node_name, "root", utils.ShellQuoteArgs(cmd))
2128 7e49b6ce Michael Hanselmann
2129 7e49b6ce Michael Hanselmann
    if result.failed:
2130 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2131 7e49b6ce Michael Hanselmann
      if node_name:
2132 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2133 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2134 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2135 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2136 7e49b6ce Michael Hanselmann
2137 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2138 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2139 7e49b6ce Michael Hanselmann

2140 7e49b6ce Michael Hanselmann
    @type fn: callable
2141 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2142 7e49b6ce Michael Hanselmann

2143 7e49b6ce Michael Hanselmann
    """
2144 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2145 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2146 7e49b6ce Michael Hanselmann
    watcher_block = utils.FileLock.Open(constants.WATCHER_STATEFILE)
2147 7e49b6ce Michael Hanselmann
    try:
2148 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2149 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2150 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2151 7e49b6ce Michael Hanselmann
2152 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2153 7e49b6ce Michael Hanselmann
      # ones are finished
2154 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2155 7e49b6ce Michael Hanselmann
      self._RunCmd(None, [constants.DAEMON_UTIL, "stop-master"])
2156 7e49b6ce Michael Hanselmann
      try:
2157 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2158 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2159 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2160 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "stop-all"])
2161 7e49b6ce Michael Hanselmann
2162 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2163 7e49b6ce Michael Hanselmann
        try:
2164 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2165 d512e84b Michael Hanselmann
        except Exception, err:
2166 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2167 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2168 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2169 7e49b6ce Michael Hanselmann
          raise
2170 7e49b6ce Michael Hanselmann
      finally:
2171 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2172 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2173 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2174 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "start-all"])
2175 7e49b6ce Michael Hanselmann
    finally:
2176 7e49b6ce Michael Hanselmann
      # Resume watcher
2177 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2178 7e49b6ce Michael Hanselmann
2179 7e49b6ce Michael Hanselmann
2180 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2181 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2182 7e49b6ce Michael Hanselmann

2183 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2184 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2185 7e49b6ce Michael Hanselmann
  @type fn: callable
2186 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2187 7e49b6ce Michael Hanselmann

2188 7e49b6ce Michael Hanselmann
  """
2189 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2190 7e49b6ce Michael Hanselmann
2191 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2192 7e49b6ce Michael Hanselmann
  cl = GetClient()
2193 7e49b6ce Michael Hanselmann
2194 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2195 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2196 7e49b6ce Michael Hanselmann
2197 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2198 7e49b6ce Michael Hanselmann
2199 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2200 7e49b6ce Michael Hanselmann
  del cl
2201 7e49b6ce Michael Hanselmann
2202 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2203 7e49b6ce Michael Hanselmann
2204 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2205 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2206 7e49b6ce Michael Hanselmann
2207 7e49b6ce Michael Hanselmann
2208 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2209 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2210 9fbfbb7b Iustin Pop
                  units=None):
2211 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2212 137161c9 Michael Hanselmann

2213 9fbfbb7b Iustin Pop
  @type headers: dict
2214 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2215 9fbfbb7b Iustin Pop
      the table
2216 9fbfbb7b Iustin Pop
  @type fields: list
2217 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2218 9fbfbb7b Iustin Pop
      the data field
2219 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2220 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2221 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2222 9fbfbb7b Iustin Pop
      each field
2223 9fbfbb7b Iustin Pop
  @type data: list
2224 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2225 9fbfbb7b Iustin Pop
  @type numfields: list
2226 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2227 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2228 9fbfbb7b Iustin Pop
  @type unitfields: list
2229 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2230 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2231 9fbfbb7b Iustin Pop
  @type units: string or None
2232 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2233 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2234 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2235 137161c9 Michael Hanselmann

2236 137161c9 Michael Hanselmann
  """
2237 9fbfbb7b Iustin Pop
  if units is None:
2238 9fbfbb7b Iustin Pop
    if separator:
2239 9fbfbb7b Iustin Pop
      units = "m"
2240 9fbfbb7b Iustin Pop
    else:
2241 9fbfbb7b Iustin Pop
      units = "h"
2242 9fbfbb7b Iustin Pop
2243 137161c9 Michael Hanselmann
  if numfields is None:
2244 137161c9 Michael Hanselmann
    numfields = []
2245 137161c9 Michael Hanselmann
  if unitfields is None:
2246 137161c9 Michael Hanselmann
    unitfields = []
2247 137161c9 Michael Hanselmann
2248 fe267188 Iustin Pop
  numfields = utils.FieldSet(*numfields)   # pylint: disable-msg=W0142
2249 fe267188 Iustin Pop
  unitfields = utils.FieldSet(*unitfields) # pylint: disable-msg=W0142
2250 00430f8e Iustin Pop
2251 137161c9 Michael Hanselmann
  format_fields = []
2252 137161c9 Michael Hanselmann
  for field in fields:
2253 01ca31ae Iustin Pop
    if headers and field not in headers:
2254 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2255 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2256 71c1af58 Iustin Pop
      # variable fields)
2257 71c1af58 Iustin Pop
      headers[field] = field
2258 137161c9 Michael Hanselmann
    if separator is not None:
2259 137161c9 Michael Hanselmann
      format_fields.append("%s")
2260 00430f8e Iustin Pop
    elif numfields.Matches(field):
2261 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2262 137161c9 Michael Hanselmann
    else:
2263 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2264 137161c9 Michael Hanselmann
2265 137161c9 Michael Hanselmann
  if separator is None:
2266 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2267 c04bc777 Iustin Pop
    format_str = ' '.join(format_fields)
2268 137161c9 Michael Hanselmann
  else:
2269 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2270 137161c9 Michael Hanselmann
2271 137161c9 Michael Hanselmann
  for row in data:
2272 dcbd6288 Guido Trotter
    if row is None:
2273 dcbd6288 Guido Trotter
      continue
2274 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2275 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2276 137161c9 Michael Hanselmann
        try:
2277 137161c9 Michael Hanselmann
          val = int(val)
2278 691744c4 Iustin Pop
        except (TypeError, ValueError):
2279 137161c9 Michael Hanselmann
          pass
2280 137161c9 Michael Hanselmann
        else:
2281 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2282 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2283 137161c9 Michael Hanselmann
      if separator is None:
2284 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2285 137161c9 Michael Hanselmann
2286 16be8703 Iustin Pop
  result = []
2287 137161c9 Michael Hanselmann
  if headers:
2288 137161c9 Michael Hanselmann
    args = []
2289 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2290 137161c9 Michael Hanselmann
      hdr = headers[name]
2291 137161c9 Michael Hanselmann
      if separator is None:
2292 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2293 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2294 137161c9 Michael Hanselmann
      args.append(hdr)
2295 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2296 137161c9 Michael Hanselmann
2297 ec39d63c Michael Hanselmann
  if separator is None:
2298 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2299 ec39d63c Michael Hanselmann
2300 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2301 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2302 ec39d63c Michael Hanselmann
2303 137161c9 Michael Hanselmann
  for line in data:
2304 137161c9 Michael Hanselmann
    args = []
2305 dcbd6288 Guido Trotter
    if line is None:
2306 dcbd6288 Guido Trotter
      line = ['-' for _ in fields]
2307 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2308 137161c9 Michael Hanselmann
      if separator is None:
2309 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2310 137161c9 Michael Hanselmann
      args.append(line[idx])
2311 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2312 16be8703 Iustin Pop
2313 16be8703 Iustin Pop
  return result
2314 3386e7a9 Iustin Pop
2315 3386e7a9 Iustin Pop
2316 ee3aedff Michael Hanselmann
def _FormatBool(value):
2317 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
2318 ee3aedff Michael Hanselmann

2319 ee3aedff Michael Hanselmann
  """
2320 ee3aedff Michael Hanselmann
  if value:
2321 ee3aedff Michael Hanselmann
    return "Y"
2322 ee3aedff Michael Hanselmann
  return "N"
2323 ee3aedff Michael Hanselmann
2324 ee3aedff Michael Hanselmann
2325 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2326 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2327 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2328 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2329 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2330 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2331 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2332 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2333 ee3aedff Michael Hanselmann
  }
2334 ee3aedff Michael Hanselmann
2335 ee3aedff Michael Hanselmann
2336 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2337 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2338 ee3aedff Michael Hanselmann

2339 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2340 ee3aedff Michael Hanselmann
  @type override: dict
2341 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2342 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2343 ee3aedff Michael Hanselmann
  @type unit: string
2344 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2345 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2346 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2347 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2348 ee3aedff Michael Hanselmann

2349 ee3aedff Michael Hanselmann
  """
2350 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2351 ee3aedff Michael Hanselmann
  if fmt is not None:
2352 ee3aedff Michael Hanselmann
    return fmt
2353 ee3aedff Michael Hanselmann
2354 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2355 ee3aedff Michael Hanselmann
2356 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2357 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2358 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2359 ee3aedff Michael Hanselmann
2360 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2361 ee3aedff Michael Hanselmann
  if fmt is not None:
2362 ee3aedff Michael Hanselmann
    return fmt
2363 ee3aedff Michael Hanselmann
2364 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
2365 ee3aedff Michael Hanselmann
2366 ee3aedff Michael Hanselmann
2367 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
2368 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
2369 ee3aedff Michael Hanselmann

2370 ee3aedff Michael Hanselmann
  """
2371 ee3aedff Michael Hanselmann
  def __init__(self, fn, status_fn):
2372 ee3aedff Michael Hanselmann
    """Initializes this class.
2373 ee3aedff Michael Hanselmann

2374 ee3aedff Michael Hanselmann
    @type fn: callable
2375 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2376 ee3aedff Michael Hanselmann
    @type status_fn: callable
2377 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
2378 ee3aedff Michael Hanselmann

2379 ee3aedff Michael Hanselmann
    """
2380 ee3aedff Michael Hanselmann
    self._fn = fn
2381 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
2382 ee3aedff Michael Hanselmann
2383 ee3aedff Michael Hanselmann
  def __call__(self, data):
2384 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
2385 ee3aedff Michael Hanselmann

2386 ee3aedff Michael Hanselmann
    """
2387 ee3aedff Michael Hanselmann
    (status, value) = data
2388 ee3aedff Michael Hanselmann
2389 ee3aedff Michael Hanselmann
    # Report status
2390 ee3aedff Michael Hanselmann
    self._status_fn(status)
2391 ee3aedff Michael Hanselmann
2392 ee3aedff Michael Hanselmann
    if status == constants.QRFS_NORMAL:
2393 ee3aedff Michael Hanselmann
      return self._fn(value)
2394 ee3aedff Michael Hanselmann
2395 ee3aedff Michael Hanselmann
    assert value is None, \
2396 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
2397 ee3aedff Michael Hanselmann
2398 ee3aedff Michael Hanselmann
    if status == constants.QRFS_UNKNOWN:
2399 2466c0fd Michael Hanselmann
      return "(unknown)"
2400 ee3aedff Michael Hanselmann
2401 ee3aedff Michael Hanselmann
    if status == constants.QRFS_NODATA:
2402 2466c0fd Michael Hanselmann
      return "(nodata)"
2403 ee3aedff Michael Hanselmann
2404 ee3aedff Michael Hanselmann
    if status == constants.QRFS_UNAVAIL:
2405 2466c0fd Michael Hanselmann
      return "(unavail)"
2406 ee3aedff Michael Hanselmann
2407 a6070ef7 Michael Hanselmann
    if status == constants.QRFS_OFFLINE:
2408 a6070ef7 Michael Hanselmann
      return "(offline)"
2409 a6070ef7 Michael Hanselmann
2410 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
2411 ee3aedff Michael Hanselmann
2412 ee3aedff Michael Hanselmann
2413 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
2414 ee3aedff Michael Hanselmann
                      header=False):
2415 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
2416 ee3aedff Michael Hanselmann

2417 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
2418 ee3aedff Michael Hanselmann
  @param result: result of query operation
2419 ee3aedff Michael Hanselmann
  @type unit: string
2420 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
2421 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
2422 ee3aedff Michael Hanselmann
  @type format_override: dict
2423 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2424 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2425 ee3aedff Michael Hanselmann
  @type separator: string or None
2426 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2427 ee3aedff Michael Hanselmann
  @type header: bool
2428 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
2429 ee3aedff Michael Hanselmann

2430 ee3aedff Michael Hanselmann
  """
2431 ee3aedff Michael Hanselmann
  if unit is None:
2432 ee3aedff Michael Hanselmann
    if separator:
2433 ee3aedff Michael Hanselmann
      unit = "m"
2434 ee3aedff Michael Hanselmann
    else:
2435 ee3aedff Michael Hanselmann
      unit = "h"
2436 ee3aedff Michael Hanselmann
2437 ee3aedff Michael Hanselmann
  if format_override is None:
2438 ee3aedff Michael Hanselmann
    format_override = {}
2439 ee3aedff Michael Hanselmann
2440 ee3aedff Michael Hanselmann
  stats = dict.fromkeys(constants.QRFS_ALL, 0)
2441 ee3aedff Michael Hanselmann
2442 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
2443 ee3aedff Michael Hanselmann
    if status in stats:
2444 ee3aedff Michael Hanselmann
      stats[status] += 1
2445 ee3aedff Michael Hanselmann
2446 ee3aedff Michael Hanselmann
  columns = []
2447 ee3aedff Michael Hanselmann
  for fdef in result.fields:
2448 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
2449 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
2450 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
2451 ee3aedff Michael Hanselmann
                               _QueryColumnFormatter(fn, _RecordStatus),
2452 ee3aedff Michael Hanselmann
                               align_right))
2453 ee3aedff Michael Hanselmann
2454 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
2455 ee3aedff Michael Hanselmann
2456 ee3aedff Michael Hanselmann
  # Collect statistics
2457 ee3aedff Michael Hanselmann
  assert len(stats) == len(constants.QRFS_ALL)
2458 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
2459 ee3aedff Michael Hanselmann
2460 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
2461 ee3aedff Michael Hanselmann
  # detected via the field definitions.
2462 ee3aedff Michael Hanselmann
  if (stats[constants.QRFS_UNKNOWN] or
2463 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
2464 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
2465 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
2466 ee3aedff Michael Hanselmann
                  if key != constants.QRFS_NORMAL):
2467 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
2468 ee3aedff Michael Hanselmann
  else:
2469 ee3aedff Michael Hanselmann
    status = QR_NORMAL
2470 ee3aedff Michael Hanselmann
2471 ee3aedff Michael Hanselmann
  return (status, table)
2472 ee3aedff Michael Hanselmann
2473 ee3aedff Michael Hanselmann
2474 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
2475 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
2476 ee3aedff Michael Hanselmann

2477 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2478 ee3aedff Michael Hanselmann

2479 ee3aedff Michael Hanselmann
  """
2480 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
2481 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
2482 ee3aedff Michael Hanselmann
2483 ee3aedff Michael Hanselmann
2484 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
2485 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
2486 ee3aedff Michael Hanselmann

2487 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2488 ee3aedff Michael Hanselmann

2489 ee3aedff Michael Hanselmann
  """
2490 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
2491 ee3aedff Michael Hanselmann
  if unknown:
2492 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
2493 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
2494 ee3aedff Michael Hanselmann
    return True
2495 ee3aedff Michael Hanselmann
2496 ee3aedff Michael Hanselmann
  return False
2497 ee3aedff Michael Hanselmann
2498 ee3aedff Michael Hanselmann
2499 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
2500 ee3aedff Michael Hanselmann
                format_override=None):
2501 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
2502 ee3aedff Michael Hanselmann

2503 ee3aedff Michael Hanselmann
  @param resource: One of L{constants.QR_OP_LUXI}
2504 ee3aedff Michael Hanselmann
  @type fields: list of strings
2505 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
2506 ee3aedff Michael Hanselmann
  @type names: list of strings
2507 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
2508 ee3aedff Michael Hanselmann
  @type unit: string or None
2509 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
2510 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
2511 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
2512 ee3aedff Michael Hanselmann
  @type separator: string or None
2513 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2514 ee3aedff Michael Hanselmann
  @type header: bool
2515 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2516 ee3aedff Michael Hanselmann
  @type format_override: dict
2517 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2518 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2519 ee3aedff Michael Hanselmann

2520 ee3aedff Michael Hanselmann
  """
2521 ee3aedff Michael Hanselmann
  if cl is None:
2522 ee3aedff Michael Hanselmann
    cl = GetClient()
2523 ee3aedff Michael Hanselmann
2524 ee3aedff Michael Hanselmann
  if not names:
2525 ee3aedff Michael Hanselmann
    names = None
2526 ee3aedff Michael Hanselmann
2527 ee3aedff Michael Hanselmann
  response = cl.Query(resource, fields, qlang.MakeSimpleFilter("name", names))
2528 ee3aedff Michael Hanselmann
2529 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
2530 ee3aedff Michael Hanselmann
2531 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
2532 ee3aedff Michael Hanselmann
                                     header=header,
2533 ee3aedff Michael Hanselmann
                                     format_override=format_override)
2534 ee3aedff Michael Hanselmann
2535 ee3aedff Michael Hanselmann
  for line in data:
2536 ee3aedff Michael Hanselmann
    ToStdout(line)
2537 ee3aedff Michael Hanselmann
2538 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
2539 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
2540 ee3aedff Michael Hanselmann
2541 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
2542 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
2543 ee3aedff Michael Hanselmann
2544 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
2545 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
2546 ee3aedff Michael Hanselmann
2547 ee3aedff Michael Hanselmann
2548 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
2549 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
2550 ee3aedff Michael Hanselmann

2551 ee3aedff Michael Hanselmann
  @param resource: One of L{constants.QR_OP_LUXI}
2552 ee3aedff Michael Hanselmann
  @type fields: list of strings
2553 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
2554 ee3aedff Michael Hanselmann
  @type separator: string or None
2555 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2556 ee3aedff Michael Hanselmann
  @type header: bool
2557 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2558 ee3aedff Michael Hanselmann

2559 ee3aedff Michael Hanselmann
  """
2560 ee3aedff Michael Hanselmann
  if cl is None:
2561 ee3aedff Michael Hanselmann
    cl = GetClient()
2562 ee3aedff Michael Hanselmann
2563 ee3aedff Michael Hanselmann
  if not fields:
2564 ee3aedff Michael Hanselmann
    fields = None
2565 ee3aedff Michael Hanselmann
2566 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
2567 ee3aedff Michael Hanselmann
2568 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
2569 ee3aedff Michael Hanselmann
2570 ee3aedff Michael Hanselmann
  columns = [
2571 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
2572 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
2573 ee3aedff Michael Hanselmann
    # TODO: Add field description to master daemon
2574 ee3aedff Michael Hanselmann
    ]
2575 ee3aedff Michael Hanselmann
2576 ee3aedff Michael Hanselmann
  rows = [[fdef.name, fdef.title] for fdef in response.fields]
2577 ee3aedff Michael Hanselmann
2578 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
2579 ee3aedff Michael Hanselmann
    ToStdout(line)
2580 ee3aedff Michael Hanselmann
2581 ee3aedff Michael Hanselmann
  if found_unknown:
2582 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
2583 ee3aedff Michael Hanselmann
2584 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
2585 ee3aedff Michael Hanselmann
2586 ee3aedff Michael Hanselmann
2587 ee3aedff Michael Hanselmann
class TableColumn:
2588 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
2589 ee3aedff Michael Hanselmann

2590 ee3aedff Michael Hanselmann
  """
2591 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
2592 ee3aedff Michael Hanselmann
    """Initializes this class.
2593 ee3aedff Michael Hanselmann

2594 ee3aedff Michael Hanselmann
    @type title: string
2595 ee3aedff Michael Hanselmann
    @param title: Column title
2596 ee3aedff Michael Hanselmann
    @type fn: callable
2597 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2598 ee3aedff Michael Hanselmann
    @type align_right: bool
2599 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
2600 ee3aedff Michael Hanselmann

2601 ee3aedff Michael Hanselmann
    """
2602 ee3aedff Michael Hanselmann
    self.title = title
2603 ee3aedff Michael Hanselmann
    self.format = fn
2604 ee3aedff Michael Hanselmann
    self.align_right = align_right
2605 ee3aedff Michael Hanselmann
2606 ee3aedff Michael Hanselmann
2607 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
2608 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
2609 ee3aedff Michael Hanselmann

2610 ee3aedff Michael Hanselmann
  """
2611 ee3aedff Michael Hanselmann
  if align_right:
2612 ee3aedff Michael Hanselmann
    sign = ""
2613 ee3aedff Michael Hanselmann
  else:
2614 ee3aedff Michael Hanselmann
    sign = "-"
2615 ee3aedff Michael Hanselmann
2616 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
2617 ee3aedff Michael Hanselmann
2618 ee3aedff Michael Hanselmann
2619 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
2620 ee3aedff Michael Hanselmann
  """Formats data as a table.
2621 ee3aedff Michael Hanselmann

2622 ee3aedff Michael Hanselmann
  @type rows: list of lists
2623 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
2624 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
2625 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
2626 ee3aedff Michael Hanselmann
  @type header: bool
2627 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2628 ee3aedff Michael Hanselmann
  @type separator: string or None
2629 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
2630 ee3aedff Michael Hanselmann

2631 ee3aedff Michael Hanselmann
  """
2632 ee3aedff Michael Hanselmann
  if header:
2633 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
2634 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
2635 ee3aedff Michael Hanselmann
  else:
2636 ee3aedff Michael Hanselmann
    data = []
2637 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
2638 ee3aedff Michael Hanselmann
2639 ee3aedff Michael Hanselmann
  # Format row data
2640 ee3aedff Michael Hanselmann
  for row in rows:
2641 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
2642 ee3aedff Michael Hanselmann
2643 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
2644 ee3aedff Michael Hanselmann
2645 ee3aedff Michael Hanselmann
    if separator is None:
2646 ee3aedff Michael Hanselmann
      # Update column widths
2647 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
2648 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
2649 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
2650 ee3aedff Michael Hanselmann
2651 ee3aedff Michael Hanselmann
    data.append(formatted)
2652 ee3aedff Michael Hanselmann
2653 ee3aedff Michael Hanselmann
  if separator is not None:
2654 ee3aedff Michael Hanselmann
    # Return early if a separator is used
2655 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
2656 ee3aedff Michael Hanselmann
2657 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
2658 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
2659 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
2660 ee3aedff Michael Hanselmann
2661 ee3aedff Michael Hanselmann
  # Build format string
2662 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
2663 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
2664 ee3aedff Michael Hanselmann
2665 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
2666 ee3aedff Michael Hanselmann
2667 ee3aedff Michael Hanselmann
2668 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
2669 3386e7a9 Iustin Pop
  """Formats a given timestamp.
2670 3386e7a9 Iustin Pop

2671 3386e7a9 Iustin Pop
  @type ts: timestamp
2672 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
2673 3386e7a9 Iustin Pop

2674 3386e7a9 Iustin Pop
  @rtype: string
2675 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
2676 3386e7a9 Iustin Pop

2677 3386e7a9 Iustin Pop
  """
2678 e0ec0ff6 Iustin Pop
  if not isinstance (ts, (tuple, list)) or len(ts) != 2:
2679 e0ec0ff6 Iustin Pop
    return '?'
2680 3386e7a9 Iustin Pop
  sec, usec = ts
2681 3386e7a9 Iustin Pop
  return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
2682 2241e2b9 Iustin Pop
2683 2241e2b9 Iustin Pop
2684 2241e2b9 Iustin Pop
def ParseTimespec(value):
2685 2241e2b9 Iustin Pop
  """Parse a time specification.
2686 2241e2b9 Iustin Pop

2687 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
2688 2241e2b9 Iustin Pop

2689 2241e2b9 Iustin Pop
    - s: seconds
2690 2241e2b9 Iustin Pop
    - m: minutes
2691 2241e2b9 Iustin Pop
    - h: hours
2692 2241e2b9 Iustin Pop
    - d: day
2693 2241e2b9 Iustin Pop
    - w: weeks
2694 2241e2b9 Iustin Pop

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

2697 2241e2b9 Iustin Pop
  """
2698 2241e2b9 Iustin Pop
  value = str(value)
2699 2241e2b9 Iustin Pop
  if not value:
2700 2241e2b9 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed")
2701 2241e2b9 Iustin Pop
  suffix_map = {
2702 2241e2b9 Iustin Pop
    's': 1,
2703 2241e2b9 Iustin Pop
    'm': 60,
2704 2241e2b9 Iustin Pop
    'h': 3600,
2705 2241e2b9 Iustin Pop
    'd': 86400,
2706 2241e2b9 Iustin Pop
    'w': 604800,
2707 2241e2b9 Iustin Pop
    }
2708 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
2709 2241e2b9 Iustin Pop
    try:
2710 2241e2b9 Iustin Pop
      value = int(value)
2711 691744c4 Iustin Pop
    except (TypeError, ValueError):
2712 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2713 2241e2b9 Iustin Pop
  else:
2714 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
2715 2241e2b9 Iustin Pop
    value = value[:-1]
2716 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
2717 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
2718 2241e2b9 Iustin Pop
                                 " suffix passed)")
2719 2241e2b9 Iustin Pop
    try:
2720 2241e2b9 Iustin Pop
      value = int(value) * multiplier
2721 691744c4 Iustin Pop
    except (TypeError, ValueError):
2722 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2723 2241e2b9 Iustin Pop
  return value
2724 46fbdd04 Iustin Pop
2725 46fbdd04 Iustin Pop
2726 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
2727 e9e26bb3 Iustin Pop
                   filter_master=False):
2728 4040a784 Iustin Pop
  """Returns the names of online nodes.
2729 4040a784 Iustin Pop

2730 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
2731 4040a784 Iustin Pop
  the online nodes.
2732 4040a784 Iustin Pop

2733 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
2734 4040a784 Iustin Pop
      offline ones)
2735 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
2736 4040a784 Iustin Pop
  @type nowarn: boolean
2737 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
2738 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
2739 4040a784 Iustin Pop
      note is not displayed
2740 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
2741 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
2742 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
2743 e9e26bb3 Iustin Pop
      (if any)
2744 e9e26bb3 Iustin Pop
  @type filter_master: boolean
2745 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
2746 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
2747 e9e26bb3 Iustin Pop
      node name against the list)
2748 4040a784 Iustin Pop

2749 4040a784 Iustin Pop
  """
2750 4040a784 Iustin Pop
  if cl is None:
2751 4040a784 Iustin Pop
    cl = GetClient()
2752 4040a784 Iustin Pop
2753 e9e26bb3 Iustin Pop
  if secondary_ips:
2754 e9e26bb3 Iustin Pop
    name_idx = 2
2755 e9e26bb3 Iustin Pop
  else:
2756 e9e26bb3 Iustin Pop
    name_idx = 0
2757 e9e26bb3 Iustin Pop
2758 e9e26bb3 Iustin Pop
  if filter_master:
2759 e9e26bb3 Iustin Pop
    master_node = cl.QueryConfigValues(["master_node"])[0]
2760 e9e26bb3 Iustin Pop
    filter_fn = lambda x: x != master_node
2761 e9e26bb3 Iustin Pop
  else:
2762 e9e26bb3 Iustin Pop
    filter_fn = lambda _: True
2763 e9e26bb3 Iustin Pop
2764 e9e26bb3 Iustin Pop
  result = cl.QueryNodes(names=nodes, fields=["name", "offline", "sip"],
2765 2e7b8369 Iustin Pop
                         use_locking=False)
2766 4040a784 Iustin Pop
  offline = [row[0] for row in result if row[1]]
2767 4040a784 Iustin Pop
  if offline and not nowarn:
2768 1f864b60 Iustin Pop
    ToStderr("Note: skipping offline node(s): %s" % utils.CommaJoin(offline))
2769 e9e26bb3 Iustin Pop
  return [row[name_idx] for row in result if not row[1] and filter_fn(row[0])]
2770 4040a784 Iustin Pop
2771 4040a784 Iustin Pop
2772 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
2773 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
2774 46fbdd04 Iustin Pop

2775 46fbdd04 Iustin Pop
  @type stream: file object
2776 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
2777 46fbdd04 Iustin Pop
  @type txt: str
2778 46fbdd04 Iustin Pop
  @param txt: the message
2779 46fbdd04 Iustin Pop

2780 46fbdd04 Iustin Pop
  """
2781 46fbdd04 Iustin Pop
  if args:
2782 46fbdd04 Iustin Pop
    args = tuple(args)
2783 46fbdd04 Iustin Pop
    stream.write(txt % args)
2784 46fbdd04 Iustin Pop
  else:
2785 46fbdd04 Iustin Pop
    stream.write(txt)
2786 46fbdd04 Iustin Pop
  stream.write('\n')
2787 46fbdd04 Iustin Pop
  stream.flush()
2788 46fbdd04 Iustin Pop
2789 46fbdd04 Iustin Pop
2790 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
2791 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
2792 46fbdd04 Iustin Pop

2793 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
2794 46fbdd04 Iustin Pop

2795 46fbdd04 Iustin Pop
  @type txt: str
2796 46fbdd04 Iustin Pop
  @param txt: the message
2797 46fbdd04 Iustin Pop

2798 46fbdd04 Iustin Pop
  """
2799 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
2800 46fbdd04 Iustin Pop
2801 46fbdd04 Iustin Pop
2802 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
2803 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
2804 46fbdd04 Iustin Pop

2805 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
2806 46fbdd04 Iustin Pop

2807 46fbdd04 Iustin Pop
  @type txt: str
2808 46fbdd04 Iustin Pop
  @param txt: the message
2809 46fbdd04 Iustin Pop

2810 46fbdd04 Iustin Pop
  """
2811 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
2812 479636a3 Iustin Pop
2813 479636a3 Iustin Pop
2814 479636a3 Iustin Pop
class JobExecutor(object):
2815 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
2816 479636a3 Iustin Pop

2817 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
2818 479636a3 Iustin Pop
  GetResults() calls.
2819 479636a3 Iustin Pop

2820 479636a3 Iustin Pop
  """
2821 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
2822 479636a3 Iustin Pop
    self.queue = []
2823 479636a3 Iustin Pop
    if cl is None:
2824 479636a3 Iustin Pop
      cl = GetClient()
2825 479636a3 Iustin Pop
    self.cl = cl
2826 479636a3 Iustin Pop
    self.verbose = verbose
2827 23b4b983 Iustin Pop
    self.jobs = []
2828 cff5fa7f Iustin Pop
    self.opts = opts
2829 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
2830 479636a3 Iustin Pop
2831 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
2832 23b4b983 Iustin Pop
    """Record a job for later submit.
2833 479636a3 Iustin Pop

2834 479636a3 Iustin Pop
    @type name: string
2835 479636a3 Iustin Pop
    @param name: a description of the job, will be used in WaitJobSet
2836 479636a3 Iustin Pop
    """
2837 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
2838 23b4b983 Iustin Pop
    self.queue.append((name, ops))
2839 23b4b983 Iustin Pop
2840 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
2841 23b4b983 Iustin Pop
    """Submit all pending jobs.
2842 23b4b983 Iustin Pop

2843 23b4b983 Iustin Pop
    """
2844 66ecc479 Guido Trotter
    if each:
2845 66ecc479 Guido Trotter
      results = []
2846 66ecc479 Guido Trotter
      for row in self.queue:
2847 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
2848 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
2849 66ecc479 Guido Trotter
        results.append([True, self.cl.SubmitJob(row[1])])
2850 66ecc479 Guido Trotter
    else:
2851 66ecc479 Guido Trotter
      results = self.cl.SubmitManyJobs([row[1] for row in self.queue])
2852 5299e61f Iustin Pop
    for (idx, ((status, data), (name, _))) in enumerate(zip(results,
2853 5299e61f Iustin Pop
                                                            self.queue)):
2854 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
2855 5299e61f Iustin Pop
2856 5299e61f Iustin Pop
  def _ChooseJob(self):
2857 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
2858 5299e61f Iustin Pop

2859 5299e61f Iustin Pop
    """
2860 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
2861 5299e61f Iustin Pop
2862 5299e61f Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs], ["status"])
2863 5299e61f Iustin Pop
    assert result
2864 5299e61f Iustin Pop
2865 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
2866 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
2867 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
2868 91c622a8 Iustin Pop
                        constants.JOB_STATUS_WAITLOCK,
2869 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
2870 91c622a8 Iustin Pop
        # job is still present and waiting
2871 5299e61f Iustin Pop
        continue
2872 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
2873 5299e61f Iustin Pop
      self.jobs.remove(job_data)
2874 5299e61f Iustin Pop
      return job_data
2875 5299e61f Iustin Pop
2876 5299e61f Iustin Pop
    # no job found
2877 5299e61f Iustin Pop
    return self.jobs.pop(0)
2878 479636a3 Iustin Pop
2879 479636a3 Iustin Pop
  def GetResults(self):
2880 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
2881 479636a3 Iustin Pop

2882 479636a3 Iustin Pop
    @rtype: list
2883 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
2884 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
2885 479636a3 Iustin Pop
        there will be the error message
2886 479636a3 Iustin Pop

2887 479636a3 Iustin Pop
    """
2888 23b4b983 Iustin Pop
    if not self.jobs:
2889 23b4b983 Iustin Pop
      self.SubmitPending()
2890 479636a3 Iustin Pop
    results = []
2891 479636a3 Iustin Pop
    if self.verbose:
2892 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
2893 23b4b983 Iustin Pop
      if ok_jobs:
2894 1f864b60 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
2895 5299e61f Iustin Pop
2896 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
2897 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
2898 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
2899 c63355f2 Iustin Pop
      ToStderr("Failed to submit job for %s: %s", name, jid)
2900 c63355f2 Iustin Pop
      results.append((idx, False, jid))
2901 5299e61f Iustin Pop
2902 5299e61f Iustin Pop
    while self.jobs:
2903 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
2904 5299e61f Iustin Pop
      ToStdout("Waiting for job %s for %s...", jid, name)
2905 479636a3 Iustin Pop
      try:
2906 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
2907 479636a3 Iustin Pop
        success = True
2908 91c622a8 Iustin Pop
      except errors.JobLost, err:
2909 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
2910 91c622a8 Iustin Pop
        ToStderr("Job %s for %s has been archived, cannot check its result",
2911 91c622a8 Iustin Pop
                 jid, name)
2912 91c622a8 Iustin Pop
        success = False
2913 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
2914 479636a3 Iustin Pop
        _, job_result = FormatError(err)
2915 479636a3 Iustin Pop
        success = False
2916 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
2917 479636a3 Iustin Pop
        ToStderr("Job %s for %s has failed: %s", jid, name, job_result)
2918 479636a3 Iustin Pop
2919 5299e61f Iustin Pop
      results.append((idx, success, job_result))
2920 5299e61f Iustin Pop
2921 5299e61f Iustin Pop
    # sort based on the index, then drop it
2922 5299e61f Iustin Pop
    results.sort()
2923 5299e61f Iustin Pop
    results = [i[1:] for i in results]
2924 5299e61f Iustin Pop
2925 479636a3 Iustin Pop
    return results
2926 479636a3 Iustin Pop
2927 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
2928 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
2929 479636a3 Iustin Pop

2930 479636a3 Iustin Pop
    @type wait: boolean
2931 479636a3 Iustin Pop
    @param wait: whether to wait or not
2932 479636a3 Iustin Pop

2933 479636a3 Iustin Pop
    """
2934 479636a3 Iustin Pop
    if wait:
2935 479636a3 Iustin Pop
      return self.GetResults()
2936 479636a3 Iustin Pop
    else:
2937 23b4b983 Iustin Pop
      if not self.jobs:
2938 23b4b983 Iustin Pop
        self.SubmitPending()
2939 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
2940 23b4b983 Iustin Pop
        if status:
2941 23b4b983 Iustin Pop
          ToStdout("%s: %s", result, name)
2942 23b4b983 Iustin Pop
        else:
2943 23b4b983 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
2944 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
2945 acd19189 René Nussbaumer
2946 acd19189 René Nussbaumer
2947 acd19189 René Nussbaumer
def FormatParameterDict(buf, param_dict, actual, level=1):
2948 acd19189 René Nussbaumer
  """Formats a parameter dictionary.
2949 acd19189 René Nussbaumer

2950 acd19189 René Nussbaumer
  @type buf: L{StringIO}
2951 acd19189 René Nussbaumer
  @param buf: the buffer into which to write
2952 acd19189 René Nussbaumer
  @type param_dict: dict
2953 acd19189 René Nussbaumer
  @param param_dict: the own parameters
2954 acd19189 René Nussbaumer
  @type actual: dict
2955 acd19189 René Nussbaumer
  @param actual: the current parameter set (including defaults)
2956 acd19189 René Nussbaumer
  @param level: Level of indent
2957 acd19189 René Nussbaumer

2958 acd19189 René Nussbaumer
  """
2959 acd19189 René Nussbaumer
  indent = "  " * level
2960 acd19189 René Nussbaumer
  for key in sorted(actual):
2961 acd19189 René Nussbaumer
    val = param_dict.get(key, "default (%s)" % actual[key])
2962 acd19189 René Nussbaumer
    buf.write("%s- %s: %s\n" % (indent, key, val))