Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 5f06ce5e

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

286 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
287 863d7f46 Michael Hanselmann

288 863d7f46 Michael Hanselmann
  """
289 b459a848 Andrea Spadaccini
  # pylint: disable=W0622
290 863d7f46 Michael Hanselmann
  def __init__(self, min=0, max=None, choices=None):
291 863d7f46 Michael Hanselmann
    _Argument.__init__(self, min=min, max=max)
292 863d7f46 Michael Hanselmann
    self.choices = choices
293 863d7f46 Michael Hanselmann
294 863d7f46 Michael Hanselmann
  def __repr__(self):
295 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s choices=%r>" %
296 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max, self.choices))
297 863d7f46 Michael Hanselmann
298 863d7f46 Michael Hanselmann
299 863d7f46 Michael Hanselmann
class ArgChoice(ArgSuggest):
300 863d7f46 Michael Hanselmann
  """Choice argument.
301 863d7f46 Michael Hanselmann

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

305 863d7f46 Michael Hanselmann
  """
306 863d7f46 Michael Hanselmann
307 863d7f46 Michael Hanselmann
308 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
309 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
310 863d7f46 Michael Hanselmann

311 863d7f46 Michael Hanselmann
  """
312 863d7f46 Michael Hanselmann
313 863d7f46 Michael Hanselmann
314 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
315 863d7f46 Michael Hanselmann
  """Instances argument.
316 863d7f46 Michael Hanselmann

317 863d7f46 Michael Hanselmann
  """
318 863d7f46 Michael Hanselmann
319 863d7f46 Michael Hanselmann
320 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
321 863d7f46 Michael Hanselmann
  """Node argument.
322 863d7f46 Michael Hanselmann

323 863d7f46 Michael Hanselmann
  """
324 863d7f46 Michael Hanselmann
325 667dbd6b Adeodato Simo
326 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
327 667dbd6b Adeodato Simo
  """Node group argument.
328 667dbd6b Adeodato Simo

329 667dbd6b Adeodato Simo
  """
330 667dbd6b Adeodato Simo
331 667dbd6b Adeodato Simo
332 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
333 863d7f46 Michael Hanselmann
  """Job ID argument.
334 863d7f46 Michael Hanselmann

335 863d7f46 Michael Hanselmann
  """
336 863d7f46 Michael Hanselmann
337 863d7f46 Michael Hanselmann
338 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
339 863d7f46 Michael Hanselmann
  """File path argument.
340 863d7f46 Michael Hanselmann

341 863d7f46 Michael Hanselmann
  """
342 863d7f46 Michael Hanselmann
343 863d7f46 Michael Hanselmann
344 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
345 863d7f46 Michael Hanselmann
  """Command argument.
346 863d7f46 Michael Hanselmann

347 863d7f46 Michael Hanselmann
  """
348 863d7f46 Michael Hanselmann
349 863d7f46 Michael Hanselmann
350 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
351 83ec7961 Michael Hanselmann
  """Host argument.
352 83ec7961 Michael Hanselmann

353 83ec7961 Michael Hanselmann
  """
354 83ec7961 Michael Hanselmann
355 83ec7961 Michael Hanselmann
356 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
357 f9faf9c3 René Nussbaumer
  """OS argument.
358 f9faf9c3 René Nussbaumer

359 f9faf9c3 René Nussbaumer
  """
360 f9faf9c3 René Nussbaumer
361 f9faf9c3 René Nussbaumer
362 4a265c08 Michael Hanselmann
ARGS_NONE = []
363 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
364 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
365 667dbd6b Adeodato Simo
ARGS_MANY_GROUPS = [ArgGroup()]
366 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
367 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
368 dadf6b7d Michael Hanselmann
# TODO
369 dadf6b7d Michael Hanselmann
ARGS_ONE_GROUP = [ArgGroup(min=1, max=1)]
370 f9faf9c3 René Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
371 4a265c08 Michael Hanselmann
372 4a265c08 Michael Hanselmann
373 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
374 846baef9 Iustin Pop
  """Extract the tag type object.
375 846baef9 Iustin Pop

376 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
377 846baef9 Iustin Pop

378 846baef9 Iustin Pop
  """
379 846baef9 Iustin Pop
  if not hasattr(opts, "tag_type"):
380 846baef9 Iustin Pop
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
381 846baef9 Iustin Pop
  kind = opts.tag_type
382 846baef9 Iustin Pop
  if kind == constants.TAG_CLUSTER:
383 846baef9 Iustin Pop
    retval = kind, kind
384 819cbfe5 Michael Hanselmann
  elif kind in (constants.TAG_NODEGROUP,
385 819cbfe5 Michael Hanselmann
                constants.TAG_NODE,
386 819cbfe5 Michael Hanselmann
                constants.TAG_INSTANCE):
387 846baef9 Iustin Pop
    if not args:
388 0c434948 Iustin Pop
      raise errors.OpPrereqError("no arguments passed to the command")
389 846baef9 Iustin Pop
    name = args.pop(0)
390 846baef9 Iustin Pop
    retval = kind, name
391 846baef9 Iustin Pop
  else:
392 846baef9 Iustin Pop
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
393 846baef9 Iustin Pop
  return retval
394 846baef9 Iustin Pop
395 846baef9 Iustin Pop
396 810c50b7 Iustin Pop
def _ExtendTags(opts, args):
397 810c50b7 Iustin Pop
  """Extend the args if a source file has been given.
398 810c50b7 Iustin Pop

399 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
400 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
401 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
402 810c50b7 Iustin Pop

403 810c50b7 Iustin Pop
  """
404 810c50b7 Iustin Pop
  fname = opts.tags_source
405 810c50b7 Iustin Pop
  if fname is None:
406 810c50b7 Iustin Pop
    return
407 810c50b7 Iustin Pop
  if fname == "-":
408 810c50b7 Iustin Pop
    new_fh = sys.stdin
409 810c50b7 Iustin Pop
  else:
410 810c50b7 Iustin Pop
    new_fh = open(fname, "r")
411 810c50b7 Iustin Pop
  new_data = []
412 810c50b7 Iustin Pop
  try:
413 810c50b7 Iustin Pop
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
414 810c50b7 Iustin Pop
    # because of python bug 1633941
415 810c50b7 Iustin Pop
    while True:
416 810c50b7 Iustin Pop
      line = new_fh.readline()
417 810c50b7 Iustin Pop
      if not line:
418 810c50b7 Iustin Pop
        break
419 810c50b7 Iustin Pop
      new_data.append(line.strip())
420 810c50b7 Iustin Pop
  finally:
421 810c50b7 Iustin Pop
    new_fh.close()
422 810c50b7 Iustin Pop
  args.extend(new_data)
423 810c50b7 Iustin Pop
424 810c50b7 Iustin Pop
425 846baef9 Iustin Pop
def ListTags(opts, args):
426 846baef9 Iustin Pop
  """List the tags on a given object.
427 846baef9 Iustin Pop

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

433 846baef9 Iustin Pop
  """
434 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
435 7699c3af Iustin Pop
  cl = GetClient()
436 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
437 846baef9 Iustin Pop
  result = list(result)
438 846baef9 Iustin Pop
  result.sort()
439 846baef9 Iustin Pop
  for tag in result:
440 03298ebe Michael Hanselmann
    ToStdout(tag)
441 846baef9 Iustin Pop
442 846baef9 Iustin Pop
443 846baef9 Iustin Pop
def AddTags(opts, args):
444 846baef9 Iustin Pop
  """Add tags on a given object.
445 846baef9 Iustin Pop

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

451 846baef9 Iustin Pop
  """
452 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
453 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
454 846baef9 Iustin Pop
  if not args:
455 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be added")
456 d1602edc Iustin Pop
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
457 af1a81d1 Michael Hanselmann
  SubmitOpCode(op, opts=opts)
458 846baef9 Iustin Pop
459 846baef9 Iustin Pop
460 846baef9 Iustin Pop
def RemoveTags(opts, args):
461 846baef9 Iustin Pop
  """Remove tags from a given object.
462 846baef9 Iustin Pop

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

468 846baef9 Iustin Pop
  """
469 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
470 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
471 846baef9 Iustin Pop
  if not args:
472 846baef9 Iustin Pop
    raise errors.OpPrereqError("No tags to be removed")
473 3f0ab95f Iustin Pop
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
474 af1a81d1 Michael Hanselmann
  SubmitOpCode(op, opts=opts)
475 846baef9 Iustin Pop
476 a8083063 Iustin Pop
477 b459a848 Andrea Spadaccini
def check_unit(option, opt, value): # pylint: disable=W0613
478 65fe4693 Iustin Pop
  """OptParsers custom converter for units.
479 65fe4693 Iustin Pop

480 65fe4693 Iustin Pop
  """
481 a8083063 Iustin Pop
  try:
482 a8083063 Iustin Pop
    return utils.ParseUnit(value)
483 a8083063 Iustin Pop
  except errors.UnitParseError, err:
484 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
485 a8083063 Iustin Pop
486 a8083063 Iustin Pop
487 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
488 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
489 a8469393 Iustin Pop

490 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
491 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
492 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
493 a8469393 Iustin Pop
  have value=True.
494 a8469393 Iustin Pop

495 a8469393 Iustin Pop
  @type opt: string
496 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
497 a8469393 Iustin Pop
      data, used in building error messages
498 a8469393 Iustin Pop
  @type data: string
499 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
500 a8469393 Iustin Pop
  @rtype: dict
501 a8469393 Iustin Pop
  @return: {key=val, key=val}
502 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
503 a8469393 Iustin Pop

504 a8469393 Iustin Pop
  """
505 a8469393 Iustin Pop
  kv_dict = {}
506 4f31882e Guido Trotter
  if data:
507 1b3a7656 Iustin Pop
    for elem in utils.UnescapeAndSplit(data, sep=","):
508 4f31882e Guido Trotter
      if "=" in elem:
509 4f31882e Guido Trotter
        key, val = elem.split("=", 1)
510 a8469393 Iustin Pop
      else:
511 4f31882e Guido Trotter
        if elem.startswith(NO_PREFIX):
512 4f31882e Guido Trotter
          key, val = elem[len(NO_PREFIX):], False
513 4f31882e Guido Trotter
        elif elem.startswith(UN_PREFIX):
514 4f31882e Guido Trotter
          key, val = elem[len(UN_PREFIX):], None
515 4f31882e Guido Trotter
        else:
516 4f31882e Guido Trotter
          key, val = elem, True
517 4f31882e Guido Trotter
      if key in kv_dict:
518 4f31882e Guido Trotter
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
519 4f31882e Guido Trotter
                                    (key, opt))
520 4f31882e Guido Trotter
      kv_dict[key] = val
521 a8469393 Iustin Pop
  return kv_dict
522 a8469393 Iustin Pop
523 a8469393 Iustin Pop
524 b459a848 Andrea Spadaccini
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
525 552c8dff Michael Hanselmann
  """Custom parser for ident:key=val,key=val options.
526 552c8dff Michael Hanselmann

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

530 a8469393 Iustin Pop
  """
531 a8469393 Iustin Pop
  if ":" not in value:
532 d0c8c01d Iustin Pop
    ident, rest = value, ""
533 a8469393 Iustin Pop
  else:
534 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
535 8b46606c Guido Trotter
536 8b46606c Guido Trotter
  if ident.startswith(NO_PREFIX):
537 8b46606c Guido Trotter
    if rest:
538 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
539 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
540 8b46606c Guido Trotter
    retval = (ident[len(NO_PREFIX):], False)
541 8b46606c Guido Trotter
  elif ident.startswith(UN_PREFIX):
542 8b46606c Guido Trotter
    if rest:
543 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
544 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
545 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
546 8b46606c Guido Trotter
  else:
547 a8469393 Iustin Pop
    kv_dict = _SplitKeyVal(opt, rest)
548 a8469393 Iustin Pop
    retval = (ident, kv_dict)
549 a8469393 Iustin Pop
  return retval
550 a8469393 Iustin Pop
551 a8469393 Iustin Pop
552 b459a848 Andrea Spadaccini
def check_key_val(option, opt, value):  # pylint: disable=W0613
553 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
554 552c8dff Michael Hanselmann

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

557 a8469393 Iustin Pop
  """
