Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 0ea11dcb

History | View | Annotate | Download (120.9 kB)

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

332 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
333 863d7f46 Michael Hanselmann

334 863d7f46 Michael Hanselmann
  """
335 b459a848 Andrea Spadaccini
  # pylint: disable=W0622
336 863d7f46 Michael Hanselmann
  def __init__(self, min=0, max=None, choices=None):
337 863d7f46 Michael Hanselmann
    _Argument.__init__(self, min=min, max=max)
338 863d7f46 Michael Hanselmann
    self.choices = choices
339 863d7f46 Michael Hanselmann
340 863d7f46 Michael Hanselmann
  def __repr__(self):
341 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s choices=%r>" %
342 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max, self.choices))
343 863d7f46 Michael Hanselmann
344 863d7f46 Michael Hanselmann
345 863d7f46 Michael Hanselmann
class ArgChoice(ArgSuggest):
346 863d7f46 Michael Hanselmann
  """Choice argument.
347 863d7f46 Michael Hanselmann

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

351 863d7f46 Michael Hanselmann
  """
352 863d7f46 Michael Hanselmann
353 863d7f46 Michael Hanselmann
354 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
355 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
356 863d7f46 Michael Hanselmann

357 863d7f46 Michael Hanselmann
  """
358 863d7f46 Michael Hanselmann
359 863d7f46 Michael Hanselmann
360 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
361 863d7f46 Michael Hanselmann
  """Instances argument.
362 863d7f46 Michael Hanselmann

363 863d7f46 Michael Hanselmann
  """
364 863d7f46 Michael Hanselmann
365 863d7f46 Michael Hanselmann
366 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
367 863d7f46 Michael Hanselmann
  """Node argument.
368 863d7f46 Michael Hanselmann

369 863d7f46 Michael Hanselmann
  """
370 863d7f46 Michael Hanselmann
371 667dbd6b Adeodato Simo
372 9c784fb3 Dimitris Aragiorgis
class ArgNetwork(_Argument):
373 9c784fb3 Dimitris Aragiorgis
  """Network argument.
374 9c784fb3 Dimitris Aragiorgis

375 9c784fb3 Dimitris Aragiorgis
  """
376 9c784fb3 Dimitris Aragiorgis
377 3c286190 Dimitris Aragiorgis
378 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
379 667dbd6b Adeodato Simo
  """Node group argument.
380 667dbd6b Adeodato Simo

381 667dbd6b Adeodato Simo
  """
382 667dbd6b Adeodato Simo
383 667dbd6b Adeodato Simo
384 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
385 863d7f46 Michael Hanselmann
  """Job ID argument.
386 863d7f46 Michael Hanselmann

387 863d7f46 Michael Hanselmann
  """
388 863d7f46 Michael Hanselmann
389 863d7f46 Michael Hanselmann
390 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
391 863d7f46 Michael Hanselmann
  """File path argument.
392 863d7f46 Michael Hanselmann

393 863d7f46 Michael Hanselmann
  """
394 863d7f46 Michael Hanselmann
395 863d7f46 Michael Hanselmann
396 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
397 863d7f46 Michael Hanselmann
  """Command argument.
398 863d7f46 Michael Hanselmann

399 863d7f46 Michael Hanselmann
  """
400 863d7f46 Michael Hanselmann
401 863d7f46 Michael Hanselmann
402 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
403 83ec7961 Michael Hanselmann
  """Host argument.
404 83ec7961 Michael Hanselmann

405 83ec7961 Michael Hanselmann
  """
406 83ec7961 Michael Hanselmann
407 83ec7961 Michael Hanselmann
408 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
409 f9faf9c3 René Nussbaumer
  """OS argument.
410 f9faf9c3 René Nussbaumer

411 f9faf9c3 René Nussbaumer
  """
412 f9faf9c3 René Nussbaumer
413 f9faf9c3 René Nussbaumer
414 4a265c08 Michael Hanselmann
ARGS_NONE = []
415 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
416 9c784fb3 Dimitris Aragiorgis
ARGS_MANY_NETWORKS = [ArgNetwork()]
417 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
418 667dbd6b Adeodato Simo
ARGS_MANY_GROUPS = [ArgGroup()]
419 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
420 9c784fb3 Dimitris Aragiorgis
ARGS_ONE_NETWORK = [ArgNetwork(min=1, max=1)]
421 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
422 dadf6b7d Michael Hanselmann
# TODO
423 dadf6b7d Michael Hanselmann
ARGS_ONE_GROUP = [ArgGroup(min=1, max=1)]
424 f9faf9c3 René Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
425 4a265c08 Michael Hanselmann
426 4a265c08 Michael Hanselmann
427 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
428 846baef9 Iustin Pop
  """Extract the tag type object.
429 846baef9 Iustin Pop

430 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
431 846baef9 Iustin Pop

432 846baef9 Iustin Pop
  """
433 846baef9 Iustin Pop
  if not hasattr(opts, "tag_type"):
434 846baef9 Iustin Pop
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
435 846baef9 Iustin Pop
  kind = opts.tag_type
436 846baef9 Iustin Pop
  if kind == constants.TAG_CLUSTER:
437 bcd35e09 Dato Simó
    retval = kind, None
438 819cbfe5 Michael Hanselmann
  elif kind in (constants.TAG_NODEGROUP,
439 819cbfe5 Michael Hanselmann
                constants.TAG_NODE,
440 8140e24f Dimitris Aragiorgis
                constants.TAG_NETWORK,
441 819cbfe5 Michael Hanselmann
                constants.TAG_INSTANCE):
442 846baef9 Iustin Pop
    if not args:
