Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 819cbfe5

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

266 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
267 863d7f46 Michael Hanselmann

268 863d7f46 Michael Hanselmann
  """
269 7260cfbe Iustin Pop
  # pylint: disable-msg=W0622
270 863d7f46 Michael Hanselmann
  def __init__(self, min=0, max=None, choices=None):
271 863d7f46 Michael Hanselmann
    _Argument.__init__(self, min=min, max=max)
272 863d7f46 Michael Hanselmann
    self.choices = choices
273 863d7f46 Michael Hanselmann
274 863d7f46 Michael Hanselmann
  def __repr__(self):
275 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s choices=%r>" %
276 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max, self.choices))
277 863d7f46 Michael Hanselmann
278 863d7f46 Michael Hanselmann
279 863d7f46 Michael Hanselmann
class ArgChoice(ArgSuggest):
280 863d7f46 Michael Hanselmann
  """Choice argument.
281 863d7f46 Michael Hanselmann

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

285 863d7f46 Michael Hanselmann
  """
286 863d7f46 Michael Hanselmann
287 863d7f46 Michael Hanselmann
288 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
289 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
290 863d7f46 Michael Hanselmann

291 863d7f46 Michael Hanselmann
  """
292 863d7f46 Michael Hanselmann
293 863d7f46 Michael Hanselmann
294 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
295 863d7f46 Michael Hanselmann
  """Instances argument.
296 863d7f46 Michael Hanselmann

297 863d7f46 Michael Hanselmann
  """
298 863d7f46 Michael Hanselmann
299 863d7f46 Michael Hanselmann
300 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
301 863d7f46 Michael Hanselmann
  """Node argument.
302 863d7f46 Michael Hanselmann

303 863d7f46 Michael Hanselmann
  """
304 863d7f46 Michael Hanselmann
305 667dbd6b Adeodato Simo
306 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
307 667dbd6b Adeodato Simo
  """Node group argument.
308 667dbd6b Adeodato Simo

309 667dbd6b Adeodato Simo
  """
310 667dbd6b Adeodato Simo
311 667dbd6b Adeodato Simo
312 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
313 863d7f46 Michael Hanselmann
  """Job ID argument.
314 863d7f46 Michael Hanselmann

315 863d7f46 Michael Hanselmann
  """
316 863d7f46 Michael Hanselmann
317 863d7f46 Michael Hanselmann
318 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
319 863d7f46 Michael Hanselmann
  """File path argument.
320 863d7f46 Michael Hanselmann

321 863d7f46 Michael Hanselmann
  """
322 863d7f46 Michael Hanselmann
323 863d7f46 Michael Hanselmann
324 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
325 863d7f46 Michael Hanselmann
  """Command argument.
326 863d7f46 Michael Hanselmann

327 863d7f46 Michael Hanselmann
  """
328 863d7f46 Michael Hanselmann
329 863d7f46 Michael Hanselmann
330 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
331 83ec7961 Michael Hanselmann
  """Host argument.
332 83ec7961 Michael Hanselmann

333 83ec7961 Michael Hanselmann
  """
334 83ec7961 Michael Hanselmann
335 83ec7961 Michael Hanselmann
336 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
337 f9faf9c3 René Nussbaumer
  """OS argument.
338 f9faf9c3 René Nussbaumer

339 f9faf9c3 René Nussbaumer
  """
340 f9faf9c3 René Nussbaumer
341 f9faf9c3 René Nussbaumer
342 4a265c08 Michael Hanselmann
ARGS_NONE = []
343 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
344 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
345 667dbd6b Adeodato Simo
ARGS_MANY_GROUPS = [ArgGroup()]
346 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
347 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
348 667dbd6b Adeodato Simo
ARGS_ONE_GROUP = [ArgInstance(min=1, max=1)]
349 f9faf9c3 René Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
350 4a265c08 Michael Hanselmann
351 4a265c08 Michael Hanselmann
352 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
353 846baef9 Iustin Pop
  """Extract the tag type object.
354 846baef9 Iustin Pop

355 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
356 846baef9 Iustin Pop

357 846baef9 Iustin Pop
  """
358 846baef9 Iustin Pop
  if not hasattr(opts, "tag_type"):
359 846baef9 Iustin Pop
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
360 846baef9 Iustin Pop
  kind = opts.tag_type
361 846baef9 Iustin Pop
  if kind == constants.TAG_CLUSTER:
362 846baef9 Iustin Pop
    retval = kind, kind
363 819cbfe5 Michael Hanselmann
  elif kind in (constants.TAG_NODEGROUP,
364 819cbfe5 Michael Hanselmann
                constants.TAG_NODE,
365 819cbfe5 Michael Hanselmann
                constants.TAG_INSTANCE):
366 846baef9 Iustin Pop
    if not args:
367 0c434948 Iustin Pop
      raise errors.OpPrereqError("no arguments passed to the command")
368 846baef9 Iustin Pop
    name = args.pop(0)
369 846baef9 Iustin Pop
    retval = kind, name
370 846baef9 Iustin Pop
  else:
371 846baef9 Iustin Pop
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
372 846baef9 Iustin Pop
  return retval
373 846baef9 Iustin Pop
374 846baef9 Iustin Pop
375 810c50b7 Iustin Pop
def _ExtendTags(opts, args):
376 810c50b7 Iustin Pop
  """Extend the args if a source file has been given.
377 810c50b7 Iustin Pop

378 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
379 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
380 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
381 810c50b7 Iustin Pop

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

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

412 846baef9 Iustin Pop
  """
413 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
414 7699c3af Iustin Pop
  cl = GetClient()
415 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
416 846baef9 Iustin Pop
  result = list(result)
417 846baef9 Iustin Pop
  result.sort()
418 846baef9 Iustin Pop
  for tag in result:
419 03298ebe Michael Hanselmann
    ToStdout(tag)
420 846baef9 Iustin Pop
421 846baef9 Iustin Pop
422 846baef9 Iustin Pop
def AddTags(opts, args):
423 846baef9 Iustin Pop
  """Add tags on a given object.
424 846baef9 Iustin Pop

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

430 846baef9 Iustin Pop
  """
431 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
432 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
433 846baef9 Iustin Pop
  if not args:
434 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be added")
435 d1602edc Iustin Pop
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
436 af1a81d1 Michael Hanselmann
  SubmitOpCode(op, opts=opts)
437 846baef9 Iustin Pop
438 846baef9 Iustin Pop
439 846baef9 Iustin Pop
def RemoveTags(opts, args):
440 846baef9 Iustin Pop
  """Remove tags from a given object.
441 846baef9 Iustin Pop

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

447 846baef9 Iustin Pop
  """
448 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
449 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
450 846baef9 Iustin Pop
  if not args:
451 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be removed")
452 3f0ab95f Iustin Pop
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
453 af1a81d1 Michael Hanselmann
  SubmitOpCode(op, opts=opts)
454 846baef9 Iustin Pop
455 a8083063 Iustin Pop
456 8929d28c Iustin Pop
def check_unit(option, opt, value): # pylint: disable-msg=W0613
457 65fe4693 Iustin Pop
  """OptParsers custom converter for units.
458 65fe4693 Iustin Pop

459 65fe4693 Iustin Pop
  """
460 a8083063 Iustin Pop
  try:
461 a8083063 Iustin Pop
    return utils.ParseUnit(value)
462 a8083063 Iustin Pop
  except errors.UnitParseError, err:
463 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
464 a8083063 Iustin Pop
465 a8083063 Iustin Pop
466 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
467 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
468 a8469393 Iustin Pop

469 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
470 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
471 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
472 a8469393 Iustin Pop
  have value=True.
473 a8469393 Iustin Pop

474 a8469393 Iustin Pop
  @type opt: string
475 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
476 a8469393 Iustin Pop
      data, used in building error messages
477 a8469393 Iustin Pop
  @type data: string
478 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
479 a8469393 Iustin Pop
  @rtype: dict
480 a8469393 Iustin Pop
  @return: {key=val, key=val}
481 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
482 a8469393 Iustin Pop

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

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

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

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

536 a8469393 Iustin Pop
  """
537 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
538 a8469393 Iustin Pop
539 a8469393 Iustin Pop
540 e7b61bb0 Iustin Pop
def check_bool(option, opt, value): # pylint: disable-msg=W0613
541 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
542 e7b61bb0 Iustin Pop

543 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
544 e7b61bb0 Iustin Pop

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

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

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

1226 c41eea6e Iustin Pop
  @param argv: the command line
1227 c41eea6e Iustin Pop
  @param commands: dictionary with special contents, see the design
1228 c41eea6e Iustin Pop
      doc for cmdline handling
1229 c41eea6e Iustin Pop
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
1230 098c0958 Michael Hanselmann

1231 a8083063 Iustin Pop
  """
1232 a8083063 Iustin Pop
  if len(argv) == 0:
1233 a8083063 Iustin Pop
    binary = "<command>"
1234 a8083063 Iustin Pop
  else:
1235 a8083063 Iustin Pop
    binary = argv[0].split("/")[-1]
1236 a8083063 Iustin Pop
1237 a8083063 Iustin Pop
  if len(argv) > 1 and argv[1] == "--version":
1238 84a12e40 Iustin Pop
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
1239 84a12e40 Iustin Pop
             constants.RELEASE_VERSION)
1240 a8083063 Iustin Pop
    # Quit right away. That way we don't have to care about this special
1241 a8083063 Iustin Pop
    # argument. optparse.py does it the same.
1242 a8083063 Iustin Pop
    sys.exit(0)
1243 a8083063 Iustin Pop
1244 de47cf8f Guido Trotter
  if len(argv) < 2 or not (argv[1] in commands or
1245 70a35b6f Guido Trotter
                           argv[1] in aliases):
1246 a8083063 Iustin Pop
    # let's do a nice thing
1247 a8083063 Iustin Pop
    sortedcmds = commands.keys()
1248 a8083063 Iustin Pop
    sortedcmds.sort()
1249 03298ebe Michael Hanselmann
1250 03298ebe Michael Hanselmann
    ToStdout("Usage: %s {command} [options...] [argument...]", binary)
1251 03298ebe Michael Hanselmann
    ToStdout("%s <command> --help to see details, or man %s", binary, binary)
1252 03298ebe Michael Hanselmann
    ToStdout("")
1253 03298ebe Michael Hanselmann
1254 a8083063 Iustin Pop
    # compute the max line length for cmd + usage
1255 4e713df6 Iustin Pop
    mlen = max([len(" %s" % cmd) for cmd in commands])
1256 a8083063 Iustin Pop
    mlen = min(60, mlen) # should not get here...
1257 03298ebe Michael Hanselmann
1258 a8083063 Iustin Pop
    # and format a nice command list
1259 03298ebe Michael Hanselmann
    ToStdout("Commands:")
1260 a8083063 Iustin Pop
    for cmd in sortedcmds:
1261 4e713df6 Iustin Pop
      cmdstr = " %s" % (cmd,)
1262 9a033156 Iustin Pop
      help_text = commands[cmd][4]