558 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
559 a8469393 Iustin Pop
560 a8469393 Iustin Pop
561 b459a848 Andrea Spadaccini
def check_bool(option, opt, value): # pylint: disable=W0613
562 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
563 e7b61bb0 Iustin Pop

564 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
565 e7b61bb0 Iustin Pop

566 e7b61bb0 Iustin Pop
  """
567 e7b61bb0 Iustin Pop
  value = value.lower()
568 e7b61bb0 Iustin Pop
  if value == constants.VALUE_FALSE or value == "no":
569 e7b61bb0 Iustin Pop
    return False
570 e7b61bb0 Iustin Pop
  elif value == constants.VALUE_TRUE or value == "yes":
571 e7b61bb0 Iustin Pop
    return True
572 e7b61bb0 Iustin Pop
  else:
573 e7b61bb0 Iustin Pop
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
574 e7b61bb0 Iustin Pop
575 e7b61bb0 Iustin Pop
576 63d44c55 Michael Hanselmann
# completion_suggestion is normally a list. Using numeric values not evaluating
577 63d44c55 Michael Hanselmann
# to False for dynamic completion.
578 63d44c55 Michael Hanselmann
(OPT_COMPL_MANY_NODES,
579 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_NODE,
580 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_INSTANCE,
581 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_OS,
582 2d3ed64b Michael Hanselmann
 OPT_COMPL_ONE_IALLOCATOR,
583 36e247e1 Guido Trotter
 OPT_COMPL_INST_ADD_NODES,
584 36e247e1 Guido Trotter
 OPT_COMPL_ONE_NODEGROUP) = range(100, 107)
585 63d44c55 Michael Hanselmann
586 63d44c55 Michael Hanselmann
OPT_COMPL_ALL = frozenset([
587 63d44c55 Michael Hanselmann
  OPT_COMPL_MANY_NODES,
588 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_NODE,
589 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_INSTANCE,
590 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_OS,
591 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_IALLOCATOR,
592 2d3ed64b Michael Hanselmann
  OPT_COMPL_INST_ADD_NODES,
593 36e247e1 Guido Trotter
  OPT_COMPL_ONE_NODEGROUP,
594 63d44c55 Michael Hanselmann
  ])
595 63d44c55 Michael Hanselmann
596 63d44c55 Michael Hanselmann
597 552c8dff Michael Hanselmann
class CliOption(Option):
598 552c8dff Michael Hanselmann
  """Custom option class for optparse.
599 a8469393 Iustin Pop

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

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

1325 c41eea6e Iustin Pop
  @param argv: the command line
1326 c41eea6e Iustin Pop
  @param commands: dictionary with special contents, see the design
1327 c41eea6e Iustin Pop
      doc for cmdline handling
1328 c41eea6e Iustin Pop
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
1329 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1330 098c0958 Michael Hanselmann

1331 a8083063 Iustin Pop
  """
1332 ef9fa5b9 René Nussbaumer
  assert not (env_override - set(commands))
1333 ef9fa5b9 René Nussbaumer
1334 a8083063 Iustin Pop
  if len(argv) == 0:
1335 a8083063 Iustin Pop
    binary = "<command>"
1336 a8083063 Iustin Pop
  else:
1337 a8083063 Iustin Pop
    binary = argv[0].split("/")[-1]
1338 a8083063 Iustin Pop
1339 a8083063 Iustin Pop
  if len(argv) > 1 and argv[1] == "--version":
1340 84a12e40 Iustin Pop
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
1341 84a12e40 Iustin Pop
             constants.RELEASE_VERSION)
1342 a8083063 Iustin Pop
    # Quit right away. That way we don't have to care about this special
1343 a8083063 Iustin Pop
    # argument. optparse.py does it the same.
1344 a8083063 Iustin Pop
    sys.exit(0)
1345 a8083063 Iustin Pop
1346 de47cf8f Guido Trotter
  if len(argv) < 2 or not (argv[1] in commands or
1347 70a35b6f Guido Trotter
                           argv[1] in aliases):
1348 a8083063 Iustin Pop
    # let's do a nice thing
1349 a8083063 Iustin Pop
    sortedcmds = commands.keys()
1350 a8083063 Iustin Pop
    sortedcmds.sort()
1351 03298ebe Michael Hanselmann
1352 03298ebe Michael Hanselmann
    ToStdout("Usage: %s {command} [options...] [argument...]", binary)
1353 03298ebe Michael Hanselmann
    ToStdout("%s <command> --help to see details, or man %s", binary, binary)
1354 03298ebe Michael Hanselmann
    ToStdout("")
1355 03298ebe Michael Hanselmann
1356 a8083063 Iustin Pop
    # compute the max line length for cmd + usage
1357 4e713df6 Iustin Pop
    mlen = max([len(" %s" % cmd) for cmd in commands])
1358 a8083063 Iustin Pop
    mlen = min(60, mlen) # should not get here...
1359 03298ebe Michael Hanselmann
1360 a8083063 Iustin Pop
    # and format a nice command list
1361 03298ebe Michael Hanselmann
    ToStdout("Commands:")
1362 a8083063 Iustin Pop
    for cmd in sortedcmds:
1363 4e713df6 Iustin Pop
      cmdstr = " %s" % (cmd,)
1364 9a033156 Iustin Pop
      help_text = commands[cmd][4]
1365 03298ebe Michael Hanselmann
      help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1366 03298ebe Michael Hanselmann
      ToStdout("%-*s - %s", mlen, cmdstr, help_lines.pop(0))
1367 a8083063 Iustin Pop
      for line in help_lines:
1368 03298ebe Michael Hanselmann
        ToStdout("%-*s   %s", mlen, "", line)
1369 03298ebe Michael Hanselmann
1370 03298ebe Michael Hanselmann
    ToStdout("")
1371 03298ebe Michael Hanselmann
1372 a8083063 Iustin Pop
    return None, None, None
1373 de47cf8f Guido Trotter
1374 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1375 a8083063 Iustin Pop
  cmd = argv.pop(1)
1376 de47cf8f Guido Trotter
  if cmd in aliases:
1377 de47cf8f Guido Trotter
    if cmd in commands:
1378 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' overrides an existing"
1379 de47cf8f Guido Trotter
                                   " command" % cmd)
1380 de47cf8f Guido Trotter
1381 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1382 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1383 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1384 de47cf8f Guido Trotter
1385 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1386 de47cf8f Guido Trotter
1387 ef9fa5b9 René Nussbaumer
  if cmd in env_override:
1388 ef9fa5b9 René Nussbaumer
    args_env_name = ("%s_%s" % (binary.replace("-", "_"), cmd)).upper()
1389 ef9fa5b9 René Nussbaumer
    env_args = os.environ.get(args_env_name)
1390 ef9fa5b9 René Nussbaumer
    if env_args:
1391 ef9fa5b9 René Nussbaumer
      argv = utils.InsertAtPos(argv, 1, shlex.split(env_args))
1392 ef9fa5b9 René Nussbaumer
1393 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1394 5786c087 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1395 a8083063 Iustin Pop
                        description=description,
1396 a8083063 Iustin Pop
                        formatter=TitledHelpFormatter(),
1397 a8083063 Iustin Pop
                        usage="%%prog %s %s" % (cmd, usage))
1398 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1399 ef9fa5b9 René Nussbaumer
  options, args = parser.parse_args(args=argv[1:])
1400 a8005e17 Michael Hanselmann
1401 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1402 a8083063 Iustin Pop
    return None, None, None
1403 a8083063 Iustin Pop
1404 a8083063 Iustin Pop
  return func, options, args
1405 a8083063 Iustin Pop
1406 a8083063 Iustin Pop
1407 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1408 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1409 a8005e17 Michael Hanselmann

1410 a8005e17 Michael Hanselmann
  Algorithm:
1411 a8005e17 Michael Hanselmann

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

1414 a8005e17 Michael Hanselmann
    1. For each argument in definition
1415 a8005e17 Michael Hanselmann

1416 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1417 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1418 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1419 a8005e17 Michael Hanselmann

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

1422 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1423 a8005e17 Michael Hanselmann

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

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

1428 a8005e17 Michael Hanselmann
  """
1429 a8005e17 Michael Hanselmann
  if args and not args_def:
1430 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1431 a8005e17 Michael Hanselmann
    return False
1432 a8005e17 Michael Hanselmann
1433 a8005e17 Michael Hanselmann
  min_count = None
1434 a8005e17 Michael Hanselmann
  max_count = None
1435 a8005e17 Michael Hanselmann
  check_max = None
1436 a8005e17 Michael Hanselmann
1437 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1438 a8005e17 Michael Hanselmann
1439 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1440 a8005e17 Michael Hanselmann
    if min_count is None:
1441 a8005e17 Michael Hanselmann
      min_count = arg.min
1442 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1443 a8005e17 Michael Hanselmann
      min_count += arg.min
1444 a8005e17 Michael Hanselmann
1445 a8005e17 Michael Hanselmann
    if max_count is None:
1446 a8005e17 Michael Hanselmann
      max_count = arg.max
1447 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1448 a8005e17 Michael Hanselmann
      max_count += arg.max
1449 a8005e17 Michael Hanselmann
1450 a8005e17 Michael Hanselmann
    if idx == last_idx:
1451 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1452 a8005e17 Michael Hanselmann
1453 a8005e17 Michael Hanselmann
    elif arg.max is None:
1454 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1455 a8005e17 Michael Hanselmann
1456 a8005e17 Michael Hanselmann
  if check_max:
1457 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1458 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1459 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1460 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1461 a8005e17 Michael Hanselmann
      return False
1462 a8005e17 Michael Hanselmann
1463 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1464 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1465 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1466 a8005e17 Michael Hanselmann
               cmd, max_count)
1467 a8005e17 Michael Hanselmann
      return False
1468 a8005e17 Michael Hanselmann
1469 a8005e17 Michael Hanselmann
  # Command with some required arguments
1470 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1471 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1472 a8005e17 Michael Hanselmann
             cmd, min_count)
1473 a8005e17 Michael Hanselmann
    return False
1474 a8005e17 Michael Hanselmann
1475 a8005e17 Michael Hanselmann
  return True
1476 a8005e17 Michael Hanselmann
1477 a8005e17 Michael Hanselmann
1478 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1479 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1480 60d49723 Michael Hanselmann

1481 60d49723 Michael Hanselmann
  """
1482 d0c8c01d Iustin Pop
  if value and ":" in value:
1483 d0c8c01d Iustin Pop
    return value.split(":", 1)
1484 60d49723 Michael Hanselmann
  else:
1485 60d49723 Michael Hanselmann
    return (value, None)
1486 60d49723 Michael Hanselmann
1487 60d49723 Michael Hanselmann
1488 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1489 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1490 07150497 Guido Trotter

1491 07150497 Guido Trotter
  @type os_name: string
1492 07150497 Guido Trotter
  @param os_name: base name of the os
1493 07150497 Guido Trotter
  @type os_variants: list or None
1494 07150497 Guido Trotter
  @param os_variants: list of supported variants
1495 07150497 Guido Trotter
  @rtype: list
1496 07150497 Guido Trotter
  @return: list of valid names
1497 07150497 Guido Trotter

1498 07150497 Guido Trotter
  """
1499 07150497 Guido Trotter
  if os_variants:
1500 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1501 07150497 Guido Trotter
  else:
1502 07150497 Guido Trotter
    return [os_name]
1503 07150497 Guido Trotter
1504 07150497 Guido Trotter
1505 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1506 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1507 a4ebd726 Michael Hanselmann

1508 a4ebd726 Michael Hanselmann
  @type selected: string or None