443 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("no arguments passed to the command",
444 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
445 846baef9 Iustin Pop
    name = args.pop(0)
446 846baef9 Iustin Pop
    retval = kind, name
447 846baef9 Iustin Pop
  else:
448 846baef9 Iustin Pop
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
449 846baef9 Iustin Pop
  return retval
450 846baef9 Iustin Pop
451 846baef9 Iustin Pop
452 810c50b7 Iustin Pop
def _ExtendTags(opts, args):
453 810c50b7 Iustin Pop
  """Extend the args if a source file has been given.
454 810c50b7 Iustin Pop

455 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
456 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
457 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
458 810c50b7 Iustin Pop

459 810c50b7 Iustin Pop
  """
460 810c50b7 Iustin Pop
  fname = opts.tags_source
461 810c50b7 Iustin Pop
  if fname is None:
462 810c50b7 Iustin Pop
    return
463 810c50b7 Iustin Pop
  if fname == "-":
464 810c50b7 Iustin Pop
    new_fh = sys.stdin
465 810c50b7 Iustin Pop
  else:
466 810c50b7 Iustin Pop
    new_fh = open(fname, "r")
467 810c50b7 Iustin Pop
  new_data = []
468 810c50b7 Iustin Pop
  try:
469 810c50b7 Iustin Pop
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
470 810c50b7 Iustin Pop
    # because of python bug 1633941
471 810c50b7 Iustin Pop
    while True:
472 810c50b7 Iustin Pop
      line = new_fh.readline()
473 810c50b7 Iustin Pop
      if not line:
474 810c50b7 Iustin Pop
        break
475 810c50b7 Iustin Pop
      new_data.append(line.strip())
476 810c50b7 Iustin Pop
  finally:
477 810c50b7 Iustin Pop
    new_fh.close()
478 810c50b7 Iustin Pop
  args.extend(new_data)
479 810c50b7 Iustin Pop
480 810c50b7 Iustin Pop
481 846baef9 Iustin Pop
def ListTags(opts, args):
482 846baef9 Iustin Pop
  """List the tags on a given object.
483 846baef9 Iustin Pop

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

489 846baef9 Iustin Pop
  """
490 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
491 f2374060 Iustin Pop
  cl = GetClient(query=True)
492 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
493 846baef9 Iustin Pop
  result = list(result)
494 846baef9 Iustin Pop
  result.sort()
495 846baef9 Iustin Pop
  for tag in result:
496 03298ebe Michael Hanselmann
    ToStdout(tag)
497 846baef9 Iustin Pop
498 846baef9 Iustin Pop
499 846baef9 Iustin Pop
def AddTags(opts, args):
500 846baef9 Iustin Pop
  """Add tags on a given object.
501 846baef9 Iustin Pop

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

507 846baef9 Iustin Pop
  """
508 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
509 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
510 846baef9 Iustin Pop
  if not args:
511 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("No tags to be added", errors.ECODE_INVAL)
512 d1602edc Iustin Pop
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
513 6bc3ed14 Michael Hanselmann
  SubmitOrSend(op, opts)
514 846baef9 Iustin Pop
515 846baef9 Iustin Pop
516 846baef9 Iustin Pop
def RemoveTags(opts, args):
517 846baef9 Iustin Pop
  """Remove tags from a given object.
518 846baef9 Iustin Pop

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

524 846baef9 Iustin Pop
  """
525 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
526 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
527 846baef9 Iustin Pop
  if not args:
528 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("No tags to be removed", errors.ECODE_INVAL)
529 3f0ab95f Iustin Pop
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
530 6bc3ed14 Michael Hanselmann
  SubmitOrSend(op, opts)
531 846baef9 Iustin Pop
532 a8083063 Iustin Pop
533 b459a848 Andrea Spadaccini
def check_unit(option, opt, value): # pylint: disable=W0613
534 65fe4693 Iustin Pop
  """OptParsers custom converter for units.
535 65fe4693 Iustin Pop

536 65fe4693 Iustin Pop
  """
537 a8083063 Iustin Pop
  try:
538 a8083063 Iustin Pop
    return utils.ParseUnit(value)
539 a8083063 Iustin Pop
  except errors.UnitParseError, err:
540 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
541 a8083063 Iustin Pop
542 a8083063 Iustin Pop
543 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
544 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
545 a8469393 Iustin Pop

546 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
547 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
548 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
549 a8469393 Iustin Pop
  have value=True.
550 a8469393 Iustin Pop

551 a8469393 Iustin Pop
  @type opt: string
552 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
553 a8469393 Iustin Pop
      data, used in building error messages
554 a8469393 Iustin Pop
  @type data: string
555 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
556 a8469393 Iustin Pop
  @rtype: dict
557 a8469393 Iustin Pop
  @return: {key=val, key=val}
558 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
559 a8469393 Iustin Pop

560 a8469393 Iustin Pop
  """
561 a8469393 Iustin Pop
  kv_dict = {}
562 4f31882e Guido Trotter
  if data:
563 1b3a7656 Iustin Pop
    for elem in utils.UnescapeAndSplit(data, sep=","):
564 4f31882e Guido Trotter
      if "=" in elem:
565 4f31882e Guido Trotter
        key, val = elem.split("=", 1)
566 a8469393 Iustin Pop
      else:
567 4f31882e Guido Trotter
        if elem.startswith(NO_PREFIX):
568 4f31882e Guido Trotter
          key, val = elem[len(NO_PREFIX):], False
569 4f31882e Guido Trotter
        elif elem.startswith(UN_PREFIX):
570 4f31882e Guido Trotter
          key, val = elem[len(UN_PREFIX):], None
571 4f31882e Guido Trotter
        else:
572 4f31882e Guido Trotter
          key, val = elem, True
573 4f31882e Guido Trotter
      if key in kv_dict:
574 4f31882e Guido Trotter
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
575 4f31882e Guido Trotter
                                    (key, opt))
576 4f31882e Guido Trotter
      kv_dict[key] = val
577 a8469393 Iustin Pop
  return kv_dict
578 a8469393 Iustin Pop
579 a8469393 Iustin Pop
580 b459a848 Andrea Spadaccini
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
581 552c8dff Michael Hanselmann
  """Custom parser for ident:key=val,key=val options.
582 552c8dff Michael Hanselmann

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

586 a8469393 Iustin Pop
  """
587 a8469393 Iustin Pop
  if ":" not in value:
588 d0c8c01d Iustin Pop
    ident, rest = value, ""
589 a8469393 Iustin Pop
  else:
590 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
591 8b46606c Guido Trotter
592 8b46606c Guido Trotter
  if ident.startswith(NO_PREFIX):
593 8b46606c Guido Trotter
    if rest:
594 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
595 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
596 8b46606c Guido Trotter
    retval = (ident[len(NO_PREFIX):], False)
597 956631b6 Michael Hanselmann
  elif (ident.startswith(UN_PREFIX) and
598 956631b6 Michael Hanselmann
        (len(ident) <= len(UN_PREFIX) or
599 956631b6 Michael Hanselmann
         not ident[len(UN_PREFIX)][0].isdigit())):
600 8b46606c Guido Trotter
    if rest:
601 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
602 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
603 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
604 8b46606c Guido Trotter
  else:
605 a8469393 Iustin Pop
    kv_dict = _SplitKeyVal(opt, rest)
606 a8469393 Iustin Pop
    retval = (ident, kv_dict)
607 a8469393 Iustin Pop
  return retval
608 a8469393 Iustin Pop
609 a8469393 Iustin Pop
610 b459a848 Andrea Spadaccini
def check_key_val(option, opt, value):  # pylint: disable=W0613
611 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
612 552c8dff Michael Hanselmann

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

615 a8469393 Iustin Pop
  """
616 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
617 a8469393 Iustin Pop
618 a8469393 Iustin Pop
619 b459a848 Andrea Spadaccini
def check_bool(option, opt, value): # pylint: disable=W0613
620 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
621 e7b61bb0 Iustin Pop

622 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
623 e7b61bb0 Iustin Pop

624 e7b61bb0 Iustin Pop
  """
625 e7b61bb0 Iustin Pop
  value = value.lower()
626 e7b61bb0 Iustin Pop
  if value == constants.VALUE_FALSE or value == "no":
627 e7b61bb0 Iustin Pop
    return False
628 e7b61bb0 Iustin Pop
  elif value == constants.VALUE_TRUE or value == "yes":
629 e7b61bb0 Iustin Pop
    return True
630 e7b61bb0 Iustin Pop
  else:
631 e7b61bb0 Iustin Pop
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
632 e7b61bb0 Iustin Pop
633 e7b61bb0 Iustin Pop
634 499eb088 Iustin Pop
def check_list(option, opt, value): # pylint: disable=W0613
635 499eb088 Iustin Pop
  """Custom parser for comma-separated lists.
636 499eb088 Iustin Pop

637 499eb088 Iustin Pop
  """
638 499eb088 Iustin Pop
  # we have to make this explicit check since "".split(",") is [""],
639 499eb088 Iustin Pop
  # not an empty list :(
640 499eb088 Iustin Pop
  if not value:
641 499eb088 Iustin Pop
    return []
642 499eb088 Iustin Pop
  else:
643 499eb088 Iustin Pop
    return utils.UnescapeAndSplit(value)
644 499eb088 Iustin Pop
645 499eb088 Iustin Pop
646 cd415612 René Nussbaumer
def check_maybefloat(option, opt, value): # pylint: disable=W0613
647 cd415612 René Nussbaumer
  """Custom parser for float numbers which might be also defaults.
648 cd415612 René Nussbaumer

649 cd415612 René Nussbaumer
  """
650 cd415612 René Nussbaumer
  value = value.lower()
651 cd415612 René Nussbaumer
652 cd415612 René Nussbaumer
  if value == constants.VALUE_DEFAULT:
653 cd415612 René Nussbaumer
    return value
654 cd415612 René Nussbaumer
  else:
655 cd415612 René Nussbaumer
    return float(value)
656 cd415612 René Nussbaumer
657 cd415612 René Nussbaumer
658 63d44c55 Michael Hanselmann
# completion_suggestion is normally a list. Using numeric values not evaluating
659 63d44c55 Michael Hanselmann
# to False for dynamic completion.
660 63d44c55 Michael Hanselmann
(OPT_COMPL_MANY_NODES,
661 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_NODE,
662 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_INSTANCE,
663 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_OS,
664 2d3ed64b Michael Hanselmann
 OPT_COMPL_ONE_IALLOCATOR,
665 9c784fb3 Dimitris Aragiorgis
 OPT_COMPL_ONE_NETWORK,
666 36e247e1 Guido Trotter
 OPT_COMPL_INST_ADD_NODES,
667 9c784fb3 Dimitris Aragiorgis
 OPT_COMPL_ONE_NODEGROUP) = range(100, 108)
668 63d44c55 Michael Hanselmann
669 63d44c55 Michael Hanselmann
OPT_COMPL_ALL = frozenset([
670 63d44c55 Michael Hanselmann
  OPT_COMPL_MANY_NODES,
671 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_NODE,
672 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_INSTANCE,
673 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_OS,
674 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_IALLOCATOR,
675 9c784fb3 Dimitris Aragiorgis
  OPT_COMPL_ONE_NETWORK,
676 2d3ed64b Michael Hanselmann
  OPT_COMPL_INST_ADD_NODES,
677 36e247e1 Guido Trotter
  OPT_COMPL_ONE_NODEGROUP,
678 63d44c55 Michael Hanselmann
  ])
679 63d44c55 Michael Hanselmann
680 63d44c55 Michael Hanselmann
681 552c8dff Michael Hanselmann
class CliOption(Option):
682 552c8dff Michael Hanselmann
  """Custom option class for optparse.
683 a8469393 Iustin Pop

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

1376 552328b8 Michael Hanselmann
  """
1377 552328b8 Michael Hanselmann
  value = _PRIONAME_TO_VALUE[value]
1378 552328b8 Michael Hanselmann
1379 552328b8 Michael Hanselmann
  setattr(parser.values, option.dest, value)
1380 552328b8 Michael Hanselmann
1381 552328b8 Michael Hanselmann
1382 84a5b33c Michael Hanselmann
PRIORITY_OPT = cli_option("--priority", default=None, dest="priority",
1383 84a5b33c Michael Hanselmann
                          metavar="|".join(name for name, _ in _PRIORITY_NAMES),
1384 84a5b33c Michael Hanselmann
                          choices=_PRIONAME_TO_VALUE.keys(),
1385 552328b8 Michael Hanselmann
                          action="callback", type="choice",
1386 552328b8 Michael Hanselmann
                          callback=_PriorityOptionCb,
1387 aa06f8c6 Michael Hanselmann
                          help="Priority for opcode processing")
1388 84a5b33c Michael Hanselmann
1389 61a14bb3 Iustin Pop
HID_OS_OPT = cli_option("--hidden", dest="hidden",
1390 61a14bb3 Iustin Pop
                        type="bool", default=None, metavar=_YORNO,
1391 61a14bb3 Iustin Pop
                        help="Sets the hidden flag on the OS")
1392 61a14bb3 Iustin Pop
1393 61a14bb3 Iustin Pop
BLK_OS_OPT = cli_option("--blacklisted", dest="blacklisted",
1394 61a14bb3 Iustin Pop
                        type="bool", default=None, metavar=_YORNO,
1395 61a14bb3 Iustin Pop
                        help="Sets the blacklisted flag on the OS")
1396 61a14bb3 Iustin Pop
1397 b883637f René Nussbaumer
PREALLOC_WIPE_DISKS_OPT = cli_option("--prealloc-wipe-disks", default=None,
1398 b883637f René Nussbaumer
                                     type="bool", metavar=_YORNO,
1399 b883637f René Nussbaumer
                                     dest="prealloc_wipe_disks",
1400 b883637f René Nussbaumer
                                     help=("Wipe disks prior to instance"
1401 b883637f René Nussbaumer
                                           " creation"))
1402 b883637f René Nussbaumer
1403 a535cef7 René Nussbaumer
NODE_PARAMS_OPT = cli_option("--node-parameters", dest="ndparams",
1404 3c2b6a98 René Nussbaumer
                             type="keyval", default=None,
1405 a535cef7 René Nussbaumer
                             help="Node parameters")
1406 a535cef7 René Nussbaumer
1407 90e99856 Adeodato Simo
ALLOC_POLICY_OPT = cli_option("--alloc-policy", dest="alloc_policy",
1408 90e99856 Adeodato Simo
                              action="store", metavar="POLICY", default=None,
1409 90e99856 Adeodato Simo
                              help="Allocation policy for the node group")
1410 90e99856 Adeodato Simo
1411 d2881c71 René Nussbaumer
NODE_POWERED_OPT = cli_option("--node-powered", default=None,
1412 d2881c71 René Nussbaumer
                              type="bool", metavar=_YORNO,
1413 d2881c71 René Nussbaumer
                              dest="node_powered",
1414 d2881c71 René Nussbaumer
                              help="Specify if the SoR for node is powered")
1415 d2881c71 René Nussbaumer
1416 41543d8b René Nussbaumer
OOB_TIMEOUT_OPT = cli_option("--oob-timeout", dest="oob_timeout", type="int",
1417 5ae4945a Iustin Pop
                             default=constants.OOB_TIMEOUT,
1418 5ae4945a Iustin Pop
                             help="Maximum time to wait for out-of-band helper")
1419 41543d8b René Nussbaumer
1420 0c086a13 René Nussbaumer
POWER_DELAY_OPT = cli_option("--power-delay", dest="power_delay", type="float",
1421 0c086a13 René Nussbaumer
                             default=constants.OOB_POWER_DELAY,
1422 0c086a13 René Nussbaumer
                             help="Time in seconds to wait between power-ons")
1423 0c086a13 René Nussbaumer
1424 442587bf Michael Hanselmann
FORCE_FILTER_OPT = cli_option("-F", "--filter", dest="force_filter",
1425 442587bf Michael Hanselmann
                              action="store_true", default=False,
1426 442587bf Michael Hanselmann
                              help=("Whether command argument should be treated"
1427 442587bf Michael Hanselmann
                                    " as filter"))
1428 442587bf Michael Hanselmann
1429 885a0fc4 Iustin Pop
NO_REMEMBER_OPT = cli_option("--no-remember",
1430 885a0fc4 Iustin Pop
                             dest="no_remember",
1431 885a0fc4 Iustin Pop
                             action="store_true", default=False,
1432 885a0fc4 Iustin Pop
                             help="Perform but do not record the change"
1433 885a0fc4 Iustin Pop
                             " in the configuration")
1434 885a0fc4 Iustin Pop
1435 aafee533 Michael Hanselmann
PRIMARY_ONLY_OPT = cli_option("-p", "--primary-only",
1436 aafee533 Michael Hanselmann
                              default=False, action="store_true",
1437 aafee533 Michael Hanselmann
                              help="Evacuate primary instances only")
1438 aafee533 Michael Hanselmann
1439 aafee533 Michael Hanselmann
SECONDARY_ONLY_OPT = cli_option("-s", "--secondary-only",
1440 aafee533 Michael Hanselmann
                                default=False, action="store_true",
1441 aafee533 Michael Hanselmann
                                help="Evacuate secondary instances only"
1442 aafee533 Michael Hanselmann
                                     " (applies only to internally mirrored"
1443 aafee533 Michael Hanselmann
                                     " disk templates, e.g. %s)" %
1444 aafee533 Michael Hanselmann
                                     utils.CommaJoin(constants.DTS_INT_MIRROR))
1445 aafee533 Michael Hanselmann
1446 323f9095 Stephen Shirley
STARTUP_PAUSED_OPT = cli_option("--paused", dest="startup_paused",
1447 323f9095 Stephen Shirley
                                action="store_true", default=False,
1448 323f9095 Stephen Shirley
                                help="Pause instance at startup")
1449 323f9095 Stephen Shirley
1450 f6eb380d Michael Hanselmann
TO_GROUP_OPT = cli_option("--to", dest="to", metavar="<group>",
1451 f6eb380d Michael Hanselmann
                          help="Destination node group (name or uuid)",
1452 f6eb380d Michael Hanselmann
                          default=None, action="append",
1453 f6eb380d Michael Hanselmann
                          completion_suggest=OPT_COMPL_ONE_NODEGROUP)
1454 f6eb380d Michael Hanselmann
1455 93f2399e Andrea Spadaccini
IGNORE_ERRORS_OPT = cli_option("-I", "--ignore-errors", default=[],
1456 93f2399e Andrea Spadaccini
                               action="append", dest="ignore_errors",
1457 93f2399e Andrea Spadaccini
                               choices=list(constants.CV_ALL_ECODES_STRINGS),
1458 93f2399e Andrea Spadaccini
                               help="Error code to be ignored")
1459 93f2399e Andrea Spadaccini
1460 38f29a36 René Nussbaumer
DISK_STATE_OPT = cli_option("--disk-state", default=[], dest="disk_state",
1461 38f29a36 René Nussbaumer
                            action="append",
1462 a1cef552 Iustin Pop
                            help=("Specify disk state information in the"
1463 a1cef552 Iustin Pop
                                  " format"
1464 a1cef552 Iustin Pop
                                  " storage_type/identifier:option=value,...;"
1465 a1cef552 Iustin Pop
                                  " note this is unused for now"),
1466 38f29a36 René Nussbaumer
                            type="identkeyval")
1467 38f29a36 René Nussbaumer
1468 38f29a36 René Nussbaumer
HV_STATE_OPT = cli_option("--hypervisor-state", default=[], dest="hv_state",
1469 38f29a36 René Nussbaumer
                          action="append",
1470 38f29a36 René Nussbaumer
                          help=("Specify hypervisor state information in the"
1471 a1cef552 Iustin Pop
                                " format hypervisor:option=value,...;"
1472 a1cef552 Iustin Pop
                                " note this is unused for now"),
1473 38f29a36 René Nussbaumer
                          type="identkeyval")
1474 38f29a36 René Nussbaumer
1475 b6aaf437 René Nussbaumer
IGNORE_IPOLICY_OPT = cli_option("--ignore-ipolicy", dest="ignore_ipolicy",
1476 b6aaf437 René Nussbaumer
                                action="store_true", default=False,
1477 b6aaf437 René Nussbaumer
                                help="Ignore instance policy violations")
1478 b6aaf437 René Nussbaumer
1479 2c0af7da Guido Trotter
RUNTIME_MEM_OPT = cli_option("-m", "--runtime-memory", dest="runtime_mem",
1480 2c0af7da Guido Trotter
                             help="Sets the instance's runtime memory,"
1481 2c0af7da Guido Trotter
                             " ballooning it up or down to the new value",
1482 2c0af7da Guido Trotter
                             default=None, type="unit", metavar="<size>")
1483 61a14bb3 Iustin Pop
1484 ef8270dc Iustin Pop
ABSOLUTE_OPT = cli_option("--absolute", dest="absolute",
1485 ef8270dc Iustin Pop
                          action="store_true", default=False,
1486 ef8270dc Iustin Pop
                          help="Marks the grow as absolute instead of the"
1487 ef8270dc Iustin Pop
                          " (default) relative mode")
1488 ef8270dc Iustin Pop
1489 9c784fb3 Dimitris Aragiorgis
NETWORK_OPT = cli_option("--network",
1490 9c784fb3 Dimitris Aragiorgis
                         action="store", default=None, dest="network",
1491 9c784fb3 Dimitris Aragiorgis
                         help="IP network in CIDR notation")
1492 9c784fb3 Dimitris Aragiorgis
1493 9c784fb3 Dimitris Aragiorgis
GATEWAY_OPT = cli_option("--gateway",
1494 9c784fb3 Dimitris Aragiorgis
                         action="store", default=None, dest="gateway",
1495 9c784fb3 Dimitris Aragiorgis
                         help="IP address of the router (gateway)")
1496 9c784fb3 Dimitris Aragiorgis
1497 9c784fb3 Dimitris Aragiorgis
ADD_RESERVED_IPS_OPT = cli_option("--add-reserved-ips",
1498 9c784fb3 Dimitris Aragiorgis
                                  action="store", default=None,
1499 9c784fb3 Dimitris Aragiorgis
                                  dest="add_reserved_ips",
1500 9c784fb3 Dimitris Aragiorgis
                                  help="Comma-separated list of"
1501 9c784fb3 Dimitris Aragiorgis
                                  " reserved IPs to add")
1502 9c784fb3 Dimitris Aragiorgis
1503 9c784fb3 Dimitris Aragiorgis
REMOVE_RESERVED_IPS_OPT = cli_option("--remove-reserved-ips",
1504 9c784fb3 Dimitris Aragiorgis
                                     action="store", default=None,
1505 9c784fb3 Dimitris Aragiorgis
                                     dest="remove_reserved_ips",
1506 9c784fb3 Dimitris Aragiorgis
                                     help="Comma-delimited list of"
1507 9c784fb3 Dimitris Aragiorgis
                                     " reserved IPs to remove")
1508 9c784fb3 Dimitris Aragiorgis
1509 9c784fb3 Dimitris Aragiorgis
NETWORK_TYPE_OPT = cli_option("--network-type",
1510 9c784fb3 Dimitris Aragiorgis
                              action="store", default=None, dest="network_type",
1511 9c784fb3 Dimitris Aragiorgis
                              help="Network type: private, public, None")
1512 9c784fb3 Dimitris Aragiorgis
1513 9c784fb3 Dimitris Aragiorgis
NETWORK6_OPT = cli_option("--network6",
1514 9c784fb3 Dimitris Aragiorgis
                          action="store", default=None, dest="network6",
1515 9c784fb3 Dimitris Aragiorgis
                          help="IP network in CIDR notation")
1516 9c784fb3 Dimitris Aragiorgis
1517 9c784fb3 Dimitris Aragiorgis
GATEWAY6_OPT = cli_option("--gateway6",
1518 9c784fb3 Dimitris Aragiorgis
                          action="store", default=None, dest="gateway6",
1519 9c784fb3 Dimitris Aragiorgis
                          help="IP6 address of the router (gateway)")
1520 9c784fb3 Dimitris Aragiorgis
1521 9c784fb3 Dimitris Aragiorgis
NOCONFLICTSCHECK_OPT = cli_option("--no-conflicts-check",
1522 9c784fb3 Dimitris Aragiorgis
                                  dest="conflicts_check",
1523 9c784fb3 Dimitris Aragiorgis
                                  default=True,
1524 9c784fb3 Dimitris Aragiorgis
                                  action="store_false",
1525 9c784fb3 Dimitris Aragiorgis
                                  help="Don't check for conflicting IPs")
1526 9c784fb3 Dimitris Aragiorgis
1527 5786c087 Michael Hanselmann
#: Options provided by all commands
1528 5786c087 Michael Hanselmann
COMMON_OPTS = [DEBUG_OPT]
1529 5786c087 Michael Hanselmann
1530 eb28ecf6 Guido Trotter
# common options for creating instances. add and import then add their own
1531 eb28ecf6 Guido Trotter
# specific ones.
1532 eb28ecf6 Guido Trotter
COMMON_CREATE_OPTS = [
1533 eb28ecf6 Guido Trotter
  BACKEND_OPT,
1534 eb28ecf6 Guido Trotter
  DISK_OPT,
1535 eb28ecf6 Guido Trotter
  DISK_TEMPLATE_OPT,
1536 eb28ecf6 Guido Trotter
  FILESTORE_DIR_OPT,
1537 eb28ecf6 Guido Trotter
  FILESTORE_DRIVER_OPT,
1538 eb28ecf6 Guido Trotter
  HYPERVISOR_OPT,
1539 eb28ecf6 Guido Trotter
  IALLOCATOR_OPT,
1540 eb28ecf6 Guido Trotter
  NET_OPT,
1541 eb28ecf6 Guido Trotter
  NODE_PLACEMENT_OPT,
1542 eb28ecf6 Guido Trotter
  NOIPCHECK_OPT,
1543 9c784fb3 Dimitris Aragiorgis
  NOCONFLICTSCHECK_OPT,
1544 eb28ecf6 Guido Trotter
  NONAMECHECK_OPT,
1545 eb28ecf6 Guido Trotter
  NONICS_OPT,
1546 eb28ecf6 Guido Trotter
  NWSYNC_OPT,
1547 eb28ecf6 Guido Trotter
  OSPARAMS_OPT,
1548 eb28ecf6 Guido Trotter
  OS_SIZE_OPT,
1549 eb28ecf6 Guido Trotter
  SUBMIT_OPT,
1550 0f8810df Michael Hanselmann
  TAG_ADD_OPT,
1551 eb28ecf6 Guido Trotter
  DRY_RUN_OPT,
1552 eb28ecf6 Guido Trotter
  PRIORITY_OPT,
1553 eb28ecf6 Guido Trotter
  ]
1554 eb28ecf6 Guido Trotter
1555 0ce212e5 Iustin Pop
# common instance policy options
1556 0ce212e5 Iustin Pop
INSTANCE_POLICY_OPTS = [
1557 0ce212e5 Iustin Pop
  SPECS_CPU_COUNT_OPT,
1558 0ce212e5 Iustin Pop
  SPECS_DISK_COUNT_OPT,
1559 0ce212e5 Iustin Pop
  SPECS_DISK_SIZE_OPT,
1560 0ce212e5 Iustin Pop
  SPECS_MEM_SIZE_OPT,
1561 0ce212e5 Iustin Pop
  SPECS_NIC_COUNT_OPT,
1562 d04c9d45 Iustin Pop
  IPOLICY_DISK_TEMPLATES,
1563 976b78ba Iustin Pop
  IPOLICY_VCPU_RATIO,
1564 ad5cc6bd René Nussbaumer
  IPOLICY_SPINDLE_RATIO,
1565 0ce212e5 Iustin Pop
  ]
1566 0ce212e5 Iustin Pop
1567 771734c9 Iustin Pop
1568 d971402f Michael Hanselmann
class _ShowUsage(Exception):
1569 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1570 d971402f Michael Hanselmann

1571 d971402f Michael Hanselmann
  """
1572 d971402f Michael Hanselmann
  def __init__(self, exit_error):
1573 d971402f Michael Hanselmann
    """Initializes instances of this class.
1574 d971402f Michael Hanselmann

1575 d971402f Michael Hanselmann
    @type exit_error: bool
1576 d971402f Michael Hanselmann
    @param exit_error: Whether to report failure on exit
1577 d971402f Michael Hanselmann

1578 d971402f Michael Hanselmann
    """
1579 d971402f Michael Hanselmann
    Exception.__init__(self)
1580 d971402f Michael Hanselmann
    self.exit_error = exit_error
1581 d971402f Michael Hanselmann
1582 d971402f Michael Hanselmann
1583 d971402f Michael Hanselmann
class _ShowVersion(Exception):
1584 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1585 d971402f Michael Hanselmann

1586 d971402f Michael Hanselmann
  """
1587 d971402f Michael Hanselmann
1588 d971402f Michael Hanselmann
1589 d971402f Michael Hanselmann
def _ParseArgs(binary, argv, commands, aliases, env_override):
1590 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1591 a8083063 Iustin Pop

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

1595 d971402f Michael Hanselmann
  @param binary: Script name
1596 d971402f Michael Hanselmann
  @param argv: Command line arguments
1597 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1598 d971402f Michael Hanselmann
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1599 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1600 d971402f Michael Hanselmann
  @raise _ShowUsage: If usage description should be shown
1601 d971402f Michael Hanselmann
  @raise _ShowVersion: If version should be shown
1602 098c0958 Michael Hanselmann

1603 a8083063 Iustin Pop
  """
1604 ef9fa5b9 René Nussbaumer
  assert not (env_override - set(commands))
1605 d971402f Michael Hanselmann
  assert not (set(aliases.keys()) & set(commands.keys()))
1606 ef9fa5b9 René Nussbaumer
1607 d971402f Michael Hanselmann
  if len(argv) > 1:
1608 d971402f Michael Hanselmann
    cmd = argv[1]
1609 a8083063 Iustin Pop
  else:
1610 d971402f Michael Hanselmann
    # No option or command given
1611 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1612 a8083063 Iustin Pop
1613 d971402f Michael Hanselmann
  if cmd == "--version":
1614 d971402f Michael Hanselmann
    raise _ShowVersion()
1615 d971402f Michael Hanselmann
  elif cmd == "--help":
1616 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=False)
1617 d971402f Michael Hanselmann
  elif not (cmd in commands or cmd in aliases):