1263 03298ebe Michael Hanselmann
      help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1264 03298ebe Michael Hanselmann
      ToStdout("%-*s - %s", mlen, cmdstr, help_lines.pop(0))
1265 a8083063 Iustin Pop
      for line in help_lines:
1266 03298ebe Michael Hanselmann
        ToStdout("%-*s   %s", mlen, "", line)
1267 03298ebe Michael Hanselmann
1268 03298ebe Michael Hanselmann
    ToStdout("")
1269 03298ebe Michael Hanselmann
1270 a8083063 Iustin Pop
    return None, None, None
1271 de47cf8f Guido Trotter
1272 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1273 a8083063 Iustin Pop
  cmd = argv.pop(1)
1274 de47cf8f Guido Trotter
  if cmd in aliases:
1275 de47cf8f Guido Trotter
    if cmd in commands:
1276 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' overrides an existing"
1277 de47cf8f Guido Trotter
                                   " command" % cmd)
1278 de47cf8f Guido Trotter
1279 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1280 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1281 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1282 de47cf8f Guido Trotter
1283 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1284 de47cf8f Guido Trotter
1285 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1286 5786c087 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1287 a8083063 Iustin Pop
                        description=description,
1288 a8083063 Iustin Pop
                        formatter=TitledHelpFormatter(),
1289 a8083063 Iustin Pop
                        usage="%%prog %s %s" % (cmd, usage))
1290 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1291 a8083063 Iustin Pop
  options, args = parser.parse_args()
1292 a8005e17 Michael Hanselmann
1293 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1294 a8083063 Iustin Pop
    return None, None, None
1295 a8083063 Iustin Pop
1296 a8083063 Iustin Pop
  return func, options, args
1297 a8083063 Iustin Pop
1298 a8083063 Iustin Pop
1299 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1300 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1301 a8005e17 Michael Hanselmann

1302 a8005e17 Michael Hanselmann
  Algorithm:
1303 a8005e17 Michael Hanselmann

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

1306 a8005e17 Michael Hanselmann
    1. For each argument in definition
1307 a8005e17 Michael Hanselmann

1308 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1309 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1310 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1311 a8005e17 Michael Hanselmann

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

1314 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1315 a8005e17 Michael Hanselmann

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

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

1320 a8005e17 Michael Hanselmann
  """
1321 a8005e17 Michael Hanselmann
  if args and not args_def:
1322 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1323 a8005e17 Michael Hanselmann
    return False
1324 a8005e17 Michael Hanselmann
1325 a8005e17 Michael Hanselmann
  min_count = None
1326 a8005e17 Michael Hanselmann
  max_count = None
1327 a8005e17 Michael Hanselmann
  check_max = None
1328 a8005e17 Michael Hanselmann
1329 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1330 a8005e17 Michael Hanselmann
1331 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1332 a8005e17 Michael Hanselmann
    if min_count is None:
1333 a8005e17 Michael Hanselmann
      min_count = arg.min
1334 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1335 a8005e17 Michael Hanselmann
      min_count += arg.min
1336 a8005e17 Michael Hanselmann
1337 a8005e17 Michael Hanselmann
    if max_count is None:
1338 a8005e17 Michael Hanselmann
      max_count = arg.max
1339 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1340 a8005e17 Michael Hanselmann
      max_count += arg.max
1341 a8005e17 Michael Hanselmann
1342 a8005e17 Michael Hanselmann
    if idx == last_idx:
1343 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1344 a8005e17 Michael Hanselmann
1345 a8005e17 Michael Hanselmann
    elif arg.max is None:
1346 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1347 a8005e17 Michael Hanselmann
1348 a8005e17 Michael Hanselmann
  if check_max:
1349 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1350 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1351 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1352 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1353 a8005e17 Michael Hanselmann
      return False
1354 a8005e17 Michael Hanselmann
1355 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1356 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1357 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1358 a8005e17 Michael Hanselmann
               cmd, max_count)
1359 a8005e17 Michael Hanselmann
      return False
1360 a8005e17 Michael Hanselmann
1361 a8005e17 Michael Hanselmann
  # Command with some required arguments
1362 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1363 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1364 a8005e17 Michael Hanselmann
             cmd, min_count)
1365 a8005e17 Michael Hanselmann
    return False
1366 a8005e17 Michael Hanselmann
1367 a8005e17 Michael Hanselmann
  return True
1368 a8005e17 Michael Hanselmann
1369 a8005e17 Michael Hanselmann
1370 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1371 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1372 60d49723 Michael Hanselmann

1373 60d49723 Michael Hanselmann
  """
1374 60d49723 Michael Hanselmann
  if value and ':' in value:
1375 60d49723 Michael Hanselmann
    return value.split(':', 1)
1376 60d49723 Michael Hanselmann
  else:
1377 60d49723 Michael Hanselmann
    return (value, None)
1378 60d49723 Michael Hanselmann
1379 60d49723 Michael Hanselmann
1380 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1381 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1382 07150497 Guido Trotter

1383 07150497 Guido Trotter
  @type os_name: string
1384 07150497 Guido Trotter
  @param os_name: base name of the os
1385 07150497 Guido Trotter
  @type os_variants: list or None
1386 07150497 Guido Trotter
  @param os_variants: list of supported variants
1387 07150497 Guido Trotter
  @rtype: list
1388 07150497 Guido Trotter
  @return: list of valid names
1389 07150497 Guido Trotter

1390 07150497 Guido Trotter
  """
1391 07150497 Guido Trotter
  if os_variants:
1392 07150497 Guido Trotter
    return ['%s+%s' % (os_name, v) for v in os_variants]
1393 07150497 Guido Trotter
  else:
1394 07150497 Guido Trotter
    return [os_name]
1395 07150497 Guido Trotter
1396 07150497 Guido Trotter
1397 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1398 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1399 a4ebd726 Michael Hanselmann

1400 a4ebd726 Michael Hanselmann
  @type selected: string or None
1401 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1402 a4ebd726 Michael Hanselmann
  @type default: list
1403 a4ebd726 Michael Hanselmann
  @param default: Default fields
1404 a4ebd726 Michael Hanselmann

1405 a4ebd726 Michael Hanselmann
  """
1406 a4ebd726 Michael Hanselmann
  if selected is None:
1407 a4ebd726 Michael Hanselmann
    return default
1408 a4ebd726 Michael Hanselmann
1409 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1410 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1411 a4ebd726 Michael Hanselmann
1412 a4ebd726 Michael Hanselmann
  return selected.split(",")
1413 a4ebd726 Michael Hanselmann
1414 a4ebd726 Michael Hanselmann
1415 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1416 4331f6cd Michael Hanselmann
1417 4331f6cd Michael Hanselmann
1418 47988778 Iustin Pop
def AskUser(text, choices=None):
1419 47988778 Iustin Pop
  """Ask the user a question.
1420 a8083063 Iustin Pop

1421 c41eea6e Iustin Pop
  @param text: the question to ask
1422 a8083063 Iustin Pop

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

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

1432 a8083063 Iustin Pop
  """
1433 47988778 Iustin Pop
  if choices is None:
1434 47988778 Iustin Pop
    choices = [('y', True, 'Perform the operation'),
1435 47988778 Iustin Pop
               ('n', False, 'Do not perform the operation')]
1436 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1437 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1438 47988778 Iustin Pop
  for entry in choices:
1439 47988778 Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == '?':
1440 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1441 47988778 Iustin Pop
1442 47988778 Iustin Pop
  answer = choices[-1][1]
1443 47988778 Iustin Pop
  new_text = []
1444 47988778 Iustin Pop
  for line in text.splitlines():
1445 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1446 47988778 Iustin Pop
  text = "\n".join(new_text)
1447 a8083063 Iustin Pop
  try:
1448 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1449 a8083063 Iustin Pop
  except IOError:
1450 47988778 Iustin Pop
    return answer
1451 a8083063 Iustin Pop
  try:
1452 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1453 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1454 47988778 Iustin Pop
    chars.append('?')
1455 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1456 47988778 Iustin Pop
    while True:
1457 47988778 Iustin Pop
      f.write(text)
1458 47988778 Iustin Pop
      f.write('\n')
1459 47988778 Iustin Pop
      f.write("/".join(chars))
1460 47988778 Iustin Pop
      f.write(": ")
1461 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1462 47988778 Iustin Pop
      if line in maps:
1463 47988778 Iustin Pop
        answer = maps[line]
1464 47988778 Iustin Pop
        break
1465 47988778 Iustin Pop
      elif line == '?':
1466 47988778 Iustin Pop
        for entry in choices:
1467 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1468 47988778 Iustin Pop
        f.write("\n")
1469 47988778 Iustin Pop
        continue
1470 a8083063 Iustin Pop
  finally:
1471 a8083063 Iustin Pop
    f.close()
1472 a8083063 Iustin Pop
  return answer
1473 a8083063 Iustin Pop
1474 a8083063 Iustin Pop
1475 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1476 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1477 e9d741b6 Iustin Pop

1478 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1479 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1480 e9d741b6 Iustin Pop

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

1483 e9d741b6 Iustin Pop
  """
1484 e9d741b6 Iustin Pop
1485 e9d741b6 Iustin Pop
1486 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1487 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1488 a8083063 Iustin Pop

1489 0a1e74d9 Iustin Pop
  @type ops: list
1490 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1491 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1492 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1493 0a1e74d9 Iustin Pop
             if None, a new client will be created
1494 a8083063 Iustin Pop

1495 a8083063 Iustin Pop
  """
1496 e2212007 Iustin Pop
  if cl is None:
1497 b33e986b Iustin Pop
    cl = GetClient()
1498 685ee993 Iustin Pop
1499 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1500 0a1e74d9 Iustin Pop
1501 0a1e74d9 Iustin Pop
  return job_id
1502 0a1e74d9 Iustin Pop
1503 0a1e74d9 Iustin Pop
1504 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1505 4e338533 Michael Hanselmann
  """Generic job-polling function.
1506 0a1e74d9 Iustin Pop

1507 4e338533 Michael Hanselmann
  @type job_id: number
1508 4e338533 Michael Hanselmann
  @param job_id: Job ID
1509 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1510 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1511 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1512 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1513 0a1e74d9 Iustin Pop

1514 0a1e74d9 Iustin Pop
  """
1515 6c5a7090 Michael Hanselmann
  prev_job_info = None
1516 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1517 6c5a7090 Michael Hanselmann
1518 f4484122 Michael Hanselmann
  status = None
1519 f4484122 Michael Hanselmann
1520 685ee993 Iustin Pop
  while True:
1521 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1522 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
1523 6c5a7090 Michael Hanselmann
    if not result:
1524 685ee993 Iustin Pop
      # job not found, go away!
1525 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1526 4e338533 Michael Hanselmann
1527 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
1528 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
1529 f4484122 Michael Hanselmann
1530 f4484122 Michael Hanselmann
      # Wait again
1531 f4484122 Michael Hanselmann
      continue