1509 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1510 a4ebd726 Michael Hanselmann
  @type default: list
1511 a4ebd726 Michael Hanselmann
  @param default: Default fields
1512 a4ebd726 Michael Hanselmann

1513 a4ebd726 Michael Hanselmann
  """
1514 a4ebd726 Michael Hanselmann
  if selected is None:
1515 a4ebd726 Michael Hanselmann
    return default
1516 a4ebd726 Michael Hanselmann
1517 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1518 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1519 a4ebd726 Michael Hanselmann
1520 a4ebd726 Michael Hanselmann
  return selected.split(",")
1521 a4ebd726 Michael Hanselmann
1522 a4ebd726 Michael Hanselmann
1523 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1524 4331f6cd Michael Hanselmann
1525 4331f6cd Michael Hanselmann
1526 47988778 Iustin Pop
def AskUser(text, choices=None):
1527 47988778 Iustin Pop
  """Ask the user a question.
1528 a8083063 Iustin Pop

1529 c41eea6e Iustin Pop
  @param text: the question to ask
1530 a8083063 Iustin Pop

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

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

1540 a8083063 Iustin Pop
  """
1541 47988778 Iustin Pop
  if choices is None:
1542 d0c8c01d Iustin Pop
    choices = [("y", True, "Perform the operation"),
1543 d0c8c01d Iustin Pop
               ("n", False, "Do not perform the operation")]
1544 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1545 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1546 47988778 Iustin Pop
  for entry in choices:
1547 d0c8c01d Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1548 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1549 47988778 Iustin Pop
1550 47988778 Iustin Pop
  answer = choices[-1][1]
1551 47988778 Iustin Pop
  new_text = []
1552 47988778 Iustin Pop
  for line in text.splitlines():
1553 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1554 47988778 Iustin Pop
  text = "\n".join(new_text)
1555 a8083063 Iustin Pop
  try:
1556 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1557 a8083063 Iustin Pop
  except IOError:
1558 47988778 Iustin Pop
    return answer
1559 a8083063 Iustin Pop
  try:
1560 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1561 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1562 d0c8c01d Iustin Pop
    chars.append("?")
1563 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1564 47988778 Iustin Pop
    while True:
1565 47988778 Iustin Pop
      f.write(text)
1566 d0c8c01d Iustin Pop
      f.write("\n")
1567 47988778 Iustin Pop
      f.write("/".join(chars))
1568 47988778 Iustin Pop
      f.write(": ")
1569 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1570 47988778 Iustin Pop
      if line in maps:
1571 47988778 Iustin Pop
        answer = maps[line]
1572 47988778 Iustin Pop
        break
1573 d0c8c01d Iustin Pop
      elif line == "?":
1574 47988778 Iustin Pop
        for entry in choices:
1575 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1576 47988778 Iustin Pop
        f.write("\n")
1577 47988778 Iustin Pop
        continue
1578 a8083063 Iustin Pop
  finally:
1579 a8083063 Iustin Pop
    f.close()
1580 a8083063 Iustin Pop
  return answer
1581 a8083063 Iustin Pop
1582 a8083063 Iustin Pop
1583 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1584 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1585 e9d741b6 Iustin Pop

1586 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1587 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1588 e9d741b6 Iustin Pop

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

1591 e9d741b6 Iustin Pop
  """
1592 e9d741b6 Iustin Pop
1593 e9d741b6 Iustin Pop
1594 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1595 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1596 a8083063 Iustin Pop

1597 0a1e74d9 Iustin Pop
  @type ops: list
1598 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1599 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1600 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1601 0a1e74d9 Iustin Pop
             if None, a new client will be created
1602 a8083063 Iustin Pop

1603 a8083063 Iustin Pop
  """
1604 e2212007 Iustin Pop
  if cl is None:
1605 b33e986b Iustin Pop
    cl = GetClient()
1606 685ee993 Iustin Pop
1607 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1608 0a1e74d9 Iustin Pop
1609 0a1e74d9 Iustin Pop
  return job_id
1610 0a1e74d9 Iustin Pop
1611 0a1e74d9 Iustin Pop
1612 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1613 4e338533 Michael Hanselmann
  """Generic job-polling function.
1614 0a1e74d9 Iustin Pop

1615 4e338533 Michael Hanselmann
  @type job_id: number
1616 4e338533 Michael Hanselmann
  @param job_id: Job ID
1617 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1618 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1619 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1620 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1621 0a1e74d9 Iustin Pop

1622 0a1e74d9 Iustin Pop
  """
1623 6c5a7090 Michael Hanselmann
  prev_job_info = None
1624 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1625 6c5a7090 Michael Hanselmann
1626 f4484122 Michael Hanselmann
  status = None
1627 f4484122 Michael Hanselmann
1628 685ee993 Iustin Pop
  while True:
1629 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1630 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
1631 6c5a7090 Michael Hanselmann
    if not result:
1632 685ee993 Iustin Pop
      # job not found, go away!
1633 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1634 4e338533 Michael Hanselmann
1635 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
1636 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
1637 f4484122 Michael Hanselmann
1638 f4484122 Michael Hanselmann
      # Wait again
1639 f4484122 Michael Hanselmann
      continue
1640 685ee993 Iustin Pop
1641 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1642 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1643 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1644 6c5a7090 Michael Hanselmann
1645 6c5a7090 Michael Hanselmann
    if log_entries:
1646 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1647 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
1648 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
1649 4e338533 Michael Hanselmann
                                    log_type, message)
1650 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1651 6c5a7090 Michael Hanselmann
1652 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1653 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1654 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1655 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1656 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1657 685ee993 Iustin Pop
      break
1658 6c5a7090 Michael Hanselmann
1659 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1660 685ee993 Iustin Pop
1661 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1662 0bbe448c Michael Hanselmann
  if not jobs:
1663 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1664 685ee993 Iustin Pop
1665 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1666 4e338533 Michael Hanselmann
1667 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1668 53c04d04 Iustin Pop
    return result
1669 4e338533 Michael Hanselmann
1670 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
1671 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1672 4e338533 Michael Hanselmann
1673 4e338533 Michael Hanselmann
  has_ok = False
1674 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
1675 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
1676 4e338533 Michael Hanselmann
      has_ok = True
1677 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
1678 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
1679 4e338533 Michael Hanselmann
1680 4e338533 Michael Hanselmann
      if has_ok:
1681 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
1682 4e338533 Michael Hanselmann
                                 (idx, msg))
1683 4e338533 Michael Hanselmann
1684 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
1685 4e338533 Michael Hanselmann
1686 4e338533 Michael Hanselmann
  # default failure mode
1687 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
1688 4e338533 Michael Hanselmann
1689 4e338533 Michael Hanselmann
1690 4e338533 Michael Hanselmann
class JobPollCbBase:
1691 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
1692 4e338533 Michael Hanselmann

1693 4e338533 Michael Hanselmann
  """
1694 4e338533 Michael Hanselmann
  def __init__(self):
1695 4e338533 Michael Hanselmann
    """Initializes this class.
1696 4e338533 Michael Hanselmann

1697 4e338533 Michael Hanselmann
    """
1698 4e338533 Michael Hanselmann
1699 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1700 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1701 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1702 4e338533 Michael Hanselmann

1703 4e338533 Michael Hanselmann
    """
1704 4e338533 Michael Hanselmann
    raise NotImplementedError()
1705 4e338533 Michael Hanselmann
1706 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1707 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1708 4e338533 Michael Hanselmann

1709 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
1710 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
1711 4e338533 Michael Hanselmann
    @type fields: list of strings
1712 4e338533 Michael Hanselmann
    @param fields: Fields
1713 4e338533 Michael Hanselmann

1714 4e338533 Michael Hanselmann
    """
1715 4e338533 Michael Hanselmann
    raise NotImplementedError()
1716 4e338533 Michael Hanselmann
1717 4e338533 Michael Hanselmann
1718 4e338533 Michael Hanselmann
class JobPollReportCbBase:
1719 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
1720 4e338533 Michael Hanselmann

1721 4e338533 Michael Hanselmann
  """
1722 4e338533 Michael Hanselmann
  def __init__(self):
1723 4e338533 Michael Hanselmann
    """Initializes this class.
1724 4e338533 Michael Hanselmann

1725 4e338533 Michael Hanselmann
    """
1726 4e338533 Michael Hanselmann
1727 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1728 4e338533 Michael Hanselmann
    """Handles a log message.
1729 4e338533 Michael Hanselmann

1730 4e338533 Michael Hanselmann
    """
1731 4e338533 Michael Hanselmann
    raise NotImplementedError()
1732 4e338533 Michael Hanselmann
1733 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1734 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
1735 4e338533 Michael Hanselmann

1736 4e338533 Michael Hanselmann
    @type job_id: number
1737 4e338533 Michael Hanselmann
    @param job_id: Job ID
1738 4e338533 Michael Hanselmann
    @type status: string or None
1739 4e338533 Michael Hanselmann
    @param status: Job status if available
1740 4e338533 Michael Hanselmann

1741 4e338533 Michael Hanselmann
    """
1742 4e338533 Michael Hanselmann
    raise NotImplementedError()
1743 4e338533 Michael Hanselmann
1744 4e338533 Michael Hanselmann
1745 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
1746 4e338533 Michael Hanselmann
  def __init__(self, cl):
1747 4e338533 Michael Hanselmann
    """Initializes this class.
1748 4e338533 Michael Hanselmann

1749 4e338533 Michael Hanselmann
    """
1750 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
1751 4e338533 Michael Hanselmann
    self.cl = cl
1752 4e338533 Michael Hanselmann
1753 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1754 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1755 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1756 4e338533 Michael Hanselmann

1757 4e338533 Michael Hanselmann
    """
1758 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
1759 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
1760 4e338533 Michael Hanselmann
1761 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1762 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1763 4e338533 Michael Hanselmann

1764 4e338533 Michael Hanselmann
    """
1765 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
1766 4e338533 Michael Hanselmann
1767 4e338533 Michael Hanselmann
1768 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
1769 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
1770 4e338533 Michael Hanselmann
    """Initializes this class.
1771 4e338533 Michael Hanselmann

1772 4e338533 Michael Hanselmann
    """
1773 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1774 4e338533 Michael Hanselmann
1775 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
1776 4e338533 Michael Hanselmann
1777 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
1778 4e338533 Michael Hanselmann
1779 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1780 4e338533 Michael Hanselmann
    """Handles a log message.
1781 4e338533 Michael Hanselmann

1782 4e338533 Michael Hanselmann
    """
1783 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
1784 4e338533 Michael Hanselmann
1785 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1786 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1787 4e338533 Michael Hanselmann

1788 4e338533 Michael Hanselmann
    """
1789 4e338533 Michael Hanselmann
    # Ignore
1790 4e338533 Michael Hanselmann
1791 4e338533 Michael Hanselmann
1792 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
1793 4e338533 Michael Hanselmann
  def __init__(self):
1794 4e338533 Michael Hanselmann
    """Initializes this class.
1795 4e338533 Michael Hanselmann

1796 4e338533 Michael Hanselmann
    """
1797 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
1798 4e338533 Michael Hanselmann
1799 4e338533 Michael Hanselmann
    self.notified_queued = False
1800 4e338533 Michael Hanselmann
    self.notified_waitlock = False
1801 4e338533 Michael Hanselmann
1802 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1803 4e338533 Michael Hanselmann
    """Handles a log message.
1804 4e338533 Michael Hanselmann

1805 4e338533 Michael Hanselmann
    """
1806 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
1807 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
1808 4e338533 Michael Hanselmann
1809 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
1810 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
1811 4e338533 Michael Hanselmann

1812 4e338533 Michael Hanselmann
    """
1813 4e338533 Michael Hanselmann
    if status is None:
1814 4e338533 Michael Hanselmann
      return
1815 4e338533 Michael Hanselmann
1816 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
1817 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
1818 4e338533 Michael Hanselmann
      self.notified_queued = True