1618 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1619 de47cf8f Guido Trotter
1620 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1621 de47cf8f Guido Trotter
  if cmd in aliases:
1622 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1623 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1624 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1625 de47cf8f Guido Trotter
1626 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1627 de47cf8f Guido Trotter
1628 ef9fa5b9 René Nussbaumer
  if cmd in env_override:
1629 ef9fa5b9 René Nussbaumer
    args_env_name = ("%s_%s" % (binary.replace("-", "_"), cmd)).upper()
1630 ef9fa5b9 René Nussbaumer
    env_args = os.environ.get(args_env_name)
1631 ef9fa5b9 René Nussbaumer
    if env_args:
1632 d971402f Michael Hanselmann
      argv = utils.InsertAtPos(argv, 2, shlex.split(env_args))
1633 ef9fa5b9 René Nussbaumer
1634 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1635 bf5338b3 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1636 bf5338b3 Michael Hanselmann
                        description=description,
1637 bf5338b3 Michael Hanselmann
                        formatter=TitledHelpFormatter(),
1638 bf5338b3 Michael Hanselmann
                        usage="%%prog %s %s" % (cmd, usage))
1639 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1640 d971402f Michael Hanselmann
  options, args = parser.parse_args(args=argv[2:])
1641 a8005e17 Michael Hanselmann
1642 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1643 a8083063 Iustin Pop
    return None, None, None
1644 a8083063 Iustin Pop
1645 a8083063 Iustin Pop
  return func, options, args
1646 a8083063 Iustin Pop
1647 a8083063 Iustin Pop
1648 d971402f Michael Hanselmann
def _FormatUsage(binary, commands):
1649 d971402f Michael Hanselmann
  """Generates a nice description of all commands.
1650 d971402f Michael Hanselmann

1651 d971402f Michael Hanselmann
  @param binary: Script name
1652 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1653 d971402f Michael Hanselmann

1654 d971402f Michael Hanselmann
  """
1655 d971402f Michael Hanselmann
  # compute the max line length for cmd + usage
1656 d971402f Michael Hanselmann
  mlen = min(60, max(map(len, commands)))
1657 d971402f Michael Hanselmann
1658 d971402f Michael Hanselmann
  yield "Usage: %s {command} [options...] [argument...]" % binary
1659 d971402f Michael Hanselmann
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1660 d971402f Michael Hanselmann
  yield ""
1661 d971402f Michael Hanselmann
  yield "Commands:"
1662 d971402f Michael Hanselmann
1663 d971402f Michael Hanselmann
  # and format a nice command list
1664 d971402f Michael Hanselmann
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1665 d971402f Michael Hanselmann
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1666 d971402f Michael Hanselmann
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1667 d971402f Michael Hanselmann
    for line in help_lines:
1668 d971402f Michael Hanselmann
      yield " %-*s   %s" % (mlen, "", line)
1669 d971402f Michael Hanselmann
1670 d971402f Michael Hanselmann
  yield ""
1671 d971402f Michael Hanselmann
1672 d971402f Michael Hanselmann
1673 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1674 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1675 a8005e17 Michael Hanselmann

1676 a8005e17 Michael Hanselmann
  Algorithm:
1677 a8005e17 Michael Hanselmann

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

1680 a8005e17 Michael Hanselmann
    1. For each argument in definition
1681 a8005e17 Michael Hanselmann

1682 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1683 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1684 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1685 a8005e17 Michael Hanselmann

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

1688 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1689 a8005e17 Michael Hanselmann

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

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

1694 a8005e17 Michael Hanselmann
  """
1695 a8005e17 Michael Hanselmann
  if args and not args_def:
1696 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1697 a8005e17 Michael Hanselmann
    return False
1698 a8005e17 Michael Hanselmann
1699 a8005e17 Michael Hanselmann
  min_count = None
1700 a8005e17 Michael Hanselmann
  max_count = None
1701 a8005e17 Michael Hanselmann
  check_max = None
1702 a8005e17 Michael Hanselmann
1703 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1704 a8005e17 Michael Hanselmann
1705 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1706 a8005e17 Michael Hanselmann
    if min_count is None:
1707 a8005e17 Michael Hanselmann
      min_count = arg.min
1708 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1709 a8005e17 Michael Hanselmann
      min_count += arg.min
1710 a8005e17 Michael Hanselmann
1711 a8005e17 Michael Hanselmann
    if max_count is None:
1712 a8005e17 Michael Hanselmann
      max_count = arg.max
1713 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1714 a8005e17 Michael Hanselmann
      max_count += arg.max
1715 a8005e17 Michael Hanselmann
1716 a8005e17 Michael Hanselmann
    if idx == last_idx:
1717 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1718 a8005e17 Michael Hanselmann
1719 a8005e17 Michael Hanselmann
    elif arg.max is None:
1720 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1721 a8005e17 Michael Hanselmann
1722 a8005e17 Michael Hanselmann
  if check_max:
1723 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1724 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1725 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1726 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1727 a8005e17 Michael Hanselmann
      return False
1728 a8005e17 Michael Hanselmann
1729 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1730 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1731 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1732 a8005e17 Michael Hanselmann
               cmd, max_count)
1733 a8005e17 Michael Hanselmann
      return False
1734 a8005e17 Michael Hanselmann
1735 a8005e17 Michael Hanselmann
  # Command with some required arguments
1736 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1737 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1738 a8005e17 Michael Hanselmann
             cmd, min_count)
1739 a8005e17 Michael Hanselmann
    return False
1740 a8005e17 Michael Hanselmann
1741 a8005e17 Michael Hanselmann
  return True
1742 a8005e17 Michael Hanselmann
1743 a8005e17 Michael Hanselmann
1744 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1745 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1746 60d49723 Michael Hanselmann

1747 60d49723 Michael Hanselmann
  """
1748 d0c8c01d Iustin Pop
  if value and ":" in value:
1749 d0c8c01d Iustin Pop
    return value.split(":", 1)
1750 60d49723 Michael Hanselmann
  else:
1751 60d49723 Michael Hanselmann
    return (value, None)
1752 60d49723 Michael Hanselmann
1753 60d49723 Michael Hanselmann
1754 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1755 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1756 07150497 Guido Trotter

1757 07150497 Guido Trotter
  @type os_name: string
1758 07150497 Guido Trotter
  @param os_name: base name of the os
1759 07150497 Guido Trotter
  @type os_variants: list or None
1760 07150497 Guido Trotter
  @param os_variants: list of supported variants
1761 07150497 Guido Trotter
  @rtype: list
1762 07150497 Guido Trotter
  @return: list of valid names
1763 07150497 Guido Trotter

1764 07150497 Guido Trotter
  """
1765 07150497 Guido Trotter
  if os_variants:
1766 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1767 07150497 Guido Trotter
  else:
1768 07150497 Guido Trotter
    return [os_name]
1769 07150497 Guido Trotter
1770 07150497 Guido Trotter
1771 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1772 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1773 a4ebd726 Michael Hanselmann

1774 a4ebd726 Michael Hanselmann
  @type selected: string or None
1775 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1776 a4ebd726 Michael Hanselmann
  @type default: list
1777 a4ebd726 Michael Hanselmann
  @param default: Default fields
1778 a4ebd726 Michael Hanselmann

1779 a4ebd726 Michael Hanselmann
  """
1780 a4ebd726 Michael Hanselmann
  if selected is None:
1781 a4ebd726 Michael Hanselmann
    return default
1782 a4ebd726 Michael Hanselmann
1783 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1784 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1785 a4ebd726 Michael Hanselmann
1786 a4ebd726 Michael Hanselmann
  return selected.split(",")
1787 a4ebd726 Michael Hanselmann
1788 a4ebd726 Michael Hanselmann
1789 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1790 4331f6cd Michael Hanselmann
1791 4331f6cd Michael Hanselmann
1792 47988778 Iustin Pop
def AskUser(text, choices=None):
1793 47988778 Iustin Pop
  """Ask the user a question.
1794 a8083063 Iustin Pop

1795 c41eea6e Iustin Pop
  @param text: the question to ask
1796 a8083063 Iustin Pop

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

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

1806 a8083063 Iustin Pop
  """
1807 47988778 Iustin Pop
  if choices is None:
1808 d0c8c01d Iustin Pop
    choices = [("y", True, "Perform the operation"),
1809 d0c8c01d Iustin Pop
               ("n", False, "Do not perform the operation")]
1810 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1811 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1812 47988778 Iustin Pop
  for entry in choices:
1813 d0c8c01d Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1814 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1815 47988778 Iustin Pop
1816 47988778 Iustin Pop
  answer = choices[-1][1]
1817 47988778 Iustin Pop
  new_text = []
1818 47988778 Iustin Pop
  for line in text.splitlines():
1819 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1820 47988778 Iustin Pop
  text = "\n".join(new_text)
1821 a8083063 Iustin Pop
  try:
1822 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1823 a8083063 Iustin Pop
  except IOError:
1824 47988778 Iustin Pop
    return answer
1825 a8083063 Iustin Pop
  try:
1826 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1827 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1828 d0c8c01d Iustin Pop
    chars.append("?")
1829 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1830 47988778 Iustin Pop
    while True:
1831 47988778 Iustin Pop
      f.write(text)
1832 d0c8c01d Iustin Pop
      f.write("\n")
1833 47988778 Iustin Pop
      f.write("/".join(chars))
1834 47988778 Iustin Pop
      f.write(": ")
1835 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1836 47988778 Iustin Pop
      if line in maps:
1837 47988778 Iustin Pop
        answer = maps[line]
1838 47988778 Iustin Pop
        break
1839 d0c8c01d Iustin Pop
      elif line == "?":
1840 47988778 Iustin Pop
        for entry in choices:
1841 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1842 47988778 Iustin Pop
        f.write("\n")
1843 47988778 Iustin Pop
        continue
1844 a8083063 Iustin Pop
  finally:
1845 a8083063 Iustin Pop
    f.close()
1846 a8083063 Iustin Pop
  return answer
1847 a8083063 Iustin Pop
1848 a8083063 Iustin Pop
1849 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1850 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1851 e9d741b6 Iustin Pop

1852 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1853 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1854 e9d741b6 Iustin Pop

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

1857 e9d741b6 Iustin Pop
  """
1858 e9d741b6 Iustin Pop
1859 e9d741b6 Iustin Pop
1860 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1861 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1862 a8083063 Iustin Pop

1863 0a1e74d9 Iustin Pop
  @type ops: list
1864 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1865 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1866 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1867 0a1e74d9 Iustin Pop
             if None, a new client will be created
1868 a8083063 Iustin Pop

1869 a8083063 Iustin Pop
  """
1870 e2212007 Iustin Pop
  if cl is None:
1871 b33e986b Iustin Pop
    cl = GetClient()