1532 685ee993 Iustin Pop
1533 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1534 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1535 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1536 6c5a7090 Michael Hanselmann
1537 6c5a7090 Michael Hanselmann
    if log_entries:
1538 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1539 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
1540 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
1541 4e338533 Michael Hanselmann
                                    log_type, message)
1542 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1543 6c5a7090 Michael Hanselmann
1544 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1545 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1546 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1547 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1548 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1549 685ee993 Iustin Pop
      break
1550 6c5a7090 Michael Hanselmann
1551 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1552 685ee993 Iustin Pop
1553 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1554 0bbe448c Michael Hanselmann
  if not jobs:
1555 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1556 685ee993 Iustin Pop
1557 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1558 4e338533 Michael Hanselmann
1559 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1560 53c04d04 Iustin Pop
    return result
1561 4e338533 Michael Hanselmann
1562 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
1563 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1564 4e338533 Michael Hanselmann
1565 4e338533 Michael Hanselmann
  has_ok = False
1566 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
1567 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
1568 4e338533 Michael Hanselmann
      has_ok = True
1569 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
1570 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
1571 4e338533 Michael Hanselmann
1572 4e338533 Michael Hanselmann
      if has_ok:
1573 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
1574 4e338533 Michael Hanselmann
                                 (idx, msg))
1575 4e338533 Michael Hanselmann
1576 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
1577 4e338533 Michael Hanselmann
1578 4e338533 Michael Hanselmann
  # default failure mode
1579 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
1580 4e338533 Michael Hanselmann
1581 4e338533 Michael Hanselmann
1582 4e338533 Michael Hanselmann
class JobPollCbBase:
1583 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
1584 4e338533 Michael Hanselmann

1585 4e338533 Michael Hanselmann
  """
1586 4e338533 Michael Hanselmann
  def __init__(self):
1587 4e338533 Michael Hanselmann
    """Initializes this class.
1588 4e338533 Michael Hanselmann

1589 4e338533 Michael Hanselmann
    """
1590 4e338533 Michael Hanselmann
1591 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1592 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1593 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1594 4e338533 Michael Hanselmann

1595 4e338533 Michael Hanselmann
    """
1596 4e338533 Michael Hanselmann
    raise NotImplementedError()
1597 4e338533 Michael Hanselmann
1598 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1599 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1600 4e338533 Michael Hanselmann

1601 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
1602 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
1603 4e338533 Michael Hanselmann
    @type fields: list of strings
1604 4e338533 Michael Hanselmann
    @param fields: Fields
1605 4e338533 Michael Hanselmann

1606 4e338533 Michael Hanselmann
    """
1607 4e338533 Michael Hanselmann
    raise NotImplementedError()
1608 4e338533 Michael Hanselmann
1609 4e338533 Michael Hanselmann
1610 4e338533 Michael Hanselmann
class JobPollReportCbBase:
1611 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
1612 4e338533 Michael Hanselmann

1613 4e338533 Michael Hanselmann
  """
1614 4e338533 Michael Hanselmann
  def __init__(self):
1615 4e338533 Michael Hanselmann
    """Initializes this class.
1616 4e338533 Michael Hanselmann

1617 4e338533 Michael Hanselmann
    """
1618 4e338533 Michael Hanselmann
1619 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1620 4e338533 Michael Hanselmann
    """Handles a log message.
1621 4e338533 Michael Hanselmann

1622 4e338533 Michael Hanselmann
    """
1623 4e338533 Michael Hanselmann
    raise NotImplementedError()
1624 4e338533 Michael Hanselmann
1625 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1626 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
1627 4e338533 Michael Hanselmann

1628 4e338533 Michael Hanselmann
    @type job_id: number
1629 4e338533 Michael Hanselmann
    @param job_id: Job ID
1630 4e338533 Michael Hanselmann
    @type status: string or None
1631 4e338533 Michael Hanselmann
    @param status: Job status if available
1632 4e338533 Michael Hanselmann

1633 4e338533 Michael Hanselmann
    """
1634 4e338533 Michael Hanselmann
    raise NotImplementedError()
1635 4e338533 Michael Hanselmann
1636 4e338533 Michael Hanselmann
1637 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
1638 4e338533 Michael Hanselmann
  def __init__(self, cl):
1639 4e338533 Michael Hanselmann
    """Initializes this class.
1640 4e338533 Michael Hanselmann

1641 4e338533 Michael Hanselmann
    """
1642 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
1643 4e338533 Michael Hanselmann
    self.cl = cl
1644 4e338533 Michael Hanselmann
1645 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1646 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1647 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1648 4e338533 Michael Hanselmann

1649 4e338533 Michael Hanselmann
    """
1650 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
1651 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
1652 4e338533 Michael Hanselmann
1653 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1654 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1655 4e338533 Michael Hanselmann

1656 4e338533 Michael Hanselmann
    """
1657 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
1658 4e338533 Michael Hanselmann
1659 4e338533 Michael Hanselmann
1660 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
1661 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
1662 4e338533 Michael Hanselmann
    """Initializes this class.
1663 4e338533 Michael Hanselmann

1664 4e338533 Michael Hanselmann
    """
1665 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1666 4e338533 Michael Hanselmann
1667 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
1668 4e338533 Michael Hanselmann
1669 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
1670 4e338533 Michael Hanselmann
1671 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1672 4e338533 Michael Hanselmann
    """Handles a log message.
1673 4e338533 Michael Hanselmann

1674 4e338533 Michael Hanselmann
    """
1675 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
1676 4e338533 Michael Hanselmann
1677 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1678 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1679 4e338533 Michael Hanselmann

1680 4e338533 Michael Hanselmann
    """
1681 4e338533 Michael Hanselmann
    # Ignore
1682 4e338533 Michael Hanselmann
1683 4e338533 Michael Hanselmann
1684 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
1685 4e338533 Michael Hanselmann
  def __init__(self):
1686 4e338533 Michael Hanselmann
    """Initializes this class.
1687 4e338533 Michael Hanselmann

1688 4e338533 Michael Hanselmann
    """
1689 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1690 4e338533 Michael Hanselmann
1691 4e338533 Michael Hanselmann
    self.notified_queued = False
1692 4e338533 Michael Hanselmann
    self.notified_waitlock = False
1693 4e338533 Michael Hanselmann
1694 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1695 4e338533 Michael Hanselmann
    """Handles a log message.
1696 4e338533 Michael Hanselmann

1697 4e338533 Michael Hanselmann
    """
1698 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
1699 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
1700 4e338533 Michael Hanselmann
1701 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1702 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1703 4e338533 Michael Hanselmann

1704 4e338533 Michael Hanselmann
    """
1705 4e338533 Michael Hanselmann
    if status is None:
1706 4e338533 Michael Hanselmann
      return
1707 4e338533 Michael Hanselmann
1708 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
1709 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
1710 4e338533 Michael Hanselmann
      self.notified_queued = True
1711 4e338533 Michael Hanselmann
1712 4e338533 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITLOCK and not self.notified_waitlock:
1713 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
1714 4e338533 Michael Hanselmann
      self.notified_waitlock = True
1715 4e338533 Michael Hanselmann
1716 4e338533 Michael Hanselmann
1717 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
1718 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
1719 8a7f1c61 Michael Hanselmann

1720 8a7f1c61 Michael Hanselmann
  """
1721 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
1722 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
1723 8a7f1c61 Michael Hanselmann
1724 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
1725 8a7f1c61 Michael Hanselmann
1726 8a7f1c61 Michael Hanselmann
1727 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
1728 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
1729 4e338533 Michael Hanselmann

1730 4e338533 Michael Hanselmann
  @type job_id: job identified
1731 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
1732 4e338533 Michael Hanselmann
  @type cl: luxi.Client
1733 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
1734 4e338533 Michael Hanselmann
             if None, a new client will be created
1735 4e338533 Michael Hanselmann

1736 4e338533 Michael Hanselmann
  """
1737 4e338533 Michael Hanselmann
  if cl is None:
1738 4e338533 Michael Hanselmann
    cl = GetClient()
1739 4e338533 Michael Hanselmann
1740 583163a6 Michael Hanselmann
  if reporter is None:
1741 583163a6 Michael Hanselmann
    if feedback_fn:
1742 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
1743 583163a6 Michael Hanselmann
    else:
1744 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
1745 583163a6 Michael Hanselmann
  elif feedback_fn:
1746 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
1747 4e338533 Michael Hanselmann
1748 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
1749 ceab32dd Iustin Pop
1750 ceab32dd Iustin Pop
1751 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
1752 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
1753 0a1e74d9 Iustin Pop

1754 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
1755 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
1756 0a1e74d9 Iustin Pop
  interaction functions.
1757 0a1e74d9 Iustin Pop

1758 0a1e74d9 Iustin Pop
  """
1759 0a1e74d9 Iustin Pop
  if cl is None:
1760 0a1e74d9 Iustin Pop
    cl = GetClient()
1761 0a1e74d9 Iustin Pop
1762 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
1763 293ba2d8 Iustin Pop
1764 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
1765 0a1e74d9 Iustin Pop
1766 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
1767 583163a6 Michael Hanselmann
                       reporter=reporter)
1768 53c04d04 Iustin Pop
1769 53c04d04 Iustin Pop
  return op_results[0]
1770 0a1e74d9 Iustin Pop
1771 0a1e74d9 Iustin Pop
1772 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
1773 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
1774 94428652 Iustin Pop

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

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

1783 94428652 Iustin Pop
  """
1784 94428652 Iustin Pop
  if opts and opts.submit_only:
1785 293ba2d8 Iustin Pop
    job = [op]
1786 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
1787 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
1788 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
1789 94428652 Iustin Pop
  else:
1790 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
1791 293ba2d8 Iustin Pop
1792 293ba2d8 Iustin Pop
1793 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
1794 293ba2d8 Iustin Pop
  """Processor for generic options.
1795 293ba2d8 Iustin Pop

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

1799 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
1800 293ba2d8 Iustin Pop
  @param options: command line options or None
1801 293ba2d8 Iustin Pop
  @return: None (in-place modification)
1802 293ba2d8 Iustin Pop