1819 4e338533 Michael Hanselmann
1820 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
1821 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
1822 4e338533 Michael Hanselmann
      self.notified_waitlock = True
1823 4e338533 Michael Hanselmann
1824 4e338533 Michael Hanselmann
1825 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
1826 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
1827 8a7f1c61 Michael Hanselmann

1828 8a7f1c61 Michael Hanselmann
  """
1829 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
1830 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
1831 8a7f1c61 Michael Hanselmann
1832 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
1833 8a7f1c61 Michael Hanselmann
1834 8a7f1c61 Michael Hanselmann
1835 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
1836 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
1837 4e338533 Michael Hanselmann

1838 4e338533 Michael Hanselmann
  @type job_id: job identified
1839 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
1840 4e338533 Michael Hanselmann
  @type cl: luxi.Client
1841 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
1842 4e338533 Michael Hanselmann
             if None, a new client will be created
1843 4e338533 Michael Hanselmann

1844 4e338533 Michael Hanselmann
  """
1845 4e338533 Michael Hanselmann
  if cl is None:
1846 4e338533 Michael Hanselmann
    cl = GetClient()
1847 4e338533 Michael Hanselmann
1848 583163a6 Michael Hanselmann
  if reporter is None:
1849 583163a6 Michael Hanselmann
    if feedback_fn:
1850 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
1851 583163a6 Michael Hanselmann
    else:
1852 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
1853 583163a6 Michael Hanselmann
  elif feedback_fn:
1854 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
1855 4e338533 Michael Hanselmann
1856 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
1857 ceab32dd Iustin Pop
1858 ceab32dd Iustin Pop
1859 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
1860 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
1861 0a1e74d9 Iustin Pop

1862 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
1863 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
1864 0a1e74d9 Iustin Pop
  interaction functions.
1865 0a1e74d9 Iustin Pop

1866 0a1e74d9 Iustin Pop
  """
1867 0a1e74d9 Iustin Pop
  if cl is None:
1868 0a1e74d9 Iustin Pop
    cl = GetClient()
1869 0a1e74d9 Iustin Pop
1870 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
1871 293ba2d8 Iustin Pop
1872 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
1873 0a1e74d9 Iustin Pop
1874 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
1875 583163a6 Michael Hanselmann
                       reporter=reporter)
1876 53c04d04 Iustin Pop
1877 53c04d04 Iustin Pop
  return op_results[0]
1878 0a1e74d9 Iustin Pop
1879 0a1e74d9 Iustin Pop
1880 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
1881 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
1882 94428652 Iustin Pop

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

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

1891 94428652 Iustin Pop
  """
1892 94428652 Iustin Pop
  if opts and opts.submit_only:
1893 293ba2d8 Iustin Pop
    job = [op]
1894 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
1895 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
1896 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
1897 94428652 Iustin Pop
  else:
1898 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
1899 293ba2d8 Iustin Pop
1900 293ba2d8 Iustin Pop
1901 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
1902 293ba2d8 Iustin Pop
  """Processor for generic options.
1903 293ba2d8 Iustin Pop

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

1907 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
1908 293ba2d8 Iustin Pop
  @param options: command line options or None
1909 293ba2d8 Iustin Pop
  @return: None (in-place modification)
1910 293ba2d8 Iustin Pop

1911 293ba2d8 Iustin Pop
  """
1912 293ba2d8 Iustin Pop
  if not options:
1913 293ba2d8 Iustin Pop
    return
1914 293ba2d8 Iustin Pop
  for op in opcode_list:
1915 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
1916 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
1917 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
1918 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
1919 aa06f8c6 Michael Hanselmann
      op.priority = _PRIONAME_TO_VALUE[options.priority]
1920 94428652 Iustin Pop
1921 94428652 Iustin Pop
1922 af30b2fd Michael Hanselmann
def GetClient():
1923 af30b2fd Michael Hanselmann
  # TODO: Cache object?
1924 b33e986b Iustin Pop
  try:
1925 b33e986b Iustin Pop
    client = luxi.Client()
1926 b33e986b Iustin Pop
  except luxi.NoMasterError:
1927 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
1928 d9a51679 Michael Hanselmann
1929 d9a51679 Michael Hanselmann
    # Try to read ssconf file
1930 d9a51679 Michael Hanselmann
    try:
1931 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
1932 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
1933 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
1934 d9a51679 Michael Hanselmann
                                 " not part of a cluster")
1935 d9a51679 Michael Hanselmann
1936 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
1937 b33e986b Iustin Pop
    if master != myself:
1938 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
1939 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
1940 b33e986b Iustin Pop
                                 master)
1941 d9a51679 Michael Hanselmann
    raise
1942 b33e986b Iustin Pop
  return client
1943 af30b2fd Michael Hanselmann
1944 af30b2fd Michael Hanselmann
1945 73702ee7 Iustin Pop
def FormatError(err):
1946 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
1947 73702ee7 Iustin Pop

1948 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
1949 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
1950 73702ee7 Iustin Pop
  second, a string describing the error message (not
1951 73702ee7 Iustin Pop
  newline-terminated).
1952 73702ee7 Iustin Pop

1953 73702ee7 Iustin Pop
  """
1954 73702ee7 Iustin Pop
  retcode = 1
1955 73702ee7 Iustin Pop
  obuf = StringIO()
1956 e2e521d0 Iustin Pop
  msg = str(err)
1957 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
1958 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
1959 46fbdd04 Iustin Pop
    logging.error(txt)
1960 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
1961 73702ee7 Iustin Pop
    obuf.write("Aborting.")
1962 73702ee7 Iustin Pop
    retcode = 2
1963 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
1964 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
1965 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
1966 73702ee7 Iustin Pop
      if out:
1967 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
1968 73702ee7 Iustin Pop
                   (node, script, out))
1969 73702ee7 Iustin Pop
      else:
1970 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
1971 73702ee7 Iustin Pop
                   (node, script))
1972 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
1973 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
1974 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
1975 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
1976 73702ee7 Iustin Pop
    if err.args[0] == this_host:
1977 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
1978 73702ee7 Iustin Pop
    else:
1979 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
1980 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
1981 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
1982 5c983ee5 Iustin Pop
    if len(err.args) == 2:
1983 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1984 5c983ee5 Iustin Pop
               " operation:\nerror type: %s, error details:\n%s" %
1985 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
1986 5c983ee5 Iustin Pop
    else:
1987 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
1988 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
1989 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
1990 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
1991 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
1992 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
1993 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
1994 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
1995 686d7433 Iustin Pop
               " accept new requests\n")
1996 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
1997 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
1998 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
1999 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
2000 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
2001 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
2002 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
2003 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
2004 03a8dbdc Iustin Pop
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
2005 082c5adb Michael Hanselmann
               " and listening for connections?")
2006 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
2007 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
2008 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
2009 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
2010 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
2011 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
2012 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
2013 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
2014 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
2015 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
2016 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
2017 03a8dbdc Iustin Pop
               "%s" % msg)
2018 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
2019 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
2020 cb1e6c3c Michael Hanselmann
  elif isinstance(err, errors.QueryFilterParseError):
2021 cb1e6c3c Michael Hanselmann
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
2022 cb1e6c3c Michael Hanselmann
    obuf.write("\n".join(err.GetDetails()))
2023 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
2024 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
2025 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
2026 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
2027 e9d741b6 Iustin Pop
    retcode = 0
2028 73702ee7 Iustin Pop
  else:
2029 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
2030 d0c8c01d Iustin Pop
  return retcode, obuf.getvalue().rstrip("\n")
2031 73702ee7 Iustin Pop
2032 73702ee7 Iustin Pop
2033 ef9fa5b9 René Nussbaumer
def GenericMain(commands, override=None, aliases=None,
2034 ef9fa5b9 René Nussbaumer
                env_override=frozenset()):
2035 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
2036 a8083063 Iustin Pop

2037 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2038 ef9fa5b9 René Nussbaumer
                   for command line handling.
2039 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2040 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2041 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2042 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2043 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2044 ef9fa5b9 René Nussbaumer
                       default args for commands
2045 a8083063 Iustin Pop

2046 a8083063 Iustin Pop
  """
2047 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
2048 a8083063 Iustin Pop
  if sys.argv:
2049 a8083063 Iustin Pop
    binary = os.path.basename(sys.argv[0]) or sys.argv[0]
2050 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
2051 a8083063 Iustin Pop
      binary += " " + sys.argv[1]
2052 a8083063 Iustin Pop
      old_cmdline = " ".join(sys.argv[2:])
2053 a8083063 Iustin Pop
    else:
2054 a8083063 Iustin Pop
      old_cmdline = ""
2055 a8083063 Iustin Pop
  else:
2056 a8083063 Iustin Pop
    binary = "<unknown program>"
2057 a8083063 Iustin Pop
    old_cmdline = ""
2058 a8083063 Iustin Pop
2059 de47cf8f Guido Trotter
  if aliases is None:
2060 de47cf8f Guido Trotter
    aliases = {}
2061 de47cf8f Guido Trotter
2062 3126878d Guido Trotter
  try:
2063 ef9fa5b9 René Nussbaumer
    func, options, args = _ParseArgs(sys.argv, commands, aliases, env_override)
2064 3126878d Guido Trotter
  except errors.ParameterError, err:
2065 3126878d Guido Trotter
    result, err_msg = FormatError(err)
2066 3126878d Guido Trotter
    ToStderr(err_msg)
2067 3126878d Guido Trotter
    return 1
2068 3126878d Guido Trotter
2069 a8083063 Iustin Pop
  if func is None: # parse error
2070 a8083063 Iustin Pop
    return 1
2071 a8083063 Iustin Pop
2072 334d1483 Iustin Pop
  if override is not None:
2073 334d1483 Iustin Pop
    for key, val in override.iteritems():
2074 334d1483 Iustin Pop
      setattr(options, key, val)
2075 334d1483 Iustin Pop
2076 cfcc79c6 Michael Hanselmann
  utils.SetupLogging(constants.LOG_COMMANDS, binary, debug=options.debug,
2077 cfcc79c6 Michael Hanselmann
                     stderr_logging=True)
2078 a8083063 Iustin Pop
2079 a8083063 Iustin Pop
  if old_cmdline:
2080 46fbdd04 Iustin Pop
    logging.info("run with arguments '%s'", old_cmdline)
2081 a8083063 Iustin Pop
  else:
2082 46fbdd04 Iustin Pop
    logging.info("run with no arguments")
2083 a8083063 Iustin Pop
2084 a8083063 Iustin Pop
  try:
2085 a4af651e Iustin Pop
    result = func(options, args)
2086 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
2087 d8353c3a Iustin Pop
          JobSubmittedException), err:
2088 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
2089 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
2090 46fbdd04 Iustin Pop
    ToStderr(err_msg)
2091 8a53b55f Iustin Pop
  except KeyboardInterrupt:
2092 8a53b55f Iustin Pop
    result = constants.EXIT_FAILURE
2093 8a53b55f Iustin Pop
    ToStderr("Aborted. Note that if the operation created any jobs, they"
2094 8a53b55f Iustin Pop
             " might have been submitted and"
2095 8a53b55f Iustin Pop
             " will continue to run in the background.")
2096 225e2544 Iustin Pop
  except IOError, err:
2097 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
2098 225e2544 Iustin Pop
      # our terminal went away, we'll exit
2099 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
2100 225e2544 Iustin Pop
    else:
2101 225e2544 Iustin Pop
      raise
2102 a8083063 Iustin Pop
2103 a8083063 Iustin Pop
  return result
2104 137161c9 Michael Hanselmann
2105 137161c9 Michael Hanselmann
2106 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
2107 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
2108 845c79d8 Michael Hanselmann