1872 685ee993 Iustin Pop
1873 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1874 0a1e74d9 Iustin Pop
1875 0a1e74d9 Iustin Pop
  return job_id
1876 0a1e74d9 Iustin Pop
1877 0a1e74d9 Iustin Pop
1878 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1879 4e338533 Michael Hanselmann
  """Generic job-polling function.
1880 0a1e74d9 Iustin Pop

1881 4e338533 Michael Hanselmann
  @type job_id: number
1882 4e338533 Michael Hanselmann
  @param job_id: Job ID
1883 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1884 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1885 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1886 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1887 0a1e74d9 Iustin Pop

1888 0a1e74d9 Iustin Pop
  """
1889 6c5a7090 Michael Hanselmann
  prev_job_info = None
1890 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1891 6c5a7090 Michael Hanselmann
1892 f4484122 Michael Hanselmann
  status = None
1893 f4484122 Michael Hanselmann
1894 685ee993 Iustin Pop
  while True:
1895 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1896 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
1897 6c5a7090 Michael Hanselmann
    if not result:
1898 685ee993 Iustin Pop
      # job not found, go away!
1899 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1900 4e338533 Michael Hanselmann
1901 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
1902 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
1903 f4484122 Michael Hanselmann
1904 f4484122 Michael Hanselmann
      # Wait again
1905 f4484122 Michael Hanselmann
      continue
1906 685ee993 Iustin Pop
1907 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1908 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1909 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1910 6c5a7090 Michael Hanselmann
1911 6c5a7090 Michael Hanselmann
    if log_entries:
1912 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1913 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
1914 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
1915 4e338533 Michael Hanselmann
                                    log_type, message)
1916 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1917 6c5a7090 Michael Hanselmann
1918 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1919 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1920 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1921 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1922 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1923 685ee993 Iustin Pop
      break
1924 6c5a7090 Michael Hanselmann
1925 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1926 685ee993 Iustin Pop
1927 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1928 0bbe448c Michael Hanselmann
  if not jobs:
1929 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1930 685ee993 Iustin Pop
1931 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1932 4e338533 Michael Hanselmann
1933 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1934 53c04d04 Iustin Pop
    return result
1935 4e338533 Michael Hanselmann
1936 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
1937 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1938 4e338533 Michael Hanselmann
1939 4e338533 Michael Hanselmann
  has_ok = False
1940 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
1941 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
1942 4e338533 Michael Hanselmann
      has_ok = True
1943 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
1944 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
1945 4e338533 Michael Hanselmann
1946 4e338533 Michael Hanselmann
      if has_ok:
1947 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
1948 4e338533 Michael Hanselmann
                                 (idx, msg))
1949 4e338533 Michael Hanselmann
1950 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
1951 4e338533 Michael Hanselmann
1952 4e338533 Michael Hanselmann
  # default failure mode
1953 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
1954 4e338533 Michael Hanselmann
1955 4e338533 Michael Hanselmann
1956 4e338533 Michael Hanselmann
class JobPollCbBase:
1957 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
1958 4e338533 Michael Hanselmann

1959 4e338533 Michael Hanselmann
  """
1960 4e338533 Michael Hanselmann
  def __init__(self):
1961 4e338533 Michael Hanselmann
    """Initializes this class.
1962 4e338533 Michael Hanselmann

1963 4e338533 Michael Hanselmann
    """
1964 4e338533 Michael Hanselmann
1965 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1966 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1967 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1968 4e338533 Michael Hanselmann

1969 4e338533 Michael Hanselmann
    """
1970 4e338533 Michael Hanselmann
    raise NotImplementedError()
1971 4e338533 Michael Hanselmann
1972 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
1973 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
1974 4e338533 Michael Hanselmann

1975 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
1976 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
1977 4e338533 Michael Hanselmann
    @type fields: list of strings
1978 4e338533 Michael Hanselmann
    @param fields: Fields
1979 4e338533 Michael Hanselmann

1980 4e338533 Michael Hanselmann
    """
1981 4e338533 Michael Hanselmann
    raise NotImplementedError()
1982 4e338533 Michael Hanselmann
1983 4e338533 Michael Hanselmann
1984 4e338533 Michael Hanselmann
class JobPollReportCbBase:
1985 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
1986 4e338533 Michael Hanselmann

1987 4e338533 Michael Hanselmann
  """
1988 4e338533 Michael Hanselmann
  def __init__(self):
1989 4e338533 Michael Hanselmann
    """Initializes this class.
1990 4e338533 Michael Hanselmann

1991 4e338533 Michael Hanselmann
    """
1992 4e338533 Michael Hanselmann
1993 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
1994 4e338533 Michael Hanselmann
    """Handles a log message.
1995 4e338533 Michael Hanselmann

1996 4e338533 Michael Hanselmann
    """
1997 4e338533 Michael Hanselmann
    raise NotImplementedError()
1998 4e338533 Michael Hanselmann
1999 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2000 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
2001 4e338533 Michael Hanselmann

2002 4e338533 Michael Hanselmann
    @type job_id: number
2003 4e338533 Michael Hanselmann
    @param job_id: Job ID
2004 4e338533 Michael Hanselmann
    @type status: string or None
2005 4e338533 Michael Hanselmann
    @param status: Job status if available
2006 4e338533 Michael Hanselmann

2007 4e338533 Michael Hanselmann
    """
2008 4e338533 Michael Hanselmann
    raise NotImplementedError()
2009 4e338533 Michael Hanselmann
2010 4e338533 Michael Hanselmann
2011 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
2012 4e338533 Michael Hanselmann
  def __init__(self, cl):
2013 4e338533 Michael Hanselmann
    """Initializes this class.
2014 4e338533 Michael Hanselmann

2015 4e338533 Michael Hanselmann
    """
2016 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
2017 4e338533 Michael Hanselmann
    self.cl = cl
2018 4e338533 Michael Hanselmann
2019 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2020 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2021 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2022 4e338533 Michael Hanselmann

2023 4e338533 Michael Hanselmann
    """
2024 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2025 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
2026 4e338533 Michael Hanselmann
2027 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2028 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2029 4e338533 Michael Hanselmann

2030 4e338533 Michael Hanselmann
    """
2031 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
2032 4e338533 Michael Hanselmann
2033 4e338533 Michael Hanselmann
2034 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2035 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
2036 4e338533 Michael Hanselmann
    """Initializes this class.
2037 4e338533 Michael Hanselmann

2038 4e338533 Michael Hanselmann
    """
2039 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2040 4e338533 Michael Hanselmann
2041 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
2042 4e338533 Michael Hanselmann
2043 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
2044 4e338533 Michael Hanselmann
2045 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2046 4e338533 Michael Hanselmann
    """Handles a log message.
2047 4e338533 Michael Hanselmann

2048 4e338533 Michael Hanselmann
    """
2049 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
2050 4e338533 Michael Hanselmann
2051 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2052 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2053 4e338533 Michael Hanselmann

2054 4e338533 Michael Hanselmann
    """
2055 4e338533 Michael Hanselmann
    # Ignore
2056 4e338533 Michael Hanselmann
2057 4e338533 Michael Hanselmann
2058 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
2059 4e338533 Michael Hanselmann
  def __init__(self):
2060 4e338533 Michael Hanselmann
    """Initializes this class.
2061 4e338533 Michael Hanselmann

2062 4e338533 Michael Hanselmann
    """
2063 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2064 4e338533 Michael Hanselmann
2065 4e338533 Michael Hanselmann
    self.notified_queued = False
2066 4e338533 Michael Hanselmann
    self.notified_waitlock = False
2067 4e338533 Michael Hanselmann
2068 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2069 4e338533 Michael Hanselmann
    """Handles a log message.
2070 4e338533 Michael Hanselmann

2071 4e338533 Michael Hanselmann
    """
2072 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2073 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
2074 4e338533 Michael Hanselmann
2075 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2076 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2077 4e338533 Michael Hanselmann

2078 4e338533 Michael Hanselmann
    """
2079 4e338533 Michael Hanselmann
    if status is None:
2080 4e338533 Michael Hanselmann
      return
2081 4e338533 Michael Hanselmann
2082 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2083 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
2084 4e338533 Michael Hanselmann
      self.notified_queued = True
2085 4e338533 Michael Hanselmann
2086 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2087 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2088 4e338533 Michael Hanselmann
      self.notified_waitlock = True
2089 4e338533 Michael Hanselmann
2090 4e338533 Michael Hanselmann
2091 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
2092 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
2093 8a7f1c61 Michael Hanselmann

2094 8a7f1c61 Michael Hanselmann
  """
2095 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
2096 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
2097 8a7f1c61 Michael Hanselmann
2098 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
2099 8a7f1c61 Michael Hanselmann
2100 8a7f1c61 Michael Hanselmann
2101 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2102 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
2103 4e338533 Michael Hanselmann

2104 4e338533 Michael Hanselmann
  @type job_id: job identified
2105 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
2106 4e338533 Michael Hanselmann
  @type cl: luxi.Client
2107 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
2108 4e338533 Michael Hanselmann
             if None, a new client will be created
2109 4e338533 Michael Hanselmann

2110 4e338533 Michael Hanselmann
  """
2111 4e338533 Michael Hanselmann
  if cl is None:
2112 4e338533 Michael Hanselmann
    cl = GetClient()
2113 4e338533 Michael Hanselmann
2114 583163a6 Michael Hanselmann
  if reporter is None:
2115 583163a6 Michael Hanselmann
    if feedback_fn:
2116 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2117 583163a6 Michael Hanselmann
    else:
2118 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
2119 583163a6 Michael Hanselmann
  elif feedback_fn:
2120 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2121 4e338533 Michael Hanselmann
2122 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2123 ceab32dd Iustin Pop
2124 ceab32dd Iustin Pop
2125 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2126 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
2127 0a1e74d9 Iustin Pop

2128 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
2129 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
2130 0a1e74d9 Iustin Pop
  interaction functions.
2131 0a1e74d9 Iustin Pop

2132 0a1e74d9 Iustin Pop
  """
2133 0a1e74d9 Iustin Pop
  if cl is None:
2134 0a1e74d9 Iustin Pop
    cl = GetClient()
2135 0a1e74d9 Iustin Pop
2136 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
2137 293ba2d8 Iustin Pop
2138 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
2139 0a1e74d9 Iustin Pop
2140 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2141 583163a6 Michael Hanselmann
                       reporter=reporter)
2142 53c04d04 Iustin Pop
2143 53c04d04 Iustin Pop
  return op_results[0]
2144 0a1e74d9 Iustin Pop
2145 0a1e74d9 Iustin Pop
2146 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2147 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
2148 94428652 Iustin Pop

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

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

2157 94428652 Iustin Pop
  """
2158 94428652 Iustin Pop
  if opts and opts.submit_only:
2159 293ba2d8 Iustin Pop
    job = [op]
2160 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
2161 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
2162 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
2163 94428652 Iustin Pop
  else:
2164 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2165 293ba2d8 Iustin Pop
2166 293ba2d8 Iustin Pop
2167 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
2168 293ba2d8 Iustin Pop
  """Processor for generic options.
2169 293ba2d8 Iustin Pop

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

2173 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
2174 293ba2d8 Iustin Pop
  @param options: command line options or None
2175 293ba2d8 Iustin Pop
  @return: None (in-place modification)
2176 293ba2d8 Iustin Pop

2177 293ba2d8 Iustin Pop
  """
2178 293ba2d8 Iustin Pop
  if not options:
2179 293ba2d8 Iustin Pop
    return
2180 293ba2d8 Iustin Pop
  for op in opcode_list:
2181 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
2182 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
2183 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
2184 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
2185 552328b8 Michael Hanselmann
      op.priority = options.priority
2186 94428652 Iustin Pop
2187 94428652 Iustin Pop
2188 42ab9ac4 Iustin Pop
def GetClient(query=False):
2189 42ab9ac4 Iustin Pop
  """Connects to the a luxi socket and returns a client.
2190 42ab9ac4 Iustin Pop

2191 42ab9ac4 Iustin Pop
  @type query: boolean
2192 42ab9ac4 Iustin Pop
  @param query: this signifies that the client will only be
2193 42ab9ac4 Iustin Pop
      used for queries; if the build-time parameter
2194 42ab9ac4 Iustin Pop
      enable-split-queries is enabled, then the client will be
2195 42ab9ac4 Iustin Pop
      connected to the query socket instead of the masterd socket
2196 42ab9ac4 Iustin Pop

2197 42ab9ac4 Iustin Pop
  """
2198 42ab9ac4 Iustin Pop
  if query and constants.ENABLE_SPLIT_QUERY:
2199 ee4a14c0 Michael Hanselmann
    address = pathutils.QUERY_SOCKET
2200 42ab9ac4 Iustin Pop
  else:
2201 42ab9ac4 Iustin Pop
    address = None
2202 af30b2fd Michael Hanselmann
  # TODO: Cache object?
2203 b33e986b Iustin Pop
  try:
2204 42ab9ac4 Iustin Pop
    client = luxi.Client(address=address)
2205 b33e986b Iustin Pop
  except luxi.NoMasterError:
2206 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
2207 d9a51679 Michael Hanselmann
2208 d9a51679 Michael Hanselmann
    # Try to read ssconf file
2209 d9a51679 Michael Hanselmann
    try:
2210 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
2211 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
2212 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2213 2cfbc784 Iustin Pop
                                 " not part of a cluster",
2214 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2215 d9a51679 Michael Hanselmann
2216 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2217 b33e986b Iustin Pop
    if master != myself:
2218 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
2219 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
2220 2cfbc784 Iustin Pop
                                 master, errors.ECODE_INVAL)
2221 d9a51679 Michael Hanselmann
    raise
2222 b33e986b Iustin Pop
  return client
2223 af30b2fd Michael Hanselmann
2224 af30b2fd Michael Hanselmann
2225 73702ee7 Iustin Pop
def FormatError(err):
2226 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
2227 73702ee7 Iustin Pop

2228 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
2229 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
2230 73702ee7 Iustin Pop
  second, a string describing the error message (not
2231 73702ee7 Iustin Pop
  newline-terminated).
2232 73702ee7 Iustin Pop

2233 73702ee7 Iustin Pop
  """
2234 73702ee7 Iustin Pop
  retcode = 1
2235 73702ee7 Iustin Pop
  obuf = StringIO()
2236 e2e521d0 Iustin Pop
  msg = str(err)
2237 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
2238 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
2239 46fbdd04 Iustin Pop
    logging.error(txt)
2240 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
2241 73702ee7 Iustin Pop
    obuf.write("Aborting.")
2242 73702ee7 Iustin Pop
    retcode = 2
2243 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
2244 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
2245 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
2246 73702ee7 Iustin Pop
      if out:
2247 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
2248 73702ee7 Iustin Pop
                   (node, script, out))
2249 73702ee7 Iustin Pop
      else:
2250 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
2251 73702ee7 Iustin Pop
                   (node, script))
2252 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
2253 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
2254 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
2255 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
2256 73702ee7 Iustin Pop
    if err.args[0] == this_host:
2257 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
2258 73702ee7 Iustin Pop
    else:
2259 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
2260 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
2261 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
2262 5c983ee5 Iustin Pop
    if len(err.args) == 2:
2263 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2264 5ae4945a Iustin Pop
                 " operation:\nerror type: %s, error details:\n%s" %
2265 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
2266 5c983ee5 Iustin Pop
    else:
2267 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2268 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
2269 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
2270 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
2271 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
2272 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
2273 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
2274 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
2275 686d7433 Iustin Pop
               " accept new requests\n")