1803 293ba2d8 Iustin Pop
  """
1804 293ba2d8 Iustin Pop
  if not options:
1805 293ba2d8 Iustin Pop
    return
1806 293ba2d8 Iustin Pop
  for op in opcode_list:
1807 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
1808 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
1809 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
1810 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
1811 aa06f8c6 Michael Hanselmann
      op.priority = _PRIONAME_TO_VALUE[options.priority]
1812 94428652 Iustin Pop
1813 94428652 Iustin Pop
1814 af30b2fd Michael Hanselmann
def GetClient():
1815 af30b2fd Michael Hanselmann
  # TODO: Cache object?
1816 b33e986b Iustin Pop
  try:
1817 b33e986b Iustin Pop
    client = luxi.Client()
1818 b33e986b Iustin Pop
  except luxi.NoMasterError:
1819 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
1820 d9a51679 Michael Hanselmann
1821 d9a51679 Michael Hanselmann
    # Try to read ssconf file
1822 d9a51679 Michael Hanselmann
    try:
1823 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
1824 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
1825 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
1826 d9a51679 Michael Hanselmann
                                 " not part of a cluster")
1827 d9a51679 Michael Hanselmann
1828 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
1829 b33e986b Iustin Pop
    if master != myself:
1830 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
1831 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
1832 b33e986b Iustin Pop
                                 master)
1833 d9a51679 Michael Hanselmann
    raise
1834 b33e986b Iustin Pop
  return client
1835 af30b2fd Michael Hanselmann
1836 af30b2fd Michael Hanselmann
1837 73702ee7 Iustin Pop
def FormatError(err):
1838 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
1839 73702ee7 Iustin Pop

1840 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
1841 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
1842 73702ee7 Iustin Pop
  second, a string describing the error message (not
1843 73702ee7 Iustin Pop
  newline-terminated).
1844 73702ee7 Iustin Pop

1845 73702ee7 Iustin Pop
  """
1846 73702ee7 Iustin Pop
  retcode = 1
1847 73702ee7 Iustin Pop
  obuf = StringIO()
1848 e2e521d0 Iustin Pop
  msg = str(err)
1849 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
1850 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
1851 46fbdd04 Iustin Pop
    logging.error(txt)
1852 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
1853 73702ee7 Iustin Pop
    obuf.write("Aborting.")
1854 73702ee7 Iustin Pop
    retcode = 2
1855 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
1856 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
1857 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
1858 73702ee7 Iustin Pop
      if out:
1859 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
1860 73702ee7 Iustin Pop
                   (node, script, out))
1861 73702ee7 Iustin Pop
      else:
1862 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
1863 73702ee7 Iustin Pop
                   (node, script))
1864 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
1865 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
1866 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
1867 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
1868 73702ee7 Iustin Pop
    if err.args[0] == this_host:
1869 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
1870 73702ee7 Iustin Pop
    else:
1871 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
1872 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
1873 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
1874 5c983ee5 Iustin Pop
    if len(err.args) == 2:
1875 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1876 5c983ee5 Iustin Pop
               " operation:\nerror type: %s, error details:\n%s" %
1877 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
1878 5c983ee5 Iustin Pop
    else:
1879 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1880 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
1881 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
1882 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
1883 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
1884 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
1885 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
1886 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
1887 686d7433 Iustin Pop
               " accept new requests\n")
1888 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
1889 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
1890 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
1891 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
1892 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
1893 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
1894 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
1895 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
1896 03a8dbdc Iustin Pop
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
1897 082c5adb Michael Hanselmann
               " and listening for connections?")
1898 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
1899 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
1900 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
1901 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
1902 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
1903 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
1904 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
1905 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
1906 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
1907 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
1908 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
1909 03a8dbdc Iustin Pop
               "%s" % msg)
1910 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
1911 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
1912 cb1e6c3c Michael Hanselmann
  elif isinstance(err, errors.QueryFilterParseError):
1913 cb1e6c3c Michael Hanselmann
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
1914 cb1e6c3c Michael Hanselmann
    obuf.write("\n".join(err.GetDetails()))
1915 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
1916 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
1917 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
1918 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
1919 e9d741b6 Iustin Pop
    retcode = 0
1920 73702ee7 Iustin Pop
  else:
1921 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
1922 73702ee7 Iustin Pop
  return retcode, obuf.getvalue().rstrip('\n')
1923 73702ee7 Iustin Pop
1924 73702ee7 Iustin Pop
1925 de47cf8f Guido Trotter
def GenericMain(commands, override=None, aliases=None):
1926 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
1927 a8083063 Iustin Pop

1928 334d1483 Iustin Pop
  Arguments:
1929 334d1483 Iustin Pop
    - commands: a dictionary with a special structure, see the design doc
1930 334d1483 Iustin Pop
                for command line handling.
1931 334d1483 Iustin Pop
    - override: if not None, we expect a dictionary with keys that will
1932 334d1483 Iustin Pop
                override command line options; this can be used to pass
1933 334d1483 Iustin Pop
                options from the scripts to generic functions
1934 de47cf8f Guido Trotter
    - aliases: dictionary with command aliases {'alias': 'target, ...}
1935 a8083063 Iustin Pop

1936 a8083063 Iustin Pop
  """
1937 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
1938 a8083063 Iustin Pop
  if sys.argv:
1939 a8083063 Iustin Pop
    binary = os.path.basename(sys.argv[0]) or sys.argv[0]
1940 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
1941 a8083063 Iustin Pop
      binary += " " + sys.argv[1]
1942 a8083063 Iustin Pop
      old_cmdline = " ".join(sys.argv[2:])
1943 a8083063 Iustin Pop
    else:
1944 a8083063 Iustin Pop
      old_cmdline = ""
1945 a8083063 Iustin Pop
  else:
1946 a8083063 Iustin Pop
    binary = "<unknown program>"
1947 a8083063 Iustin Pop
    old_cmdline = ""
1948 a8083063 Iustin Pop
1949 de47cf8f Guido Trotter
  if aliases is None:
1950 de47cf8f Guido Trotter
    aliases = {}
1951 de47cf8f Guido Trotter
1952 3126878d Guido Trotter
  try:
1953 3126878d Guido Trotter
    func, options, args = _ParseArgs(sys.argv, commands, aliases)
1954 3126878d Guido Trotter
  except errors.ParameterError, err:
1955 3126878d Guido Trotter
    result, err_msg = FormatError(err)
1956 3126878d Guido Trotter
    ToStderr(err_msg)
1957 3126878d Guido Trotter
    return 1
1958 3126878d Guido Trotter
1959 a8083063 Iustin Pop
  if func is None: # parse error
1960 a8083063 Iustin Pop
    return 1
1961 a8083063 Iustin Pop
1962 334d1483 Iustin Pop
  if override is not None:
1963 334d1483 Iustin Pop
    for key, val in override.iteritems():
1964 334d1483 Iustin Pop
      setattr(options, key, val)
1965 334d1483 Iustin Pop
1966 cfcc79c6 Michael Hanselmann
  utils.SetupLogging(constants.LOG_COMMANDS, binary, debug=options.debug,
1967 cfcc79c6 Michael Hanselmann
                     stderr_logging=True)
1968 a8083063 Iustin Pop
1969 a8083063 Iustin Pop
  if old_cmdline:
1970 46fbdd04 Iustin Pop
    logging.info("run with arguments '%s'", old_cmdline)
1971 a8083063 Iustin Pop
  else:
1972 46fbdd04 Iustin Pop
    logging.info("run with no arguments")
1973 a8083063 Iustin Pop
1974 a8083063 Iustin Pop
  try:
1975 a4af651e Iustin Pop
    result = func(options, args)
1976 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
1977 d8353c3a Iustin Pop
          JobSubmittedException), err:
1978 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
1979 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
1980 46fbdd04 Iustin Pop
    ToStderr(err_msg)
1981 8a53b55f Iustin Pop
  except KeyboardInterrupt:
1982 8a53b55f Iustin Pop
    result = constants.EXIT_FAILURE
1983 8a53b55f Iustin Pop
    ToStderr("Aborted. Note that if the operation created any jobs, they"
1984 8a53b55f Iustin Pop
             " might have been submitted and"
1985 8a53b55f Iustin Pop
             " will continue to run in the background.")
1986 a8083063 Iustin Pop
1987 a8083063 Iustin Pop
  return result
1988 137161c9 Michael Hanselmann
1989 137161c9 Michael Hanselmann
1990 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
1991 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
1992 845c79d8 Michael Hanselmann

1993 845c79d8 Michael Hanselmann
  """
1994 845c79d8 Michael Hanselmann
  try:
1995 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
1996 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
1997 845c79d8 Michael Hanselmann
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
1998 845c79d8 Michael Hanselmann
1999 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2000 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2001 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2002 845c79d8 Michael Hanselmann
2003 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2004 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2005 845c79d8 Michael Hanselmann
                                 " got %s" % (nidx, ndict))
2006 845c79d8 Michael Hanselmann
2007 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2008 845c79d8 Michael Hanselmann
2009 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2010 845c79d8 Michael Hanselmann
2011 845c79d8 Michael Hanselmann
  return nics
2012 845c79d8 Michael Hanselmann
2013 845c79d8 Michael Hanselmann
2014 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2015 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2016 d77490c5 Iustin Pop

2017 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2018 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2019 d77490c5 Iustin Pop
  @type args: list
2020 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2021 d77490c5 Iustin Pop
  @rtype: int
2022 d77490c5 Iustin Pop
  @return: the desired exit code
2023 d77490c5 Iustin Pop