2109 845c79d8 Michael Hanselmann
  """
2110 845c79d8 Michael Hanselmann
  try:
2111 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2112 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2113 845c79d8 Michael Hanselmann
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
2114 845c79d8 Michael Hanselmann
2115 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2116 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2117 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2118 845c79d8 Michael Hanselmann
2119 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2120 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2121 845c79d8 Michael Hanselmann
                                 " got %s" % (nidx, ndict))
2122 845c79d8 Michael Hanselmann
2123 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2124 845c79d8 Michael Hanselmann
2125 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2126 845c79d8 Michael Hanselmann
2127 845c79d8 Michael Hanselmann
  return nics
2128 845c79d8 Michael Hanselmann
2129 845c79d8 Michael Hanselmann
2130 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2131 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2132 d77490c5 Iustin Pop

2133 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2134 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2135 d77490c5 Iustin Pop
  @type args: list
2136 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2137 d77490c5 Iustin Pop
  @rtype: int
2138 d77490c5 Iustin Pop
  @return: the desired exit code
2139 d77490c5 Iustin Pop

2140 d77490c5 Iustin Pop
  """
2141 d77490c5 Iustin Pop
  instance = args[0]
2142 d77490c5 Iustin Pop
2143 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
2144 d77490c5 Iustin Pop
2145 d77490c5 Iustin Pop
  hypervisor = None
2146 d77490c5 Iustin Pop
  hvparams = {}
2147 d77490c5 Iustin Pop
  if opts.hypervisor:
2148 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
2149 d77490c5 Iustin Pop
2150 d77490c5 Iustin Pop
  if opts.nics:
2151 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
2152 d77490c5 Iustin Pop
  elif opts.no_nics:
2153 d77490c5 Iustin Pop
    # no nics
2154 d77490c5 Iustin Pop
    nics = []
2155 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
2156 d77490c5 Iustin Pop
    # default of one nic, all auto
2157 d77490c5 Iustin Pop
    nics = [{}]
2158 0af0f641 Iustin Pop
  else:
2159 0af0f641 Iustin Pop
    # mode == import
2160 0af0f641 Iustin Pop
    nics = []
2161 d77490c5 Iustin Pop
2162 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
2163 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
2164 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
2165 d77490c5 Iustin Pop
                                 " information passed")
2166 d77490c5 Iustin Pop
    disks = []
2167 d77490c5 Iustin Pop
  else:
2168 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
2169 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
2170 d77490c5 Iustin Pop
      raise errors.OpPrereqError("No disk information specified")
2171 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
2172 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
2173 d77490c5 Iustin Pop
                                 " '-s' option")
2174 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2175 ccfa86ba Michael Hanselmann
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2176 9b12ed0f Iustin Pop
2177 9b12ed0f Iustin Pop
    if opts.disks:
2178 9b12ed0f Iustin Pop
      try:
2179 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2180 9b12ed0f Iustin Pop
      except ValueError, err:
2181 9b12ed0f Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
2182 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2183 9b12ed0f Iustin Pop
    else:
2184 9b12ed0f Iustin Pop
      disks = []
2185 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2186 d77490c5 Iustin Pop
      didx = int(didx)
2187 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2188 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2189 d77490c5 Iustin Pop
        raise errors.OpPrereqError(msg)
2190 ccfa86ba Michael Hanselmann
      elif constants.IDISK_SIZE in ddict:
2191 ccfa86ba Michael Hanselmann
        if constants.IDISK_ADOPT in ddict:
2192 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2193 5029db65 Iustin Pop
                                     " (disk %d)" % didx)
2194 5029db65 Iustin Pop
        try:
2195 ccfa86ba Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
2196 ccfa86ba Michael Hanselmann
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2197 5029db65 Iustin Pop
        except ValueError, err:
2198 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2199 5029db65 Iustin Pop
                                     (didx, err))
2200 ccfa86ba Michael Hanselmann
      elif constants.IDISK_ADOPT in ddict:
2201 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2202 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2203 5029db65 Iustin Pop
                                     " import")
2204 ccfa86ba Michael Hanselmann
        ddict[constants.IDISK_SIZE] = 0
2205 5029db65 Iustin Pop
      else:
2206 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2207 5029db65 Iustin Pop
                                   " disk %d" % didx)
2208 d77490c5 Iustin Pop
      disks[didx] = ddict
2209 d77490c5 Iustin Pop
2210 a57981c5 Apollon Oikonomopoulos
  if opts.tags is not None:
2211 0f8810df Michael Hanselmann
    tags = opts.tags.split(",")
2212 a57981c5 Apollon Oikonomopoulos
  else:
2213 a57981c5 Apollon Oikonomopoulos
    tags = []
2214 a57981c5 Apollon Oikonomopoulos
2215 b2e233a5 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT)
2216 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2217 d77490c5 Iustin Pop
2218 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2219 d77490c5 Iustin Pop
    start = opts.start
2220 d77490c5 Iustin Pop
    os_type = opts.os
2221 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2222 d77490c5 Iustin Pop
    src_node = None
2223 d77490c5 Iustin Pop
    src_path = None
2224 25a8792c Iustin Pop
    no_install = opts.no_install
2225 e588764d Iustin Pop
    identify_defaults = False
2226 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2227 d77490c5 Iustin Pop
    start = False
2228 d77490c5 Iustin Pop
    os_type = None
2229 1ee8e01a Guido Trotter
    force_variant = False
2230 d77490c5 Iustin Pop
    src_node = opts.src_node
2231 d77490c5 Iustin Pop
    src_path = opts.src_dir
2232 25a8792c Iustin Pop
    no_install = None
2233 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2234 d77490c5 Iustin Pop
  else:
2235 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2236 d77490c5 Iustin Pop
2237 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2238 d77490c5 Iustin Pop
                                disks=disks,
2239 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2240 d77490c5 Iustin Pop
                                nics=nics,
2241 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2242 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2243 460d22be Iustin Pop
                                name_check=opts.name_check,
2244 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2245 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2246 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2247 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2248 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2249 d77490c5 Iustin Pop
                                hvparams=hvparams,
2250 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2251 062a7100 Iustin Pop
                                osparams=opts.osparams,
2252 d77490c5 Iustin Pop
                                mode=mode,
2253 d77490c5 Iustin Pop
                                start=start,
2254 d77490c5 Iustin Pop
                                os_type=os_type,
2255 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2256 d77490c5 Iustin Pop
                                src_node=src_node,
2257 25a8792c Iustin Pop
                                src_path=src_path,
2258 a57981c5 Apollon Oikonomopoulos
                                tags=tags,
2259 e588764d Iustin Pop
                                no_install=no_install,
2260 e588764d Iustin Pop
                                identify_defaults=identify_defaults)
2261 d77490c5 Iustin Pop
2262 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2263 d77490c5 Iustin Pop
  return 0
2264 d77490c5 Iustin Pop
2265 d77490c5 Iustin Pop
2266 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2267 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2268 7e49b6ce Michael Hanselmann

2269 7e49b6ce Michael Hanselmann
  """
2270 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2271 7e49b6ce Michael Hanselmann
    """Initializes this class.
2272 7e49b6ce Michael Hanselmann

2273 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2274 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2275 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2276 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2277 7e49b6ce Michael Hanselmann
    @type master_node: string
2278 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2279 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2280 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2281 7e49b6ce Michael Hanselmann

2282 7e49b6ce Michael Hanselmann
    """
2283 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2284 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2285 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2286 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2287 7e49b6ce Michael Hanselmann
2288 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2289 7e49b6ce Michael Hanselmann
2290 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2291 7e49b6ce Michael Hanselmann
                            if name != master_node]
2292 7e49b6ce Michael Hanselmann
2293 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2294 7e49b6ce Michael Hanselmann
2295 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2296 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2297 7e49b6ce Michael Hanselmann

2298 7e49b6ce Michael Hanselmann
    @type node_name: string
2299 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2300 7e49b6ce Michael Hanselmann
    @type cmd: list
2301 7e49b6ce Michael Hanselmann
    @param cmd: Command
2302 7e49b6ce Michael Hanselmann

2303 7e49b6ce Michael Hanselmann
    """
2304 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2305 7e49b6ce Michael Hanselmann
      # No need to use SSH
2306 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2307 7e49b6ce Michael Hanselmann
    else:
2308 7e49b6ce Michael Hanselmann
      result = self.ssh.Run(node_name, "root", utils.ShellQuoteArgs(cmd))
2309 7e49b6ce Michael Hanselmann
2310 7e49b6ce Michael Hanselmann
    if result.failed:
2311 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2312 7e49b6ce Michael Hanselmann
      if node_name:
2313 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2314 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2315 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2316 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2317 7e49b6ce Michael Hanselmann
2318 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2319 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2320 7e49b6ce Michael Hanselmann

2321 7e49b6ce Michael Hanselmann
    @type fn: callable
2322 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2323 7e49b6ce Michael Hanselmann

2324 7e49b6ce Michael Hanselmann
    """
2325 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2326 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2327 16e0b9c9 Michael Hanselmann
    watcher_block = utils.FileLock.Open(constants.WATCHER_LOCK_FILE)
2328 7e49b6ce Michael Hanselmann
    try:
2329 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2330 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2331 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2332 7e49b6ce Michael Hanselmann
2333 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2334 7e49b6ce Michael Hanselmann
      # ones are finished
2335 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2336 7e49b6ce Michael Hanselmann
      self._RunCmd(None, [constants.DAEMON_UTIL, "stop-master"])
2337 7e49b6ce Michael Hanselmann
      try:
2338 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2339 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2340 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2341 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "stop-all"])
2342 7e49b6ce Michael Hanselmann
2343 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2344 7e49b6ce Michael Hanselmann
        try:
2345 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2346 d512e84b Michael Hanselmann
        except Exception, err:
2347 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2348 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2349 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2350 7e49b6ce Michael Hanselmann
          raise
2351 7e49b6ce Michael Hanselmann
      finally:
2352 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2353 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2354 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2355 7e49b6ce Michael Hanselmann
          self._RunCmd(node_name, [constants.DAEMON_UTIL, "start-all"])
2356 7e49b6ce Michael Hanselmann
    finally:
2357 7e49b6ce Michael Hanselmann
      # Resume watcher
2358 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2359 7e49b6ce Michael Hanselmann
2360 7e49b6ce Michael Hanselmann
2361 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2362 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2363 7e49b6ce Michael Hanselmann

2364 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2365 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2366 7e49b6ce Michael Hanselmann
  @type fn: callable
2367 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2368 7e49b6ce Michael Hanselmann

2369 7e49b6ce Michael Hanselmann
  """
2370 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2371 7e49b6ce Michael Hanselmann
2372 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2373 7e49b6ce Michael Hanselmann
  cl = GetClient()
2374 7e49b6ce Michael Hanselmann
2375 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2376 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2377 7e49b6ce Michael Hanselmann
2378 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2379 7e49b6ce Michael Hanselmann
2380 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2381 7e49b6ce Michael Hanselmann
  del cl
2382 7e49b6ce Michael Hanselmann
2383 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2384 7e49b6ce Michael Hanselmann
2385 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2386 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2387 7e49b6ce Michael Hanselmann
2388 7e49b6ce Michael Hanselmann
2389 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2390 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2391 9fbfbb7b Iustin Pop
                  units=None):
2392 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2393 137161c9 Michael Hanselmann

2394 9fbfbb7b Iustin Pop
  @type headers: dict
2395 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2396 9fbfbb7b Iustin Pop
      the table
2397 9fbfbb7b Iustin Pop
  @type fields: list
2398 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2399 9fbfbb7b Iustin Pop
      the data field
2400 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2401 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2402 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2403 9fbfbb7b Iustin Pop
      each field
2404 9fbfbb7b Iustin Pop
  @type data: list
2405 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2406 9fbfbb7b Iustin Pop
  @type numfields: list
2407 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2408 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2409 9fbfbb7b Iustin Pop
  @type unitfields: list
2410 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2411 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2412 9fbfbb7b Iustin Pop
  @type units: string or None
2413 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2414 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2415 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2416 137161c9 Michael Hanselmann