2276 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
2277 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
2278 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
2279 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
2280 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
2281 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
2282 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
2283 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
2284 03a8dbdc Iustin Pop
    obuf.write("Cannot communicate with the master daemon.\nIs it running"
2285 082c5adb Michael Hanselmann
               " and listening for connections?")
2286 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
2287 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
2288 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
2289 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
2290 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
2291 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
2292 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
2293 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
2294 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
2295 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
2296 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
2297 03a8dbdc Iustin Pop
               "%s" % msg)
2298 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
2299 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
2300 cb1e6c3c Michael Hanselmann
  elif isinstance(err, errors.QueryFilterParseError):
2301 cb1e6c3c Michael Hanselmann
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
2302 cb1e6c3c Michael Hanselmann
    obuf.write("\n".join(err.GetDetails()))
2303 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
2304 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
2305 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
2306 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
2307 e9d741b6 Iustin Pop
    retcode = 0
2308 73702ee7 Iustin Pop
  else:
2309 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
2310 d0c8c01d Iustin Pop
  return retcode, obuf.getvalue().rstrip("\n")
2311 73702ee7 Iustin Pop
2312 73702ee7 Iustin Pop
2313 ef9fa5b9 René Nussbaumer
def GenericMain(commands, override=None, aliases=None,
2314 ef9fa5b9 René Nussbaumer
                env_override=frozenset()):
2315 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
2316 a8083063 Iustin Pop

2317 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2318 ef9fa5b9 René Nussbaumer
                   for command line handling.
2319 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2320 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2321 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2322 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2323 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2324 ef9fa5b9 René Nussbaumer
                       default args for commands
2325 a8083063 Iustin Pop

2326 a8083063 Iustin Pop
  """
2327 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
2328 a8083063 Iustin Pop
  if sys.argv:
2329 c1f19851 Michael Hanselmann
    binary = os.path.basename(sys.argv[0])
2330 c1f19851 Michael Hanselmann
    if not binary:
2331 c1f19851 Michael Hanselmann
      binary = sys.argv[0]
2332 c1f19851 Michael Hanselmann
2333 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
2334 c1f19851 Michael Hanselmann
      logname = utils.ShellQuoteArgs([binary, sys.argv[1]])
2335 a8083063 Iustin Pop
    else:
2336 c1f19851 Michael Hanselmann
      logname = binary
2337 c1f19851 Michael Hanselmann
2338 c1f19851 Michael Hanselmann
    cmdline = utils.ShellQuoteArgs([binary] + sys.argv[1:])
2339 a8083063 Iustin Pop
  else:
2340 a8083063 Iustin Pop
    binary = "<unknown program>"
2341 c1f19851 Michael Hanselmann
    cmdline = "<unknown>"
2342 a8083063 Iustin Pop
2343 de47cf8f Guido Trotter
  if aliases is None:
2344 de47cf8f Guido Trotter
    aliases = {}
2345 de47cf8f Guido Trotter
2346 3126878d Guido Trotter
  try:
2347 d971402f Michael Hanselmann
    (func, options, args) = _ParseArgs(binary, sys.argv, commands, aliases,
2348 d971402f Michael Hanselmann
                                       env_override)
2349 d971402f Michael Hanselmann
  except _ShowVersion:
2350 d971402f Michael Hanselmann
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
2351 d971402f Michael Hanselmann
             constants.RELEASE_VERSION)
2352 d971402f Michael Hanselmann
    return constants.EXIT_SUCCESS
2353 d971402f Michael Hanselmann
  except _ShowUsage, err:
2354 d971402f Michael Hanselmann
    for line in _FormatUsage(binary, commands):
2355 d971402f Michael Hanselmann
      ToStdout(line)
2356 d971402f Michael Hanselmann
2357 d971402f Michael Hanselmann
    if err.exit_error:
2358 d971402f Michael Hanselmann
      return constants.EXIT_FAILURE
2359 d971402f Michael Hanselmann
    else:
2360 d971402f Michael Hanselmann
      return constants.EXIT_SUCCESS
2361 3126878d Guido Trotter
  except errors.ParameterError, err:
2362 3126878d Guido Trotter
    result, err_msg = FormatError(err)
2363 3126878d Guido Trotter
    ToStderr(err_msg)
2364 3126878d Guido Trotter
    return 1
2365 3126878d Guido Trotter
2366 a8083063 Iustin Pop
  if func is None: # parse error
2367 a8083063 Iustin Pop
    return 1
2368 a8083063 Iustin Pop
2369 334d1483 Iustin Pop
  if override is not None:
2370 334d1483 Iustin Pop
    for key, val in override.iteritems():
2371 334d1483 Iustin Pop
      setattr(options, key, val)
2372 334d1483 Iustin Pop
2373 ee4a14c0 Michael Hanselmann
  utils.SetupLogging(pathutils.LOG_COMMANDS, logname, debug=options.debug,
2374 cfcc79c6 Michael Hanselmann
                     stderr_logging=True)
2375 a8083063 Iustin Pop
2376 c1f19851 Michael Hanselmann
  logging.info("Command line: %s", cmdline)
2377 a8083063 Iustin Pop
2378 a8083063 Iustin Pop
  try:
2379 a4af651e Iustin Pop
    result = func(options, args)
2380 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
2381 d8353c3a Iustin Pop
          JobSubmittedException), err:
2382 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
2383 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
2384 46fbdd04 Iustin Pop
    ToStderr(err_msg)
2385 8a53b55f Iustin Pop
  except KeyboardInterrupt:
2386 8a53b55f Iustin Pop
    result = constants.EXIT_FAILURE
2387 8a53b55f Iustin Pop
    ToStderr("Aborted. Note that if the operation created any jobs, they"
2388 8a53b55f Iustin Pop
             " might have been submitted and"
2389 8a53b55f Iustin Pop
             " will continue to run in the background.")
2390 225e2544 Iustin Pop
  except IOError, err:
2391 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
2392 225e2544 Iustin Pop
      # our terminal went away, we'll exit
2393 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
2394 225e2544 Iustin Pop
    else:
2395 225e2544 Iustin Pop
      raise
2396 a8083063 Iustin Pop
2397 a8083063 Iustin Pop
  return result
2398 137161c9 Michael Hanselmann
2399 137161c9 Michael Hanselmann
2400 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
2401 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
2402 845c79d8 Michael Hanselmann

2403 845c79d8 Michael Hanselmann
  """
2404 845c79d8 Michael Hanselmann
  try:
2405 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2406 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2407 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2408 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
2409 845c79d8 Michael Hanselmann
2410 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2411 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2412 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2413 845c79d8 Michael Hanselmann
2414 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2415 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2416 2cfbc784 Iustin Pop
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2417 845c79d8 Michael Hanselmann
2418 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2419 845c79d8 Michael Hanselmann
2420 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2421 845c79d8 Michael Hanselmann
2422 845c79d8 Michael Hanselmann
  return nics
2423 845c79d8 Michael Hanselmann
2424 845c79d8 Michael Hanselmann
2425 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2426 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2427 d77490c5 Iustin Pop

2428 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2429 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2430 d77490c5 Iustin Pop
  @type args: list
2431 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2432 d77490c5 Iustin Pop
  @rtype: int
2433 d77490c5 Iustin Pop
  @return: the desired exit code
2434 d77490c5 Iustin Pop

2435 d77490c5 Iustin Pop
  """
2436 d77490c5 Iustin Pop
  instance = args[0]
2437 d77490c5 Iustin Pop
2438 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
2439 d77490c5 Iustin Pop
2440 d77490c5 Iustin Pop
  hypervisor = None
2441 d77490c5 Iustin Pop
  hvparams = {}
2442 d77490c5 Iustin Pop
  if opts.hypervisor:
2443 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
2444 d77490c5 Iustin Pop
2445 d77490c5 Iustin Pop
  if opts.nics:
2446 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
2447 d77490c5 Iustin Pop
  elif opts.no_nics:
2448 d77490c5 Iustin Pop
    # no nics
2449 d77490c5 Iustin Pop
    nics = []
2450 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
2451 d77490c5 Iustin Pop
    # default of one nic, all auto
2452 d77490c5 Iustin Pop
    nics = [{}]
2453 0af0f641 Iustin Pop
  else:
2454 0af0f641 Iustin Pop
    # mode == import
2455 0af0f641 Iustin Pop
    nics = []
2456 d77490c5 Iustin Pop
2457 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
2458 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
2459 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
2460 2cfbc784 Iustin Pop
                                 " information passed", errors.ECODE_INVAL)
2461 d77490c5 Iustin Pop
    disks = []
2462 d77490c5 Iustin Pop
  else:
2463 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
2464 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
2465 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("No disk information specified",
2466 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2467 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
2468 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
2469 2cfbc784 Iustin Pop
                                 " '-s' option", errors.ECODE_INVAL)
2470 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2471 ccfa86ba Michael Hanselmann
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2472 9b12ed0f Iustin Pop
2473 9b12ed0f Iustin Pop
    if opts.disks:
2474 9b12ed0f Iustin Pop
      try:
2475 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2476 9b12ed0f Iustin Pop
      except ValueError, err:
2477 2cfbc784 Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
2478 2cfbc784 Iustin Pop
                                   errors.ECODE_INVAL)
2479 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2480 9b12ed0f Iustin Pop
    else:
2481 9b12ed0f Iustin Pop
      disks = []
2482 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2483 d77490c5 Iustin Pop
      didx = int(didx)
2484 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2485 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2486 2cfbc784 Iustin Pop
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
2487 ccfa86ba Michael Hanselmann
      elif constants.IDISK_SIZE in ddict:
2488 ccfa86ba Michael Hanselmann
        if constants.IDISK_ADOPT in ddict:
2489 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2490 2cfbc784 Iustin Pop
                                     " (disk %d)" % didx, errors.ECODE_INVAL)
2491 5029db65 Iustin Pop
        try:
2492 ccfa86ba Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
2493 ccfa86ba Michael Hanselmann
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2494 5029db65 Iustin Pop
        except ValueError, err:
2495 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2496 2cfbc784 Iustin Pop
                                     (didx, err), errors.ECODE_INVAL)
2497 ccfa86ba Michael Hanselmann
      elif constants.IDISK_ADOPT in ddict:
2498 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2499 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2500 2cfbc784 Iustin Pop
                                     " import", errors.ECODE_INVAL)
2501 ccfa86ba Michael Hanselmann
        ddict[constants.IDISK_SIZE] = 0
2502 5029db65 Iustin Pop
      else:
2503 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2504 2cfbc784 Iustin Pop
                                   " disk %d" % didx, errors.ECODE_INVAL)
2505 d77490c5 Iustin Pop
      disks[didx] = ddict
2506 d77490c5 Iustin Pop
2507 a57981c5 Apollon Oikonomopoulos
  if opts.tags is not None:
2508 0f8810df Michael Hanselmann
    tags = opts.tags.split(",")
2509 a57981c5 Apollon Oikonomopoulos
  else:
2510 a57981c5 Apollon Oikonomopoulos
    tags = []
2511 a57981c5 Apollon Oikonomopoulos
2512 b2e233a5 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT)
2513 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2514 d77490c5 Iustin Pop
2515 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2516 d77490c5 Iustin Pop
    start = opts.start
2517 d77490c5 Iustin Pop
    os_type = opts.os
2518 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2519 d77490c5 Iustin Pop
    src_node = None
2520 d77490c5 Iustin Pop
    src_path = None
2521 25a8792c Iustin Pop
    no_install = opts.no_install
2522 e588764d Iustin Pop
    identify_defaults = False
2523 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2524 d77490c5 Iustin Pop
    start = False
2525 d77490c5 Iustin Pop
    os_type = None
2526 1ee8e01a Guido Trotter
    force_variant = False
2527 d77490c5 Iustin Pop
    src_node = opts.src_node
2528 d77490c5 Iustin Pop
    src_path = opts.src_dir
2529 25a8792c Iustin Pop
    no_install = None
2530 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2531 d77490c5 Iustin Pop
  else:
2532 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2533 d77490c5 Iustin Pop
2534 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2535 d77490c5 Iustin Pop
                                disks=disks,
2536 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2537 d77490c5 Iustin Pop
                                nics=nics,
2538 d4117a72 Apollon Oikonomopoulos
                                conflicts_check=opts.conflicts_check,
2539 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2540 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2541 460d22be Iustin Pop
                                name_check=opts.name_check,
2542 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2543 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2544 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2545 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2546 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2547 d77490c5 Iustin Pop
                                hvparams=hvparams,
2548 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2549 062a7100 Iustin Pop
                                osparams=opts.osparams,
2550 d77490c5 Iustin Pop
                                mode=mode,
2551 d77490c5 Iustin Pop
                                start=start,
2552 d77490c5 Iustin Pop
                                os_type=os_type,
2553 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2554 d77490c5 Iustin Pop
                                src_node=src_node,
2555 25a8792c Iustin Pop
                                src_path=src_path,
2556 a57981c5 Apollon Oikonomopoulos
                                tags=tags,
2557 e588764d Iustin Pop
                                no_install=no_install,
2558 10889e0c René Nussbaumer
                                identify_defaults=identify_defaults,
2559 10889e0c René Nussbaumer
                                ignore_ipolicy=opts.ignore_ipolicy)
2560 d77490c5 Iustin Pop
2561 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2562 d77490c5 Iustin Pop
  return 0
2563 d77490c5 Iustin Pop
2564 d77490c5 Iustin Pop
2565 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2566 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2567 7e49b6ce Michael Hanselmann

2568 7e49b6ce Michael Hanselmann
  """
2569 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2570 7e49b6ce Michael Hanselmann
    """Initializes this class.
2571 7e49b6ce Michael Hanselmann

2572 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2573 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2574 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2575 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2576 7e49b6ce Michael Hanselmann
    @type master_node: string
2577 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2578 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2579 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2580 7e49b6ce Michael Hanselmann

2581 7e49b6ce Michael Hanselmann
    """
2582 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2583 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2584 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2585 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2586 7e49b6ce Michael Hanselmann
2587 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2588 7e49b6ce Michael Hanselmann
2589 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2590 7e49b6ce Michael Hanselmann
                            if name != master_node]
2591 7e49b6ce Michael Hanselmann
2592 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2593 7e49b6ce Michael Hanselmann
2594 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2595 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2596 7e49b6ce Michael Hanselmann

2597 7e49b6ce Michael Hanselmann
    @type node_name: string
2598 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2599 7e49b6ce Michael Hanselmann
    @type cmd: list
2600 7e49b6ce Michael Hanselmann
    @param cmd: Command
2601 7e49b6ce Michael Hanselmann

2602 7e49b6ce Michael Hanselmann
    """
2603 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2604 7e49b6ce Michael Hanselmann
      # No need to use SSH
2605 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2606 7e49b6ce Michael Hanselmann
    else:
2607 052783ff Michael Hanselmann
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2608 052783ff Michael Hanselmann
                            utils.ShellQuoteArgs(cmd))
2609 7e49b6ce Michael Hanselmann
2610 7e49b6ce Michael Hanselmann
    if result.failed:
2611 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2612 7e49b6ce Michael Hanselmann
      if node_name:
2613 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2614 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2615 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2616 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2617 7e49b6ce Michael Hanselmann
2618 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2619 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2620 7e49b6ce Michael Hanselmann

2621 7e49b6ce Michael Hanselmann
    @type fn: callable
2622 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2623 7e49b6ce Michael Hanselmann

2624 7e49b6ce Michael Hanselmann
    """
2625 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2626 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2627 ee4a14c0 Michael Hanselmann
    watcher_block = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
2628 7e49b6ce Michael Hanselmann
    try:
2629 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2630 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2631 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2632 7e49b6ce Michael Hanselmann
2633 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2634 7e49b6ce Michael Hanselmann
      # ones are finished
2635 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2636 ee4a14c0 Michael Hanselmann
      self._RunCmd(None, [pathutils.DAEMON_UTIL, "stop-master"])
2637 7e49b6ce Michael Hanselmann
      try:
2638 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2639 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2640 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2641 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "stop-all"])
2642 7e49b6ce Michael Hanselmann
2643 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2644 7e49b6ce Michael Hanselmann
        try:
2645 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2646 d512e84b Michael Hanselmann
        except Exception, err:
2647 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2648 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2649 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2650 7e49b6ce Michael Hanselmann
          raise
2651 7e49b6ce Michael Hanselmann
      finally:
2652 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2653 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2654 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2655 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "start-all"])
2656 7e49b6ce Michael Hanselmann
    finally:
2657 7e49b6ce Michael Hanselmann
      # Resume watcher
2658 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2659 7e49b6ce Michael Hanselmann
2660 7e49b6ce Michael Hanselmann
2661 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2662 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2663 7e49b6ce Michael Hanselmann

2664 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2665 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2666 7e49b6ce Michael Hanselmann
  @type fn: callable
2667 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2668 7e49b6ce Michael Hanselmann

2669 7e49b6ce Michael Hanselmann
  """
2670 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2671 7e49b6ce Michael Hanselmann
2672 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2673 7e49b6ce Michael Hanselmann
  cl = GetClient()
2674 7e49b6ce Michael Hanselmann
2675 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2676 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2677 7e49b6ce Michael Hanselmann
2678 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2679 7e49b6ce Michael Hanselmann
2680 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2681 7e49b6ce Michael Hanselmann
  del cl
2682 7e49b6ce Michael Hanselmann
2683 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2684 7e49b6ce Michael Hanselmann
2685 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2686 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2687 7e49b6ce Michael Hanselmann
2688 7e49b6ce Michael Hanselmann
2689 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2690 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2691 9fbfbb7b Iustin Pop
                  units=None):
2692 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2693 137161c9 Michael Hanselmann

2694 9fbfbb7b Iustin Pop
  @type headers: dict
2695 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2696 9fbfbb7b Iustin Pop
      the table
2697 9fbfbb7b Iustin Pop
  @type fields: list
2698 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2699 9fbfbb7b Iustin Pop
      the data field
2700 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2701 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2702 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2703 9fbfbb7b Iustin Pop
      each field
2704 9fbfbb7b Iustin Pop
  @type data: list
2705 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2706 9fbfbb7b Iustin Pop
  @type numfields: list
2707 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2708 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2709 9fbfbb7b Iustin Pop
  @type unitfields: list
2710 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2711 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2712 9fbfbb7b Iustin Pop
  @type units: string or None
2713 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2714 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2715 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2716 137161c9 Michael Hanselmann

2717 137161c9 Michael Hanselmann
  """
2718 9fbfbb7b Iustin Pop
  if units is None:
2719 9fbfbb7b Iustin Pop
    if separator:
2720 9fbfbb7b Iustin Pop
      units = "m"
2721 9fbfbb7b Iustin Pop
    else:
2722 9fbfbb7b Iustin Pop
      units = "h"
2723 9fbfbb7b Iustin Pop
2724 137161c9 Michael Hanselmann
  if numfields is None:
2725 137161c9 Michael Hanselmann
    numfields = []
2726 137161c9 Michael Hanselmann
  if unitfields is None:
2727 137161c9 Michael Hanselmann
    unitfields = []
2728 137161c9 Michael Hanselmann
2729 b459a848 Andrea Spadaccini
  numfields = utils.FieldSet(*numfields)   # pylint: disable=W0142
2730 b459a848 Andrea Spadaccini
  unitfields = utils.FieldSet(*unitfields) # pylint: disable=W0142
2731 00430f8e Iustin Pop
2732 137161c9 Michael Hanselmann
  format_fields = []
2733 137161c9 Michael Hanselmann
  for field in fields:
2734 01ca31ae Iustin Pop
    if headers and field not in headers:
2735 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2736 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2737 71c1af58 Iustin Pop
      # variable fields)
2738 71c1af58 Iustin Pop
      headers[field] = field
2739 137161c9 Michael Hanselmann
    if separator is not None:
2740 137161c9 Michael Hanselmann
      format_fields.append("%s")
2741 00430f8e Iustin Pop
    elif numfields.Matches(field):
2742 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2743 137161c9 Michael Hanselmann
    else:
2744 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2745 137161c9 Michael Hanselmann
2746 137161c9 Michael Hanselmann
  if separator is None:
2747 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2748 d0c8c01d Iustin Pop
    format_str = " ".join(format_fields)
2749 137161c9 Michael Hanselmann
  else:
2750 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2751 137161c9 Michael Hanselmann
2752 137161c9 Michael Hanselmann
  for row in data:
2753 dcbd6288 Guido Trotter
    if row is None:
2754 dcbd6288 Guido Trotter
      continue
2755 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2756 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2757 137161c9 Michael Hanselmann
        try:
2758 137161c9 Michael Hanselmann
          val = int(val)
2759 691744c4 Iustin Pop
        except (TypeError, ValueError):
2760 137161c9 Michael Hanselmann
          pass
2761 137161c9 Michael Hanselmann
        else:
2762 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2763 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2764 137161c9 Michael Hanselmann
      if separator is None:
2765 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2766 137161c9 Michael Hanselmann
2767 16be8703 Iustin Pop
  result = []
2768 137161c9 Michael Hanselmann
  if headers:
2769 137161c9 Michael Hanselmann
    args = []
2770 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2771 137161c9 Michael Hanselmann
      hdr = headers[name]
2772 137161c9 Michael Hanselmann
      if separator is None:
2773 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2774 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2775 137161c9 Michael Hanselmann
      args.append(hdr)
2776 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2777 137161c9 Michael Hanselmann
2778 ec39d63c Michael Hanselmann
  if separator is None:
2779 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2780 ec39d63c Michael Hanselmann
2781 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2782 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2783 ec39d63c Michael Hanselmann
2784 137161c9 Michael Hanselmann
  for line in data:
2785 137161c9 Michael Hanselmann
    args = []
2786 dcbd6288 Guido Trotter
    if line is None:
2787 d0c8c01d Iustin Pop
      line = ["-" for _ in fields]
2788 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2789 137161c9 Michael Hanselmann
      if separator is None:
2790 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2791 137161c9 Michael Hanselmann
      args.append(line[idx])
2792 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2793 16be8703 Iustin Pop
2794 16be8703 Iustin Pop
  return result
2795 3386e7a9 Iustin Pop
2796 3386e7a9 Iustin Pop
2797 ee3aedff Michael Hanselmann
def _FormatBool(value):
2798 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
2799 ee3aedff Michael Hanselmann

2800 ee3aedff Michael Hanselmann
  """
2801 ee3aedff Michael Hanselmann
  if value:
2802 ee3aedff Michael Hanselmann
    return "Y"
2803 ee3aedff Michael Hanselmann
  return "N"
2804 ee3aedff Michael Hanselmann
2805 ee3aedff Michael Hanselmann
2806 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2807 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2808 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2809 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2810 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2811 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2812 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2813 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2814 ee3aedff Michael Hanselmann
  }
2815 ee3aedff Michael Hanselmann
2816 ee3aedff Michael Hanselmann
2817 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2818 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2819 ee3aedff Michael Hanselmann

2820 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2821 ee3aedff Michael Hanselmann
  @type override: dict
2822 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2823 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2824 ee3aedff Michael Hanselmann
  @type unit: string
2825 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2826 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2827 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2828 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2829 ee3aedff Michael Hanselmann

2830 ee3aedff Michael Hanselmann
  """
2831 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2832 ee3aedff Michael Hanselmann
  if fmt is not None:
2833 ee3aedff Michael Hanselmann
    return fmt
2834 ee3aedff Michael Hanselmann
2835 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2836 ee3aedff Michael Hanselmann
2837 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2838 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2839 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2840 ee3aedff Michael Hanselmann
2841 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2842 ee3aedff Michael Hanselmann
  if fmt is not None:
2843 ee3aedff Michael Hanselmann
    return fmt
2844 ee3aedff Michael Hanselmann
2845 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
2846 ee3aedff Michael Hanselmann
2847 ee3aedff Michael Hanselmann
2848 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
2849 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
2850 ee3aedff Michael Hanselmann

2851 ee3aedff Michael Hanselmann
  """
2852 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
2853 ee3aedff Michael Hanselmann
    """Initializes this class.
2854 ee3aedff Michael Hanselmann

2855 ee3aedff Michael Hanselmann
    @type fn: callable
2856 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2857 ee3aedff Michael Hanselmann
    @type status_fn: callable
2858 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
2859 f0b1bafe Iustin Pop
    @type verbose: boolean
2860 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
2861 ee3aedff Michael Hanselmann

2862 ee3aedff Michael Hanselmann
    """
2863 ee3aedff Michael Hanselmann
    self._fn = fn
2864 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
2865 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
2866 ee3aedff Michael Hanselmann
2867 ee3aedff Michael Hanselmann
  def __call__(self, data):
2868 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
2869 ee3aedff Michael Hanselmann

2870 ee3aedff Michael Hanselmann
    """
2871 ee3aedff Michael Hanselmann
    (status, value) = data
2872 ee3aedff Michael Hanselmann
2873 ee3aedff Michael Hanselmann
    # Report status
2874 ee3aedff Michael Hanselmann
    self._status_fn(status)
2875 ee3aedff Michael Hanselmann
2876 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
2877 ee3aedff Michael Hanselmann
      return self._fn(value)
2878 ee3aedff Michael Hanselmann
2879 ee3aedff Michael Hanselmann
    assert value is None, \
2880 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
2881 ee3aedff Michael Hanselmann
2882 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
2883 ee3aedff Michael Hanselmann
2884 ee3aedff Michael Hanselmann
2885 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
2886 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
2887 ee3aedff Michael Hanselmann

2888 ae95e419 René Nussbaumer
  @param status: The result status
2889 f2c6673d Michael Hanselmann
  @type verbose: boolean
2890 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
2891 ae95e419 René Nussbaumer
  @return: Text of result status
2892 a6070ef7 Michael Hanselmann

2893 ae95e419 René Nussbaumer
  """
2894 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
2895 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
2896 ae95e419 René Nussbaumer
  try:
2897 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
2898 ae95e419 René Nussbaumer
  except KeyError:
2899 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
2900 cbfa4f0f Michael Hanselmann
  else:
2901 cbfa4f0f Michael Hanselmann
    if verbose:
2902 cbfa4f0f Michael Hanselmann
      return verbose_text
2903 cbfa4f0f Michael Hanselmann
    return normal_text
2904 ee3aedff Michael Hanselmann
2905 ee3aedff Michael Hanselmann
2906 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
2907 f0b1bafe Iustin Pop
                      header=False, verbose=False):
2908 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
2909 ee3aedff Michael Hanselmann

2910 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
2911 ee3aedff Michael Hanselmann
  @param result: result of query operation
2912 ee3aedff Michael Hanselmann
  @type unit: string
2913 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
2914 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
2915 ee3aedff Michael Hanselmann
  @type format_override: dict
2916 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2917 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2918 ee3aedff Michael Hanselmann
  @type separator: string or None
2919 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2920 ee3aedff Michael Hanselmann
  @type header: bool
2921 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
2922 f0b1bafe Iustin Pop
  @type verbose: boolean
2923 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2924 ee3aedff Michael Hanselmann

2925 ee3aedff Michael Hanselmann
  """
2926 ee3aedff Michael Hanselmann
  if unit is None:
2927 ee3aedff Michael Hanselmann
    if separator:
2928 ee3aedff Michael Hanselmann
      unit = "m"
2929 ee3aedff Michael Hanselmann
    else:
2930 ee3aedff Michael Hanselmann
      unit = "h"
2931 ee3aedff Michael Hanselmann
2932 ee3aedff Michael Hanselmann
  if format_override is None:
2933 ee3aedff Michael Hanselmann
    format_override = {}
2934 ee3aedff Michael Hanselmann
2935 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
2936 ee3aedff Michael Hanselmann
2937 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
2938 ee3aedff Michael Hanselmann
    if status in stats:
2939 ee3aedff Michael Hanselmann
      stats[status] += 1
2940 ee3aedff Michael Hanselmann
2941 ee3aedff Michael Hanselmann
  columns = []
2942 ee3aedff Michael Hanselmann
  for fdef in result.fields:
2943 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
2944 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
2945 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
2946 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
2947 f0b1bafe Iustin Pop
                                                     verbose),
2948 ee3aedff Michael Hanselmann
                               align_right))
2949 ee3aedff Michael Hanselmann
2950 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
2951 ee3aedff Michael Hanselmann
2952 ee3aedff Michael Hanselmann
  # Collect statistics
2953 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
2954 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
2955 ee3aedff Michael Hanselmann
2956 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
2957 ee3aedff Michael Hanselmann
  # detected via the field definitions.
2958 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
2959 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
2960 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
2961 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
2962 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
2963 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
2964 ee3aedff Michael Hanselmann
  else:
2965 ee3aedff Michael Hanselmann
    status = QR_NORMAL
2966 ee3aedff Michael Hanselmann
2967 ee3aedff Michael Hanselmann
  return (status, table)
2968 ee3aedff Michael Hanselmann
2969 ee3aedff Michael Hanselmann
2970 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
2971 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
2972 ee3aedff Michael Hanselmann

2973 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2974 ee3aedff Michael Hanselmann

2975 ee3aedff Michael Hanselmann
  """
2976 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
2977 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
2978 ee3aedff Michael Hanselmann
2979 ee3aedff Michael Hanselmann
2980 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
2981 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
2982 ee3aedff Michael Hanselmann

2983 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
2984 ee3aedff Michael Hanselmann

2985 ee3aedff Michael Hanselmann
  """
2986 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
2987 ee3aedff Michael Hanselmann
  if unknown:
2988 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
2989 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
2990 ee3aedff Michael Hanselmann
    return True
2991 ee3aedff Michael Hanselmann
2992 ee3aedff Michael Hanselmann
  return False
2993 ee3aedff Michael Hanselmann
2994 ee3aedff Michael Hanselmann
2995 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
2996 03ec545a Michael Hanselmann
                format_override=None, verbose=False, force_filter=False,
2997 6f287cf3 Iustin Pop
                namefield=None, qfilter=None, isnumeric=False):
2998 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
2999 ee3aedff Michael Hanselmann

3000 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3001 ee3aedff Michael Hanselmann
  @type fields: list of strings
3002 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3003 ee3aedff Michael Hanselmann
  @type names: list of strings
3004 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
3005 ee3aedff Michael Hanselmann
  @type unit: string or None
3006 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3007 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
3008 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
3009 ee3aedff Michael Hanselmann
  @type separator: string or None
3010 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3011 ee3aedff Michael Hanselmann
  @type header: bool
3012 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3013 2928de47 Michael Hanselmann
  @type force_filter: bool
3014 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
3015 ee3aedff Michael Hanselmann
  @type format_override: dict
3016 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3017 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3018 f0b1bafe Iustin Pop
  @type verbose: boolean
3019 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3020 03ec545a Michael Hanselmann
  @type namefield: string
3021 03ec545a Michael Hanselmann
  @param namefield: Name of field to use for simple filters (see
3022 03ec545a Michael Hanselmann
    L{qlang.MakeFilter} for details)
3023 f037e9d7 Michael Hanselmann
  @type qfilter: list or None