2024 d77490c5 Iustin Pop
  """
2025 d77490c5 Iustin Pop
  instance = args[0]
2026 d77490c5 Iustin Pop
2027 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
2028 d77490c5 Iustin Pop
2029 d77490c5 Iustin Pop
  hypervisor = None
2030 d77490c5 Iustin Pop
  hvparams = {}
2031 d77490c5 Iustin Pop
  if opts.hypervisor:
2032 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
2033 d77490c5 Iustin Pop
2034 d77490c5 Iustin Pop
  if opts.nics:
2035 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
2036 d77490c5 Iustin Pop
  elif opts.no_nics:
2037 d77490c5 Iustin Pop
    # no nics
2038 d77490c5 Iustin Pop
    nics = []
2039 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
2040 d77490c5 Iustin Pop
    # default of one nic, all auto
2041 d77490c5 Iustin Pop
    nics = [{}]
2042 0af0f641 Iustin Pop
  else:
2043 0af0f641 Iustin Pop
    # mode == import
2044 0af0f641 Iustin Pop
    nics = []
2045 d77490c5 Iustin Pop
2046 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
2047 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
2048 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
2049 d77490c5 Iustin Pop
                                 " information passed")
2050 d77490c5 Iustin Pop
    disks = []
2051 d77490c5 Iustin Pop
  else:
2052 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
2053 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
2054 d77490c5 Iustin Pop
      raise errors.OpPrereqError("No disk information specified")
2055 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
2056 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
2057 d77490c5 Iustin Pop
                                 " '-s' option")
2058 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2059 ccfa86ba Michael Hanselmann
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2060 9b12ed0f Iustin Pop
2061 9b12ed0f Iustin Pop
    if opts.disks:
2062 9b12ed0f Iustin Pop
      try:
2063 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2064 9b12ed0f Iustin Pop
      except ValueError, err:
2065 9b12ed0f Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
2066 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2067 9b12ed0f Iustin Pop
    else:
2068 9b12ed0f Iustin Pop
      disks = []
2069 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2070 d77490c5 Iustin Pop
      didx = int(didx)
2071 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2072 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2073 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
2074 ccfa86ba Michael Hanselmann
      elif constants.IDISK_SIZE in ddict:
2075 ccfa86ba Michael Hanselmann
        if constants.IDISK_ADOPT in ddict:
2076 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2077 5029db65 Iustin Pop
                                     " (disk %d)" % didx)
2078 5029db65 Iustin Pop
        try:
2079 ccfa86ba Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
2080 ccfa86ba Michael Hanselmann
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2081 5029db65 Iustin Pop
        except ValueError, err:
2082 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2083 5029db65 Iustin Pop
                                     (didx, err))
2084 ccfa86ba Michael Hanselmann
      elif constants.IDISK_ADOPT in ddict:
2085 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2086 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2087 5029db65 Iustin Pop
                                     " import")
2088 ccfa86ba Michael Hanselmann
        ddict[constants.IDISK_SIZE] = 0
2089 5029db65 Iustin Pop
      else:
2090 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2091 5029db65 Iustin Pop
                                   " disk %d" % didx)
2092 d77490c5 Iustin Pop
      disks[didx] = ddict
2093 d77490c5 Iustin Pop
2094 d77490c5 Iustin Pop
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
2095 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2096 d77490c5 Iustin Pop
2097 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2098 d77490c5 Iustin Pop
    start = opts.start
2099 d77490c5 Iustin Pop
    os_type = opts.os
2100 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2101 d77490c5 Iustin Pop
    src_node = None
2102 d77490c5 Iustin Pop
    src_path = None
2103 25a8792c Iustin Pop
    no_install = opts.no_install
2104 e588764d Iustin Pop
    identify_defaults = False
2105 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2106 d77490c5 Iustin Pop
    start = False
2107 d77490c5 Iustin Pop
    os_type = None
2108 1ee8e01a Guido Trotter
    force_variant = False
2109 d77490c5 Iustin Pop
    src_node = opts.src_node
2110 d77490c5 Iustin Pop
    src_path = opts.src_dir
2111 25a8792c Iustin Pop
    no_install = None
2112 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2113 d77490c5 Iustin Pop
  else:
2114 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2115 d77490c5 Iustin Pop
2116 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2117 d77490c5 Iustin Pop
                                disks=disks,
2118 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2119 d77490c5 Iustin Pop
                                nics=nics,
2120 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2121 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2122 460d22be Iustin Pop
                                name_check=opts.name_check,
2123 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2124 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2125 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2126 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2127 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2128 d77490c5 Iustin Pop
                                hvparams=hvparams,
2129 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2130 062a7100 Iustin Pop
                                osparams=opts.osparams,
2131 d77490c5 Iustin Pop
                                mode=mode,
2132 d77490c5 Iustin Pop
                                start=start,
2133 d77490c5 Iustin Pop
                                os_type=os_type,
2134 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2135 d77490c5 Iustin Pop
                                src_node=src_node,
2136 25a8792c Iustin Pop
                                src_path=src_path,
2137 e588764d Iustin Pop
                                no_install=no_install,
2138 e588764d Iustin Pop
                                identify_defaults=identify_defaults)
2139 d77490c5 Iustin Pop
2140 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2141 d77490c5 Iustin Pop
  return 0
2142 d77490c5 Iustin Pop
2143 d77490c5 Iustin Pop
2144 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2145 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2146 7e49b6ce Michael Hanselmann

2147 7e49b6ce Michael Hanselmann
  """
2148 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2149 7e49b6ce Michael Hanselmann
    """Initializes this class.
2150 7e49b6ce Michael Hanselmann

2151 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2152 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2153 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2154 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2155 7e49b6ce Michael Hanselmann
    @type master_node: string
2156 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2157 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2158 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2159 7e49b6ce Michael Hanselmann

2160 7e49b6ce Michael Hanselmann
    """
2161 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2162 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2163 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2164 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2165 7e49b6ce Michael Hanselmann
2166 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2167 7e49b6ce Michael Hanselmann
2168 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2169 7e49b6ce Michael Hanselmann
                            if name != master_node]
2170 7e49b6ce Michael Hanselmann
2171 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2172 7e49b6ce Michael Hanselmann
2173 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2174 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2175 7e49b6ce Michael Hanselmann

2176 7e49b6ce Michael Hanselmann
    @type node_name: string
2177 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2178 7e49b6ce Michael Hanselmann
    @type cmd: list
2179 7e49b6ce Michael Hanselmann
    @param cmd: Command
2180 7e49b6ce Michael Hanselmann

2181 7e49b6ce Michael Hanselmann
    """
2182 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2183 7e49b6ce Michael Hanselmann
      # No need to use SSH
2184 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2185 7e49b6ce Michael Hanselmann
    else:
2186 7e49b6ce Michael Hanselmann
      result = self.ssh.Run(node_name, "root", utils.ShellQuoteArgs(cmd))
2187 7e49b6ce Michael Hanselmann
2188 7e49b6ce Michael Hanselmann
    if result.failed:
2189 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2190 7e49b6ce Michael Hanselmann
      if node_name:
2191 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2192 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2193 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2194 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2195 7e49b6ce Michael Hanselmann
2196 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2197 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2198 7e49b6ce Michael Hanselmann

2199 7e49b6ce Michael Hanselmann
    @type fn: callable
2200 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2201 7e49b6ce Michael Hanselmann

2202 7e49b6ce Michael Hanselmann
    """
2203 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2204 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2205 7e49b6ce Michael Hanselmann
    watcher_block = utils.FileLock.Open(constants.WATCHER_STATEFILE)
2206 7e49b6ce Michael Hanselmann
    try:
2207 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2208 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2209 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2210 7e49b6ce Michael Hanselmann
2211 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2212 7e49b6ce Michael Hanselmann
      # ones are finished
2213 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2214 7e49b6ce Michael Hanselmann
      self._RunCmd(None, [constants.DAEMON_UTIL, "stop-master"])
2215 7e49b6ce Michael Hanselmann
      try:
2216 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2217 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2218 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2219 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "stop-all"])
2220 7e49b6ce Michael Hanselmann
2221 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2222 7e49b6ce Michael Hanselmann
        try:
2223 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2224 d512e84b Michael Hanselmann
        except Exception, err:
2225 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2226 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2227 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2228 7e49b6ce Michael Hanselmann
          raise
2229 7e49b6ce Michael Hanselmann
      finally:
2230 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2231 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2232 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2233 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "start-all"])
2234 7e49b6ce Michael Hanselmann
    finally:
2235 7e49b6ce Michael Hanselmann
      # Resume watcher
2236 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2237 7e49b6ce Michael Hanselmann
2238 7e49b6ce Michael Hanselmann
2239 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2240 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2241 7e49b6ce Michael Hanselmann

2242 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2243 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2244 7e49b6ce Michael Hanselmann
  @type fn: callable
2245 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2246 7e49b6ce Michael Hanselmann

2247 7e49b6ce Michael Hanselmann
  """
2248 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2249 7e49b6ce Michael Hanselmann
2250 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2251 7e49b6ce Michael Hanselmann
  cl = GetClient()
2252 7e49b6ce Michael Hanselmann
2253 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2254 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2255 7e49b6ce Michael Hanselmann
2256 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2257 7e49b6ce Michael Hanselmann
2258 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2259 7e49b6ce Michael Hanselmann
  del cl
2260 7e49b6ce Michael Hanselmann
2261 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2262 7e49b6ce Michael Hanselmann
2263 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2264 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2265 7e49b6ce Michael Hanselmann
2266 7e49b6ce Michael Hanselmann
2267 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2268 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2269 9fbfbb7b Iustin Pop
                  units=None):
2270 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2271 137161c9 Michael Hanselmann

2272 9fbfbb7b Iustin Pop
  @type headers: dict
2273 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2274 9fbfbb7b Iustin Pop
      the table
2275 9fbfbb7b Iustin Pop
  @type fields: list
2276 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2277 9fbfbb7b Iustin Pop
      the data field
2278 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2279 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2280 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2281 9fbfbb7b Iustin Pop
      each field
2282 9fbfbb7b Iustin Pop
  @type data: list
2283 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2284 9fbfbb7b Iustin Pop
  @type numfields: list
2285 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2286 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2287 9fbfbb7b Iustin Pop
  @type unitfields: list
2288 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2289 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2290 9fbfbb7b Iustin Pop
  @type units: string or None
2291 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2292 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2293 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2294 137161c9 Michael Hanselmann

2295 137161c9 Michael Hanselmann
  """
2296 9fbfbb7b Iustin Pop
  if units is None:
2297 9fbfbb7b Iustin Pop
    if separator:
2298 9fbfbb7b Iustin Pop
      units = "m"
2299 9fbfbb7b Iustin Pop
    else:
2300 9fbfbb7b Iustin Pop
      units = "h"
2301 9fbfbb7b Iustin Pop
2302 137161c9 Michael Hanselmann
  if numfields is None:
2303 137161c9 Michael Hanselmann
    numfields = []
2304 137161c9 Michael Hanselmann
  if unitfields is None:
2305 137161c9 Michael Hanselmann
    unitfields = []
2306 137161c9 Michael Hanselmann
2307 fe267188 Iustin Pop
  numfields = utils.FieldSet(*numfields)   # pylint: disable-msg=W0142
2308 fe267188 Iustin Pop
  unitfields = utils.FieldSet(*unitfields) # pylint: disable-msg=W0142
2309 00430f8e Iustin Pop
2310 137161c9 Michael Hanselmann
  format_fields = []
2311 137161c9 Michael Hanselmann
  for field in fields:
2312 01ca31ae Iustin Pop
    if headers and field not in headers:
2313 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2314 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2315 71c1af58 Iustin Pop
      # variable fields)
2316 71c1af58 Iustin Pop
      headers[field] = field
2317 137161c9 Michael Hanselmann
    if separator is not None:
2318 137161c9 Michael Hanselmann
      format_fields.append("%s")
2319 00430f8e Iustin Pop
    elif numfields.Matches(field):
2320 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2321 137161c9 Michael Hanselmann
    else:
2322 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2323 137161c9 Michael Hanselmann
2324 137161c9 Michael Hanselmann
  if separator is None:
2325 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2326 c04bc777 Iustin Pop
    format_str = ' '.join(format_fields)
2327 137161c9 Michael Hanselmann
  else:
2328 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2329 137161c9 Michael Hanselmann
2330 137161c9 Michael Hanselmann
  for row in data:
2331 dcbd6288 Guido Trotter
    if row is None:
2332 dcbd6288 Guido Trotter
      continue
2333 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2334 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2335 137161c9 Michael Hanselmann
        try:
2336 137161c9 Michael Hanselmann
          val = int(val)
2337 691744c4 Iustin Pop
        except (TypeError, ValueError):
2338 137161c9 Michael Hanselmann
          pass
2339 137161c9 Michael Hanselmann
        else:
2340 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2341 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2342 137161c9 Michael Hanselmann
      if separator is None:
2343 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2344 137161c9 Michael Hanselmann
2345 16be8703 Iustin Pop
  result = []
2346 137161c9 Michael Hanselmann
  if headers:
2347 137161c9 Michael Hanselmann
    args = []
2348 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2349 137161c9 Michael Hanselmann
      hdr = headers[name]
2350 137161c9 Michael Hanselmann
      if separator is None:
2351 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2352 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2353 137161c9 Michael Hanselmann
      args.append(hdr)
2354 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2355 137161c9 Michael Hanselmann
2356 ec39d63c Michael Hanselmann
  if separator is None:
2357 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2358 ec39d63c Michael Hanselmann
2359 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2360 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2361 ec39d63c Michael Hanselmann
2362 137161c9 Michael Hanselmann
  for line in data:
2363 137161c9 Michael Hanselmann
    args = []
2364 dcbd6288 Guido Trotter
    if line is None:
2365 dcbd6288 Guido Trotter
      line = ['-' for _ in fields]
2366 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2367 137161c9 Michael Hanselmann
      if separator is None:
2368 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2369 137161c9 Michael Hanselmann
      args.append(line[idx])
2370 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2371 16be8703 Iustin Pop
2372 16be8703 Iustin Pop
  return result
2373 3386e7a9 Iustin Pop
2374 3386e7a9 Iustin Pop
2375 ee3aedff Michael Hanselmann
def _FormatBool(value):
2376 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
2377 ee3aedff Michael Hanselmann

2378 ee3aedff Michael Hanselmann
  """
2379 ee3aedff Michael Hanselmann
  if value:
2380 ee3aedff Michael Hanselmann
    return "Y"
2381 ee3aedff Michael Hanselmann
  return "N"
2382 ee3aedff Michael Hanselmann
2383 ee3aedff Michael Hanselmann
2384 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2385 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2386 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2387 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2388 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2389 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2390 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2391 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2392 ee3aedff Michael Hanselmann
  }
2393 ee3aedff Michael Hanselmann
2394 ee3aedff Michael Hanselmann
2395 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2396 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2397 ee3aedff Michael Hanselmann

2398 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2399 ee3aedff Michael Hanselmann
  @type override: dict
2400 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2401 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2402 ee3aedff Michael Hanselmann
  @type unit: string
2403 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2404 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2405 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2406 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2407 ee3aedff Michael Hanselmann

2408 ee3aedff Michael Hanselmann
  """
2409 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2410 ee3aedff Michael Hanselmann
  if fmt is not None:
2411 ee3aedff Michael Hanselmann
    return fmt
2412 ee3aedff Michael Hanselmann
2413 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2414 ee3aedff Michael Hanselmann
2415 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2416 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2417 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2418 ee3aedff Michael Hanselmann
2419 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2420 ee3aedff Michael Hanselmann
  if fmt is not None:
2421 ee3aedff Michael Hanselmann
    return fmt
2422 ee3aedff Michael Hanselmann
2423 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
2424 ee3aedff Michael Hanselmann
2425 ee3aedff Michael Hanselmann
2426 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
2427 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
2428 ee3aedff Michael Hanselmann

2429 ee3aedff Michael Hanselmann
  """
2430 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
2431 ee3aedff Michael Hanselmann
    """Initializes this class.
2432 ee3aedff Michael Hanselmann

2433 ee3aedff Michael Hanselmann
    @type fn: callable
2434 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2435 ee3aedff Michael Hanselmann
    @type status_fn: callable
2436 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
2437 f0b1bafe Iustin Pop
    @type verbose: boolean
2438 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
2439 ee3aedff Michael Hanselmann

2440 ee3aedff Michael Hanselmann
    """
2441 ee3aedff Michael Hanselmann
    self._fn = fn
2442 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
2443 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
2444 ee3aedff Michael Hanselmann
2445 ee3aedff Michael Hanselmann
  def __call__(self, data):
2446 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
2447 ee3aedff Michael Hanselmann

2448 ee3aedff Michael Hanselmann
    """
2449 ee3aedff Michael Hanselmann
    (status, value) = data
2450 ee3aedff Michael Hanselmann
2451 ee3aedff Michael Hanselmann
    # Report status
2452 ee3aedff Michael Hanselmann
    self._status_fn(status)
2453 ee3aedff Michael Hanselmann
2454 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
2455 ee3aedff Michael Hanselmann
      return self._fn(value)
2456 ee3aedff Michael Hanselmann
2457 ee3aedff Michael Hanselmann
    assert value is None, \
2458 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
2459 ee3aedff Michael Hanselmann
2460 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
2461 ee3aedff Michael Hanselmann
2462 ee3aedff Michael Hanselmann
2463 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
2464 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
2465 ee3aedff Michael Hanselmann

2466 ae95e419 René Nussbaumer
  @param status: The result status
2467 f2c6673d Michael Hanselmann
  @type verbose: boolean
2468 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
2469 ae95e419 René Nussbaumer
  @return: Text of result status
2470 a6070ef7 Michael Hanselmann

2471 ae95e419 René Nussbaumer
  """
2472 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
2473 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
2474 ae95e419 René Nussbaumer
  try:
2475 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
2476 ae95e419 René Nussbaumer
  except KeyError:
2477 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
2478 cbfa4f0f Michael Hanselmann
  else:
2479 cbfa4f0f Michael Hanselmann
    if verbose:
2480 cbfa4f0f Michael Hanselmann
      return verbose_text
2481 cbfa4f0f Michael Hanselmann
    return normal_text
2482 ee3aedff Michael Hanselmann
2483 ee3aedff Michael Hanselmann
2484 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
2485 f0b1bafe Iustin Pop
                      header=False, verbose=False):
2486 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
2487 ee3aedff Michael Hanselmann

2488 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
2489 ee3aedff Michael Hanselmann
  @param result: result of query operation
2490 ee3aedff Michael Hanselmann
  @type unit: string
2491 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
2492 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
2493 ee3aedff Michael Hanselmann
  @type format_override: dict
2494 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2495 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2496 ee3aedff Michael Hanselmann
  @type separator: string or None
2497 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2498 ee3aedff Michael Hanselmann
  @type header: bool
2499 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
2500 f0b1bafe Iustin Pop
  @type verbose: boolean
2501 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2502 ee3aedff Michael Hanselmann

2503 ee3aedff Michael Hanselmann
  """
2504 ee3aedff Michael Hanselmann
  if unit is None:
2505 ee3aedff Michael Hanselmann
    if separator:
2506 ee3aedff Michael Hanselmann
      unit = "m"
2507 ee3aedff Michael Hanselmann
    else:
2508 ee3aedff Michael Hanselmann
      unit = "h"
2509 ee3aedff Michael Hanselmann
2510 ee3aedff Michael Hanselmann
  if format_override is None:
2511 ee3aedff Michael Hanselmann
    format_override = {}
2512 ee3aedff Michael Hanselmann
2513 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
2514 ee3aedff Michael Hanselmann
2515 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
2516 ee3aedff Michael Hanselmann
    if status in stats:
2517 ee3aedff Michael Hanselmann
      stats[status] += 1
2518 ee3aedff Michael Hanselmann
2519 ee3aedff Michael Hanselmann
  columns = []
2520 ee3aedff Michael Hanselmann
  for fdef in result.fields:
2521 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
2522 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
2523 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
2524 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
2525 f0b1bafe Iustin Pop
                                                     verbose),
2526 ee3aedff Michael Hanselmann
                               align_right))
2527 ee3aedff Michael Hanselmann
2528 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
2529 ee3aedff Michael Hanselmann
2530 ee3aedff Michael Hanselmann
  # Collect statistics
2531 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
2532 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
2533 ee3aedff Michael Hanselmann
2534 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
2535 ee3aedff Michael Hanselmann
  # detected via the field definitions.
2536 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
2537 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
2538 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
2539 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
2540 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
2541 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
2542 ee3aedff Michael Hanselmann
  else:
2543 ee3aedff Michael Hanselmann
    status = QR_NORMAL
2544 ee3aedff Michael Hanselmann
2545 ee3aedff Michael Hanselmann
  return (status, table)
2546 ee3aedff Michael Hanselmann
2547 ee3aedff Michael Hanselmann
2548 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
2549 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
2550 ee3aedff Michael Hanselmann

2551 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2552 ee3aedff Michael Hanselmann

2553 ee3aedff Michael Hanselmann
  """
2554 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
2555 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
2556 ee3aedff Michael Hanselmann
2557 ee3aedff Michael Hanselmann
2558 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
2559 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
2560 ee3aedff Michael Hanselmann

2561 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2562 ee3aedff Michael Hanselmann

2563 ee3aedff Michael Hanselmann
  """
2564 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
2565 ee3aedff Michael Hanselmann
  if unknown:
2566 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
2567 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
2568 ee3aedff Michael Hanselmann
    return True
2569 ee3aedff Michael Hanselmann
2570 ee3aedff Michael Hanselmann
  return False
2571 ee3aedff Michael Hanselmann
2572 ee3aedff Michael Hanselmann
2573 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
2574 2928de47 Michael Hanselmann
                format_override=None, verbose=False, force_filter=False):
2575 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
2576 ee3aedff Michael Hanselmann

2577 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
2578 ee3aedff Michael Hanselmann
  @type fields: list of strings
2579 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
2580 ee3aedff Michael Hanselmann
  @type names: list of strings
2581 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
2582 ee3aedff Michael Hanselmann
  @type unit: string or None
2583 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
2584 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
2585 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
2586 ee3aedff Michael Hanselmann
  @type separator: string or None
2587 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2588 ee3aedff Michael Hanselmann
  @type header: bool
2589 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2590 2928de47 Michael Hanselmann
  @type force_filter: bool
2591 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
2592 ee3aedff Michael Hanselmann
  @type format_override: dict
2593 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2594 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2595 f0b1bafe Iustin Pop
  @type verbose: boolean
2596 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2597 ee3aedff Michael Hanselmann

2598 ee3aedff Michael Hanselmann
  """
2599 ee3aedff Michael Hanselmann
  if cl is None:
2600 ee3aedff Michael Hanselmann
    cl = GetClient()
2601 ee3aedff Michael Hanselmann
2602 ee3aedff Michael Hanselmann
  if not names:
2603 ee3aedff Michael Hanselmann
    names = None
2604 ee3aedff Michael Hanselmann
2605 2928de47 Michael Hanselmann
  if (force_filter or
2606 2928de47 Michael Hanselmann
      (names and len(names) == 1 and qlang.MaybeFilter(names[0]))):
2607 2928de47 Michael Hanselmann
    try:
2608 2928de47 Michael Hanselmann
      (filter_text, ) = names
2609 2928de47 Michael Hanselmann
    except ValueError:
2610 2928de47 Michael Hanselmann
      raise errors.OpPrereqError("Exactly one argument must be given as a"
2611 2928de47 Michael Hanselmann
                                 " filter")
2612 2928de47 Michael Hanselmann
2613 2928de47 Michael Hanselmann
    logging.debug("Parsing '%s' as filter", filter_text)
2614 2928de47 Michael Hanselmann
    filter_ = qlang.ParseFilter(filter_text)
2615 2928de47 Michael Hanselmann
  else:
2616 2928de47 Michael Hanselmann
    filter_ = qlang.MakeSimpleFilter("name", names)
2617 2928de47 Michael Hanselmann
2618 2928de47 Michael Hanselmann
  response = cl.Query(resource, fields, filter_)
2619 ee3aedff Michael Hanselmann
2620 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
2621 ee3aedff Michael Hanselmann
2622 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
2623 ee3aedff Michael Hanselmann
                                     header=header,
2624 f0b1bafe Iustin Pop
                                     format_override=format_override,
2625 f0b1bafe Iustin Pop
                                     verbose=verbose)
2626 ee3aedff Michael Hanselmann
2627 ee3aedff Michael Hanselmann
  for line in data:
2628 ee3aedff Michael Hanselmann
    ToStdout(line)
2629 ee3aedff Michael Hanselmann
2630 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
2631 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
2632 ee3aedff Michael Hanselmann
2633 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
2634 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
2635 ee3aedff Michael Hanselmann
2636 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
2637 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
2638 ee3aedff Michael Hanselmann
2639 ee3aedff Michael Hanselmann
2640 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
2641 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
2642 ee3aedff Michael Hanselmann

2643 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
2644 ee3aedff Michael Hanselmann
  @type fields: list of strings
2645 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
2646 ee3aedff Michael Hanselmann
  @type separator: string or None
2647 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2648 ee3aedff Michael Hanselmann
  @type header: bool
2649 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2650 ee3aedff Michael Hanselmann

2651 ee3aedff Michael Hanselmann
  """