2417 137161c9 Michael Hanselmann
  """
2418 9fbfbb7b Iustin Pop
  if units is None:
2419 9fbfbb7b Iustin Pop
    if separator:
2420 9fbfbb7b Iustin Pop
      units = "m"
2421 9fbfbb7b Iustin Pop
    else:
2422 9fbfbb7b Iustin Pop
      units = "h"
2423 9fbfbb7b Iustin Pop
2424 137161c9 Michael Hanselmann
  if numfields is None:
2425 137161c9 Michael Hanselmann
    numfields = []
2426 137161c9 Michael Hanselmann
  if unitfields is None:
2427 137161c9 Michael Hanselmann
    unitfields = []
2428 137161c9 Michael Hanselmann
2429 b459a848 Andrea Spadaccini
  numfields = utils.FieldSet(*numfields)   # pylint: disable=W0142
2430 b459a848 Andrea Spadaccini
  unitfields = utils.FieldSet(*unitfields) # pylint: disable=W0142
2431 00430f8e Iustin Pop
2432 137161c9 Michael Hanselmann
  format_fields = []
2433 137161c9 Michael Hanselmann
  for field in fields:
2434 01ca31ae Iustin Pop
    if headers and field not in headers:
2435 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2436 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2437 71c1af58 Iustin Pop
      # variable fields)
2438 71c1af58 Iustin Pop
      headers[field] = field
2439 137161c9 Michael Hanselmann
    if separator is not None:
2440 137161c9 Michael Hanselmann
      format_fields.append("%s")
2441 00430f8e Iustin Pop
    elif numfields.Matches(field):
2442 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2443 137161c9 Michael Hanselmann
    else:
2444 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2445 137161c9 Michael Hanselmann
2446 137161c9 Michael Hanselmann
  if separator is None:
2447 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2448 d0c8c01d Iustin Pop
    format_str = " ".join(format_fields)
2449 137161c9 Michael Hanselmann
  else:
2450 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2451 137161c9 Michael Hanselmann
2452 137161c9 Michael Hanselmann
  for row in data:
2453 dcbd6288 Guido Trotter
    if row is None:
2454 dcbd6288 Guido Trotter
      continue
2455 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2456 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2457 137161c9 Michael Hanselmann
        try:
2458 137161c9 Michael Hanselmann
          val = int(val)
2459 691744c4 Iustin Pop
        except (TypeError, ValueError):
2460 137161c9 Michael Hanselmann
          pass
2461 137161c9 Michael Hanselmann
        else:
2462 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2463 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2464 137161c9 Michael Hanselmann
      if separator is None:
2465 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2466 137161c9 Michael Hanselmann
2467 16be8703 Iustin Pop
  result = []
2468 137161c9 Michael Hanselmann
  if headers:
2469 137161c9 Michael Hanselmann
    args = []
2470 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2471 137161c9 Michael Hanselmann
      hdr = headers[name]
2472 137161c9 Michael Hanselmann
      if separator is None:
2473 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2474 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2475 137161c9 Michael Hanselmann
      args.append(hdr)
2476 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2477 137161c9 Michael Hanselmann
2478 ec39d63c Michael Hanselmann
  if separator is None:
2479 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2480 ec39d63c Michael Hanselmann
2481 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2482 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2483 ec39d63c Michael Hanselmann
2484 137161c9 Michael Hanselmann
  for line in data:
2485 137161c9 Michael Hanselmann
    args = []
2486 dcbd6288 Guido Trotter
    if line is None:
2487 d0c8c01d Iustin Pop
      line = ["-" for _ in fields]
2488 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2489 137161c9 Michael Hanselmann
      if separator is None:
2490 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2491 137161c9 Michael Hanselmann
      args.append(line[idx])
2492 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2493 16be8703 Iustin Pop
2494 16be8703 Iustin Pop
  return result
2495 3386e7a9 Iustin Pop
2496 3386e7a9 Iustin Pop
2497 ee3aedff Michael Hanselmann
def _FormatBool(value):
2498 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
2499 ee3aedff Michael Hanselmann

2500 ee3aedff Michael Hanselmann
  """
2501 ee3aedff Michael Hanselmann
  if value:
2502 ee3aedff Michael Hanselmann
    return "Y"
2503 ee3aedff Michael Hanselmann
  return "N"
2504 ee3aedff Michael Hanselmann
2505 ee3aedff Michael Hanselmann
2506 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2507 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2508 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2509 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2510 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2511 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2512 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2513 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2514 ee3aedff Michael Hanselmann
  }
2515 ee3aedff Michael Hanselmann
2516 ee3aedff Michael Hanselmann
2517 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2518 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2519 ee3aedff Michael Hanselmann

2520 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2521 ee3aedff Michael Hanselmann
  @type override: dict
2522 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2523 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2524 ee3aedff Michael Hanselmann
  @type unit: string
2525 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2526 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2527 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2528 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2529 ee3aedff Michael Hanselmann

2530 ee3aedff Michael Hanselmann
  """
2531 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2532 ee3aedff Michael Hanselmann
  if fmt is not None:
2533 ee3aedff Michael Hanselmann
    return fmt
2534 ee3aedff Michael Hanselmann
2535 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2536 ee3aedff Michael Hanselmann
2537 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2538 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2539 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2540 ee3aedff Michael Hanselmann
2541 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2542 ee3aedff Michael Hanselmann
  if fmt is not None:
2543 ee3aedff Michael Hanselmann
    return fmt
2544 ee3aedff Michael Hanselmann
2545 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
2546 ee3aedff Michael Hanselmann
2547 ee3aedff Michael Hanselmann
2548 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
2549 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
2550 ee3aedff Michael Hanselmann

2551 ee3aedff Michael Hanselmann
  """
2552 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
2553 ee3aedff Michael Hanselmann
    """Initializes this class.
2554 ee3aedff Michael Hanselmann

2555 ee3aedff Michael Hanselmann
    @type fn: callable
2556 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2557 ee3aedff Michael Hanselmann
    @type status_fn: callable
2558 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
2559 f0b1bafe Iustin Pop
    @type verbose: boolean
2560 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
2561 ee3aedff Michael Hanselmann

2562 ee3aedff Michael Hanselmann
    """
2563 ee3aedff Michael Hanselmann
    self._fn = fn
2564 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
2565 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
2566 ee3aedff Michael Hanselmann
2567 ee3aedff Michael Hanselmann
  def __call__(self, data):
2568 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
2569 ee3aedff Michael Hanselmann

2570 ee3aedff Michael Hanselmann
    """
2571 ee3aedff Michael Hanselmann
    (status, value) = data
2572 ee3aedff Michael Hanselmann
2573 ee3aedff Michael Hanselmann
    # Report status
2574 ee3aedff Michael Hanselmann
    self._status_fn(status)
2575 ee3aedff Michael Hanselmann
2576 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
2577 ee3aedff Michael Hanselmann
      return self._fn(value)
2578 ee3aedff Michael Hanselmann
2579 ee3aedff Michael Hanselmann
    assert value is None, \
2580 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
2581 ee3aedff Michael Hanselmann
2582 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
2583 ee3aedff Michael Hanselmann
2584 ee3aedff Michael Hanselmann
2585 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
2586 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
2587 ee3aedff Michael Hanselmann

2588 ae95e419 René Nussbaumer
  @param status: The result status
2589 f2c6673d Michael Hanselmann
  @type verbose: boolean
2590 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
2591 ae95e419 René Nussbaumer
  @return: Text of result status
2592 a6070ef7 Michael Hanselmann

2593 ae95e419 René Nussbaumer
  """
2594 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
2595 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
2596 ae95e419 René Nussbaumer
  try:
2597 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
2598 ae95e419 René Nussbaumer
  except KeyError:
2599 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
2600 cbfa4f0f Michael Hanselmann
  else:
2601 cbfa4f0f Michael Hanselmann
    if verbose:
2602 cbfa4f0f Michael Hanselmann
      return verbose_text
2603 cbfa4f0f Michael Hanselmann
    return normal_text
2604 ee3aedff Michael Hanselmann
2605 ee3aedff Michael Hanselmann
2606 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
2607 f0b1bafe Iustin Pop
                      header=False, verbose=False):
2608 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
2609 ee3aedff Michael Hanselmann

2610 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
2611 ee3aedff Michael Hanselmann
  @param result: result of query operation
2612 ee3aedff Michael Hanselmann
  @type unit: string
2613 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
2614 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
2615 ee3aedff Michael Hanselmann
  @type format_override: dict
2616 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2617 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2618 ee3aedff Michael Hanselmann
  @type separator: string or None
2619 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2620 ee3aedff Michael Hanselmann
  @type header: bool
2621 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
2622 f0b1bafe Iustin Pop
  @type verbose: boolean
2623 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2624 ee3aedff Michael Hanselmann

2625 ee3aedff Michael Hanselmann
  """
2626 ee3aedff Michael Hanselmann
  if unit is None:
2627 ee3aedff Michael Hanselmann
    if separator:
2628 ee3aedff Michael Hanselmann
      unit = "m"
2629 ee3aedff Michael Hanselmann
    else:
2630 ee3aedff Michael Hanselmann
      unit = "h"
2631 ee3aedff Michael Hanselmann
2632 ee3aedff Michael Hanselmann
  if format_override is None:
2633 ee3aedff Michael Hanselmann
    format_override = {}
2634 ee3aedff Michael Hanselmann
2635 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
2636 ee3aedff Michael Hanselmann
2637 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
2638 ee3aedff Michael Hanselmann
    if status in stats:
2639 ee3aedff Michael Hanselmann
      stats[status] += 1
2640 ee3aedff Michael Hanselmann
2641 ee3aedff Michael Hanselmann
  columns = []
2642 ee3aedff Michael Hanselmann
  for fdef in result.fields:
2643 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
2644 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
2645 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
2646 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
2647 f0b1bafe Iustin Pop
                                                     verbose),
2648 ee3aedff Michael Hanselmann
                               align_right))
2649 ee3aedff Michael Hanselmann
2650 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
2651 ee3aedff Michael Hanselmann
2652 ee3aedff Michael Hanselmann
  # Collect statistics
2653 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
2654 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
2655 ee3aedff Michael Hanselmann
2656 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
2657 ee3aedff Michael Hanselmann
  # detected via the field definitions.
2658 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
2659 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
2660 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
2661 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
2662 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
2663 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
2664 ee3aedff Michael Hanselmann
  else:
2665 ee3aedff Michael Hanselmann
    status = QR_NORMAL
2666 ee3aedff Michael Hanselmann
2667 ee3aedff Michael Hanselmann
  return (status, table)
2668 ee3aedff Michael Hanselmann
2669 ee3aedff Michael Hanselmann
2670 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
2671 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
2672 ee3aedff Michael Hanselmann

2673 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2674 ee3aedff Michael Hanselmann

2675 ee3aedff Michael Hanselmann
  """
2676 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
2677 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
2678 ee3aedff Michael Hanselmann
2679 ee3aedff Michael Hanselmann
2680 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
2681 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
2682 ee3aedff Michael Hanselmann

2683 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2684 ee3aedff Michael Hanselmann

2685 ee3aedff Michael Hanselmann
  """
2686 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
2687 ee3aedff Michael Hanselmann
  if unknown:
2688 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
2689 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
2690 ee3aedff Michael Hanselmann
    return True
2691 ee3aedff Michael Hanselmann
2692 ee3aedff Michael Hanselmann
  return False
2693 ee3aedff Michael Hanselmann
2694 ee3aedff Michael Hanselmann
2695 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
2696 2928de47 Michael Hanselmann
                format_override=None, verbose=False, force_filter=False):
2697 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
2698 ee3aedff Michael Hanselmann

2699 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
2700 ee3aedff Michael Hanselmann
  @type fields: list of strings
2701 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
2702 ee3aedff Michael Hanselmann
  @type names: list of strings
2703 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
2704 ee3aedff Michael Hanselmann
  @type unit: string or None
2705 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
2706 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
2707 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
2708 ee3aedff Michael Hanselmann
  @type separator: string or None
2709 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2710 ee3aedff Michael Hanselmann
  @type header: bool
2711 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2712 2928de47 Michael Hanselmann
  @type force_filter: bool
2713 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
2714 ee3aedff Michael Hanselmann
  @type format_override: dict
2715 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2716 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2717 f0b1bafe Iustin Pop
  @type verbose: boolean
2718 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2719 ee3aedff Michael Hanselmann

2720 ee3aedff Michael Hanselmann
  """