3024 f037e9d7 Michael Hanselmann
  @param qfilter: Query filter (in addition to names)
3025 6f287cf3 Iustin Pop
  @param isnumeric: bool
3026 6f287cf3 Iustin Pop
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3027 6f287cf3 Iustin Pop
    any simple filters built by namefield should use integer values to
3028 6f287cf3 Iustin Pop
    reflect that
3029 ee3aedff Michael Hanselmann

3030 ee3aedff Michael Hanselmann
  """
3031 ee3aedff Michael Hanselmann
  if not names:
3032 ee3aedff Michael Hanselmann
    names = None
3033 ee3aedff Michael Hanselmann
3034 6f287cf3 Iustin Pop
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3035 6f287cf3 Iustin Pop
                                isnumeric=isnumeric)
3036 f037e9d7 Michael Hanselmann
3037 f037e9d7 Michael Hanselmann
  if qfilter is None:
3038 f037e9d7 Michael Hanselmann
    qfilter = namefilter
3039 f037e9d7 Michael Hanselmann
  elif namefilter is not None:
3040 f037e9d7 Michael Hanselmann
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3041 2928de47 Michael Hanselmann
3042 727274dd Iustin Pop
  if cl is None:
3043 727274dd Iustin Pop
    cl = GetClient()
3044 727274dd Iustin Pop
3045 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
3046 ee3aedff Michael Hanselmann
3047 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3048 ee3aedff Michael Hanselmann
3049 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3050 ee3aedff Michael Hanselmann
                                     header=header,
3051 f0b1bafe Iustin Pop
                                     format_override=format_override,
3052 f0b1bafe Iustin Pop
                                     verbose=verbose)
3053 ee3aedff Michael Hanselmann
3054 ee3aedff Michael Hanselmann
  for line in data:
3055 ee3aedff Michael Hanselmann
    ToStdout(line)
3056 ee3aedff Michael Hanselmann
3057 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
3058 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
3059 ee3aedff Michael Hanselmann
3060 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
3061 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3062 ee3aedff Michael Hanselmann
3063 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
3064 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3065 ee3aedff Michael Hanselmann
3066 ee3aedff Michael Hanselmann
3067 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
3068 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
3069 ee3aedff Michael Hanselmann

3070 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3071 ee3aedff Michael Hanselmann
  @type fields: list of strings
3072 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3073 ee3aedff Michael Hanselmann
  @type separator: string or None
3074 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3075 ee3aedff Michael Hanselmann
  @type header: bool
3076 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3077 ee3aedff Michael Hanselmann

3078 ee3aedff Michael Hanselmann
  """
3079 ee3aedff Michael Hanselmann
  if cl is None:
3080 ee3aedff Michael Hanselmann
    cl = GetClient()
3081 ee3aedff Michael Hanselmann
3082 ee3aedff Michael Hanselmann
  if not fields:
3083 ee3aedff Michael Hanselmann
    fields = None
3084 ee3aedff Michael Hanselmann
3085 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
3086 ee3aedff Michael Hanselmann
3087 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3088 ee3aedff Michael Hanselmann
3089 ee3aedff Michael Hanselmann
  columns = [
3090 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
3091 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
3092 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
3093 ee3aedff Michael Hanselmann
    ]
3094 ee3aedff Michael Hanselmann
3095 ea1440c1 Michael Hanselmann
  rows = [[fdef.name, fdef.title, fdef.doc] for fdef in response.fields]
3096 ee3aedff Michael Hanselmann
3097 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
3098 ee3aedff Michael Hanselmann
    ToStdout(line)
3099 ee3aedff Michael Hanselmann
3100 ee3aedff Michael Hanselmann
  if found_unknown:
3101 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3102 ee3aedff Michael Hanselmann
3103 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3104 ee3aedff Michael Hanselmann
3105 ee3aedff Michael Hanselmann
3106 ee3aedff Michael Hanselmann
class TableColumn:
3107 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
3108 ee3aedff Michael Hanselmann

3109 ee3aedff Michael Hanselmann
  """
3110 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
3111 ee3aedff Michael Hanselmann
    """Initializes this class.
3112 ee3aedff Michael Hanselmann

3113 ee3aedff Michael Hanselmann
    @type title: string
3114 ee3aedff Michael Hanselmann
    @param title: Column title
3115 ee3aedff Michael Hanselmann
    @type fn: callable
3116 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3117 ee3aedff Michael Hanselmann
    @type align_right: bool
3118 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
3119 ee3aedff Michael Hanselmann

3120 ee3aedff Michael Hanselmann
    """
3121 ee3aedff Michael Hanselmann
    self.title = title
3122 ee3aedff Michael Hanselmann
    self.format = fn
3123 ee3aedff Michael Hanselmann
    self.align_right = align_right
3124 ee3aedff Michael Hanselmann
3125 ee3aedff Michael Hanselmann
3126 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
3127 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
3128 ee3aedff Michael Hanselmann

3129 ee3aedff Michael Hanselmann
  """
3130 ee3aedff Michael Hanselmann
  if align_right:
3131 ee3aedff Michael Hanselmann
    sign = ""
3132 ee3aedff Michael Hanselmann
  else:
3133 ee3aedff Michael Hanselmann
    sign = "-"
3134 ee3aedff Michael Hanselmann
3135 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
3136 ee3aedff Michael Hanselmann
3137 ee3aedff Michael Hanselmann
3138 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
3139 ee3aedff Michael Hanselmann
  """Formats data as a table.
3140 ee3aedff Michael Hanselmann

3141 ee3aedff Michael Hanselmann
  @type rows: list of lists
3142 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
3143 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
3144 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
3145 ee3aedff Michael Hanselmann
  @type header: bool
3146 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3147 ee3aedff Michael Hanselmann
  @type separator: string or None
3148 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
3149 ee3aedff Michael Hanselmann

3150 ee3aedff Michael Hanselmann
  """
3151 ee3aedff Michael Hanselmann
  if header:
3152 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
3153 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
3154 ee3aedff Michael Hanselmann
  else:
3155 ee3aedff Michael Hanselmann
    data = []
3156 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
3157 ee3aedff Michael Hanselmann
3158 ee3aedff Michael Hanselmann
  # Format row data
3159 ee3aedff Michael Hanselmann
  for row in rows:
3160 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
3161 ee3aedff Michael Hanselmann
3162 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
3163 ee3aedff Michael Hanselmann
3164 ee3aedff Michael Hanselmann
    if separator is None:
3165 ee3aedff Michael Hanselmann
      # Update column widths
3166 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3167 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
3168 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
3169 ee3aedff Michael Hanselmann
3170 ee3aedff Michael Hanselmann
    data.append(formatted)
3171 ee3aedff Michael Hanselmann
3172 ee3aedff Michael Hanselmann
  if separator is not None:
3173 ee3aedff Michael Hanselmann
    # Return early if a separator is used
3174 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
3175 ee3aedff Michael Hanselmann
3176 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
3177 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
3178 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
3179 ee3aedff Michael Hanselmann
3180 ee3aedff Michael Hanselmann
  # Build format string
3181 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3182 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
3183 ee3aedff Michael Hanselmann
3184 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
3185 ee3aedff Michael Hanselmann
3186 ee3aedff Michael Hanselmann
3187 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
3188 3386e7a9 Iustin Pop
  """Formats a given timestamp.
3189 3386e7a9 Iustin Pop

3190 3386e7a9 Iustin Pop
  @type ts: timestamp
3191 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3192 3386e7a9 Iustin Pop

3193 3386e7a9 Iustin Pop
  @rtype: string
3194 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
3195 3386e7a9 Iustin Pop

3196 3386e7a9 Iustin Pop
  """
3197 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3198 d0c8c01d Iustin Pop
    return "?"
3199 26a72a48 Michael Hanselmann
3200 26a72a48 Michael Hanselmann
  (sec, usecs) = ts
3201 26a72a48 Michael Hanselmann
  return utils.FormatTime(sec, usecs=usecs)
3202 2241e2b9 Iustin Pop
3203 2241e2b9 Iustin Pop
3204 2241e2b9 Iustin Pop
def ParseTimespec(value):
3205 2241e2b9 Iustin Pop
  """Parse a time specification.
3206 2241e2b9 Iustin Pop

3207 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
3208 2241e2b9 Iustin Pop

3209 2241e2b9 Iustin Pop
    - s: seconds
3210 2241e2b9 Iustin Pop
    - m: minutes
3211 2241e2b9 Iustin Pop
    - h: hours
3212 2241e2b9 Iustin Pop
    - d: day
3213 2241e2b9 Iustin Pop
    - w: weeks
3214 2241e2b9 Iustin Pop

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

3217 2241e2b9 Iustin Pop
  """
3218 2241e2b9 Iustin Pop
  value = str(value)
3219 2241e2b9 Iustin Pop
  if not value:
3220 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed",
3221 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
3222 2241e2b9 Iustin Pop
  suffix_map = {
3223 d0c8c01d Iustin Pop
    "s": 1,
3224 d0c8c01d Iustin Pop
    "m": 60,
3225 d0c8c01d Iustin Pop
    "h": 3600,
3226 d0c8c01d Iustin Pop
    "d": 86400,
3227 d0c8c01d Iustin Pop
    "w": 604800,
3228 2241e2b9 Iustin Pop
    }
3229 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
3230 2241e2b9 Iustin Pop
    try:
3231 2241e2b9 Iustin Pop
      value = int(value)
3232 691744c4 Iustin Pop
    except (TypeError, ValueError):
3233 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3234 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3235 2241e2b9 Iustin Pop
  else:
3236 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
3237 2241e2b9 Iustin Pop
    value = value[:-1]
3238 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
3239 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
3240 2cfbc784 Iustin Pop
                                 " suffix passed)", errors.ECODE_INVAL)
3241 2241e2b9 Iustin Pop
    try:
3242 2241e2b9 Iustin Pop
      value = int(value) * multiplier
3243 691744c4 Iustin Pop
    except (TypeError, ValueError):
3244 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3245 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3246 2241e2b9 Iustin Pop
  return value
3247 46fbdd04 Iustin Pop
3248 46fbdd04 Iustin Pop
3249 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3250 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
3251 4040a784 Iustin Pop
  """Returns the names of online nodes.
3252 4040a784 Iustin Pop

3253 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
3254 4040a784 Iustin Pop
  the online nodes.
3255 4040a784 Iustin Pop

3256 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
3257 4040a784 Iustin Pop
      offline ones)
3258 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
3259 4040a784 Iustin Pop
  @type nowarn: boolean
3260 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
3261 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
3262 4040a784 Iustin Pop
      note is not displayed
3263 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
3264 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
3265 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
3266 e9e26bb3 Iustin Pop
      (if any)
3267 e9e26bb3 Iustin Pop
  @type filter_master: boolean
3268 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
3269 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
3270 e9e26bb3 Iustin Pop
      node name against the list)
3271 05484a24 Michael Hanselmann
  @type nodegroup: string
3272 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
3273 4040a784 Iustin Pop

3274 4040a784 Iustin Pop
  """
3275 4040a784 Iustin Pop
  if cl is None:
3276 4040a784 Iustin Pop
    cl = GetClient()
3277 4040a784 Iustin Pop
3278 2e5c33db Iustin Pop
  qfilter = []
3279 05484a24 Michael Hanselmann
3280 05484a24 Michael Hanselmann
  if nodes:
3281 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3282 05484a24 Michael Hanselmann
3283 05484a24 Michael Hanselmann
  if nodegroup is not None:
3284 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3285 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3286 e9e26bb3 Iustin Pop
3287 e9e26bb3 Iustin Pop
  if filter_master:
3288 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3289 05484a24 Michael Hanselmann
3290 2e5c33db Iustin Pop
  if qfilter:
3291 2e5c33db Iustin Pop
    if len(qfilter) > 1:
3292 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
3293 05484a24 Michael Hanselmann
    else:
3294 2e5c33db Iustin Pop
      assert len(qfilter) == 1
3295 2e5c33db Iustin Pop
      final_filter = qfilter[0]
3296 e9e26bb3 Iustin Pop
  else:
3297 05484a24 Michael Hanselmann
    final_filter = None
3298 05484a24 Michael Hanselmann
3299 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3300 05484a24 Michael Hanselmann
3301 05484a24 Michael Hanselmann
  def _IsOffline(row):
3302 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
3303 05484a24 Michael Hanselmann
    return offline
3304 05484a24 Michael Hanselmann
3305 05484a24 Michael Hanselmann
  def _GetName(row):
3306 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
3307 05484a24 Michael Hanselmann
    return name
3308 05484a24 Michael Hanselmann
3309 05484a24 Michael Hanselmann
  def _GetSip(row):
3310 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
3311 05484a24 Michael Hanselmann
    return sip
3312 05484a24 Michael Hanselmann
3313 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
3314 e9e26bb3 Iustin Pop
3315 4040a784 Iustin Pop
  if offline and not nowarn:
3316 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
3317 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
3318 05484a24 Michael Hanselmann
3319 05484a24 Michael Hanselmann
  if secondary_ips:
3320 05484a24 Michael Hanselmann
    fn = _GetSip
3321 05484a24 Michael Hanselmann
  else:
3322 05484a24 Michael Hanselmann
    fn = _GetName
3323 05484a24 Michael Hanselmann
3324 05484a24 Michael Hanselmann
  return map(fn, online)
3325 4040a784 Iustin Pop
3326 4040a784 Iustin Pop
3327 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3328 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3329 46fbdd04 Iustin Pop

3330 46fbdd04 Iustin Pop
  @type stream: file object
3331 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3332 46fbdd04 Iustin Pop
  @type txt: str
3333 46fbdd04 Iustin Pop
  @param txt: the message
3334 46fbdd04 Iustin Pop

3335 46fbdd04 Iustin Pop
  """
3336 225e2544 Iustin Pop
  try:
3337 225e2544 Iustin Pop
    if args:
3338 225e2544 Iustin Pop
      args = tuple(args)
3339 225e2544 Iustin Pop
      stream.write(txt % args)
3340 225e2544 Iustin Pop
    else:
3341 225e2544 Iustin Pop
      stream.write(txt)
3342 d0c8c01d Iustin Pop
    stream.write("\n")
3343 225e2544 Iustin Pop
    stream.flush()
3344 225e2544 Iustin Pop
  except IOError, err:
3345 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3346 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3347 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3348 225e2544 Iustin Pop
    else:
3349 225e2544 Iustin Pop
      raise
3350 46fbdd04 Iustin Pop
3351 46fbdd04 Iustin Pop
3352 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3353 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3354 46fbdd04 Iustin Pop

3355 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3356 46fbdd04 Iustin Pop

3357 46fbdd04 Iustin Pop
  @type txt: str
3358 46fbdd04 Iustin Pop
  @param txt: the message
3359 46fbdd04 Iustin Pop

3360 46fbdd04 Iustin Pop
  """
3361 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3362 46fbdd04 Iustin Pop
3363 46fbdd04 Iustin Pop
3364 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3365 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3366 46fbdd04 Iustin Pop

3367 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3368 46fbdd04 Iustin Pop

3369 46fbdd04 Iustin Pop
  @type txt: str
3370 46fbdd04 Iustin Pop
  @param txt: the message
3371 46fbdd04 Iustin Pop

3372 46fbdd04 Iustin Pop
  """
3373 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3374 479636a3 Iustin Pop
3375 479636a3 Iustin Pop
3376 479636a3 Iustin Pop
class JobExecutor(object):
3377 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3378 479636a3 Iustin Pop

3379 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3380 479636a3 Iustin Pop
  GetResults() calls.
3381 479636a3 Iustin Pop

3382 479636a3 Iustin Pop
  """