2652 ee3aedff Michael Hanselmann
  if cl is None:
2653 ee3aedff Michael Hanselmann
    cl = GetClient()
2654 ee3aedff Michael Hanselmann
2655 ee3aedff Michael Hanselmann
  if not fields:
2656 ee3aedff Michael Hanselmann
    fields = None
2657 ee3aedff Michael Hanselmann
2658 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
2659 ee3aedff Michael Hanselmann
2660 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
2661 ee3aedff Michael Hanselmann
2662 ee3aedff Michael Hanselmann
  columns = [
2663 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
2664 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
2665 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
2666 ee3aedff Michael Hanselmann
    ]
2667 ee3aedff Michael Hanselmann
2668 ea1440c1 Michael Hanselmann
  rows = [[fdef.name, fdef.title, fdef.doc] for fdef in response.fields]
2669 ee3aedff Michael Hanselmann
2670 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
2671 ee3aedff Michael Hanselmann
    ToStdout(line)
2672 ee3aedff Michael Hanselmann
2673 ee3aedff Michael Hanselmann
  if found_unknown:
2674 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
2675 ee3aedff Michael Hanselmann
2676 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
2677 ee3aedff Michael Hanselmann
2678 ee3aedff Michael Hanselmann
2679 ee3aedff Michael Hanselmann
class TableColumn:
2680 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
2681 ee3aedff Michael Hanselmann

2682 ee3aedff Michael Hanselmann
  """
2683 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
2684 ee3aedff Michael Hanselmann
    """Initializes this class.
2685 ee3aedff Michael Hanselmann

2686 ee3aedff Michael Hanselmann
    @type title: string
2687 ee3aedff Michael Hanselmann
    @param title: Column title
2688 ee3aedff Michael Hanselmann
    @type fn: callable
2689 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2690 ee3aedff Michael Hanselmann
    @type align_right: bool
2691 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
2692 ee3aedff Michael Hanselmann

2693 ee3aedff Michael Hanselmann
    """
2694 ee3aedff Michael Hanselmann
    self.title = title
2695 ee3aedff Michael Hanselmann
    self.format = fn
2696 ee3aedff Michael Hanselmann
    self.align_right = align_right
2697 ee3aedff Michael Hanselmann
2698 ee3aedff Michael Hanselmann
2699 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
2700 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
2701 ee3aedff Michael Hanselmann

2702 ee3aedff Michael Hanselmann
  """
2703 ee3aedff Michael Hanselmann
  if align_right:
2704 ee3aedff Michael Hanselmann
    sign = ""
2705 ee3aedff Michael Hanselmann
  else:
2706 ee3aedff Michael Hanselmann
    sign = "-"
2707 ee3aedff Michael Hanselmann
2708 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
2709 ee3aedff Michael Hanselmann
2710 ee3aedff Michael Hanselmann
2711 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
2712 ee3aedff Michael Hanselmann
  """Formats data as a table.
2713 ee3aedff Michael Hanselmann

2714 ee3aedff Michael Hanselmann
  @type rows: list of lists
2715 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
2716 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
2717 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
2718 ee3aedff Michael Hanselmann
  @type header: bool
2719 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2720 ee3aedff Michael Hanselmann
  @type separator: string or None
2721 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
2722 ee3aedff Michael Hanselmann

2723 ee3aedff Michael Hanselmann
  """
2724 ee3aedff Michael Hanselmann
  if header:
2725 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
2726 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
2727 ee3aedff Michael Hanselmann
  else:
2728 ee3aedff Michael Hanselmann
    data = []
2729 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
2730 ee3aedff Michael Hanselmann
2731 ee3aedff Michael Hanselmann
  # Format row data
2732 ee3aedff Michael Hanselmann
  for row in rows:
2733 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
2734 ee3aedff Michael Hanselmann
2735 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
2736 ee3aedff Michael Hanselmann
2737 ee3aedff Michael Hanselmann
    if separator is None:
2738 ee3aedff Michael Hanselmann
      # Update column widths
2739 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
2740 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
2741 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
2742 ee3aedff Michael Hanselmann
2743 ee3aedff Michael Hanselmann
    data.append(formatted)
2744 ee3aedff Michael Hanselmann
2745 ee3aedff Michael Hanselmann
  if separator is not None:
2746 ee3aedff Michael Hanselmann
    # Return early if a separator is used
2747 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
2748 ee3aedff Michael Hanselmann
2749 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
2750 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
2751 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
2752 ee3aedff Michael Hanselmann
2753 ee3aedff Michael Hanselmann
  # Build format string
2754 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
2755 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
2756 ee3aedff Michael Hanselmann
2757 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
2758 ee3aedff Michael Hanselmann
2759 ee3aedff Michael Hanselmann
2760 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
2761 3386e7a9 Iustin Pop
  """Formats a given timestamp.
2762 3386e7a9 Iustin Pop

2763 3386e7a9 Iustin Pop
  @type ts: timestamp
2764 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
2765 3386e7a9 Iustin Pop

2766 3386e7a9 Iustin Pop
  @rtype: string
2767 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
2768 3386e7a9 Iustin Pop

2769 3386e7a9 Iustin Pop
  """
2770 e0ec0ff6 Iustin Pop
  if not isinstance (ts, (tuple, list)) or len(ts) != 2:
2771 e0ec0ff6 Iustin Pop
    return '?'
2772 3386e7a9 Iustin Pop
  sec, usec = ts
2773 3386e7a9 Iustin Pop
  return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
2774 2241e2b9 Iustin Pop
2775 2241e2b9 Iustin Pop
2776 2241e2b9 Iustin Pop
def ParseTimespec(value):
2777 2241e2b9 Iustin Pop
  """Parse a time specification.
2778 2241e2b9 Iustin Pop

2779 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
2780 2241e2b9 Iustin Pop

2781 2241e2b9 Iustin Pop
    - s: seconds
2782 2241e2b9 Iustin Pop
    - m: minutes
2783 2241e2b9 Iustin Pop
    - h: hours
2784 2241e2b9 Iustin Pop
    - d: day
2785 2241e2b9 Iustin Pop
    - w: weeks
2786 2241e2b9 Iustin Pop

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

2789 2241e2b9 Iustin Pop
  """
2790 2241e2b9 Iustin Pop
  value = str(value)
2791 2241e2b9 Iustin Pop
  if not value:
2792 2241e2b9 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed")
2793 2241e2b9 Iustin Pop
  suffix_map = {
2794 2241e2b9 Iustin Pop
    's': 1,
2795 2241e2b9 Iustin Pop
    'm': 60,
2796 2241e2b9 Iustin Pop
    'h': 3600,
2797 2241e2b9 Iustin Pop
    'd': 86400,
2798 2241e2b9 Iustin Pop
    'w': 604800,
2799 2241e2b9 Iustin Pop
    }
2800 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
2801 2241e2b9 Iustin Pop
    try:
2802 2241e2b9 Iustin Pop
      value = int(value)
2803 691744c4 Iustin Pop
    except (TypeError, ValueError):
2804 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2805 2241e2b9 Iustin Pop
  else:
2806 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
2807 2241e2b9 Iustin Pop
    value = value[:-1]
2808 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
2809 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
2810 2241e2b9 Iustin Pop
                                 " suffix passed)")
2811 2241e2b9 Iustin Pop
    try:
2812 2241e2b9 Iustin Pop
      value = int(value) * multiplier
2813 691744c4 Iustin Pop
    except (TypeError, ValueError):
2814 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2815 2241e2b9 Iustin Pop
  return value
2816 46fbdd04 Iustin Pop
2817 46fbdd04 Iustin Pop
2818 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
2819 e9e26bb3 Iustin Pop
                   filter_master=False):
2820 4040a784 Iustin Pop
  """Returns the names of online nodes.
2821 4040a784 Iustin Pop

2822 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
2823 4040a784 Iustin Pop
  the online nodes.
2824 4040a784 Iustin Pop

2825 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
2826 4040a784 Iustin Pop
      offline ones)
2827 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
2828 4040a784 Iustin Pop
  @type nowarn: boolean
2829 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
2830 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
2831 4040a784 Iustin Pop
      note is not displayed
2832 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
2833 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
2834 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
2835 e9e26bb3 Iustin Pop
      (if any)
2836 e9e26bb3 Iustin Pop
  @type filter_master: boolean
2837 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
2838 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
2839 e9e26bb3 Iustin Pop
      node name against the list)
2840 4040a784 Iustin Pop

2841 4040a784 Iustin Pop
  """
2842 4040a784 Iustin Pop
  if cl is None:
2843 4040a784 Iustin Pop
    cl = GetClient()
2844 4040a784 Iustin Pop
2845 e9e26bb3 Iustin Pop
  if secondary_ips:
2846 e9e26bb3 Iustin Pop
    name_idx = 2
2847 e9e26bb3 Iustin Pop
  else:
2848 e9e26bb3 Iustin Pop
    name_idx = 0
2849 e9e26bb3 Iustin Pop
2850 e9e26bb3 Iustin Pop
  if filter_master:
2851 e9e26bb3 Iustin Pop
    master_node = cl.QueryConfigValues(["master_node"])[0]
2852 e9e26bb3 Iustin Pop
    filter_fn = lambda x: x != master_node
2853 e9e26bb3 Iustin Pop
  else:
2854 e9e26bb3 Iustin Pop
    filter_fn = lambda _: True
2855 e9e26bb3 Iustin Pop
2856 e9e26bb3 Iustin Pop
  result = cl.QueryNodes(names=nodes, fields=["name", "offline", "sip"],
2857 2e7b8369 Iustin Pop
                         use_locking=False)
2858 4040a784 Iustin Pop
  offline = [row[0] for row in result if row[1]]