2721 ee3aedff Michael Hanselmann
  if not names:
2722 ee3aedff Michael Hanselmann
    names = None
2723 ee3aedff Michael Hanselmann
2724 2e5c33db Iustin Pop
  qfilter = qlang.MakeFilter(names, force_filter)
2725 2928de47 Michael Hanselmann
2726 727274dd Iustin Pop
  if cl is None:
2727 727274dd Iustin Pop
    cl = GetClient()
2728 727274dd Iustin Pop
2729 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
2730 ee3aedff Michael Hanselmann
2731 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
2732 ee3aedff Michael Hanselmann
2733 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
2734 ee3aedff Michael Hanselmann
                                     header=header,
2735 f0b1bafe Iustin Pop
                                     format_override=format_override,
2736 f0b1bafe Iustin Pop
                                     verbose=verbose)
2737 ee3aedff Michael Hanselmann
2738 ee3aedff Michael Hanselmann
  for line in data:
2739 ee3aedff Michael Hanselmann
    ToStdout(line)
2740 ee3aedff Michael Hanselmann
2741 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
2742 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
2743 ee3aedff Michael Hanselmann
2744 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
2745 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
2746 ee3aedff Michael Hanselmann
2747 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
2748 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
2749 ee3aedff Michael Hanselmann
2750 ee3aedff Michael Hanselmann
2751 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
2752 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
2753 ee3aedff Michael Hanselmann

2754 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
2755 ee3aedff Michael Hanselmann
  @type fields: list of strings
2756 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
2757 ee3aedff Michael Hanselmann
  @type separator: string or None
2758 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2759 ee3aedff Michael Hanselmann
  @type header: bool
2760 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2761 ee3aedff Michael Hanselmann

2762 ee3aedff Michael Hanselmann
  """
2763 ee3aedff Michael Hanselmann
  if cl is None:
2764 ee3aedff Michael Hanselmann
    cl = GetClient()
2765 ee3aedff Michael Hanselmann
2766 ee3aedff Michael Hanselmann
  if not fields:
2767 ee3aedff Michael Hanselmann
    fields = None
2768 ee3aedff Michael Hanselmann
2769 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
2770 ee3aedff Michael Hanselmann
2771 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
2772 ee3aedff Michael Hanselmann
2773 ee3aedff Michael Hanselmann
  columns = [
2774 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
2775 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
2776 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
2777 ee3aedff Michael Hanselmann
    ]
2778 ee3aedff Michael Hanselmann
2779 ea1440c1 Michael Hanselmann
  rows = [[fdef.name, fdef.title, fdef.doc] for fdef in response.fields]
2780 ee3aedff Michael Hanselmann
2781 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
2782 ee3aedff Michael Hanselmann
    ToStdout(line)
2783 ee3aedff Michael Hanselmann
2784 ee3aedff Michael Hanselmann
  if found_unknown:
2785 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
2786 ee3aedff Michael Hanselmann
2787 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
2788 ee3aedff Michael Hanselmann
2789 ee3aedff Michael Hanselmann
2790 ee3aedff Michael Hanselmann
class TableColumn:
2791 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
2792 ee3aedff Michael Hanselmann

2793 ee3aedff Michael Hanselmann
  """
2794 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
2795 ee3aedff Michael Hanselmann
    """Initializes this class.
2796 ee3aedff Michael Hanselmann

2797 ee3aedff Michael Hanselmann
    @type title: string
2798 ee3aedff Michael Hanselmann
    @param title: Column title
2799 ee3aedff Michael Hanselmann
    @type fn: callable
2800 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2801 ee3aedff Michael Hanselmann
    @type align_right: bool
2802 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
2803 ee3aedff Michael Hanselmann

2804 ee3aedff Michael Hanselmann
    """
2805 ee3aedff Michael Hanselmann
    self.title = title
2806 ee3aedff Michael Hanselmann
    self.format = fn
2807 ee3aedff Michael Hanselmann
    self.align_right = align_right
2808 ee3aedff Michael Hanselmann
2809 ee3aedff Michael Hanselmann
2810 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
2811 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
2812 ee3aedff Michael Hanselmann

2813 ee3aedff Michael Hanselmann
  """
2814 ee3aedff Michael Hanselmann
  if align_right:
2815 ee3aedff Michael Hanselmann
    sign = ""
2816 ee3aedff Michael Hanselmann
  else:
2817 ee3aedff Michael Hanselmann
    sign = "-"
2818 ee3aedff Michael Hanselmann
2819 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
2820 ee3aedff Michael Hanselmann
2821 ee3aedff Michael Hanselmann
2822 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
2823 ee3aedff Michael Hanselmann
  """Formats data as a table.
2824 ee3aedff Michael Hanselmann

2825 ee3aedff Michael Hanselmann
  @type rows: list of lists
2826 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
2827 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
2828 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
2829 ee3aedff Michael Hanselmann
  @type header: bool
2830 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
2831 ee3aedff Michael Hanselmann
  @type separator: string or None
2832 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
2833 ee3aedff Michael Hanselmann

2834 ee3aedff Michael Hanselmann
  """
2835 ee3aedff Michael Hanselmann
  if header:
2836 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
2837 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
2838 ee3aedff Michael Hanselmann
  else:
2839 ee3aedff Michael Hanselmann
    data = []
2840 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
2841 ee3aedff Michael Hanselmann
2842 ee3aedff Michael Hanselmann
  # Format row data
2843 ee3aedff Michael Hanselmann
  for row in rows:
2844 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
2845 ee3aedff Michael Hanselmann
2846 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
2847 ee3aedff Michael Hanselmann
2848 ee3aedff Michael Hanselmann
    if separator is None:
2849 ee3aedff Michael Hanselmann
      # Update column widths
2850 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
2851 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
2852 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
2853 ee3aedff Michael Hanselmann
2854 ee3aedff Michael Hanselmann
    data.append(formatted)
2855 ee3aedff Michael Hanselmann
2856 ee3aedff Michael Hanselmann
  if separator is not None:
2857 ee3aedff Michael Hanselmann
    # Return early if a separator is used
2858 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
2859 ee3aedff Michael Hanselmann
2860 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
2861 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
2862 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
2863 ee3aedff Michael Hanselmann
2864 ee3aedff Michael Hanselmann
  # Build format string
2865 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
2866 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
2867 ee3aedff Michael Hanselmann
2868 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
2869 ee3aedff Michael Hanselmann
2870 ee3aedff Michael Hanselmann
2871 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
2872 3386e7a9 Iustin Pop
  """Formats a given timestamp.
2873 3386e7a9 Iustin Pop

2874 3386e7a9 Iustin Pop
  @type ts: timestamp
2875 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
2876 3386e7a9 Iustin Pop

2877 3386e7a9 Iustin Pop
  @rtype: string
2878 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
2879 3386e7a9 Iustin Pop

2880 3386e7a9 Iustin Pop
  """
2881 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
2882 d0c8c01d Iustin Pop
    return "?"
2883 3386e7a9 Iustin Pop
  sec, usec = ts
2884 3386e7a9 Iustin Pop
  return time.strftime("%F %T", time.localtime(sec)) + ".%06d" % usec
2885 2241e2b9 Iustin Pop
2886 2241e2b9 Iustin Pop
2887 2241e2b9 Iustin Pop
def ParseTimespec(value):
2888 2241e2b9 Iustin Pop
  """Parse a time specification.
2889 2241e2b9 Iustin Pop

2890 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
2891 2241e2b9 Iustin Pop

2892 2241e2b9 Iustin Pop
    - s: seconds
2893 2241e2b9 Iustin Pop
    - m: minutes
2894 2241e2b9 Iustin Pop
    - h: hours
2895 2241e2b9 Iustin Pop
    - d: day
2896 2241e2b9 Iustin Pop
    - w: weeks
2897 2241e2b9 Iustin Pop

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

2900 2241e2b9 Iustin Pop
  """
2901 2241e2b9 Iustin Pop
  value = str(value)
2902 2241e2b9 Iustin Pop
  if not value:
2903 2241e2b9 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed")
2904 2241e2b9 Iustin Pop
  suffix_map = {
2905 d0c8c01d Iustin Pop
    "s": 1,
2906 d0c8c01d Iustin Pop
    "m": 60,
2907 d0c8c01d Iustin Pop
    "h": 3600,
2908 d0c8c01d Iustin Pop
    "d": 86400,
2909 d0c8c01d Iustin Pop
    "w": 604800,
2910 2241e2b9 Iustin Pop
    }
2911 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
2912 2241e2b9 Iustin Pop
    try:
2913 2241e2b9 Iustin Pop
      value = int(value)
2914 691744c4 Iustin Pop
    except (TypeError, ValueError):
2915 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2916 2241e2b9 Iustin Pop
  else:
2917 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
2918 2241e2b9 Iustin Pop
    value = value[:-1]
2919 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
2920 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
2921 2241e2b9 Iustin Pop
                                 " suffix passed)")
2922 2241e2b9 Iustin Pop
    try:
2923 2241e2b9 Iustin Pop
      value = int(value) * multiplier
2924 691744c4 Iustin Pop
    except (TypeError, ValueError):
2925 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value)
2926 2241e2b9 Iustin Pop
  return value
2927 46fbdd04 Iustin Pop
2928 46fbdd04 Iustin Pop
2929 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
2930 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
2931 4040a784 Iustin Pop
  """Returns the names of online nodes.
2932 4040a784 Iustin Pop

2933 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
2934 4040a784 Iustin Pop
  the online nodes.
2935 4040a784 Iustin Pop

2936 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
2937 4040a784 Iustin Pop
      offline ones)
2938 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
2939 4040a784 Iustin Pop
  @type nowarn: boolean
2940 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
2941 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
2942 4040a784 Iustin Pop
      note is not displayed
2943 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
2944 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
2945 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
2946 e9e26bb3 Iustin Pop
      (if any)
2947 e9e26bb3 Iustin Pop
  @type filter_master: boolean
2948 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
2949 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
2950 e9e26bb3 Iustin Pop
      node name against the list)
2951 05484a24 Michael Hanselmann
  @type nodegroup: string
2952 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
2953 4040a784 Iustin Pop