3383 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3384 479636a3 Iustin Pop
    self.queue = []
3385 479636a3 Iustin Pop
    if cl is None:
3386 479636a3 Iustin Pop
      cl = GetClient()
3387 479636a3 Iustin Pop
    self.cl = cl
3388 479636a3 Iustin Pop
    self.verbose = verbose
3389 23b4b983 Iustin Pop
    self.jobs = []
3390 cff5fa7f Iustin Pop
    self.opts = opts
3391 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3392 60452edf Michael Hanselmann
    self._counter = itertools.count()
3393 479636a3 Iustin Pop
3394 8d99a8bf Michael Hanselmann
  @staticmethod
3395 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3396 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3397 8d99a8bf Michael Hanselmann

3398 8d99a8bf Michael Hanselmann
    """
3399 8d99a8bf Michael Hanselmann
    if name:
3400 8d99a8bf Michael Hanselmann
      return fmt % name
3401 8d99a8bf Michael Hanselmann
3402 8d99a8bf Michael Hanselmann
    return ""
3403 8d99a8bf Michael Hanselmann
3404 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3405 23b4b983 Iustin Pop
    """Record a job for later submit.
3406 479636a3 Iustin Pop

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

3410 479636a3 Iustin Pop
    """
3411 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3412 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3413 23b4b983 Iustin Pop
3414 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3415 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3416 8d99a8bf Michael Hanselmann

3417 8d99a8bf Michael Hanselmann
    """
3418 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3419 8d99a8bf Michael Hanselmann
3420 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3421 23b4b983 Iustin Pop
    """Submit all pending jobs.
3422 23b4b983 Iustin Pop

3423 23b4b983 Iustin Pop
    """
3424 66ecc479 Guido Trotter
    if each:
3425 66ecc479 Guido Trotter
      results = []
3426 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3427 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3428 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3429 519fafa1 Andrea Spadaccini
        results.append([True, self.cl.SubmitJob(ops)[0]])
3430 66ecc479 Guido Trotter
    else:
3431 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3432 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3433 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3434 5299e61f Iustin Pop
3435 5299e61f Iustin Pop
  def _ChooseJob(self):
3436 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3437 5299e61f Iustin Pop

3438 5299e61f Iustin Pop
    """
3439 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3440 5299e61f Iustin Pop
3441 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3442 11705e3d Iustin Pop
                               ["status"])
3443 5299e61f Iustin Pop
    assert result
3444 5299e61f Iustin Pop
3445 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3446 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3447 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3448 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3449 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3450 91c622a8 Iustin Pop
        # job is still present and waiting
3451 5299e61f Iustin Pop
        continue
3452 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3453 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3454 5299e61f Iustin Pop
      return job_data
3455 5299e61f Iustin Pop
3456 5299e61f Iustin Pop
    # no job found
3457 5299e61f Iustin Pop
    return self.jobs.pop(0)
3458 479636a3 Iustin Pop
3459 479636a3 Iustin Pop
  def GetResults(self):
3460 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3461 479636a3 Iustin Pop

3462 479636a3 Iustin Pop
    @rtype: list
3463 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3464 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3465 479636a3 Iustin Pop
        there will be the error message
3466 479636a3 Iustin Pop

3467 479636a3 Iustin Pop
    """
3468 23b4b983 Iustin Pop
    if not self.jobs:
3469 23b4b983 Iustin Pop
      self.SubmitPending()
3470 479636a3 Iustin Pop
    results = []
3471 479636a3 Iustin Pop
    if self.verbose:
3472 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3473 23b4b983 Iustin Pop
      if ok_jobs:
3474 4474f112 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3475 5299e61f Iustin Pop
3476 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
3477 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3478 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
3479 4474f112 Iustin Pop
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3480 c63355f2 Iustin Pop
      results.append((idx, False, jid))
3481 5299e61f Iustin Pop
3482 5299e61f Iustin Pop
    while self.jobs:
3483 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
3484 4474f112 Iustin Pop
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3485 479636a3 Iustin Pop
      try:
3486 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3487 479636a3 Iustin Pop
        success = True
3488 91c622a8 Iustin Pop
      except errors.JobLost, err:
3489 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3490 4474f112 Iustin Pop
        ToStderr("Job %s%s has been archived, cannot check its result",
3491 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"))
3492 91c622a8 Iustin Pop
        success = False
3493 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3494 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3495 479636a3 Iustin Pop
        success = False
3496 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3497 4474f112 Iustin Pop
        ToStderr("Job %s%s has failed: %s",
3498 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"), job_result)
3499 479636a3 Iustin Pop
3500 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3501 5299e61f Iustin Pop
3502 5299e61f Iustin Pop
    # sort based on the index, then drop it
3503 5299e61f Iustin Pop
    results.sort()
3504 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3505 5299e61f Iustin Pop
3506 479636a3 Iustin Pop
    return results
3507 479636a3 Iustin Pop
3508 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3509 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3510 479636a3 Iustin Pop

3511 479636a3 Iustin Pop
    @type wait: boolean
3512 479636a3 Iustin Pop
    @param wait: whether to wait or not
3513 479636a3 Iustin Pop

3514 479636a3 Iustin Pop
    """
3515 479636a3 Iustin Pop
    if wait:
3516 479636a3 Iustin Pop
      return self.GetResults()
3517 479636a3 Iustin Pop
    else:
3518 23b4b983 Iustin Pop
      if not self.jobs:
3519 23b4b983 Iustin Pop
        self.SubmitPending()
3520 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3521 23b4b983 Iustin Pop
        if status:
3522 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3523 23b4b983 Iustin Pop
        else:
3524 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3525 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3526 acd19189 René Nussbaumer
3527 acd19189 René Nussbaumer
3528 acd19189 René Nussbaumer
def FormatParameterDict(buf, param_dict, actual, level=1):
3529 acd19189 René Nussbaumer
  """Formats a parameter dictionary.
3530 acd19189 René Nussbaumer

3531 acd19189 René Nussbaumer
  @type buf: L{StringIO}
3532 acd19189 René Nussbaumer
  @param buf: the buffer into which to write
3533 acd19189 René Nussbaumer
  @type param_dict: dict
3534 acd19189 René Nussbaumer
  @param param_dict: the own parameters
3535 acd19189 René Nussbaumer
  @type actual: dict
3536 acd19189 René Nussbaumer
  @param actual: the current parameter set (including defaults)
3537 acd19189 René Nussbaumer
  @param level: Level of indent
3538 acd19189 René Nussbaumer

3539 acd19189 René Nussbaumer
  """
3540 acd19189 René Nussbaumer
  indent = "  " * level
3541 64da5a53 René Nussbaumer
3542 acd19189 René Nussbaumer
  for key in sorted(actual):
3543 64da5a53 René Nussbaumer
    data = actual[key]
3544 64da5a53 René Nussbaumer
    buf.write("%s- %s:" % (indent, key))
3545 64da5a53 René Nussbaumer
3546 64da5a53 René Nussbaumer
    if isinstance(data, dict) and data:
3547 64da5a53 René Nussbaumer
      buf.write("\n")
3548 64da5a53 René Nussbaumer
      FormatParameterDict(buf, param_dict.get(key, {}), data,
3549 64da5a53 René Nussbaumer
                          level=level + 1)
3550 64da5a53 René Nussbaumer
    else:
3551 64da5a53 René Nussbaumer
      val = param_dict.get(key, "default (%s)" % data)
3552 64da5a53 René Nussbaumer
      buf.write(" %s\n" % val)
3553 25bd815c René Nussbaumer
3554 25bd815c René Nussbaumer
3555 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3556 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3557 25bd815c René Nussbaumer

3558 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3559 25bd815c René Nussbaumer
  on a given list of list_type.
3560 25bd815c René Nussbaumer

3561 25bd815c René Nussbaumer
  @type names: list
3562 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3563 25bd815c René Nussbaumer
      we ask for confirmation
3564 25bd815c René Nussbaumer
  @type list_type: str
3565 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3566 25bd815c René Nussbaumer
  @type text: str
3567 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3568 25bd815c René Nussbaumer
  @rtype: boolean
3569 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3570 25bd815c René Nussbaumer

3571 25bd815c René Nussbaumer
  """
3572 25bd815c René Nussbaumer
  count = len(names)
3573 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3574 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3575 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3576 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3577 25bd815c René Nussbaumer
3578 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3579 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3580 25bd815c René Nussbaumer
3581 25bd815c René Nussbaumer
  if count > 20:
3582 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3583 25bd815c René Nussbaumer
    question = msg
3584 25bd815c René Nussbaumer
  else:
3585 25bd815c René Nussbaumer
    question = msg + affected
3586 25bd815c René Nussbaumer
3587 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3588 25bd815c René Nussbaumer
  if choice == "v":
3589 25bd815c René Nussbaumer
    choices.pop(1)
3590 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3591 25bd815c René Nussbaumer
  return choice
3592 703fa9ab Iustin Pop
3593 703fa9ab Iustin Pop
3594 cd415612 René Nussbaumer
def _MaybeParseUnit(elements):
3595 cd415612 René Nussbaumer
  """Parses and returns an array of potential values with units.
3596 cd415612 René Nussbaumer

3597 cd415612 René Nussbaumer
  """
3598 ef40c537 René Nussbaumer
  parsed = {}
3599 ef40c537 René Nussbaumer
  for k, v in elements.items():
3600 ef40c537 René Nussbaumer
    if v == constants.VALUE_DEFAULT:
3601 ef40c537 René Nussbaumer
      parsed[k] = v
3602 cd415612 René Nussbaumer
    else:
3603 ef40c537 René Nussbaumer
      parsed[k] = utils.ParseUnit(v)
3604 cd415612 René Nussbaumer
  return parsed
3605 cd415612 René Nussbaumer
3606 cd415612 René Nussbaumer
3607 703fa9ab Iustin Pop
def CreateIPolicyFromOpts(ispecs_mem_size=None,
3608 703fa9ab Iustin Pop
                          ispecs_cpu_count=None,
3609 703fa9ab Iustin Pop
                          ispecs_disk_count=None,
3610 703fa9ab Iustin Pop
                          ispecs_disk_size=None,
3611 703fa9ab Iustin Pop
                          ispecs_nic_count=None,
3612 703fa9ab Iustin Pop
                          ipolicy_disk_templates=None,
3613 703fa9ab Iustin Pop
                          ipolicy_vcpu_ratio=None,
3614 ad5cc6bd René Nussbaumer
                          ipolicy_spindle_ratio=None,
3615 703fa9ab Iustin Pop
                          group_ipolicy=False,
3616 703fa9ab Iustin Pop
                          allowed_values=None,
3617 703fa9ab Iustin Pop
                          fill_all=False):
3618 703fa9ab Iustin Pop
  """Creation of instance policy based on command line options.
3619 703fa9ab Iustin Pop

3620 703fa9ab Iustin Pop
  @param fill_all: whether for cluster policies we should ensure that
3621 703fa9ab Iustin Pop
    all values are filled
3622 703fa9ab Iustin Pop

3623 703fa9ab Iustin Pop

3624 703fa9ab Iustin Pop
  """
3625 d67e0a94 Iustin Pop
  try:
3626 d67e0a94 Iustin Pop
    if ispecs_mem_size:
3627 cd415612 René Nussbaumer
      ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
3628 d67e0a94 Iustin Pop
    if ispecs_disk_size:
3629 cd415612 René Nussbaumer
      ispecs_disk_size = _MaybeParseUnit(ispecs_disk_size)
3630 d67e0a94 Iustin Pop
  except (TypeError, ValueError, errors.UnitParseError), err:
3631 d67e0a94 Iustin Pop
    raise errors.OpPrereqError("Invalid disk (%s) or memory (%s) size"
3632 d67e0a94 Iustin Pop
                               " in policy: %s" %
3633 d67e0a94 Iustin Pop
                               (ispecs_disk_size, ispecs_mem_size, err),
3634 d67e0a94 Iustin Pop
                               errors.ECODE_INVAL)
3635 d67e0a94 Iustin Pop
3636 703fa9ab Iustin Pop
  # prepare ipolicy dict
3637 703fa9ab Iustin Pop
  ipolicy_transposed = {
3638 703fa9ab Iustin Pop
    constants.ISPEC_MEM_SIZE: ispecs_mem_size,
3639 703fa9ab Iustin Pop
    constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
3640 703fa9ab Iustin Pop
    constants.ISPEC_DISK_COUNT: ispecs_disk_count,
3641 703fa9ab Iustin Pop
    constants.ISPEC_DISK_SIZE: ispecs_disk_size,
3642 703fa9ab Iustin Pop
    constants.ISPEC_NIC_COUNT: ispecs_nic_count,
3643 703fa9ab Iustin Pop
    }
3644 703fa9ab Iustin Pop
3645 703fa9ab Iustin Pop
  # first, check that the values given are correct
3646 703fa9ab Iustin Pop
  if group_ipolicy:
3647 703fa9ab Iustin Pop
    forced_type = TISPECS_GROUP_TYPES
3648 703fa9ab Iustin Pop
  else:
3649 703fa9ab Iustin Pop
    forced_type = TISPECS_CLUSTER_TYPES
3650 703fa9ab Iustin Pop
3651 703fa9ab Iustin Pop
  for specs in ipolicy_transposed.values():
3652 703fa9ab Iustin Pop
    utils.ForceDictType(specs, forced_type, allowed_values=allowed_values)
3653 703fa9ab Iustin Pop
3654 703fa9ab Iustin Pop
  # then transpose
3655 703fa9ab Iustin Pop
  ipolicy_out = objects.MakeEmptyIPolicy()
3656 703fa9ab Iustin Pop
  for name, specs in ipolicy_transposed.iteritems():
3657 703fa9ab Iustin Pop
    assert name in constants.ISPECS_PARAMETERS
3658 703fa9ab Iustin Pop
    for key, val in specs.items(): # {min: .. ,max: .., std: ..}
3659 703fa9ab Iustin Pop
      ipolicy_out[key][name] = val
3660 703fa9ab Iustin Pop
3661 703fa9ab Iustin Pop
  # no filldict for non-dicts
3662 703fa9ab Iustin Pop
  if not group_ipolicy and fill_all:
3663 703fa9ab Iustin Pop
    if ipolicy_disk_templates is None:
3664 703fa9ab Iustin Pop
      ipolicy_disk_templates = constants.DISK_TEMPLATES
3665 703fa9ab Iustin Pop
    if ipolicy_vcpu_ratio is None:
3666 703fa9ab Iustin Pop
      ipolicy_vcpu_ratio = \
3667 703fa9ab Iustin Pop
        constants.IPOLICY_DEFAULTS[constants.IPOLICY_VCPU_RATIO]
3668 ad5cc6bd René Nussbaumer
    if ipolicy_spindle_ratio is None:
3669 ad5cc6bd René Nussbaumer
      ipolicy_spindle_ratio = \
3670 ad5cc6bd René Nussbaumer
        constants.IPOLICY_DEFAULTS[constants.IPOLICY_SPINDLE_RATIO]
3671 703fa9ab Iustin Pop
  if ipolicy_disk_templates is not None:
3672 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
3673 703fa9ab Iustin Pop
  if ipolicy_vcpu_ratio is not None:
3674 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
3675 ad5cc6bd René Nussbaumer
  if ipolicy_spindle_ratio is not None:
3676 ad5cc6bd René Nussbaumer
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
3677 703fa9ab Iustin Pop
3678 703fa9ab Iustin Pop
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
3679 703fa9ab Iustin Pop
3680 703fa9ab Iustin Pop
  return ipolicy_out