2859 4040a784 Iustin Pop
  if offline and not nowarn:
2860 1f864b60 Iustin Pop
    ToStderr("Note: skipping offline node(s): %s" % utils.CommaJoin(offline))
2861 e9e26bb3 Iustin Pop
  return [row[name_idx] for row in result if not row[1] and filter_fn(row[0])]
2862 4040a784 Iustin Pop
2863 4040a784 Iustin Pop
2864 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
2865 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
2866 46fbdd04 Iustin Pop

2867 46fbdd04 Iustin Pop
  @type stream: file object
2868 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
2869 46fbdd04 Iustin Pop
  @type txt: str
2870 46fbdd04 Iustin Pop
  @param txt: the message
2871 46fbdd04 Iustin Pop

2872 46fbdd04 Iustin Pop
  """
2873 46fbdd04 Iustin Pop
  if args:
2874 46fbdd04 Iustin Pop
    args = tuple(args)
2875 46fbdd04 Iustin Pop
    stream.write(txt % args)
2876 46fbdd04 Iustin Pop
  else:
2877 46fbdd04 Iustin Pop
    stream.write(txt)
2878 46fbdd04 Iustin Pop
  stream.write('\n')
2879 46fbdd04 Iustin Pop
  stream.flush()
2880 46fbdd04 Iustin Pop
2881 46fbdd04 Iustin Pop
2882 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
2883 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
2884 46fbdd04 Iustin Pop

2885 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
2886 46fbdd04 Iustin Pop

2887 46fbdd04 Iustin Pop
  @type txt: str
2888 46fbdd04 Iustin Pop
  @param txt: the message
2889 46fbdd04 Iustin Pop

2890 46fbdd04 Iustin Pop
  """
2891 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
2892 46fbdd04 Iustin Pop
2893 46fbdd04 Iustin Pop
2894 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
2895 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
2896 46fbdd04 Iustin Pop

2897 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
2898 46fbdd04 Iustin Pop

2899 46fbdd04 Iustin Pop
  @type txt: str
2900 46fbdd04 Iustin Pop
  @param txt: the message
2901 46fbdd04 Iustin Pop

2902 46fbdd04 Iustin Pop
  """
2903 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
2904 479636a3 Iustin Pop
2905 479636a3 Iustin Pop
2906 479636a3 Iustin Pop
class JobExecutor(object):
2907 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
2908 479636a3 Iustin Pop

2909 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
2910 479636a3 Iustin Pop
  GetResults() calls.
2911 479636a3 Iustin Pop

2912 479636a3 Iustin Pop
  """
2913 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
2914 479636a3 Iustin Pop
    self.queue = []
2915 479636a3 Iustin Pop
    if cl is None:
2916 479636a3 Iustin Pop
      cl = GetClient()
2917 479636a3 Iustin Pop
    self.cl = cl
2918 479636a3 Iustin Pop
    self.verbose = verbose
2919 23b4b983 Iustin Pop
    self.jobs = []
2920 cff5fa7f Iustin Pop
    self.opts = opts
2921 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
2922 479636a3 Iustin Pop
2923 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
2924 23b4b983 Iustin Pop
    """Record a job for later submit.
2925 479636a3 Iustin Pop

2926 479636a3 Iustin Pop
    @type name: string
2927 479636a3 Iustin Pop
    @param name: a description of the job, will be used in WaitJobSet
2928 479636a3 Iustin Pop
    """
2929 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
2930 23b4b983 Iustin Pop
    self.queue.append((name, ops))
2931 23b4b983 Iustin Pop
2932 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
2933 23b4b983 Iustin Pop
    """Submit all pending jobs.
2934 23b4b983 Iustin Pop

2935 23b4b983 Iustin Pop
    """
2936 66ecc479 Guido Trotter
    if each:
2937 66ecc479 Guido Trotter
      results = []
2938 66ecc479 Guido Trotter
      for row in self.queue:
2939 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
2940 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
2941 66ecc479 Guido Trotter
        results.append([True, self.cl.SubmitJob(row[1])])
2942 66ecc479 Guido Trotter
    else:
2943 66ecc479 Guido Trotter
      results = self.cl.SubmitManyJobs([row[1] for row in self.queue])
2944 5299e61f Iustin Pop
    for (idx, ((status, data), (name, _))) in enumerate(zip(results,
2945 5299e61f Iustin Pop
                                                            self.queue)):
2946 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
2947 5299e61f Iustin Pop
2948 5299e61f Iustin Pop
  def _ChooseJob(self):
2949 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
2950 5299e61f Iustin Pop

2951 5299e61f Iustin Pop
    """
2952 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
2953 5299e61f Iustin Pop
2954 5299e61f Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs], ["status"])
2955 5299e61f Iustin Pop
    assert result
2956 5299e61f Iustin Pop
2957 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
2958 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
2959 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
2960 91c622a8 Iustin Pop
                        constants.JOB_STATUS_WAITLOCK,
2961 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
2962 91c622a8 Iustin Pop
        # job is still present and waiting
2963 5299e61f Iustin Pop
        continue
2964 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
2965 5299e61f Iustin Pop
      self.jobs.remove(job_data)
2966 5299e61f Iustin Pop
      return job_data
2967 5299e61f Iustin Pop
2968 5299e61f Iustin Pop
    # no job found
2969 5299e61f Iustin Pop
    return self.jobs.pop(0)
2970 479636a3 Iustin Pop
2971 479636a3 Iustin Pop
  def GetResults(self):
2972 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
2973 479636a3 Iustin Pop

2974 479636a3 Iustin Pop
    @rtype: list
2975 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
2976 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
2977 479636a3 Iustin Pop
        there will be the error message
2978 479636a3 Iustin Pop

2979 479636a3 Iustin Pop
    """
2980 23b4b983 Iustin Pop
    if not self.jobs:
2981 23b4b983 Iustin Pop
      self.SubmitPending()
2982 479636a3 Iustin Pop
    results = []
2983 479636a3 Iustin Pop
    if self.verbose:
2984 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
2985 23b4b983 Iustin Pop
      if ok_jobs:
2986 1f864b60 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
2987 5299e61f Iustin Pop
2988 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
2989 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
2990 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
2991 c63355f2 Iustin Pop
      ToStderr("Failed to submit job for %s: %s", name, jid)
2992 c63355f2 Iustin Pop
      results.append((idx, False, jid))
2993 5299e61f Iustin Pop
2994 5299e61f Iustin Pop
    while self.jobs:
2995 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
2996 5299e61f Iustin Pop
      ToStdout("Waiting for job %s for %s...", jid, name)
2997 479636a3 Iustin Pop
      try:
2998 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
2999 479636a3 Iustin Pop
        success = True
3000 91c622a8 Iustin Pop
      except errors.JobLost, err:
3001 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3002 91c622a8 Iustin Pop
        ToStderr("Job %s for %s has been archived, cannot check its result",
3003 91c622a8 Iustin Pop
                 jid, name)
3004 91c622a8 Iustin Pop
        success = False
3005 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3006 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3007 479636a3 Iustin Pop
        success = False
3008 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3009 479636a3 Iustin Pop
        ToStderr("Job %s for %s has failed: %s", jid, name, job_result)
3010 479636a3 Iustin Pop
3011 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3012 5299e61f Iustin Pop
3013 5299e61f Iustin Pop
    # sort based on the index, then drop it
3014 5299e61f Iustin Pop
    results.sort()
3015 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3016 5299e61f Iustin Pop
3017 479636a3 Iustin Pop
    return results
3018 479636a3 Iustin Pop
3019 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3020 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3021 479636a3 Iustin Pop

3022 479636a3 Iustin Pop
    @type wait: boolean
3023 479636a3 Iustin Pop
    @param wait: whether to wait or not
3024 479636a3 Iustin Pop

3025 479636a3 Iustin Pop
    """
3026 479636a3 Iustin Pop
    if wait:
3027 479636a3 Iustin Pop
      return self.GetResults()
3028 479636a3 Iustin Pop
    else:
3029 23b4b983 Iustin Pop
      if not self.jobs:
3030 23b4b983 Iustin Pop
        self.SubmitPending()
3031 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3032 23b4b983 Iustin Pop
        if status:
3033 23b4b983 Iustin Pop
          ToStdout("%s: %s", result, name)
3034 23b4b983 Iustin Pop
        else:
3035 23b4b983 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3036 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3037 acd19189 René Nussbaumer
3038 acd19189 René Nussbaumer
3039 acd19189 René Nussbaumer
def FormatParameterDict(buf, param_dict, actual, level=1):
3040 acd19189 René Nussbaumer
  """Formats a parameter dictionary.
3041 acd19189 René Nussbaumer

3042 acd19189 René Nussbaumer
  @type buf: L{StringIO}
3043 acd19189 René Nussbaumer
  @param buf: the buffer into which to write
3044 acd19189 René Nussbaumer
  @type param_dict: dict
3045 acd19189 René Nussbaumer
  @param param_dict: the own parameters
3046 acd19189 René Nussbaumer
  @type actual: dict
3047 acd19189 René Nussbaumer
  @param actual: the current parameter set (including defaults)
3048 acd19189 René Nussbaumer
  @param level: Level of indent
3049 acd19189 René Nussbaumer

3050 acd19189 René Nussbaumer
  """
3051 acd19189 René Nussbaumer
  indent = "  " * level
3052 acd19189 René Nussbaumer
  for key in sorted(actual):
3053 acd19189 René Nussbaumer
    val = param_dict.get(key, "default (%s)" % actual[key])
3054 acd19189 René Nussbaumer
    buf.write("%s- %s: %s\n" % (indent, key, val))
3055 25bd815c René Nussbaumer
3056 25bd815c René Nussbaumer
3057 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3058 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3059 25bd815c René Nussbaumer

3060 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3061 25bd815c René Nussbaumer
  on a given list of list_type.
3062 25bd815c René Nussbaumer

3063 25bd815c René Nussbaumer
  @type names: list
3064 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3065 25bd815c René Nussbaumer
      we ask for confirmation
3066 25bd815c René Nussbaumer
  @type list_type: str
3067 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3068 25bd815c René Nussbaumer
  @type text: str
3069 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3070 25bd815c René Nussbaumer
  @rtype: boolean
3071 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3072 25bd815c René Nussbaumer

3073 25bd815c René Nussbaumer
  """
3074 25bd815c René Nussbaumer
  count = len(names)
3075 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3076 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3077 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3078 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3079 25bd815c René Nussbaumer
3080 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3081 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3082 25bd815c René Nussbaumer
3083 25bd815c René Nussbaumer
  if count > 20:
3084 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3085 25bd815c René Nussbaumer
    question = msg
3086 25bd815c René Nussbaumer
  else:
3087 25bd815c René Nussbaumer
    question = msg + affected
3088 25bd815c René Nussbaumer
3089 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3090 25bd815c René Nussbaumer
  if choice == "v":
3091 25bd815c René Nussbaumer
    choices.pop(1)
3092 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3093 25bd815c René Nussbaumer
  return choice