2954 4040a784 Iustin Pop
  """
2955 4040a784 Iustin Pop
  if cl is None:
2956 4040a784 Iustin Pop
    cl = GetClient()
2957 4040a784 Iustin Pop
2958 2e5c33db Iustin Pop
  qfilter = []
2959 05484a24 Michael Hanselmann
2960 05484a24 Michael Hanselmann
  if nodes:
2961 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
2962 05484a24 Michael Hanselmann
2963 05484a24 Michael Hanselmann
  if nodegroup is not None:
2964 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
2965 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
2966 e9e26bb3 Iustin Pop
2967 e9e26bb3 Iustin Pop
  if filter_master:
2968 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
2969 05484a24 Michael Hanselmann
2970 2e5c33db Iustin Pop
  if qfilter:
2971 2e5c33db Iustin Pop
    if len(qfilter) > 1:
2972 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
2973 05484a24 Michael Hanselmann
    else:
2974 2e5c33db Iustin Pop
      assert len(qfilter) == 1
2975 2e5c33db Iustin Pop
      final_filter = qfilter[0]
2976 e9e26bb3 Iustin Pop
  else:
2977 05484a24 Michael Hanselmann
    final_filter = None
2978 05484a24 Michael Hanselmann
2979 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
2980 05484a24 Michael Hanselmann
2981 05484a24 Michael Hanselmann
  def _IsOffline(row):
2982 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
2983 05484a24 Michael Hanselmann
    return offline
2984 05484a24 Michael Hanselmann
2985 05484a24 Michael Hanselmann
  def _GetName(row):
2986 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
2987 05484a24 Michael Hanselmann
    return name
2988 05484a24 Michael Hanselmann
2989 05484a24 Michael Hanselmann
  def _GetSip(row):
2990 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
2991 05484a24 Michael Hanselmann
    return sip
2992 05484a24 Michael Hanselmann
2993 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
2994 e9e26bb3 Iustin Pop
2995 4040a784 Iustin Pop
  if offline and not nowarn:
2996 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
2997 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
2998 05484a24 Michael Hanselmann
2999 05484a24 Michael Hanselmann
  if secondary_ips:
3000 05484a24 Michael Hanselmann
    fn = _GetSip
3001 05484a24 Michael Hanselmann
  else:
3002 05484a24 Michael Hanselmann
    fn = _GetName
3003 05484a24 Michael Hanselmann
3004 05484a24 Michael Hanselmann
  return map(fn, online)
3005 4040a784 Iustin Pop
3006 4040a784 Iustin Pop
3007 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3008 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3009 46fbdd04 Iustin Pop

3010 46fbdd04 Iustin Pop
  @type stream: file object
3011 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3012 46fbdd04 Iustin Pop
  @type txt: str
3013 46fbdd04 Iustin Pop
  @param txt: the message
3014 46fbdd04 Iustin Pop

3015 46fbdd04 Iustin Pop
  """
3016 225e2544 Iustin Pop
  try:
3017 225e2544 Iustin Pop
    if args:
3018 225e2544 Iustin Pop
      args = tuple(args)
3019 225e2544 Iustin Pop
      stream.write(txt % args)
3020 225e2544 Iustin Pop
    else:
3021 225e2544 Iustin Pop
      stream.write(txt)
3022 d0c8c01d Iustin Pop
    stream.write("\n")
3023 225e2544 Iustin Pop
    stream.flush()
3024 225e2544 Iustin Pop
  except IOError, err:
3025 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3026 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3027 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3028 225e2544 Iustin Pop
    else:
3029 225e2544 Iustin Pop
      raise
3030 46fbdd04 Iustin Pop
3031 46fbdd04 Iustin Pop
3032 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3033 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3034 46fbdd04 Iustin Pop

3035 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3036 46fbdd04 Iustin Pop

3037 46fbdd04 Iustin Pop
  @type txt: str
3038 46fbdd04 Iustin Pop
  @param txt: the message
3039 46fbdd04 Iustin Pop

3040 46fbdd04 Iustin Pop
  """
3041 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3042 46fbdd04 Iustin Pop
3043 46fbdd04 Iustin Pop
3044 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3045 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3046 46fbdd04 Iustin Pop

3047 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3048 46fbdd04 Iustin Pop

3049 46fbdd04 Iustin Pop
  @type txt: str
3050 46fbdd04 Iustin Pop
  @param txt: the message
3051 46fbdd04 Iustin Pop

3052 46fbdd04 Iustin Pop
  """
3053 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3054 479636a3 Iustin Pop
3055 479636a3 Iustin Pop
3056 479636a3 Iustin Pop
class JobExecutor(object):
3057 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3058 479636a3 Iustin Pop

3059 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3060 479636a3 Iustin Pop
  GetResults() calls.
3061 479636a3 Iustin Pop

3062 479636a3 Iustin Pop
  """
3063 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3064 479636a3 Iustin Pop
    self.queue = []
3065 479636a3 Iustin Pop
    if cl is None:
3066 479636a3 Iustin Pop
      cl = GetClient()
3067 479636a3 Iustin Pop
    self.cl = cl
3068 479636a3 Iustin Pop
    self.verbose = verbose
3069 23b4b983 Iustin Pop
    self.jobs = []
3070 cff5fa7f Iustin Pop
    self.opts = opts
3071 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3072 60452edf Michael Hanselmann
    self._counter = itertools.count()
3073 479636a3 Iustin Pop
3074 8d99a8bf Michael Hanselmann
  @staticmethod
3075 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3076 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3077 8d99a8bf Michael Hanselmann

3078 8d99a8bf Michael Hanselmann
    """
3079 8d99a8bf Michael Hanselmann
    if name:
3080 8d99a8bf Michael Hanselmann
      return fmt % name
3081 8d99a8bf Michael Hanselmann
3082 8d99a8bf Michael Hanselmann
    return ""
3083 8d99a8bf Michael Hanselmann
3084 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3085 23b4b983 Iustin Pop
    """Record a job for later submit.
3086 479636a3 Iustin Pop

3087 479636a3 Iustin Pop
    @type name: string
3088 479636a3 Iustin Pop
    @param name: a description of the job, will be used in WaitJobSet
3089 8d99a8bf Michael Hanselmann

3090 479636a3 Iustin Pop
    """
3091 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3092 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3093 23b4b983 Iustin Pop
3094 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3095 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3096 8d99a8bf Michael Hanselmann

3097 8d99a8bf Michael Hanselmann
    """
3098 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3099 8d99a8bf Michael Hanselmann
3100 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3101 23b4b983 Iustin Pop
    """Submit all pending jobs.
3102 23b4b983 Iustin Pop

3103 23b4b983 Iustin Pop
    """
3104 66ecc479 Guido Trotter
    if each:
3105 66ecc479 Guido Trotter
      results = []
3106 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3107 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3108 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3109 60452edf Michael Hanselmann
        results.append([True, self.cl.SubmitJob(ops)])
3110 66ecc479 Guido Trotter
    else:
3111 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3112 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3113 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3114 5299e61f Iustin Pop
3115 5299e61f Iustin Pop
  def _ChooseJob(self):
3116 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3117 5299e61f Iustin Pop

3118 5299e61f Iustin Pop
    """
3119 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3120 5299e61f Iustin Pop
3121 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3122 11705e3d Iustin Pop
                               ["status"])
3123 5299e61f Iustin Pop
    assert result
3124 5299e61f Iustin Pop
3125 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3126 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3127 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3128 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3129 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3130 91c622a8 Iustin Pop
        # job is still present and waiting
3131 5299e61f Iustin Pop
        continue
3132 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3133 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3134 5299e61f Iustin Pop
      return job_data
3135 5299e61f Iustin Pop
3136 5299e61f Iustin Pop
    # no job found
3137 5299e61f Iustin Pop
    return self.jobs.pop(0)
3138 479636a3 Iustin Pop
3139 479636a3 Iustin Pop
  def GetResults(self):
3140 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3141 479636a3 Iustin Pop

3142 479636a3 Iustin Pop
    @rtype: list
3143 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3144 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3145 479636a3 Iustin Pop
        there will be the error message
3146 479636a3 Iustin Pop

3147 479636a3 Iustin Pop
    """
3148 23b4b983 Iustin Pop
    if not self.jobs:
3149 23b4b983 Iustin Pop
      self.SubmitPending()
3150 479636a3 Iustin Pop
    results = []
3151 479636a3 Iustin Pop
    if self.verbose:
3152 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3153 23b4b983 Iustin Pop
      if ok_jobs:
3154 4474f112 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3155 5299e61f Iustin Pop
3156 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
3157 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3158 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
3159 4474f112 Iustin Pop
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3160 c63355f2 Iustin Pop
      results.append((idx, False, jid))
3161 5299e61f Iustin Pop
3162 5299e61f Iustin Pop
    while self.jobs:
3163 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
3164 4474f112 Iustin Pop
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3165 479636a3 Iustin Pop
      try:
3166 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3167 479636a3 Iustin Pop
        success = True
3168 91c622a8 Iustin Pop
      except errors.JobLost, err:
3169 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3170 4474f112 Iustin Pop
        ToStderr("Job %s%s has been archived, cannot check its result",
3171 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"))
3172 91c622a8 Iustin Pop
        success = False
3173 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3174 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3175 479636a3 Iustin Pop
        success = False
3176 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3177 4474f112 Iustin Pop
        ToStderr("Job %s%s has failed: %s",
3178 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"), job_result)
3179 479636a3 Iustin Pop
3180 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3181 5299e61f Iustin Pop
3182 5299e61f Iustin Pop
    # sort based on the index, then drop it
3183 5299e61f Iustin Pop
    results.sort()
3184 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3185 5299e61f Iustin Pop
3186 479636a3 Iustin Pop
    return results
3187 479636a3 Iustin Pop
3188 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3189 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3190 479636a3 Iustin Pop

3191 479636a3 Iustin Pop
    @type wait: boolean
3192 479636a3 Iustin Pop
    @param wait: whether to wait or not
3193 479636a3 Iustin Pop

3194 479636a3 Iustin Pop
    """
3195 479636a3 Iustin Pop
    if wait:
3196 479636a3 Iustin Pop
      return self.GetResults()
3197 479636a3 Iustin Pop
    else:
3198 23b4b983 Iustin Pop
      if not self.jobs:
3199 23b4b983 Iustin Pop
        self.SubmitPending()
3200 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3201 23b4b983 Iustin Pop
        if status:
3202 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3203 23b4b983 Iustin Pop
        else:
3204 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3205 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3206 acd19189 René Nussbaumer
3207 acd19189 René Nussbaumer
3208 acd19189 René Nussbaumer
def FormatParameterDict(buf, param_dict, actual, level=1):
3209 acd19189 René Nussbaumer
  """Formats a parameter dictionary.
3210 acd19189 René Nussbaumer

3211 acd19189 René Nussbaumer
  @type buf: L{StringIO}
3212 acd19189 René Nussbaumer
  @param buf: the buffer into which to write
3213 acd19189 René Nussbaumer
  @type param_dict: dict
3214 acd19189 René Nussbaumer
  @param param_dict: the own parameters
3215 acd19189 René Nussbaumer
  @type actual: dict
3216 acd19189 René Nussbaumer
  @param actual: the current parameter set (including defaults)
3217 acd19189 René Nussbaumer
  @param level: Level of indent
3218 acd19189 René Nussbaumer

3219 acd19189 René Nussbaumer
  """
3220 acd19189 René Nussbaumer
  indent = "  " * level
3221 acd19189 René Nussbaumer
  for key in sorted(actual):
3222 acd19189 René Nussbaumer
    val = param_dict.get(key, "default (%s)" % actual[key])
3223 acd19189 René Nussbaumer
    buf.write("%s- %s: %s\n" % (indent, key, val))
3224 25bd815c René Nussbaumer
3225 25bd815c René Nussbaumer
3226 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3227 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3228 25bd815c René Nussbaumer

3229 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3230 25bd815c René Nussbaumer
  on a given list of list_type.
3231 25bd815c René Nussbaumer

3232 25bd815c René Nussbaumer
  @type names: list
3233 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3234 25bd815c René Nussbaumer
      we ask for confirmation
3235 25bd815c René Nussbaumer
  @type list_type: str
3236 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3237 25bd815c René Nussbaumer
  @type text: str
3238 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3239 25bd815c René Nussbaumer
  @rtype: boolean
3240 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3241 25bd815c René Nussbaumer

3242 25bd815c René Nussbaumer
  """
3243 25bd815c René Nussbaumer
  count = len(names)
3244 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3245 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3246 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3247 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3248 25bd815c René Nussbaumer
3249 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3250 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3251 25bd815c René Nussbaumer
3252 25bd815c René Nussbaumer
  if count > 20:
3253 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3254 25bd815c René Nussbaumer
    question = msg
3255 25bd815c René Nussbaumer
  else:
3256 25bd815c René Nussbaumer
    question = msg + affected
3257 25bd815c René Nussbaumer
3258 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3259 25bd815c René Nussbaumer
  if choice == "v":
3260 25bd815c René Nussbaumer
    choices.pop(1)
3261 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3262 25bd815c René Nussbaumer
  return choice