Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 66af5ec5

History | View | Annotate | Download (127.6 kB)

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

351 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
352 863d7f46 Michael Hanselmann

353 863d7f46 Michael Hanselmann
  """
354 b459a848 Andrea Spadaccini
  # pylint: disable=W0622
355 863d7f46 Michael Hanselmann
  def __init__(self, min=0, max=None, choices=None):
356 863d7f46 Michael Hanselmann
    _Argument.__init__(self, min=min, max=max)
357 863d7f46 Michael Hanselmann
    self.choices = choices
358 863d7f46 Michael Hanselmann
359 863d7f46 Michael Hanselmann
  def __repr__(self):
360 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s choices=%r>" %
361 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max, self.choices))
362 863d7f46 Michael Hanselmann
363 863d7f46 Michael Hanselmann
364 863d7f46 Michael Hanselmann
class ArgChoice(ArgSuggest):
365 863d7f46 Michael Hanselmann
  """Choice argument.
366 863d7f46 Michael Hanselmann

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

370 863d7f46 Michael Hanselmann
  """
371 863d7f46 Michael Hanselmann
372 863d7f46 Michael Hanselmann
373 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
374 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
375 863d7f46 Michael Hanselmann

376 863d7f46 Michael Hanselmann
  """
377 863d7f46 Michael Hanselmann
378 863d7f46 Michael Hanselmann
379 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
380 863d7f46 Michael Hanselmann
  """Instances argument.
381 863d7f46 Michael Hanselmann

382 863d7f46 Michael Hanselmann
  """
383 863d7f46 Michael Hanselmann
384 863d7f46 Michael Hanselmann
385 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
386 863d7f46 Michael Hanselmann
  """Node argument.
387 863d7f46 Michael Hanselmann

388 863d7f46 Michael Hanselmann
  """
389 863d7f46 Michael Hanselmann
390 667dbd6b Adeodato Simo
391 9c784fb3 Dimitris Aragiorgis
class ArgNetwork(_Argument):
392 9c784fb3 Dimitris Aragiorgis
  """Network argument.
393 9c784fb3 Dimitris Aragiorgis

394 9c784fb3 Dimitris Aragiorgis
  """
395 9c784fb3 Dimitris Aragiorgis
396 3c286190 Dimitris Aragiorgis
397 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
398 667dbd6b Adeodato Simo
  """Node group argument.
399 667dbd6b Adeodato Simo

400 667dbd6b Adeodato Simo
  """
401 667dbd6b Adeodato Simo
402 667dbd6b Adeodato Simo
403 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
404 863d7f46 Michael Hanselmann
  """Job ID argument.
405 863d7f46 Michael Hanselmann

406 863d7f46 Michael Hanselmann
  """
407 863d7f46 Michael Hanselmann
408 863d7f46 Michael Hanselmann
409 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
410 863d7f46 Michael Hanselmann
  """File path argument.
411 863d7f46 Michael Hanselmann

412 863d7f46 Michael Hanselmann
  """
413 863d7f46 Michael Hanselmann
414 863d7f46 Michael Hanselmann
415 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
416 863d7f46 Michael Hanselmann
  """Command argument.
417 863d7f46 Michael Hanselmann

418 863d7f46 Michael Hanselmann
  """
419 863d7f46 Michael Hanselmann
420 863d7f46 Michael Hanselmann
421 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
422 83ec7961 Michael Hanselmann
  """Host argument.
423 83ec7961 Michael Hanselmann

424 83ec7961 Michael Hanselmann
  """
425 83ec7961 Michael Hanselmann
426 83ec7961 Michael Hanselmann
427 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
428 f9faf9c3 René Nussbaumer
  """OS argument.
429 f9faf9c3 René Nussbaumer

430 f9faf9c3 René Nussbaumer
  """
431 f9faf9c3 René Nussbaumer
432 f9faf9c3 René Nussbaumer
433 b954f097 Constantinos Venetsanopoulos
class ArgExtStorage(_Argument):
434 b954f097 Constantinos Venetsanopoulos
  """ExtStorage argument.
435 b954f097 Constantinos Venetsanopoulos

436 b954f097 Constantinos Venetsanopoulos
  """
437 b954f097 Constantinos Venetsanopoulos
438 b954f097 Constantinos Venetsanopoulos
439 4a265c08 Michael Hanselmann
ARGS_NONE = []
440 4a265c08 Michael Hanselmann
ARGS_MANY_INSTANCES = [ArgInstance()]
441 9c784fb3 Dimitris Aragiorgis
ARGS_MANY_NETWORKS = [ArgNetwork()]
442 4a265c08 Michael Hanselmann
ARGS_MANY_NODES = [ArgNode()]
443 667dbd6b Adeodato Simo
ARGS_MANY_GROUPS = [ArgGroup()]
444 4a265c08 Michael Hanselmann
ARGS_ONE_INSTANCE = [ArgInstance(min=1, max=1)]
445 9c784fb3 Dimitris Aragiorgis
ARGS_ONE_NETWORK = [ArgNetwork(min=1, max=1)]
446 4a265c08 Michael Hanselmann
ARGS_ONE_NODE = [ArgNode(min=1, max=1)]
447 dadf6b7d Michael Hanselmann
# TODO
448 dadf6b7d Michael Hanselmann
ARGS_ONE_GROUP = [ArgGroup(min=1, max=1)]
449 f9faf9c3 René Nussbaumer
ARGS_ONE_OS = [ArgOs(min=1, max=1)]
450 4a265c08 Michael Hanselmann
451 4a265c08 Michael Hanselmann
452 846baef9 Iustin Pop
def _ExtractTagsObject(opts, args):
453 846baef9 Iustin Pop
  """Extract the tag type object.
454 846baef9 Iustin Pop

455 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
456 846baef9 Iustin Pop

457 846baef9 Iustin Pop
  """
458 846baef9 Iustin Pop
  if not hasattr(opts, "tag_type"):
459 846baef9 Iustin Pop
    raise errors.ProgrammerError("tag_type not passed to _ExtractTagsObject")
460 846baef9 Iustin Pop
  kind = opts.tag_type
461 846baef9 Iustin Pop
  if kind == constants.TAG_CLUSTER:
462 bcd35e09 Dato Simó
    retval = kind, None
463 819cbfe5 Michael Hanselmann
  elif kind in (constants.TAG_NODEGROUP,
464 819cbfe5 Michael Hanselmann
                constants.TAG_NODE,
465 8140e24f Dimitris Aragiorgis
                constants.TAG_NETWORK,
466 819cbfe5 Michael Hanselmann
                constants.TAG_INSTANCE):
467 846baef9 Iustin Pop
    if not args:
468 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("no arguments passed to the command",
469 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
470 846baef9 Iustin Pop
    name = args.pop(0)
471 846baef9 Iustin Pop
    retval = kind, name
472 846baef9 Iustin Pop
  else:
473 846baef9 Iustin Pop
    raise errors.ProgrammerError("Unhandled tag type '%s'" % kind)
474 846baef9 Iustin Pop
  return retval
475 846baef9 Iustin Pop
476 846baef9 Iustin Pop
477 810c50b7 Iustin Pop
def _ExtendTags(opts, args):
478 810c50b7 Iustin Pop
  """Extend the args if a source file has been given.
479 810c50b7 Iustin Pop

480 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
481 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
482 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
483 810c50b7 Iustin Pop

484 810c50b7 Iustin Pop
  """
485 810c50b7 Iustin Pop
  fname = opts.tags_source
486 810c50b7 Iustin Pop
  if fname is None:
487 810c50b7 Iustin Pop
    return
488 810c50b7 Iustin Pop
  if fname == "-":
489 810c50b7 Iustin Pop
    new_fh = sys.stdin
490 810c50b7 Iustin Pop
  else:
491 810c50b7 Iustin Pop
    new_fh = open(fname, "r")
492 810c50b7 Iustin Pop
  new_data = []
493 810c50b7 Iustin Pop
  try:
494 810c50b7 Iustin Pop
    # we don't use the nice 'new_data = [line.strip() for line in fh]'
495 810c50b7 Iustin Pop
    # because of python bug 1633941
496 810c50b7 Iustin Pop
    while True:
497 810c50b7 Iustin Pop
      line = new_fh.readline()
498 810c50b7 Iustin Pop
      if not line:
499 810c50b7 Iustin Pop
        break
500 810c50b7 Iustin Pop
      new_data.append(line.strip())
501 810c50b7 Iustin Pop
  finally:
502 810c50b7 Iustin Pop
    new_fh.close()
503 810c50b7 Iustin Pop
  args.extend(new_data)
504 810c50b7 Iustin Pop
505 810c50b7 Iustin Pop
506 846baef9 Iustin Pop
def ListTags(opts, args):
507 846baef9 Iustin Pop
  """List the tags on a given object.
508 846baef9 Iustin Pop

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

514 846baef9 Iustin Pop
  """
515 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
516 f2374060 Iustin Pop
  cl = GetClient(query=True)
517 7699c3af Iustin Pop
  result = cl.QueryTags(kind, name)
518 846baef9 Iustin Pop
  result = list(result)
519 846baef9 Iustin Pop
  result.sort()
520 846baef9 Iustin Pop
  for tag in result:
521 03298ebe Michael Hanselmann
    ToStdout(tag)
522 846baef9 Iustin Pop
523 846baef9 Iustin Pop
524 846baef9 Iustin Pop
def AddTags(opts, args):
525 846baef9 Iustin Pop
  """Add tags on a given object.
526 846baef9 Iustin Pop

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

532 846baef9 Iustin Pop
  """
533 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
534 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
535 846baef9 Iustin Pop
  if not args:
536 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("No tags to be added", errors.ECODE_INVAL)
537 d1602edc Iustin Pop
  op = opcodes.OpTagsSet(kind=kind, name=name, tags=args)
538 6bc3ed14 Michael Hanselmann
  SubmitOrSend(op, opts)
539 846baef9 Iustin Pop
540 846baef9 Iustin Pop
541 846baef9 Iustin Pop
def RemoveTags(opts, args):
542 846baef9 Iustin Pop
  """Remove tags from a given object.
543 846baef9 Iustin Pop

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

549 846baef9 Iustin Pop
  """
550 846baef9 Iustin Pop
  kind, name = _ExtractTagsObject(opts, args)
551 810c50b7 Iustin Pop
  _ExtendTags(opts, args)
552 846baef9 Iustin Pop
  if not args:
553 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("No tags to be removed", errors.ECODE_INVAL)
554 3f0ab95f Iustin Pop
  op = opcodes.OpTagsDel(kind=kind, name=name, tags=args)
555 6bc3ed14 Michael Hanselmann
  SubmitOrSend(op, opts)
556 846baef9 Iustin Pop
557 a8083063 Iustin Pop
558 b459a848 Andrea Spadaccini
def check_unit(option, opt, value): # pylint: disable=W0613
559 65fe4693 Iustin Pop
  """OptParsers custom converter for units.
560 65fe4693 Iustin Pop

561 65fe4693 Iustin Pop
  """
562 a8083063 Iustin Pop
  try:
563 a8083063 Iustin Pop
    return utils.ParseUnit(value)
564 a8083063 Iustin Pop
  except errors.UnitParseError, err:
565 3ecf6786 Iustin Pop
    raise OptionValueError("option %s: %s" % (opt, err))
566 a8083063 Iustin Pop
567 a8083063 Iustin Pop
568 a8469393 Iustin Pop
def _SplitKeyVal(opt, data):
569 a8469393 Iustin Pop
  """Convert a KeyVal string into a dict.
570 a8469393 Iustin Pop

571 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
572 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
573 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
574 a8469393 Iustin Pop
  have value=True.
575 a8469393 Iustin Pop

576 a8469393 Iustin Pop
  @type opt: string
577 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
578 a8469393 Iustin Pop
      data, used in building error messages
579 a8469393 Iustin Pop
  @type data: string
580 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
581 a8469393 Iustin Pop
  @rtype: dict
582 a8469393 Iustin Pop
  @return: {key=val, key=val}
583 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
584 a8469393 Iustin Pop

585 a8469393 Iustin Pop
  """
586 a8469393 Iustin Pop
  kv_dict = {}
587 4f31882e Guido Trotter
  if data:
588 1b3a7656 Iustin Pop
    for elem in utils.UnescapeAndSplit(data, sep=","):
589 4f31882e Guido Trotter
      if "=" in elem:
590 4f31882e Guido Trotter
        key, val = elem.split("=", 1)
591 a8469393 Iustin Pop
      else:
592 4f31882e Guido Trotter
        if elem.startswith(NO_PREFIX):
593 4f31882e Guido Trotter
          key, val = elem[len(NO_PREFIX):], False
594 4f31882e Guido Trotter
        elif elem.startswith(UN_PREFIX):
595 4f31882e Guido Trotter
          key, val = elem[len(UN_PREFIX):], None
596 4f31882e Guido Trotter
        else:
597 4f31882e Guido Trotter
          key, val = elem, True
598 4f31882e Guido Trotter
      if key in kv_dict:
599 4f31882e Guido Trotter
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
600 4f31882e Guido Trotter
                                    (key, opt))
601 4f31882e Guido Trotter
      kv_dict[key] = val
602 a8469393 Iustin Pop
  return kv_dict
603 a8469393 Iustin Pop
604 a8469393 Iustin Pop
605 b459a848 Andrea Spadaccini
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
606 552c8dff Michael Hanselmann
  """Custom parser for ident:key=val,key=val options.
607 552c8dff Michael Hanselmann

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

611 a8469393 Iustin Pop
  """
612 a8469393 Iustin Pop
  if ":" not in value:
613 d0c8c01d Iustin Pop
    ident, rest = value, ""
614 a8469393 Iustin Pop
  else:
615 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
616 8b46606c Guido Trotter
617 8b46606c Guido Trotter
  if ident.startswith(NO_PREFIX):
618 8b46606c Guido Trotter
    if rest:
619 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
620 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
621 8b46606c Guido Trotter
    retval = (ident[len(NO_PREFIX):], False)
622 956631b6 Michael Hanselmann
  elif (ident.startswith(UN_PREFIX) and
623 956631b6 Michael Hanselmann
        (len(ident) <= len(UN_PREFIX) or
624 956631b6 Michael Hanselmann
         not ident[len(UN_PREFIX)][0].isdigit())):
625 8b46606c Guido Trotter
    if rest:
626 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
627 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
628 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
629 8b46606c Guido Trotter
  else:
630 a8469393 Iustin Pop
    kv_dict = _SplitKeyVal(opt, rest)
631 a8469393 Iustin Pop
    retval = (ident, kv_dict)
632 a8469393 Iustin Pop
  return retval
633 a8469393 Iustin Pop
634 a8469393 Iustin Pop
635 b459a848 Andrea Spadaccini
def check_key_val(option, opt, value):  # pylint: disable=W0613
636 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
637 552c8dff Michael Hanselmann

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

640 a8469393 Iustin Pop
  """
641 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
642 a8469393 Iustin Pop
643 a8469393 Iustin Pop
644 b459a848 Andrea Spadaccini
def check_bool(option, opt, value): # pylint: disable=W0613
645 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
646 e7b61bb0 Iustin Pop

647 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
648 e7b61bb0 Iustin Pop

649 e7b61bb0 Iustin Pop
  """
650 e7b61bb0 Iustin Pop
  value = value.lower()
651 e7b61bb0 Iustin Pop
  if value == constants.VALUE_FALSE or value == "no":
652 e7b61bb0 Iustin Pop
    return False
653 e7b61bb0 Iustin Pop
  elif value == constants.VALUE_TRUE or value == "yes":
654 e7b61bb0 Iustin Pop
    return True
655 e7b61bb0 Iustin Pop
  else:
656 e7b61bb0 Iustin Pop
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
657 e7b61bb0 Iustin Pop
658 e7b61bb0 Iustin Pop
659 499eb088 Iustin Pop
def check_list(option, opt, value): # pylint: disable=W0613
660 499eb088 Iustin Pop
  """Custom parser for comma-separated lists.
661 499eb088 Iustin Pop

662 499eb088 Iustin Pop
  """
663 499eb088 Iustin Pop
  # we have to make this explicit check since "".split(",") is [""],
664 499eb088 Iustin Pop
  # not an empty list :(
665 499eb088 Iustin Pop
  if not value:
666 499eb088 Iustin Pop
    return []
667 499eb088 Iustin Pop
  else:
668 499eb088 Iustin Pop
    return utils.UnescapeAndSplit(value)
669 499eb088 Iustin Pop
670 499eb088 Iustin Pop
671 cd415612 René Nussbaumer
def check_maybefloat(option, opt, value): # pylint: disable=W0613
672 cd415612 René Nussbaumer
  """Custom parser for float numbers which might be also defaults.
673 cd415612 René Nussbaumer

674 cd415612 René Nussbaumer
  """
675 cd415612 René Nussbaumer
  value = value.lower()
676 cd415612 René Nussbaumer
677 cd415612 René Nussbaumer
  if value == constants.VALUE_DEFAULT:
678 cd415612 René Nussbaumer
    return value
679 cd415612 René Nussbaumer
  else:
680 cd415612 René Nussbaumer
    return float(value)
681 cd415612 René Nussbaumer
682 cd415612 René Nussbaumer
683 63d44c55 Michael Hanselmann
# completion_suggestion is normally a list. Using numeric values not evaluating
684 63d44c55 Michael Hanselmann
# to False for dynamic completion.
685 63d44c55 Michael Hanselmann
(OPT_COMPL_MANY_NODES,
686 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_NODE,
687 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_INSTANCE,
688 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_OS,
689 b954f097 Constantinos Venetsanopoulos
 OPT_COMPL_ONE_EXTSTORAGE,
690 2d3ed64b Michael Hanselmann
 OPT_COMPL_ONE_IALLOCATOR,
691 9c784fb3 Dimitris Aragiorgis
 OPT_COMPL_ONE_NETWORK,
692 36e247e1 Guido Trotter
 OPT_COMPL_INST_ADD_NODES,
693 b954f097 Constantinos Venetsanopoulos
 OPT_COMPL_ONE_NODEGROUP) = range(100, 109)
694 63d44c55 Michael Hanselmann
695 b8028dcf Michael Hanselmann
OPT_COMPL_ALL = compat.UniqueFrozenset([
696 63d44c55 Michael Hanselmann
  OPT_COMPL_MANY_NODES,
697 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_NODE,
698 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_INSTANCE,
699 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_OS,
700 b954f097 Constantinos Venetsanopoulos
  OPT_COMPL_ONE_EXTSTORAGE,
701 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_IALLOCATOR,
702 9c784fb3 Dimitris Aragiorgis
  OPT_COMPL_ONE_NETWORK,
703 2d3ed64b Michael Hanselmann
  OPT_COMPL_INST_ADD_NODES,
704 36e247e1 Guido Trotter
  OPT_COMPL_ONE_NODEGROUP,
705 63d44c55 Michael Hanselmann
  ])
706 63d44c55 Michael Hanselmann
707 63d44c55 Michael Hanselmann
708 552c8dff Michael Hanselmann
class CliOption(Option):
709 552c8dff Michael Hanselmann
  """Custom option class for optparse.
710 a8469393 Iustin Pop

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

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

1616 d971402f Michael Hanselmann
  """
1617 d971402f Michael Hanselmann
  def __init__(self, exit_error):
1618 d971402f Michael Hanselmann
    """Initializes instances of this class.
1619 d971402f Michael Hanselmann

1620 d971402f Michael Hanselmann
    @type exit_error: bool
1621 d971402f Michael Hanselmann
    @param exit_error: Whether to report failure on exit
1622 d971402f Michael Hanselmann

1623 d971402f Michael Hanselmann
    """
1624 d971402f Michael Hanselmann
    Exception.__init__(self)
1625 d971402f Michael Hanselmann
    self.exit_error = exit_error
1626 d971402f Michael Hanselmann
1627 d971402f Michael Hanselmann
1628 d971402f Michael Hanselmann
class _ShowVersion(Exception):
1629 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1630 d971402f Michael Hanselmann

1631 d971402f Michael Hanselmann
  """
1632 d971402f Michael Hanselmann
1633 d971402f Michael Hanselmann
1634 d971402f Michael Hanselmann
def _ParseArgs(binary, argv, commands, aliases, env_override):
1635 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1636 a8083063 Iustin Pop

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

1640 d971402f Michael Hanselmann
  @param binary: Script name
1641 d971402f Michael Hanselmann
  @param argv: Command line arguments
1642 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1643 d971402f Michael Hanselmann
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1644 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1645 d971402f Michael Hanselmann
  @raise _ShowUsage: If usage description should be shown
1646 d971402f Michael Hanselmann
  @raise _ShowVersion: If version should be shown
1647 098c0958 Michael Hanselmann

1648 a8083063 Iustin Pop
  """
1649 ef9fa5b9 René Nussbaumer
  assert not (env_override - set(commands))
1650 d971402f Michael Hanselmann
  assert not (set(aliases.keys()) & set(commands.keys()))
1651 ef9fa5b9 René Nussbaumer
1652 d971402f Michael Hanselmann
  if len(argv) > 1:
1653 d971402f Michael Hanselmann
    cmd = argv[1]
1654 a8083063 Iustin Pop
  else:
1655 d971402f Michael Hanselmann
    # No option or command given
1656 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1657 a8083063 Iustin Pop
1658 d971402f Michael Hanselmann
  if cmd == "--version":
1659 d971402f Michael Hanselmann
    raise _ShowVersion()
1660 d971402f Michael Hanselmann
  elif cmd == "--help":
1661 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=False)
1662 d971402f Michael Hanselmann
  elif not (cmd in commands or cmd in aliases):
1663 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1664 de47cf8f Guido Trotter
1665 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1666 de47cf8f Guido Trotter
  if cmd in aliases:
1667 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1668 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1669 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1670 de47cf8f Guido Trotter
1671 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1672 de47cf8f Guido Trotter
1673 ef9fa5b9 René Nussbaumer
  if cmd in env_override:
1674 ef9fa5b9 René Nussbaumer
    args_env_name = ("%s_%s" % (binary.replace("-", "_"), cmd)).upper()
1675 ef9fa5b9 René Nussbaumer
    env_args = os.environ.get(args_env_name)
1676 ef9fa5b9 René Nussbaumer
    if env_args:
1677 d971402f Michael Hanselmann
      argv = utils.InsertAtPos(argv, 2, shlex.split(env_args))
1678 ef9fa5b9 René Nussbaumer
1679 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1680 bf5338b3 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1681 bf5338b3 Michael Hanselmann
                        description=description,
1682 bf5338b3 Michael Hanselmann
                        formatter=TitledHelpFormatter(),
1683 bf5338b3 Michael Hanselmann
                        usage="%%prog %s %s" % (cmd, usage))
1684 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1685 d971402f Michael Hanselmann
  options, args = parser.parse_args(args=argv[2:])
1686 a8005e17 Michael Hanselmann
1687 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1688 a8083063 Iustin Pop
    return None, None, None
1689 a8083063 Iustin Pop
1690 a8083063 Iustin Pop
  return func, options, args
1691 a8083063 Iustin Pop
1692 a8083063 Iustin Pop
1693 d971402f Michael Hanselmann
def _FormatUsage(binary, commands):
1694 d971402f Michael Hanselmann
  """Generates a nice description of all commands.
1695 d971402f Michael Hanselmann

1696 d971402f Michael Hanselmann
  @param binary: Script name
1697 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1698 d971402f Michael Hanselmann

1699 d971402f Michael Hanselmann
  """
1700 d971402f Michael Hanselmann
  # compute the max line length for cmd + usage
1701 d971402f Michael Hanselmann
  mlen = min(60, max(map(len, commands)))
1702 d971402f Michael Hanselmann
1703 d971402f Michael Hanselmann
  yield "Usage: %s {command} [options...] [argument...]" % binary
1704 d971402f Michael Hanselmann
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1705 d971402f Michael Hanselmann
  yield ""
1706 d971402f Michael Hanselmann
  yield "Commands:"
1707 d971402f Michael Hanselmann
1708 d971402f Michael Hanselmann
  # and format a nice command list
1709 d971402f Michael Hanselmann
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1710 d971402f Michael Hanselmann
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1711 d971402f Michael Hanselmann
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1712 d971402f Michael Hanselmann
    for line in help_lines:
1713 d971402f Michael Hanselmann
      yield " %-*s   %s" % (mlen, "", line)
1714 d971402f Michael Hanselmann
1715 d971402f Michael Hanselmann
  yield ""
1716 d971402f Michael Hanselmann
1717 d971402f Michael Hanselmann
1718 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1719 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1720 a8005e17 Michael Hanselmann

1721 a8005e17 Michael Hanselmann
  Algorithm:
1722 a8005e17 Michael Hanselmann

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

1725 a8005e17 Michael Hanselmann
    1. For each argument in definition
1726 a8005e17 Michael Hanselmann

1727 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1728 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1729 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1730 a8005e17 Michael Hanselmann

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

1733 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1734 a8005e17 Michael Hanselmann

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

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

1739 a8005e17 Michael Hanselmann
  """
1740 a8005e17 Michael Hanselmann
  if args and not args_def:
1741 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1742 a8005e17 Michael Hanselmann
    return False
1743 a8005e17 Michael Hanselmann
1744 a8005e17 Michael Hanselmann
  min_count = None
1745 a8005e17 Michael Hanselmann
  max_count = None
1746 a8005e17 Michael Hanselmann
  check_max = None
1747 a8005e17 Michael Hanselmann
1748 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1749 a8005e17 Michael Hanselmann
1750 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1751 a8005e17 Michael Hanselmann
    if min_count is None:
1752 a8005e17 Michael Hanselmann
      min_count = arg.min
1753 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1754 a8005e17 Michael Hanselmann
      min_count += arg.min
1755 a8005e17 Michael Hanselmann
1756 a8005e17 Michael Hanselmann
    if max_count is None:
1757 a8005e17 Michael Hanselmann
      max_count = arg.max
1758 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1759 a8005e17 Michael Hanselmann
      max_count += arg.max
1760 a8005e17 Michael Hanselmann
1761 a8005e17 Michael Hanselmann
    if idx == last_idx:
1762 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1763 a8005e17 Michael Hanselmann
1764 a8005e17 Michael Hanselmann
    elif arg.max is None:
1765 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1766 a8005e17 Michael Hanselmann
1767 a8005e17 Michael Hanselmann
  if check_max:
1768 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1769 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1770 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1771 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1772 a8005e17 Michael Hanselmann
      return False
1773 a8005e17 Michael Hanselmann
1774 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1775 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1776 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1777 a8005e17 Michael Hanselmann
               cmd, max_count)
1778 a8005e17 Michael Hanselmann
      return False
1779 a8005e17 Michael Hanselmann
1780 a8005e17 Michael Hanselmann
  # Command with some required arguments
1781 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1782 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1783 a8005e17 Michael Hanselmann
             cmd, min_count)
1784 a8005e17 Michael Hanselmann
    return False
1785 a8005e17 Michael Hanselmann
1786 a8005e17 Michael Hanselmann
  return True
1787 a8005e17 Michael Hanselmann
1788 a8005e17 Michael Hanselmann
1789 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1790 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1791 60d49723 Michael Hanselmann

1792 60d49723 Michael Hanselmann
  """
1793 d0c8c01d Iustin Pop
  if value and ":" in value:
1794 d0c8c01d Iustin Pop
    return value.split(":", 1)
1795 60d49723 Michael Hanselmann
  else:
1796 60d49723 Michael Hanselmann
    return (value, None)
1797 60d49723 Michael Hanselmann
1798 60d49723 Michael Hanselmann
1799 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1800 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1801 07150497 Guido Trotter

1802 07150497 Guido Trotter
  @type os_name: string
1803 07150497 Guido Trotter
  @param os_name: base name of the os
1804 07150497 Guido Trotter
  @type os_variants: list or None
1805 07150497 Guido Trotter
  @param os_variants: list of supported variants
1806 07150497 Guido Trotter
  @rtype: list
1807 07150497 Guido Trotter
  @return: list of valid names
1808 07150497 Guido Trotter

1809 07150497 Guido Trotter
  """
1810 07150497 Guido Trotter
  if os_variants:
1811 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1812 07150497 Guido Trotter
  else:
1813 07150497 Guido Trotter
    return [os_name]
1814 07150497 Guido Trotter
1815 07150497 Guido Trotter
1816 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1817 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1818 a4ebd726 Michael Hanselmann

1819 a4ebd726 Michael Hanselmann
  @type selected: string or None
1820 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1821 a4ebd726 Michael Hanselmann
  @type default: list
1822 a4ebd726 Michael Hanselmann
  @param default: Default fields
1823 a4ebd726 Michael Hanselmann

1824 a4ebd726 Michael Hanselmann
  """
1825 a4ebd726 Michael Hanselmann
  if selected is None:
1826 a4ebd726 Michael Hanselmann
    return default
1827 a4ebd726 Michael Hanselmann
1828 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1829 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1830 a4ebd726 Michael Hanselmann
1831 a4ebd726 Michael Hanselmann
  return selected.split(",")
1832 a4ebd726 Michael Hanselmann
1833 a4ebd726 Michael Hanselmann
1834 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1835 4331f6cd Michael Hanselmann
1836 4331f6cd Michael Hanselmann
1837 47988778 Iustin Pop
def AskUser(text, choices=None):
1838 47988778 Iustin Pop
  """Ask the user a question.
1839 a8083063 Iustin Pop

1840 c41eea6e Iustin Pop
  @param text: the question to ask
1841 a8083063 Iustin Pop

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

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

1851 a8083063 Iustin Pop
  """
1852 47988778 Iustin Pop
  if choices is None:
1853 d0c8c01d Iustin Pop
    choices = [("y", True, "Perform the operation"),
1854 d0c8c01d Iustin Pop
               ("n", False, "Do not perform the operation")]
1855 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1856 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1857 47988778 Iustin Pop
  for entry in choices:
1858 d0c8c01d Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1859 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1860 47988778 Iustin Pop
1861 47988778 Iustin Pop
  answer = choices[-1][1]
1862 47988778 Iustin Pop
  new_text = []
1863 47988778 Iustin Pop
  for line in text.splitlines():
1864 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1865 47988778 Iustin Pop
  text = "\n".join(new_text)
1866 a8083063 Iustin Pop
  try:
1867 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1868 a8083063 Iustin Pop
  except IOError:
1869 47988778 Iustin Pop
    return answer
1870 a8083063 Iustin Pop
  try:
1871 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1872 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1873 d0c8c01d Iustin Pop
    chars.append("?")
1874 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1875 47988778 Iustin Pop
    while True:
1876 47988778 Iustin Pop
      f.write(text)
1877 d0c8c01d Iustin Pop
      f.write("\n")
1878 47988778 Iustin Pop
      f.write("/".join(chars))
1879 47988778 Iustin Pop
      f.write(": ")
1880 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1881 47988778 Iustin Pop
      if line in maps:
1882 47988778 Iustin Pop
        answer = maps[line]
1883 47988778 Iustin Pop
        break
1884 d0c8c01d Iustin Pop
      elif line == "?":
1885 47988778 Iustin Pop
        for entry in choices:
1886 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1887 47988778 Iustin Pop
        f.write("\n")
1888 47988778 Iustin Pop
        continue
1889 a8083063 Iustin Pop
  finally:
1890 a8083063 Iustin Pop
    f.close()
1891 a8083063 Iustin Pop
  return answer
1892 a8083063 Iustin Pop
1893 a8083063 Iustin Pop
1894 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1895 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1896 e9d741b6 Iustin Pop

1897 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1898 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1899 e9d741b6 Iustin Pop

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

1902 e9d741b6 Iustin Pop
  """
1903 e9d741b6 Iustin Pop
1904 e9d741b6 Iustin Pop
1905 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1906 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1907 a8083063 Iustin Pop

1908 0a1e74d9 Iustin Pop
  @type ops: list
1909 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1910 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1911 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1912 0a1e74d9 Iustin Pop
             if None, a new client will be created
1913 a8083063 Iustin Pop

1914 a8083063 Iustin Pop
  """
1915 e2212007 Iustin Pop
  if cl is None:
1916 b33e986b Iustin Pop
    cl = GetClient()
1917 685ee993 Iustin Pop
1918 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1919 0a1e74d9 Iustin Pop
1920 0a1e74d9 Iustin Pop
  return job_id
1921 0a1e74d9 Iustin Pop
1922 0a1e74d9 Iustin Pop
1923 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1924 4e338533 Michael Hanselmann
  """Generic job-polling function.
1925 0a1e74d9 Iustin Pop

1926 4e338533 Michael Hanselmann
  @type job_id: number
1927 4e338533 Michael Hanselmann
  @param job_id: Job ID
1928 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1929 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1930 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1931 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1932 0a1e74d9 Iustin Pop

1933 0a1e74d9 Iustin Pop
  """
1934 6c5a7090 Michael Hanselmann
  prev_job_info = None
1935 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
1936 6c5a7090 Michael Hanselmann
1937 f4484122 Michael Hanselmann
  status = None
1938 f4484122 Michael Hanselmann
1939 685ee993 Iustin Pop
  while True:
1940 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
1941 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
1942 6c5a7090 Michael Hanselmann
    if not result:
1943 685ee993 Iustin Pop
      # job not found, go away!
1944 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
1945 4e338533 Michael Hanselmann
1946 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
1947 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
1948 f4484122 Michael Hanselmann
1949 f4484122 Michael Hanselmann
      # Wait again
1950 f4484122 Michael Hanselmann
      continue
1951 685ee993 Iustin Pop
1952 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
1953 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
1954 6c5a7090 Michael Hanselmann
    (status, ) = job_info
1955 6c5a7090 Michael Hanselmann
1956 6c5a7090 Michael Hanselmann
    if log_entries:
1957 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
1958 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
1959 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
1960 4e338533 Michael Hanselmann
                                    log_type, message)
1961 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
1962 6c5a7090 Michael Hanselmann
1963 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
1964 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
1965 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
1966 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
1967 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
1968 685ee993 Iustin Pop
      break
1969 6c5a7090 Michael Hanselmann
1970 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
1971 685ee993 Iustin Pop
1972 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
1973 0bbe448c Michael Hanselmann
  if not jobs:
1974 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
1975 685ee993 Iustin Pop
1976 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
1977 4e338533 Michael Hanselmann
1978 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
1979 53c04d04 Iustin Pop
    return result
1980 4e338533 Michael Hanselmann
1981 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
1982 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
1983 4e338533 Michael Hanselmann
1984 4e338533 Michael Hanselmann
  has_ok = False
1985 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
1986 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
1987 4e338533 Michael Hanselmann
      has_ok = True
1988 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
1989 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
1990 4e338533 Michael Hanselmann
1991 4e338533 Michael Hanselmann
      if has_ok:
1992 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
1993 4e338533 Michael Hanselmann
                                 (idx, msg))
1994 4e338533 Michael Hanselmann
1995 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
1996 4e338533 Michael Hanselmann
1997 4e338533 Michael Hanselmann
  # default failure mode
1998 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
1999 4e338533 Michael Hanselmann
2000 4e338533 Michael Hanselmann
2001 4e338533 Michael Hanselmann
class JobPollCbBase:
2002 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
2003 4e338533 Michael Hanselmann

2004 4e338533 Michael Hanselmann
  """
2005 4e338533 Michael Hanselmann
  def __init__(self):
2006 4e338533 Michael Hanselmann
    """Initializes this class.
2007 4e338533 Michael Hanselmann

2008 4e338533 Michael Hanselmann
    """
2009 4e338533 Michael Hanselmann
2010 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2011 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2012 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2013 4e338533 Michael Hanselmann

2014 4e338533 Michael Hanselmann
    """
2015 4e338533 Michael Hanselmann
    raise NotImplementedError()
2016 4e338533 Michael Hanselmann
2017 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2018 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2019 4e338533 Michael Hanselmann

2020 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
2021 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
2022 4e338533 Michael Hanselmann
    @type fields: list of strings
2023 4e338533 Michael Hanselmann
    @param fields: Fields
2024 4e338533 Michael Hanselmann

2025 4e338533 Michael Hanselmann
    """
2026 4e338533 Michael Hanselmann
    raise NotImplementedError()
2027 4e338533 Michael Hanselmann
2028 4e338533 Michael Hanselmann
2029 4e338533 Michael Hanselmann
class JobPollReportCbBase:
2030 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
2031 4e338533 Michael Hanselmann

2032 4e338533 Michael Hanselmann
  """
2033 4e338533 Michael Hanselmann
  def __init__(self):
2034 4e338533 Michael Hanselmann
    """Initializes this class.
2035 4e338533 Michael Hanselmann

2036 4e338533 Michael Hanselmann
    """
2037 4e338533 Michael Hanselmann
2038 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2039 4e338533 Michael Hanselmann
    """Handles a log message.
2040 4e338533 Michael Hanselmann

2041 4e338533 Michael Hanselmann
    """
2042 4e338533 Michael Hanselmann
    raise NotImplementedError()
2043 4e338533 Michael Hanselmann
2044 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2045 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
2046 4e338533 Michael Hanselmann

2047 4e338533 Michael Hanselmann
    @type job_id: number
2048 4e338533 Michael Hanselmann
    @param job_id: Job ID
2049 4e338533 Michael Hanselmann
    @type status: string or None
2050 4e338533 Michael Hanselmann
    @param status: Job status if available
2051 4e338533 Michael Hanselmann

2052 4e338533 Michael Hanselmann
    """
2053 4e338533 Michael Hanselmann
    raise NotImplementedError()
2054 4e338533 Michael Hanselmann
2055 4e338533 Michael Hanselmann
2056 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
2057 4e338533 Michael Hanselmann
  def __init__(self, cl):
2058 4e338533 Michael Hanselmann
    """Initializes this class.
2059 4e338533 Michael Hanselmann

2060 4e338533 Michael Hanselmann
    """
2061 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
2062 4e338533 Michael Hanselmann
    self.cl = cl
2063 4e338533 Michael Hanselmann
2064 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2065 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2066 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2067 4e338533 Michael Hanselmann

2068 4e338533 Michael Hanselmann
    """
2069 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2070 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
2071 4e338533 Michael Hanselmann
2072 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2073 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2074 4e338533 Michael Hanselmann

2075 4e338533 Michael Hanselmann
    """
2076 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
2077 4e338533 Michael Hanselmann
2078 4e338533 Michael Hanselmann
2079 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2080 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
2081 4e338533 Michael Hanselmann
    """Initializes this class.
2082 4e338533 Michael Hanselmann

2083 4e338533 Michael Hanselmann
    """
2084 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2085 4e338533 Michael Hanselmann
2086 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
2087 4e338533 Michael Hanselmann
2088 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
2089 4e338533 Michael Hanselmann
2090 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2091 4e338533 Michael Hanselmann
    """Handles a log message.
2092 4e338533 Michael Hanselmann

2093 4e338533 Michael Hanselmann
    """
2094 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
2095 4e338533 Michael Hanselmann
2096 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2097 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2098 4e338533 Michael Hanselmann

2099 4e338533 Michael Hanselmann
    """
2100 4e338533 Michael Hanselmann
    # Ignore
2101 4e338533 Michael Hanselmann
2102 4e338533 Michael Hanselmann
2103 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
2104 4e338533 Michael Hanselmann
  def __init__(self):
2105 4e338533 Michael Hanselmann
    """Initializes this class.
2106 4e338533 Michael Hanselmann

2107 4e338533 Michael Hanselmann
    """
2108 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2109 4e338533 Michael Hanselmann
2110 4e338533 Michael Hanselmann
    self.notified_queued = False
2111 4e338533 Michael Hanselmann
    self.notified_waitlock = False
2112 4e338533 Michael Hanselmann
2113 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2114 4e338533 Michael Hanselmann
    """Handles a log message.
2115 4e338533 Michael Hanselmann

2116 4e338533 Michael Hanselmann
    """
2117 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2118 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
2119 4e338533 Michael Hanselmann
2120 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2121 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2122 4e338533 Michael Hanselmann

2123 4e338533 Michael Hanselmann
    """
2124 4e338533 Michael Hanselmann
    if status is None:
2125 4e338533 Michael Hanselmann
      return
2126 4e338533 Michael Hanselmann
2127 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2128 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
2129 4e338533 Michael Hanselmann
      self.notified_queued = True
2130 4e338533 Michael Hanselmann
2131 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2132 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2133 4e338533 Michael Hanselmann
      self.notified_waitlock = True
2134 4e338533 Michael Hanselmann
2135 4e338533 Michael Hanselmann
2136 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
2137 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
2138 8a7f1c61 Michael Hanselmann

2139 8a7f1c61 Michael Hanselmann
  """
2140 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
2141 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
2142 8a7f1c61 Michael Hanselmann
2143 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
2144 8a7f1c61 Michael Hanselmann
2145 8a7f1c61 Michael Hanselmann
2146 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2147 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
2148 4e338533 Michael Hanselmann

2149 4e338533 Michael Hanselmann
  @type job_id: job identified
2150 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
2151 4e338533 Michael Hanselmann
  @type cl: luxi.Client
2152 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
2153 4e338533 Michael Hanselmann
             if None, a new client will be created
2154 4e338533 Michael Hanselmann

2155 4e338533 Michael Hanselmann
  """
2156 4e338533 Michael Hanselmann
  if cl is None:
2157 4e338533 Michael Hanselmann
    cl = GetClient()
2158 4e338533 Michael Hanselmann
2159 583163a6 Michael Hanselmann
  if reporter is None:
2160 583163a6 Michael Hanselmann
    if feedback_fn:
2161 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2162 583163a6 Michael Hanselmann
    else:
2163 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
2164 583163a6 Michael Hanselmann
  elif feedback_fn:
2165 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2166 4e338533 Michael Hanselmann
2167 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2168 ceab32dd Iustin Pop
2169 ceab32dd Iustin Pop
2170 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2171 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
2172 0a1e74d9 Iustin Pop

2173 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
2174 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
2175 0a1e74d9 Iustin Pop
  interaction functions.
2176 0a1e74d9 Iustin Pop

2177 0a1e74d9 Iustin Pop
  """
2178 0a1e74d9 Iustin Pop
  if cl is None:
2179 0a1e74d9 Iustin Pop
    cl = GetClient()
2180 0a1e74d9 Iustin Pop
2181 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
2182 293ba2d8 Iustin Pop
2183 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
2184 0a1e74d9 Iustin Pop
2185 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2186 583163a6 Michael Hanselmann
                       reporter=reporter)
2187 53c04d04 Iustin Pop
2188 53c04d04 Iustin Pop
  return op_results[0]
2189 0a1e74d9 Iustin Pop
2190 0a1e74d9 Iustin Pop
2191 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2192 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
2193 94428652 Iustin Pop

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

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

2202 94428652 Iustin Pop
  """
2203 94428652 Iustin Pop
  if opts and opts.submit_only:
2204 293ba2d8 Iustin Pop
    job = [op]
2205 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
2206 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
2207 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
2208 94428652 Iustin Pop
  else:
2209 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2210 293ba2d8 Iustin Pop
2211 293ba2d8 Iustin Pop
2212 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
2213 293ba2d8 Iustin Pop
  """Processor for generic options.
2214 293ba2d8 Iustin Pop

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

2218 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
2219 293ba2d8 Iustin Pop
  @param options: command line options or None
2220 293ba2d8 Iustin Pop
  @return: None (in-place modification)
2221 293ba2d8 Iustin Pop

2222 293ba2d8 Iustin Pop
  """
2223 293ba2d8 Iustin Pop
  if not options:
2224 293ba2d8 Iustin Pop
    return
2225 293ba2d8 Iustin Pop
  for op in opcode_list:
2226 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
2227 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
2228 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
2229 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
2230 552328b8 Michael Hanselmann
      op.priority = options.priority
2231 94428652 Iustin Pop
2232 94428652 Iustin Pop
2233 42ab9ac4 Iustin Pop
def GetClient(query=False):
2234 42ab9ac4 Iustin Pop
  """Connects to the a luxi socket and returns a client.
2235 42ab9ac4 Iustin Pop

2236 42ab9ac4 Iustin Pop
  @type query: boolean
2237 42ab9ac4 Iustin Pop
  @param query: this signifies that the client will only be
2238 42ab9ac4 Iustin Pop
      used for queries; if the build-time parameter
2239 42ab9ac4 Iustin Pop
      enable-split-queries is enabled, then the client will be
2240 42ab9ac4 Iustin Pop
      connected to the query socket instead of the masterd socket
2241 42ab9ac4 Iustin Pop

2242 42ab9ac4 Iustin Pop
  """
2243 055d6ac0 Iustin Pop
  override_socket = os.getenv(constants.LUXI_OVERRIDE, "")
2244 055d6ac0 Iustin Pop
  if override_socket:
2245 055d6ac0 Iustin Pop
    if override_socket == constants.LUXI_OVERRIDE_MASTER:
2246 055d6ac0 Iustin Pop
      address = pathutils.MASTER_SOCKET
2247 055d6ac0 Iustin Pop
    elif override_socket == constants.LUXI_OVERRIDE_QUERY:
2248 055d6ac0 Iustin Pop
      address = pathutils.QUERY_SOCKET
2249 055d6ac0 Iustin Pop
    else:
2250 055d6ac0 Iustin Pop
      address = override_socket
2251 055d6ac0 Iustin Pop
  elif query and constants.ENABLE_SPLIT_QUERY:
2252 ee4a14c0 Michael Hanselmann
    address = pathutils.QUERY_SOCKET
2253 42ab9ac4 Iustin Pop
  else:
2254 42ab9ac4 Iustin Pop
    address = None
2255 af30b2fd Michael Hanselmann
  # TODO: Cache object?
2256 b33e986b Iustin Pop
  try:
2257 42ab9ac4 Iustin Pop
    client = luxi.Client(address=address)
2258 b33e986b Iustin Pop
  except luxi.NoMasterError:
2259 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
2260 d9a51679 Michael Hanselmann
2261 d9a51679 Michael Hanselmann
    # Try to read ssconf file
2262 d9a51679 Michael Hanselmann
    try:
2263 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
2264 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
2265 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2266 2cfbc784 Iustin Pop
                                 " not part of a cluster",
2267 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2268 d9a51679 Michael Hanselmann
2269 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2270 b33e986b Iustin Pop
    if master != myself:
2271 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
2272 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
2273 2cfbc784 Iustin Pop
                                 master, errors.ECODE_INVAL)
2274 d9a51679 Michael Hanselmann
    raise
2275 b33e986b Iustin Pop
  return client
2276 af30b2fd Michael Hanselmann
2277 af30b2fd Michael Hanselmann
2278 73702ee7 Iustin Pop
def FormatError(err):
2279 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
2280 73702ee7 Iustin Pop

2281 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
2282 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
2283 73702ee7 Iustin Pop
  second, a string describing the error message (not
2284 73702ee7 Iustin Pop
  newline-terminated).
2285 73702ee7 Iustin Pop

2286 73702ee7 Iustin Pop
  """
2287 73702ee7 Iustin Pop
  retcode = 1
2288 73702ee7 Iustin Pop
  obuf = StringIO()
2289 e2e521d0 Iustin Pop
  msg = str(err)
2290 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
2291 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
2292 46fbdd04 Iustin Pop
    logging.error(txt)
2293 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
2294 73702ee7 Iustin Pop
    obuf.write("Aborting.")
2295 73702ee7 Iustin Pop
    retcode = 2
2296 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
2297 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
2298 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
2299 73702ee7 Iustin Pop
      if out:
2300 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
2301 73702ee7 Iustin Pop
                   (node, script, out))
2302 73702ee7 Iustin Pop
      else:
2303 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
2304 73702ee7 Iustin Pop
                   (node, script))
2305 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
2306 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
2307 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
2308 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
2309 73702ee7 Iustin Pop
    if err.args[0] == this_host:
2310 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
2311 73702ee7 Iustin Pop
    else:
2312 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
2313 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
2314 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
2315 5c983ee5 Iustin Pop
    if len(err.args) == 2:
2316 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2317 5ae4945a Iustin Pop
                 " operation:\nerror type: %s, error details:\n%s" %
2318 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
2319 5c983ee5 Iustin Pop
    else:
2320 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2321 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
2322 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
2323 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
2324 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
2325 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
2326 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
2327 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
2328 686d7433 Iustin Pop
               " accept new requests\n")
2329 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
2330 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
2331 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
2332 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
2333 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
2334 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
2335 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
2336 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
2337 7f5edc60 Iustin Pop
    if err.args[0] == pathutils.MASTER_SOCKET:
2338 055d6ac0 Iustin Pop
      daemon = "the master daemon"
2339 055d6ac0 Iustin Pop
    elif err.args[0] == pathutils.QUERY_SOCKET:
2340 055d6ac0 Iustin Pop
      daemon = "the config daemon"
2341 7f5edc60 Iustin Pop
    else:
2342 055d6ac0 Iustin Pop
      daemon = "socket '%s'" % str(err.args[0])
2343 055d6ac0 Iustin Pop
    obuf.write("Cannot communicate with %s.\nIs the process running"
2344 7f5edc60 Iustin Pop
               " and listening for connections?" % daemon)
2345 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
2346 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
2347 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
2348 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
2349 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
2350 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
2351 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
2352 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
2353 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
2354 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
2355 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
2356 03a8dbdc Iustin Pop
               "%s" % msg)
2357 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
2358 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
2359 cb1e6c3c Michael Hanselmann
  elif isinstance(err, errors.QueryFilterParseError):
2360 cb1e6c3c Michael Hanselmann
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
2361 cb1e6c3c Michael Hanselmann
    obuf.write("\n".join(err.GetDetails()))
2362 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
2363 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
2364 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
2365 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
2366 e9d741b6 Iustin Pop
    retcode = 0
2367 73702ee7 Iustin Pop
  else:
2368 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
2369 d0c8c01d Iustin Pop
  return retcode, obuf.getvalue().rstrip("\n")
2370 73702ee7 Iustin Pop
2371 73702ee7 Iustin Pop
2372 ef9fa5b9 René Nussbaumer
def GenericMain(commands, override=None, aliases=None,
2373 ef9fa5b9 René Nussbaumer
                env_override=frozenset()):
2374 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
2375 a8083063 Iustin Pop

2376 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2377 ef9fa5b9 René Nussbaumer
                   for command line handling.
2378 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2379 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2380 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2381 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2382 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2383 ef9fa5b9 René Nussbaumer
                       default args for commands
2384 a8083063 Iustin Pop

2385 a8083063 Iustin Pop
  """
2386 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
2387 a8083063 Iustin Pop
  if sys.argv:
2388 c1f19851 Michael Hanselmann
    binary = os.path.basename(sys.argv[0])
2389 c1f19851 Michael Hanselmann
    if not binary:
2390 c1f19851 Michael Hanselmann
      binary = sys.argv[0]
2391 c1f19851 Michael Hanselmann
2392 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
2393 c1f19851 Michael Hanselmann
      logname = utils.ShellQuoteArgs([binary, sys.argv[1]])
2394 a8083063 Iustin Pop
    else:
2395 c1f19851 Michael Hanselmann
      logname = binary
2396 c1f19851 Michael Hanselmann
2397 c1f19851 Michael Hanselmann
    cmdline = utils.ShellQuoteArgs([binary] + sys.argv[1:])
2398 a8083063 Iustin Pop
  else:
2399 a8083063 Iustin Pop
    binary = "<unknown program>"
2400 c1f19851 Michael Hanselmann
    cmdline = "<unknown>"
2401 a8083063 Iustin Pop
2402 de47cf8f Guido Trotter
  if aliases is None:
2403 de47cf8f Guido Trotter
    aliases = {}
2404 de47cf8f Guido Trotter
2405 3126878d Guido Trotter
  try:
2406 d971402f Michael Hanselmann
    (func, options, args) = _ParseArgs(binary, sys.argv, commands, aliases,
2407 d971402f Michael Hanselmann
                                       env_override)
2408 d971402f Michael Hanselmann
  except _ShowVersion:
2409 d971402f Michael Hanselmann
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
2410 d971402f Michael Hanselmann
             constants.RELEASE_VERSION)
2411 d971402f Michael Hanselmann
    return constants.EXIT_SUCCESS
2412 d971402f Michael Hanselmann
  except _ShowUsage, err:
2413 d971402f Michael Hanselmann
    for line in _FormatUsage(binary, commands):
2414 d971402f Michael Hanselmann
      ToStdout(line)
2415 d971402f Michael Hanselmann
2416 d971402f Michael Hanselmann
    if err.exit_error:
2417 d971402f Michael Hanselmann
      return constants.EXIT_FAILURE
2418 d971402f Michael Hanselmann
    else:
2419 d971402f Michael Hanselmann
      return constants.EXIT_SUCCESS
2420 3126878d Guido Trotter
  except errors.ParameterError, err:
2421 3126878d Guido Trotter
    result, err_msg = FormatError(err)
2422 3126878d Guido Trotter
    ToStderr(err_msg)
2423 3126878d Guido Trotter
    return 1
2424 3126878d Guido Trotter
2425 a8083063 Iustin Pop
  if func is None: # parse error
2426 a8083063 Iustin Pop
    return 1
2427 a8083063 Iustin Pop
2428 334d1483 Iustin Pop
  if override is not None:
2429 334d1483 Iustin Pop
    for key, val in override.iteritems():
2430 334d1483 Iustin Pop
      setattr(options, key, val)
2431 334d1483 Iustin Pop
2432 ee4a14c0 Michael Hanselmann
  utils.SetupLogging(pathutils.LOG_COMMANDS, logname, debug=options.debug,
2433 cfcc79c6 Michael Hanselmann
                     stderr_logging=True)
2434 a8083063 Iustin Pop
2435 c1f19851 Michael Hanselmann
  logging.info("Command line: %s", cmdline)
2436 a8083063 Iustin Pop
2437 a8083063 Iustin Pop
  try:
2438 a4af651e Iustin Pop
    result = func(options, args)
2439 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
2440 d8353c3a Iustin Pop
          JobSubmittedException), err:
2441 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
2442 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
2443 46fbdd04 Iustin Pop
    ToStderr(err_msg)
2444 8a53b55f Iustin Pop
  except KeyboardInterrupt:
2445 8a53b55f Iustin Pop
    result = constants.EXIT_FAILURE
2446 8a53b55f Iustin Pop
    ToStderr("Aborted. Note that if the operation created any jobs, they"
2447 8a53b55f Iustin Pop
             " might have been submitted and"
2448 8a53b55f Iustin Pop
             " will continue to run in the background.")
2449 225e2544 Iustin Pop
  except IOError, err:
2450 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
2451 225e2544 Iustin Pop
      # our terminal went away, we'll exit
2452 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
2453 225e2544 Iustin Pop
    else:
2454 225e2544 Iustin Pop
      raise
2455 a8083063 Iustin Pop
2456 a8083063 Iustin Pop
  return result
2457 137161c9 Michael Hanselmann
2458 137161c9 Michael Hanselmann
2459 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
2460 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
2461 845c79d8 Michael Hanselmann

2462 845c79d8 Michael Hanselmann
  """
2463 845c79d8 Michael Hanselmann
  try:
2464 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2465 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2466 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2467 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
2468 845c79d8 Michael Hanselmann
2469 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2470 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2471 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2472 845c79d8 Michael Hanselmann
2473 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2474 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2475 2cfbc784 Iustin Pop
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2476 845c79d8 Michael Hanselmann
2477 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2478 845c79d8 Michael Hanselmann
2479 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2480 845c79d8 Michael Hanselmann
2481 845c79d8 Michael Hanselmann
  return nics
2482 845c79d8 Michael Hanselmann
2483 845c79d8 Michael Hanselmann
2484 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2485 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2486 d77490c5 Iustin Pop

2487 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2488 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2489 d77490c5 Iustin Pop
  @type args: list
2490 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2491 d77490c5 Iustin Pop
  @rtype: int
2492 d77490c5 Iustin Pop
  @return: the desired exit code
2493 d77490c5 Iustin Pop

2494 d77490c5 Iustin Pop
  """
2495 d77490c5 Iustin Pop
  instance = args[0]
2496 d77490c5 Iustin Pop
2497 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
2498 d77490c5 Iustin Pop
2499 d77490c5 Iustin Pop
  hypervisor = None
2500 d77490c5 Iustin Pop
  hvparams = {}
2501 d77490c5 Iustin Pop
  if opts.hypervisor:
2502 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
2503 d77490c5 Iustin Pop
2504 d77490c5 Iustin Pop
  if opts.nics:
2505 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
2506 d77490c5 Iustin Pop
  elif opts.no_nics:
2507 d77490c5 Iustin Pop
    # no nics
2508 d77490c5 Iustin Pop
    nics = []
2509 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
2510 d77490c5 Iustin Pop
    # default of one nic, all auto
2511 d77490c5 Iustin Pop
    nics = [{}]
2512 0af0f641 Iustin Pop
  else:
2513 0af0f641 Iustin Pop
    # mode == import
2514 0af0f641 Iustin Pop
    nics = []
2515 d77490c5 Iustin Pop
2516 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
2517 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
2518 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
2519 2cfbc784 Iustin Pop
                                 " information passed", errors.ECODE_INVAL)
2520 d77490c5 Iustin Pop
    disks = []
2521 d77490c5 Iustin Pop
  else:
2522 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
2523 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
2524 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("No disk information specified",
2525 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2526 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
2527 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
2528 2cfbc784 Iustin Pop
                                 " '-s' option", errors.ECODE_INVAL)
2529 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2530 ccfa86ba Michael Hanselmann
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2531 9b12ed0f Iustin Pop
2532 9b12ed0f Iustin Pop
    if opts.disks:
2533 9b12ed0f Iustin Pop
      try:
2534 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2535 9b12ed0f Iustin Pop
      except ValueError, err:
2536 2cfbc784 Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
2537 2cfbc784 Iustin Pop
                                   errors.ECODE_INVAL)
2538 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2539 9b12ed0f Iustin Pop
    else:
2540 9b12ed0f Iustin Pop
      disks = []
2541 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2542 d77490c5 Iustin Pop
      didx = int(didx)
2543 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2544 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2545 2cfbc784 Iustin Pop
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
2546 ccfa86ba Michael Hanselmann
      elif constants.IDISK_SIZE in ddict:
2547 ccfa86ba Michael Hanselmann
        if constants.IDISK_ADOPT in ddict:
2548 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2549 2cfbc784 Iustin Pop
                                     " (disk %d)" % didx, errors.ECODE_INVAL)
2550 5029db65 Iustin Pop
        try:
2551 ccfa86ba Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
2552 ccfa86ba Michael Hanselmann
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2553 5029db65 Iustin Pop
        except ValueError, err:
2554 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2555 2cfbc784 Iustin Pop
                                     (didx, err), errors.ECODE_INVAL)
2556 ccfa86ba Michael Hanselmann
      elif constants.IDISK_ADOPT in ddict:
2557 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2558 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2559 2cfbc784 Iustin Pop
                                     " import", errors.ECODE_INVAL)
2560 ccfa86ba Michael Hanselmann
        ddict[constants.IDISK_SIZE] = 0
2561 5029db65 Iustin Pop
      else:
2562 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2563 2cfbc784 Iustin Pop
                                   " disk %d" % didx, errors.ECODE_INVAL)
2564 d77490c5 Iustin Pop
      disks[didx] = ddict
2565 d77490c5 Iustin Pop
2566 a57981c5 Apollon Oikonomopoulos
  if opts.tags is not None:
2567 0f8810df Michael Hanselmann
    tags = opts.tags.split(",")
2568 a57981c5 Apollon Oikonomopoulos
  else:
2569 a57981c5 Apollon Oikonomopoulos
    tags = []
2570 a57981c5 Apollon Oikonomopoulos
2571 b2e233a5 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT)
2572 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2573 d77490c5 Iustin Pop
2574 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2575 d77490c5 Iustin Pop
    start = opts.start
2576 d77490c5 Iustin Pop
    os_type = opts.os
2577 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2578 d77490c5 Iustin Pop
    src_node = None
2579 d77490c5 Iustin Pop
    src_path = None
2580 25a8792c Iustin Pop
    no_install = opts.no_install
2581 e588764d Iustin Pop
    identify_defaults = False
2582 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2583 d77490c5 Iustin Pop
    start = False
2584 d77490c5 Iustin Pop
    os_type = None
2585 1ee8e01a Guido Trotter
    force_variant = False
2586 d77490c5 Iustin Pop
    src_node = opts.src_node
2587 d77490c5 Iustin Pop
    src_path = opts.src_dir
2588 25a8792c Iustin Pop
    no_install = None
2589 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2590 d77490c5 Iustin Pop
  else:
2591 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2592 d77490c5 Iustin Pop
2593 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2594 d77490c5 Iustin Pop
                                disks=disks,
2595 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2596 d77490c5 Iustin Pop
                                nics=nics,
2597 d4117a72 Apollon Oikonomopoulos
                                conflicts_check=opts.conflicts_check,
2598 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2599 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2600 460d22be Iustin Pop
                                name_check=opts.name_check,
2601 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2602 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2603 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2604 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2605 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2606 d77490c5 Iustin Pop
                                hvparams=hvparams,
2607 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2608 062a7100 Iustin Pop
                                osparams=opts.osparams,
2609 d77490c5 Iustin Pop
                                mode=mode,
2610 d77490c5 Iustin Pop
                                start=start,
2611 d77490c5 Iustin Pop
                                os_type=os_type,
2612 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2613 d77490c5 Iustin Pop
                                src_node=src_node,
2614 25a8792c Iustin Pop
                                src_path=src_path,
2615 a57981c5 Apollon Oikonomopoulos
                                tags=tags,
2616 e588764d Iustin Pop
                                no_install=no_install,
2617 10889e0c René Nussbaumer
                                identify_defaults=identify_defaults,
2618 10889e0c René Nussbaumer
                                ignore_ipolicy=opts.ignore_ipolicy)
2619 d77490c5 Iustin Pop
2620 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2621 d77490c5 Iustin Pop
  return 0
2622 d77490c5 Iustin Pop
2623 d77490c5 Iustin Pop
2624 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2625 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2626 7e49b6ce Michael Hanselmann

2627 7e49b6ce Michael Hanselmann
  """
2628 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2629 7e49b6ce Michael Hanselmann
    """Initializes this class.
2630 7e49b6ce Michael Hanselmann

2631 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2632 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2633 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2634 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2635 7e49b6ce Michael Hanselmann
    @type master_node: string
2636 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2637 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2638 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2639 7e49b6ce Michael Hanselmann

2640 7e49b6ce Michael Hanselmann
    """
2641 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2642 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2643 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2644 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2645 7e49b6ce Michael Hanselmann
2646 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2647 7e49b6ce Michael Hanselmann
2648 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2649 7e49b6ce Michael Hanselmann
                            if name != master_node]
2650 7e49b6ce Michael Hanselmann
2651 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2652 7e49b6ce Michael Hanselmann
2653 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2654 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2655 7e49b6ce Michael Hanselmann

2656 7e49b6ce Michael Hanselmann
    @type node_name: string
2657 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2658 7e49b6ce Michael Hanselmann
    @type cmd: list
2659 7e49b6ce Michael Hanselmann
    @param cmd: Command
2660 7e49b6ce Michael Hanselmann

2661 7e49b6ce Michael Hanselmann
    """
2662 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2663 7e49b6ce Michael Hanselmann
      # No need to use SSH
2664 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2665 7e49b6ce Michael Hanselmann
    else:
2666 052783ff Michael Hanselmann
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2667 052783ff Michael Hanselmann
                            utils.ShellQuoteArgs(cmd))
2668 7e49b6ce Michael Hanselmann
2669 7e49b6ce Michael Hanselmann
    if result.failed:
2670 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2671 7e49b6ce Michael Hanselmann
      if node_name:
2672 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2673 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2674 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2675 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2676 7e49b6ce Michael Hanselmann
2677 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2678 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2679 7e49b6ce Michael Hanselmann

2680 7e49b6ce Michael Hanselmann
    @type fn: callable
2681 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2682 7e49b6ce Michael Hanselmann

2683 7e49b6ce Michael Hanselmann
    """
2684 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2685 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2686 ee4a14c0 Michael Hanselmann
    watcher_block = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
2687 7e49b6ce Michael Hanselmann
    try:
2688 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2689 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2690 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2691 7e49b6ce Michael Hanselmann
2692 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2693 7e49b6ce Michael Hanselmann
      # ones are finished
2694 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2695 ee4a14c0 Michael Hanselmann
      self._RunCmd(None, [pathutils.DAEMON_UTIL, "stop-master"])
2696 7e49b6ce Michael Hanselmann
      try:
2697 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2698 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2699 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2700 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "stop-all"])
2701 7e49b6ce Michael Hanselmann
2702 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2703 7e49b6ce Michael Hanselmann
        try:
2704 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2705 d512e84b Michael Hanselmann
        except Exception, err:
2706 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2707 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2708 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2709 7e49b6ce Michael Hanselmann
          raise
2710 7e49b6ce Michael Hanselmann
      finally:
2711 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2712 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2713 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2714 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "start-all"])
2715 7e49b6ce Michael Hanselmann
    finally:
2716 7e49b6ce Michael Hanselmann
      # Resume watcher
2717 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2718 7e49b6ce Michael Hanselmann
2719 7e49b6ce Michael Hanselmann
2720 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2721 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2722 7e49b6ce Michael Hanselmann

2723 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2724 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2725 7e49b6ce Michael Hanselmann
  @type fn: callable
2726 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2727 7e49b6ce Michael Hanselmann

2728 7e49b6ce Michael Hanselmann
  """
2729 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2730 7e49b6ce Michael Hanselmann
2731 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2732 7e49b6ce Michael Hanselmann
  cl = GetClient()
2733 7e49b6ce Michael Hanselmann
2734 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2735 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2736 7e49b6ce Michael Hanselmann
2737 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2738 7e49b6ce Michael Hanselmann
2739 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2740 7e49b6ce Michael Hanselmann
  del cl
2741 7e49b6ce Michael Hanselmann
2742 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2743 7e49b6ce Michael Hanselmann
2744 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2745 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2746 7e49b6ce Michael Hanselmann
2747 7e49b6ce Michael Hanselmann
2748 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2749 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2750 9fbfbb7b Iustin Pop
                  units=None):
2751 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2752 137161c9 Michael Hanselmann

2753 9fbfbb7b Iustin Pop
  @type headers: dict
2754 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2755 9fbfbb7b Iustin Pop
      the table
2756 9fbfbb7b Iustin Pop
  @type fields: list
2757 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2758 9fbfbb7b Iustin Pop
      the data field
2759 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2760 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2761 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2762 9fbfbb7b Iustin Pop
      each field
2763 9fbfbb7b Iustin Pop
  @type data: list
2764 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2765 9fbfbb7b Iustin Pop
  @type numfields: list
2766 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2767 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2768 9fbfbb7b Iustin Pop
  @type unitfields: list
2769 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2770 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2771 9fbfbb7b Iustin Pop
  @type units: string or None
2772 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2773 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2774 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2775 137161c9 Michael Hanselmann

2776 137161c9 Michael Hanselmann
  """
2777 9fbfbb7b Iustin Pop
  if units is None:
2778 9fbfbb7b Iustin Pop
    if separator:
2779 9fbfbb7b Iustin Pop
      units = "m"
2780 9fbfbb7b Iustin Pop
    else:
2781 9fbfbb7b Iustin Pop
      units = "h"
2782 9fbfbb7b Iustin Pop
2783 137161c9 Michael Hanselmann
  if numfields is None:
2784 137161c9 Michael Hanselmann
    numfields = []
2785 137161c9 Michael Hanselmann
  if unitfields is None:
2786 137161c9 Michael Hanselmann
    unitfields = []
2787 137161c9 Michael Hanselmann
2788 b459a848 Andrea Spadaccini
  numfields = utils.FieldSet(*numfields)   # pylint: disable=W0142
2789 b459a848 Andrea Spadaccini
  unitfields = utils.FieldSet(*unitfields) # pylint: disable=W0142
2790 00430f8e Iustin Pop
2791 137161c9 Michael Hanselmann
  format_fields = []
2792 137161c9 Michael Hanselmann
  for field in fields:
2793 01ca31ae Iustin Pop
    if headers and field not in headers:
2794 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2795 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2796 71c1af58 Iustin Pop
      # variable fields)
2797 71c1af58 Iustin Pop
      headers[field] = field
2798 137161c9 Michael Hanselmann
    if separator is not None:
2799 137161c9 Michael Hanselmann
      format_fields.append("%s")
2800 00430f8e Iustin Pop
    elif numfields.Matches(field):
2801 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2802 137161c9 Michael Hanselmann
    else:
2803 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2804 137161c9 Michael Hanselmann
2805 137161c9 Michael Hanselmann
  if separator is None:
2806 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2807 d0c8c01d Iustin Pop
    format_str = " ".join(format_fields)
2808 137161c9 Michael Hanselmann
  else:
2809 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2810 137161c9 Michael Hanselmann
2811 137161c9 Michael Hanselmann
  for row in data:
2812 dcbd6288 Guido Trotter
    if row is None:
2813 dcbd6288 Guido Trotter
      continue
2814 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2815 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2816 137161c9 Michael Hanselmann
        try:
2817 137161c9 Michael Hanselmann
          val = int(val)
2818 691744c4 Iustin Pop
        except (TypeError, ValueError):
2819 137161c9 Michael Hanselmann
          pass
2820 137161c9 Michael Hanselmann
        else:
2821 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2822 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2823 137161c9 Michael Hanselmann
      if separator is None:
2824 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2825 137161c9 Michael Hanselmann
2826 16be8703 Iustin Pop
  result = []
2827 137161c9 Michael Hanselmann
  if headers:
2828 137161c9 Michael Hanselmann
    args = []
2829 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2830 137161c9 Michael Hanselmann
      hdr = headers[name]
2831 137161c9 Michael Hanselmann
      if separator is None:
2832 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2833 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2834 137161c9 Michael Hanselmann
      args.append(hdr)
2835 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2836 137161c9 Michael Hanselmann
2837 ec39d63c Michael Hanselmann
  if separator is None:
2838 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2839 ec39d63c Michael Hanselmann
2840 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2841 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2842 ec39d63c Michael Hanselmann
2843 137161c9 Michael Hanselmann
  for line in data:
2844 137161c9 Michael Hanselmann
    args = []
2845 dcbd6288 Guido Trotter
    if line is None:
2846 d0c8c01d Iustin Pop
      line = ["-" for _ in fields]
2847 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2848 137161c9 Michael Hanselmann
      if separator is None:
2849 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2850 137161c9 Michael Hanselmann
      args.append(line[idx])
2851 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2852 16be8703 Iustin Pop
2853 16be8703 Iustin Pop
  return result
2854 3386e7a9 Iustin Pop
2855 3386e7a9 Iustin Pop
2856 ee3aedff Michael Hanselmann
def _FormatBool(value):
2857 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
2858 ee3aedff Michael Hanselmann

2859 ee3aedff Michael Hanselmann
  """
2860 ee3aedff Michael Hanselmann
  if value:
2861 ee3aedff Michael Hanselmann
    return "Y"
2862 ee3aedff Michael Hanselmann
  return "N"
2863 ee3aedff Michael Hanselmann
2864 ee3aedff Michael Hanselmann
2865 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2866 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2867 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2868 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2869 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2870 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2871 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2872 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2873 ee3aedff Michael Hanselmann
  }
2874 ee3aedff Michael Hanselmann
2875 ee3aedff Michael Hanselmann
2876 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2877 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2878 ee3aedff Michael Hanselmann

2879 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2880 ee3aedff Michael Hanselmann
  @type override: dict
2881 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2882 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2883 ee3aedff Michael Hanselmann
  @type unit: string
2884 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2885 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2886 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2887 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2888 ee3aedff Michael Hanselmann

2889 ee3aedff Michael Hanselmann
  """
2890 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2891 ee3aedff Michael Hanselmann
  if fmt is not None:
2892 ee3aedff Michael Hanselmann
    return fmt
2893 ee3aedff Michael Hanselmann
2894 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2895 ee3aedff Michael Hanselmann
2896 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2897 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2898 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2899 ee3aedff Michael Hanselmann
2900 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2901 ee3aedff Michael Hanselmann
  if fmt is not None:
2902 ee3aedff Michael Hanselmann
    return fmt
2903 ee3aedff Michael Hanselmann
2904 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
2905 ee3aedff Michael Hanselmann
2906 ee3aedff Michael Hanselmann
2907 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
2908 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
2909 ee3aedff Michael Hanselmann

2910 ee3aedff Michael Hanselmann
  """
2911 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
2912 ee3aedff Michael Hanselmann
    """Initializes this class.
2913 ee3aedff Michael Hanselmann

2914 ee3aedff Michael Hanselmann
    @type fn: callable
2915 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2916 ee3aedff Michael Hanselmann
    @type status_fn: callable
2917 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
2918 f0b1bafe Iustin Pop
    @type verbose: boolean
2919 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
2920 ee3aedff Michael Hanselmann

2921 ee3aedff Michael Hanselmann
    """
2922 ee3aedff Michael Hanselmann
    self._fn = fn
2923 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
2924 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
2925 ee3aedff Michael Hanselmann
2926 ee3aedff Michael Hanselmann
  def __call__(self, data):
2927 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
2928 ee3aedff Michael Hanselmann

2929 ee3aedff Michael Hanselmann
    """
2930 ee3aedff Michael Hanselmann
    (status, value) = data
2931 ee3aedff Michael Hanselmann
2932 ee3aedff Michael Hanselmann
    # Report status
2933 ee3aedff Michael Hanselmann
    self._status_fn(status)
2934 ee3aedff Michael Hanselmann
2935 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
2936 ee3aedff Michael Hanselmann
      return self._fn(value)
2937 ee3aedff Michael Hanselmann
2938 ee3aedff Michael Hanselmann
    assert value is None, \
2939 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
2940 ee3aedff Michael Hanselmann
2941 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
2942 ee3aedff Michael Hanselmann
2943 ee3aedff Michael Hanselmann
2944 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
2945 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
2946 ee3aedff Michael Hanselmann

2947 ae95e419 René Nussbaumer
  @param status: The result status
2948 f2c6673d Michael Hanselmann
  @type verbose: boolean
2949 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
2950 ae95e419 René Nussbaumer
  @return: Text of result status
2951 a6070ef7 Michael Hanselmann

2952 ae95e419 René Nussbaumer
  """
2953 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
2954 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
2955 ae95e419 René Nussbaumer
  try:
2956 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
2957 ae95e419 René Nussbaumer
  except KeyError:
2958 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
2959 cbfa4f0f Michael Hanselmann
  else:
2960 cbfa4f0f Michael Hanselmann
    if verbose:
2961 cbfa4f0f Michael Hanselmann
      return verbose_text
2962 cbfa4f0f Michael Hanselmann
    return normal_text
2963 ee3aedff Michael Hanselmann
2964 ee3aedff Michael Hanselmann
2965 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
2966 f0b1bafe Iustin Pop
                      header=False, verbose=False):
2967 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
2968 ee3aedff Michael Hanselmann

2969 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
2970 ee3aedff Michael Hanselmann
  @param result: result of query operation
2971 ee3aedff Michael Hanselmann
  @type unit: string
2972 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
2973 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
2974 ee3aedff Michael Hanselmann
  @type format_override: dict
2975 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2976 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2977 ee3aedff Michael Hanselmann
  @type separator: string or None
2978 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2979 ee3aedff Michael Hanselmann
  @type header: bool
2980 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
2981 f0b1bafe Iustin Pop
  @type verbose: boolean
2982 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2983 ee3aedff Michael Hanselmann

2984 ee3aedff Michael Hanselmann
  """
2985 ee3aedff Michael Hanselmann
  if unit is None:
2986 ee3aedff Michael Hanselmann
    if separator:
2987 ee3aedff Michael Hanselmann
      unit = "m"
2988 ee3aedff Michael Hanselmann
    else:
2989 ee3aedff Michael Hanselmann
      unit = "h"
2990 ee3aedff Michael Hanselmann
2991 ee3aedff Michael Hanselmann
  if format_override is None:
2992 ee3aedff Michael Hanselmann
    format_override = {}
2993 ee3aedff Michael Hanselmann
2994 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
2995 ee3aedff Michael Hanselmann
2996 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
2997 ee3aedff Michael Hanselmann
    if status in stats:
2998 ee3aedff Michael Hanselmann
      stats[status] += 1
2999 ee3aedff Michael Hanselmann
3000 ee3aedff Michael Hanselmann
  columns = []
3001 ee3aedff Michael Hanselmann
  for fdef in result.fields:
3002 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
3003 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
3004 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
3005 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
3006 f0b1bafe Iustin Pop
                                                     verbose),
3007 ee3aedff Michael Hanselmann
                               align_right))
3008 ee3aedff Michael Hanselmann
3009 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
3010 ee3aedff Michael Hanselmann
3011 ee3aedff Michael Hanselmann
  # Collect statistics
3012 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
3013 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
3014 ee3aedff Michael Hanselmann
3015 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
3016 ee3aedff Michael Hanselmann
  # detected via the field definitions.
3017 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
3018 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
3019 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
3020 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
3021 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
3022 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
3023 ee3aedff Michael Hanselmann
  else:
3024 ee3aedff Michael Hanselmann
    status = QR_NORMAL
3025 ee3aedff Michael Hanselmann
3026 ee3aedff Michael Hanselmann
  return (status, table)
3027 ee3aedff Michael Hanselmann
3028 ee3aedff Michael Hanselmann
3029 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
3030 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
3031 ee3aedff Michael Hanselmann

3032 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3033 ee3aedff Michael Hanselmann

3034 ee3aedff Michael Hanselmann
  """
3035 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
3036 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
3037 ee3aedff Michael Hanselmann
3038 ee3aedff Michael Hanselmann
3039 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
3040 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
3041 ee3aedff Michael Hanselmann

3042 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3043 ee3aedff Michael Hanselmann

3044 ee3aedff Michael Hanselmann
  """
3045 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
3046 ee3aedff Michael Hanselmann
  if unknown:
3047 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
3048 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
3049 ee3aedff Michael Hanselmann
    return True
3050 ee3aedff Michael Hanselmann
3051 ee3aedff Michael Hanselmann
  return False
3052 ee3aedff Michael Hanselmann
3053 ee3aedff Michael Hanselmann
3054 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
3055 03ec545a Michael Hanselmann
                format_override=None, verbose=False, force_filter=False,
3056 6f287cf3 Iustin Pop
                namefield=None, qfilter=None, isnumeric=False):
3057 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
3058 ee3aedff Michael Hanselmann

3059 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3060 ee3aedff Michael Hanselmann
  @type fields: list of strings
3061 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3062 ee3aedff Michael Hanselmann
  @type names: list of strings
3063 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
3064 ee3aedff Michael Hanselmann
  @type unit: string or None
3065 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3066 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
3067 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
3068 ee3aedff Michael Hanselmann
  @type separator: string or None
3069 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3070 ee3aedff Michael Hanselmann
  @type header: bool
3071 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3072 2928de47 Michael Hanselmann
  @type force_filter: bool
3073 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
3074 ee3aedff Michael Hanselmann
  @type format_override: dict
3075 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3076 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3077 f0b1bafe Iustin Pop
  @type verbose: boolean
3078 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3079 03ec545a Michael Hanselmann
  @type namefield: string
3080 03ec545a Michael Hanselmann
  @param namefield: Name of field to use for simple filters (see
3081 03ec545a Michael Hanselmann
    L{qlang.MakeFilter} for details)
3082 f037e9d7 Michael Hanselmann
  @type qfilter: list or None
3083 f037e9d7 Michael Hanselmann
  @param qfilter: Query filter (in addition to names)
3084 6f287cf3 Iustin Pop
  @param isnumeric: bool
3085 6f287cf3 Iustin Pop
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3086 6f287cf3 Iustin Pop
    any simple filters built by namefield should use integer values to
3087 6f287cf3 Iustin Pop
    reflect that
3088 ee3aedff Michael Hanselmann

3089 ee3aedff Michael Hanselmann
  """
3090 ee3aedff Michael Hanselmann
  if not names:
3091 ee3aedff Michael Hanselmann
    names = None
3092 ee3aedff Michael Hanselmann
3093 6f287cf3 Iustin Pop
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3094 6f287cf3 Iustin Pop
                                isnumeric=isnumeric)
3095 f037e9d7 Michael Hanselmann
3096 f037e9d7 Michael Hanselmann
  if qfilter is None:
3097 f037e9d7 Michael Hanselmann
    qfilter = namefilter
3098 f037e9d7 Michael Hanselmann
  elif namefilter is not None:
3099 f037e9d7 Michael Hanselmann
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3100 2928de47 Michael Hanselmann
3101 727274dd Iustin Pop
  if cl is None:
3102 727274dd Iustin Pop
    cl = GetClient()
3103 727274dd Iustin Pop
3104 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
3105 ee3aedff Michael Hanselmann
3106 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3107 ee3aedff Michael Hanselmann
3108 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3109 ee3aedff Michael Hanselmann
                                     header=header,
3110 f0b1bafe Iustin Pop
                                     format_override=format_override,
3111 f0b1bafe Iustin Pop
                                     verbose=verbose)
3112 ee3aedff Michael Hanselmann
3113 ee3aedff Michael Hanselmann
  for line in data:
3114 ee3aedff Michael Hanselmann
    ToStdout(line)
3115 ee3aedff Michael Hanselmann
3116 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
3117 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
3118 ee3aedff Michael Hanselmann
3119 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
3120 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3121 ee3aedff Michael Hanselmann
3122 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
3123 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3124 ee3aedff Michael Hanselmann
3125 ee3aedff Michael Hanselmann
3126 c1912a48 Michael Hanselmann
def _FieldDescValues(fdef):
3127 c1912a48 Michael Hanselmann
  """Helper function for L{GenericListFields} to get query field description.
3128 c1912a48 Michael Hanselmann

3129 c1912a48 Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
3130 c1912a48 Michael Hanselmann
  @rtype: list
3131 c1912a48 Michael Hanselmann

3132 c1912a48 Michael Hanselmann
  """
3133 c1912a48 Michael Hanselmann
  return [
3134 c1912a48 Michael Hanselmann
    fdef.name,
3135 c1912a48 Michael Hanselmann
    _QFT_NAMES.get(fdef.kind, fdef.kind),
3136 c1912a48 Michael Hanselmann
    fdef.title,
3137 c1912a48 Michael Hanselmann
    fdef.doc,
3138 c1912a48 Michael Hanselmann
    ]
3139 c1912a48 Michael Hanselmann
3140 c1912a48 Michael Hanselmann
3141 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
3142 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
3143 ee3aedff Michael Hanselmann

3144 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3145 ee3aedff Michael Hanselmann
  @type fields: list of strings
3146 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3147 ee3aedff Michael Hanselmann
  @type separator: string or None
3148 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3149 ee3aedff Michael Hanselmann
  @type header: bool
3150 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3151 ee3aedff Michael Hanselmann

3152 ee3aedff Michael Hanselmann
  """
3153 ee3aedff Michael Hanselmann
  if cl is None:
3154 ee3aedff Michael Hanselmann
    cl = GetClient()
3155 ee3aedff Michael Hanselmann
3156 ee3aedff Michael Hanselmann
  if not fields:
3157 ee3aedff Michael Hanselmann
    fields = None
3158 ee3aedff Michael Hanselmann
3159 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
3160 ee3aedff Michael Hanselmann
3161 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3162 ee3aedff Michael Hanselmann
3163 ee3aedff Michael Hanselmann
  columns = [
3164 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
3165 c1912a48 Michael Hanselmann
    TableColumn("Type", str, False),
3166 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
3167 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
3168 ee3aedff Michael Hanselmann
    ]
3169 ee3aedff Michael Hanselmann
3170 c1912a48 Michael Hanselmann
  rows = map(_FieldDescValues, response.fields)
3171 ee3aedff Michael Hanselmann
3172 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
3173 ee3aedff Michael Hanselmann
    ToStdout(line)
3174 ee3aedff Michael Hanselmann
3175 ee3aedff Michael Hanselmann
  if found_unknown:
3176 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3177 ee3aedff Michael Hanselmann
3178 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3179 ee3aedff Michael Hanselmann
3180 ee3aedff Michael Hanselmann
3181 ee3aedff Michael Hanselmann
class TableColumn:
3182 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
3183 ee3aedff Michael Hanselmann

3184 ee3aedff Michael Hanselmann
  """
3185 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
3186 ee3aedff Michael Hanselmann
    """Initializes this class.
3187 ee3aedff Michael Hanselmann

3188 ee3aedff Michael Hanselmann
    @type title: string
3189 ee3aedff Michael Hanselmann
    @param title: Column title
3190 ee3aedff Michael Hanselmann
    @type fn: callable
3191 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3192 ee3aedff Michael Hanselmann
    @type align_right: bool
3193 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
3194 ee3aedff Michael Hanselmann

3195 ee3aedff Michael Hanselmann
    """
3196 ee3aedff Michael Hanselmann
    self.title = title
3197 ee3aedff Michael Hanselmann
    self.format = fn
3198 ee3aedff Michael Hanselmann
    self.align_right = align_right
3199 ee3aedff Michael Hanselmann
3200 ee3aedff Michael Hanselmann
3201 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
3202 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
3203 ee3aedff Michael Hanselmann

3204 ee3aedff Michael Hanselmann
  """
3205 ee3aedff Michael Hanselmann
  if align_right:
3206 ee3aedff Michael Hanselmann
    sign = ""
3207 ee3aedff Michael Hanselmann
  else:
3208 ee3aedff Michael Hanselmann
    sign = "-"
3209 ee3aedff Michael Hanselmann
3210 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
3211 ee3aedff Michael Hanselmann
3212 ee3aedff Michael Hanselmann
3213 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
3214 ee3aedff Michael Hanselmann
  """Formats data as a table.
3215 ee3aedff Michael Hanselmann

3216 ee3aedff Michael Hanselmann
  @type rows: list of lists
3217 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
3218 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
3219 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
3220 ee3aedff Michael Hanselmann
  @type header: bool
3221 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3222 ee3aedff Michael Hanselmann
  @type separator: string or None
3223 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
3224 ee3aedff Michael Hanselmann

3225 ee3aedff Michael Hanselmann
  """
3226 ee3aedff Michael Hanselmann
  if header:
3227 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
3228 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
3229 ee3aedff Michael Hanselmann
  else:
3230 ee3aedff Michael Hanselmann
    data = []
3231 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
3232 ee3aedff Michael Hanselmann
3233 ee3aedff Michael Hanselmann
  # Format row data
3234 ee3aedff Michael Hanselmann
  for row in rows:
3235 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
3236 ee3aedff Michael Hanselmann
3237 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
3238 ee3aedff Michael Hanselmann
3239 ee3aedff Michael Hanselmann
    if separator is None:
3240 ee3aedff Michael Hanselmann
      # Update column widths
3241 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3242 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
3243 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
3244 ee3aedff Michael Hanselmann
3245 ee3aedff Michael Hanselmann
    data.append(formatted)
3246 ee3aedff Michael Hanselmann
3247 ee3aedff Michael Hanselmann
  if separator is not None:
3248 ee3aedff Michael Hanselmann
    # Return early if a separator is used
3249 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
3250 ee3aedff Michael Hanselmann
3251 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
3252 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
3253 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
3254 ee3aedff Michael Hanselmann
3255 ee3aedff Michael Hanselmann
  # Build format string
3256 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3257 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
3258 ee3aedff Michael Hanselmann
3259 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
3260 ee3aedff Michael Hanselmann
3261 ee3aedff Michael Hanselmann
3262 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
3263 3386e7a9 Iustin Pop
  """Formats a given timestamp.
3264 3386e7a9 Iustin Pop

3265 3386e7a9 Iustin Pop
  @type ts: timestamp
3266 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3267 3386e7a9 Iustin Pop

3268 3386e7a9 Iustin Pop
  @rtype: string
3269 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
3270 3386e7a9 Iustin Pop

3271 3386e7a9 Iustin Pop
  """
3272 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3273 d0c8c01d Iustin Pop
    return "?"
3274 26a72a48 Michael Hanselmann
3275 26a72a48 Michael Hanselmann
  (sec, usecs) = ts
3276 26a72a48 Michael Hanselmann
  return utils.FormatTime(sec, usecs=usecs)
3277 2241e2b9 Iustin Pop
3278 2241e2b9 Iustin Pop
3279 2241e2b9 Iustin Pop
def ParseTimespec(value):
3280 2241e2b9 Iustin Pop
  """Parse a time specification.
3281 2241e2b9 Iustin Pop

3282 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
3283 2241e2b9 Iustin Pop

3284 2241e2b9 Iustin Pop
    - s: seconds
3285 2241e2b9 Iustin Pop
    - m: minutes
3286 2241e2b9 Iustin Pop
    - h: hours
3287 2241e2b9 Iustin Pop
    - d: day
3288 2241e2b9 Iustin Pop
    - w: weeks
3289 2241e2b9 Iustin Pop

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

3292 2241e2b9 Iustin Pop
  """
3293 2241e2b9 Iustin Pop
  value = str(value)
3294 2241e2b9 Iustin Pop
  if not value:
3295 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed",
3296 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
3297 2241e2b9 Iustin Pop
  suffix_map = {
3298 d0c8c01d Iustin Pop
    "s": 1,
3299 d0c8c01d Iustin Pop
    "m": 60,
3300 d0c8c01d Iustin Pop
    "h": 3600,
3301 d0c8c01d Iustin Pop
    "d": 86400,
3302 d0c8c01d Iustin Pop
    "w": 604800,
3303 2241e2b9 Iustin Pop
    }
3304 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
3305 2241e2b9 Iustin Pop
    try:
3306 2241e2b9 Iustin Pop
      value = int(value)
3307 691744c4 Iustin Pop
    except (TypeError, ValueError):
3308 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3309 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3310 2241e2b9 Iustin Pop
  else:
3311 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
3312 2241e2b9 Iustin Pop
    value = value[:-1]
3313 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
3314 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
3315 2cfbc784 Iustin Pop
                                 " suffix passed)", errors.ECODE_INVAL)
3316 2241e2b9 Iustin Pop
    try:
3317 2241e2b9 Iustin Pop
      value = int(value) * multiplier
3318 691744c4 Iustin Pop
    except (TypeError, ValueError):
3319 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3320 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3321 2241e2b9 Iustin Pop
  return value
3322 46fbdd04 Iustin Pop
3323 46fbdd04 Iustin Pop
3324 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3325 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
3326 4040a784 Iustin Pop
  """Returns the names of online nodes.
3327 4040a784 Iustin Pop

3328 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
3329 4040a784 Iustin Pop
  the online nodes.
3330 4040a784 Iustin Pop

3331 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
3332 4040a784 Iustin Pop
      offline ones)
3333 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
3334 4040a784 Iustin Pop
  @type nowarn: boolean
3335 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
3336 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
3337 4040a784 Iustin Pop
      note is not displayed
3338 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
3339 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
3340 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
3341 e9e26bb3 Iustin Pop
      (if any)
3342 e9e26bb3 Iustin Pop
  @type filter_master: boolean
3343 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
3344 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
3345 e9e26bb3 Iustin Pop
      node name against the list)
3346 05484a24 Michael Hanselmann
  @type nodegroup: string
3347 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
3348 4040a784 Iustin Pop

3349 4040a784 Iustin Pop
  """
3350 4040a784 Iustin Pop
  if cl is None:
3351 4040a784 Iustin Pop
    cl = GetClient()
3352 4040a784 Iustin Pop
3353 2e5c33db Iustin Pop
  qfilter = []
3354 05484a24 Michael Hanselmann
3355 05484a24 Michael Hanselmann
  if nodes:
3356 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3357 05484a24 Michael Hanselmann
3358 05484a24 Michael Hanselmann
  if nodegroup is not None:
3359 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3360 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3361 e9e26bb3 Iustin Pop
3362 e9e26bb3 Iustin Pop
  if filter_master:
3363 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3364 05484a24 Michael Hanselmann
3365 2e5c33db Iustin Pop
  if qfilter:
3366 2e5c33db Iustin Pop
    if len(qfilter) > 1:
3367 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
3368 05484a24 Michael Hanselmann
    else:
3369 2e5c33db Iustin Pop
      assert len(qfilter) == 1
3370 2e5c33db Iustin Pop
      final_filter = qfilter[0]
3371 e9e26bb3 Iustin Pop
  else:
3372 05484a24 Michael Hanselmann
    final_filter = None
3373 05484a24 Michael Hanselmann
3374 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3375 05484a24 Michael Hanselmann
3376 05484a24 Michael Hanselmann
  def _IsOffline(row):
3377 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
3378 05484a24 Michael Hanselmann
    return offline
3379 05484a24 Michael Hanselmann
3380 05484a24 Michael Hanselmann
  def _GetName(row):
3381 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
3382 05484a24 Michael Hanselmann
    return name
3383 05484a24 Michael Hanselmann
3384 05484a24 Michael Hanselmann
  def _GetSip(row):
3385 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
3386 05484a24 Michael Hanselmann
    return sip
3387 05484a24 Michael Hanselmann
3388 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
3389 e9e26bb3 Iustin Pop
3390 4040a784 Iustin Pop
  if offline and not nowarn:
3391 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
3392 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
3393 05484a24 Michael Hanselmann
3394 05484a24 Michael Hanselmann
  if secondary_ips:
3395 05484a24 Michael Hanselmann
    fn = _GetSip
3396 05484a24 Michael Hanselmann
  else:
3397 05484a24 Michael Hanselmann
    fn = _GetName
3398 05484a24 Michael Hanselmann
3399 05484a24 Michael Hanselmann
  return map(fn, online)
3400 4040a784 Iustin Pop
3401 4040a784 Iustin Pop
3402 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3403 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3404 46fbdd04 Iustin Pop

3405 46fbdd04 Iustin Pop
  @type stream: file object
3406 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3407 46fbdd04 Iustin Pop
  @type txt: str
3408 46fbdd04 Iustin Pop
  @param txt: the message
3409 46fbdd04 Iustin Pop

3410 46fbdd04 Iustin Pop
  """
3411 225e2544 Iustin Pop
  try:
3412 225e2544 Iustin Pop
    if args:
3413 225e2544 Iustin Pop
      args = tuple(args)
3414 225e2544 Iustin Pop
      stream.write(txt % args)
3415 225e2544 Iustin Pop
    else:
3416 225e2544 Iustin Pop
      stream.write(txt)
3417 d0c8c01d Iustin Pop
    stream.write("\n")
3418 225e2544 Iustin Pop
    stream.flush()
3419 225e2544 Iustin Pop
  except IOError, err:
3420 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3421 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3422 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3423 225e2544 Iustin Pop
    else:
3424 225e2544 Iustin Pop
      raise
3425 46fbdd04 Iustin Pop
3426 46fbdd04 Iustin Pop
3427 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3428 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3429 46fbdd04 Iustin Pop

3430 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3431 46fbdd04 Iustin Pop

3432 46fbdd04 Iustin Pop
  @type txt: str
3433 46fbdd04 Iustin Pop
  @param txt: the message
3434 46fbdd04 Iustin Pop

3435 46fbdd04 Iustin Pop
  """
3436 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3437 46fbdd04 Iustin Pop
3438 46fbdd04 Iustin Pop
3439 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3440 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3441 46fbdd04 Iustin Pop

3442 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3443 46fbdd04 Iustin Pop

3444 46fbdd04 Iustin Pop
  @type txt: str
3445 46fbdd04 Iustin Pop
  @param txt: the message
3446 46fbdd04 Iustin Pop

3447 46fbdd04 Iustin Pop
  """
3448 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3449 479636a3 Iustin Pop
3450 479636a3 Iustin Pop
3451 479636a3 Iustin Pop
class JobExecutor(object):
3452 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3453 479636a3 Iustin Pop

3454 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3455 479636a3 Iustin Pop
  GetResults() calls.
3456 479636a3 Iustin Pop

3457 479636a3 Iustin Pop
  """
3458 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3459 479636a3 Iustin Pop
    self.queue = []
3460 479636a3 Iustin Pop
    if cl is None:
3461 479636a3 Iustin Pop
      cl = GetClient()
3462 479636a3 Iustin Pop
    self.cl = cl
3463 479636a3 Iustin Pop
    self.verbose = verbose
3464 23b4b983 Iustin Pop
    self.jobs = []
3465 cff5fa7f Iustin Pop
    self.opts = opts
3466 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3467 60452edf Michael Hanselmann
    self._counter = itertools.count()
3468 479636a3 Iustin Pop
3469 8d99a8bf Michael Hanselmann
  @staticmethod
3470 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3471 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3472 8d99a8bf Michael Hanselmann

3473 8d99a8bf Michael Hanselmann
    """
3474 8d99a8bf Michael Hanselmann
    if name:
3475 8d99a8bf Michael Hanselmann
      return fmt % name
3476 8d99a8bf Michael Hanselmann
3477 8d99a8bf Michael Hanselmann
    return ""
3478 8d99a8bf Michael Hanselmann
3479 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3480 23b4b983 Iustin Pop
    """Record a job for later submit.
3481 479636a3 Iustin Pop

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

3485 479636a3 Iustin Pop
    """
3486 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3487 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3488 23b4b983 Iustin Pop
3489 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3490 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3491 8d99a8bf Michael Hanselmann

3492 8d99a8bf Michael Hanselmann
    """
3493 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3494 8d99a8bf Michael Hanselmann
3495 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3496 23b4b983 Iustin Pop
    """Submit all pending jobs.
3497 23b4b983 Iustin Pop

3498 23b4b983 Iustin Pop
    """
3499 66ecc479 Guido Trotter
    if each:
3500 66ecc479 Guido Trotter
      results = []
3501 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3502 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3503 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3504 519fafa1 Andrea Spadaccini
        results.append([True, self.cl.SubmitJob(ops)[0]])
3505 66ecc479 Guido Trotter
    else:
3506 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3507 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3508 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3509 5299e61f Iustin Pop
3510 5299e61f Iustin Pop
  def _ChooseJob(self):
3511 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3512 5299e61f Iustin Pop

3513 5299e61f Iustin Pop
    """
3514 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3515 5299e61f Iustin Pop
3516 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3517 11705e3d Iustin Pop
                               ["status"])
3518 5299e61f Iustin Pop
    assert result
3519 5299e61f Iustin Pop
3520 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3521 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3522 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3523 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3524 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3525 91c622a8 Iustin Pop
        # job is still present and waiting
3526 5299e61f Iustin Pop
        continue
3527 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3528 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3529 5299e61f Iustin Pop
      return job_data
3530 5299e61f Iustin Pop
3531 5299e61f Iustin Pop
    # no job found
3532 5299e61f Iustin Pop
    return self.jobs.pop(0)
3533 479636a3 Iustin Pop
3534 479636a3 Iustin Pop
  def GetResults(self):
3535 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3536 479636a3 Iustin Pop

3537 479636a3 Iustin Pop
    @rtype: list
3538 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3539 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3540 479636a3 Iustin Pop
        there will be the error message
3541 479636a3 Iustin Pop

3542 479636a3 Iustin Pop
    """
3543 23b4b983 Iustin Pop
    if not self.jobs:
3544 23b4b983 Iustin Pop
      self.SubmitPending()
3545 479636a3 Iustin Pop
    results = []
3546 479636a3 Iustin Pop
    if self.verbose:
3547 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3548 23b4b983 Iustin Pop
      if ok_jobs:
3549 4474f112 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3550 5299e61f Iustin Pop
3551 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
3552 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3553 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
3554 4474f112 Iustin Pop
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3555 c63355f2 Iustin Pop
      results.append((idx, False, jid))
3556 5299e61f Iustin Pop
3557 5299e61f Iustin Pop
    while self.jobs:
3558 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
3559 4474f112 Iustin Pop
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3560 479636a3 Iustin Pop
      try:
3561 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3562 479636a3 Iustin Pop
        success = True
3563 91c622a8 Iustin Pop
      except errors.JobLost, err:
3564 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3565 4474f112 Iustin Pop
        ToStderr("Job %s%s has been archived, cannot check its result",
3566 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"))
3567 91c622a8 Iustin Pop
        success = False
3568 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3569 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3570 479636a3 Iustin Pop
        success = False
3571 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3572 4474f112 Iustin Pop
        ToStderr("Job %s%s has failed: %s",
3573 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"), job_result)
3574 479636a3 Iustin Pop
3575 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3576 5299e61f Iustin Pop
3577 5299e61f Iustin Pop
    # sort based on the index, then drop it
3578 5299e61f Iustin Pop
    results.sort()
3579 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3580 5299e61f Iustin Pop
3581 479636a3 Iustin Pop
    return results
3582 479636a3 Iustin Pop
3583 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3584 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3585 479636a3 Iustin Pop

3586 479636a3 Iustin Pop
    @type wait: boolean
3587 479636a3 Iustin Pop
    @param wait: whether to wait or not
3588 479636a3 Iustin Pop

3589 479636a3 Iustin Pop
    """
3590 479636a3 Iustin Pop
    if wait:
3591 479636a3 Iustin Pop
      return self.GetResults()
3592 479636a3 Iustin Pop
    else:
3593 23b4b983 Iustin Pop
      if not self.jobs:
3594 23b4b983 Iustin Pop
        self.SubmitPending()
3595 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3596 23b4b983 Iustin Pop
        if status:
3597 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3598 23b4b983 Iustin Pop
        else:
3599 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3600 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3601 acd19189 René Nussbaumer
3602 acd19189 René Nussbaumer
3603 4d99964c Bernardo Dal Seno
def FormatParamsDictInfo(param_dict, actual):
3604 4d99964c Bernardo Dal Seno
  """Formats a parameter dictionary.
3605 4d99964c Bernardo Dal Seno

3606 4d99964c Bernardo Dal Seno
  @type param_dict: dict
3607 4d99964c Bernardo Dal Seno
  @param param_dict: the own parameters
3608 4d99964c Bernardo Dal Seno
  @type actual: dict
3609 4d99964c Bernardo Dal Seno
  @param actual: the current parameter set (including defaults)
3610 4d99964c Bernardo Dal Seno
  @rtype: dict
3611 4d99964c Bernardo Dal Seno
  @return: dictionary where the value of each parameter is either a fully
3612 4d99964c Bernardo Dal Seno
      formatted string or a dictionary containing formatted strings
3613 4d99964c Bernardo Dal Seno

3614 4d99964c Bernardo Dal Seno
  """
3615 4d99964c Bernardo Dal Seno
  ret = {}
3616 4d99964c Bernardo Dal Seno
  for (key, data) in actual.items():
3617 4d99964c Bernardo Dal Seno
    if isinstance(data, dict) and data:
3618 4d99964c Bernardo Dal Seno
      ret[key] = FormatParamsDictInfo(param_dict.get(key, {}), data)
3619 4d99964c Bernardo Dal Seno
    else:
3620 4d99964c Bernardo Dal Seno
      ret[key] = str(param_dict.get(key, "default (%s)" % data))
3621 4d99964c Bernardo Dal Seno
  return ret
3622 4d99964c Bernardo Dal Seno
3623 4d99964c Bernardo Dal Seno
3624 d00884a2 Bernardo Dal Seno
def _FormatListInfoDefault(data, def_data):
3625 d00884a2 Bernardo Dal Seno
  if data is not None:
3626 d00884a2 Bernardo Dal Seno
    ret = utils.CommaJoin(data)
3627 d00884a2 Bernardo Dal Seno
  else:
3628 d00884a2 Bernardo Dal Seno
    ret = "default (%s)" % utils.CommaJoin(def_data)
3629 d00884a2 Bernardo Dal Seno
  return ret
3630 d00884a2 Bernardo Dal Seno
3631 d00884a2 Bernardo Dal Seno
3632 d00884a2 Bernardo Dal Seno
def FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster):
3633 d00884a2 Bernardo Dal Seno
  """Formats an instance policy.
3634 d00884a2 Bernardo Dal Seno

3635 d00884a2 Bernardo Dal Seno
  @type custom_ipolicy: dict
3636 d00884a2 Bernardo Dal Seno
  @param custom_ipolicy: own policy
3637 d00884a2 Bernardo Dal Seno
  @type eff_ipolicy: dict
3638 d00884a2 Bernardo Dal Seno
  @param eff_ipolicy: effective policy (including defaults); ignored for
3639 d00884a2 Bernardo Dal Seno
      cluster
3640 d00884a2 Bernardo Dal Seno
  @type iscluster: bool
3641 d00884a2 Bernardo Dal Seno
  @param iscluster: the policy is at cluster level
3642 d00884a2 Bernardo Dal Seno
  @rtype: list of pairs
3643 d00884a2 Bernardo Dal Seno
  @return: formatted data, suitable for L{PrintGenericInfo}
3644 d00884a2 Bernardo Dal Seno

3645 d00884a2 Bernardo Dal Seno
  """
3646 d00884a2 Bernardo Dal Seno
  if iscluster:
3647 d00884a2 Bernardo Dal Seno
    eff_ipolicy = custom_ipolicy
3648 d00884a2 Bernardo Dal Seno
3649 d00884a2 Bernardo Dal Seno
  custom_minmax = custom_ipolicy.get(constants.ISPECS_MINMAX)
3650 d00884a2 Bernardo Dal Seno
  ret = [
3651 d00884a2 Bernardo Dal Seno
    (key,
3652 d00884a2 Bernardo Dal Seno
     FormatParamsDictInfo(custom_minmax.get(key, {}),
3653 d00884a2 Bernardo Dal Seno
                          eff_ipolicy[constants.ISPECS_MINMAX][key]))
3654 d00884a2 Bernardo Dal Seno
    for key in constants.ISPECS_MINMAX_KEYS
3655 d00884a2 Bernardo Dal Seno
    ]
3656 d00884a2 Bernardo Dal Seno
  if iscluster:
3657 d00884a2 Bernardo Dal Seno
    stdspecs = custom_ipolicy[constants.ISPECS_STD]
3658 d00884a2 Bernardo Dal Seno
    ret.append(
3659 d00884a2 Bernardo Dal Seno
      (constants.ISPECS_STD,
3660 d00884a2 Bernardo Dal Seno
       FormatParamsDictInfo(stdspecs, stdspecs))
3661 d00884a2 Bernardo Dal Seno
      )
3662 d00884a2 Bernardo Dal Seno
3663 d00884a2 Bernardo Dal Seno
  ret.append(
3664 d00884a2 Bernardo Dal Seno
    ("enabled disk templates",
3665 d00884a2 Bernardo Dal Seno
     _FormatListInfoDefault(custom_ipolicy.get(constants.IPOLICY_DTS),
3666 d00884a2 Bernardo Dal Seno
                            eff_ipolicy[constants.IPOLICY_DTS]))
3667 d00884a2 Bernardo Dal Seno
    )
3668 d00884a2 Bernardo Dal Seno
  ret.extend([
3669 d00884a2 Bernardo Dal Seno
    (key, str(custom_ipolicy.get(key, "default (%s)" % eff_ipolicy[key])))
3670 d00884a2 Bernardo Dal Seno
    for key in constants.IPOLICY_PARAMETERS
3671 d00884a2 Bernardo Dal Seno
    ])
3672 d00884a2 Bernardo Dal Seno
  return ret
3673 d00884a2 Bernardo Dal Seno
3674 d00884a2 Bernardo Dal Seno
3675 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3676 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3677 25bd815c René Nussbaumer

3678 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3679 25bd815c René Nussbaumer
  on a given list of list_type.
3680 25bd815c René Nussbaumer

3681 25bd815c René Nussbaumer
  @type names: list
3682 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3683 25bd815c René Nussbaumer
      we ask for confirmation
3684 25bd815c René Nussbaumer
  @type list_type: str
3685 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3686 25bd815c René Nussbaumer
  @type text: str
3687 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3688 25bd815c René Nussbaumer
  @rtype: boolean
3689 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3690 25bd815c René Nussbaumer

3691 25bd815c René Nussbaumer
  """
3692 25bd815c René Nussbaumer
  count = len(names)
3693 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3694 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3695 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3696 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3697 25bd815c René Nussbaumer
3698 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3699 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3700 25bd815c René Nussbaumer
3701 25bd815c René Nussbaumer
  if count > 20:
3702 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3703 25bd815c René Nussbaumer
    question = msg
3704 25bd815c René Nussbaumer
  else:
3705 25bd815c René Nussbaumer
    question = msg + affected
3706 25bd815c René Nussbaumer
3707 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3708 25bd815c René Nussbaumer
  if choice == "v":
3709 25bd815c René Nussbaumer
    choices.pop(1)
3710 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3711 25bd815c René Nussbaumer
  return choice
3712 703fa9ab Iustin Pop
3713 703fa9ab Iustin Pop
3714 cd415612 René Nussbaumer
def _MaybeParseUnit(elements):
3715 cd415612 René Nussbaumer
  """Parses and returns an array of potential values with units.
3716 cd415612 René Nussbaumer

3717 cd415612 René Nussbaumer
  """
3718 ef40c537 René Nussbaumer
  parsed = {}
3719 ef40c537 René Nussbaumer
  for k, v in elements.items():
3720 ef40c537 René Nussbaumer
    if v == constants.VALUE_DEFAULT:
3721 ef40c537 René Nussbaumer
      parsed[k] = v
3722 cd415612 René Nussbaumer
    else:
3723 ef40c537 René Nussbaumer
      parsed[k] = utils.ParseUnit(v)
3724 cd415612 René Nussbaumer
  return parsed
3725 cd415612 René Nussbaumer
3726 cd415612 René Nussbaumer
3727 d948c101 Bernardo Dal Seno
def _InitIspecsFromOpts(ipolicy, ispecs_mem_size, ispecs_cpu_count,
3728 d948c101 Bernardo Dal Seno
                        ispecs_disk_count, ispecs_disk_size, ispecs_nic_count,
3729 d948c101 Bernardo Dal Seno
                        group_ipolicy, allowed_values):
3730 d67e0a94 Iustin Pop
  try:
3731 d67e0a94 Iustin Pop
    if ispecs_mem_size:
3732 cd415612 René Nussbaumer
      ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
3733 d67e0a94 Iustin Pop
    if ispecs_disk_size:
3734 cd415612 René Nussbaumer
      ispecs_disk_size = _MaybeParseUnit(ispecs_disk_size)
3735 d67e0a94 Iustin Pop
  except (TypeError, ValueError, errors.UnitParseError), err:
3736 d67e0a94 Iustin Pop
    raise errors.OpPrereqError("Invalid disk (%s) or memory (%s) size"
3737 d67e0a94 Iustin Pop
                               " in policy: %s" %
3738 d67e0a94 Iustin Pop
                               (ispecs_disk_size, ispecs_mem_size, err),
3739 d67e0a94 Iustin Pop
                               errors.ECODE_INVAL)
3740 d67e0a94 Iustin Pop
3741 703fa9ab Iustin Pop
  # prepare ipolicy dict
3742 d948c101 Bernardo Dal Seno
  ispecs_transposed = {
3743 703fa9ab Iustin Pop
    constants.ISPEC_MEM_SIZE: ispecs_mem_size,
3744 703fa9ab Iustin Pop
    constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
3745 703fa9ab Iustin Pop
    constants.ISPEC_DISK_COUNT: ispecs_disk_count,
3746 703fa9ab Iustin Pop
    constants.ISPEC_DISK_SIZE: ispecs_disk_size,
3747 703fa9ab Iustin Pop
    constants.ISPEC_NIC_COUNT: ispecs_nic_count,
3748 703fa9ab Iustin Pop
    }
3749 703fa9ab Iustin Pop
3750 703fa9ab Iustin Pop
  # first, check that the values given are correct
3751 703fa9ab Iustin Pop
  if group_ipolicy:
3752 703fa9ab Iustin Pop
    forced_type = TISPECS_GROUP_TYPES
3753 703fa9ab Iustin Pop
  else:
3754 703fa9ab Iustin Pop
    forced_type = TISPECS_CLUSTER_TYPES
3755 d948c101 Bernardo Dal Seno
  for specs in ispecs_transposed.values():
3756 703fa9ab Iustin Pop
    utils.ForceDictType(specs, forced_type, allowed_values=allowed_values)
3757 703fa9ab Iustin Pop
3758 703fa9ab Iustin Pop
  # then transpose
3759 da5f09ef Bernardo Dal Seno
  ispecs = {
3760 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MIN: {},
3761 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MAX: {},
3762 da5f09ef Bernardo Dal Seno
    constants.ISPECS_STD: {},
3763 da5f09ef Bernardo Dal Seno
    }
3764 d948c101 Bernardo Dal Seno
  for (name, specs) in ispecs_transposed.iteritems():
3765 703fa9ab Iustin Pop
    assert name in constants.ISPECS_PARAMETERS
3766 703fa9ab Iustin Pop
    for key, val in specs.items(): # {min: .. ,max: .., std: ..}
3767 da5f09ef Bernardo Dal Seno
      assert key in ispecs
3768 da5f09ef Bernardo Dal Seno
      ispecs[key][name] = val
3769 da5f09ef Bernardo Dal Seno
  for key in constants.ISPECS_MINMAX_KEYS:
3770 da5f09ef Bernardo Dal Seno
    ipolicy[constants.ISPECS_MINMAX][key] = ispecs[key]
3771 da5f09ef Bernardo Dal Seno
  ipolicy[constants.ISPECS_STD] = ispecs[constants.ISPECS_STD]
3772 d948c101 Bernardo Dal Seno
3773 d948c101 Bernardo Dal Seno
3774 d948c101 Bernardo Dal Seno
def CreateIPolicyFromOpts(ispecs_mem_size=None,
3775 d948c101 Bernardo Dal Seno
                          ispecs_cpu_count=None,
3776 d948c101 Bernardo Dal Seno
                          ispecs_disk_count=None,
3777 d948c101 Bernardo Dal Seno
                          ispecs_disk_size=None,
3778 d948c101 Bernardo Dal Seno
                          ispecs_nic_count=None,
3779 d948c101 Bernardo Dal Seno
                          ipolicy_disk_templates=None,
3780 d948c101 Bernardo Dal Seno
                          ipolicy_vcpu_ratio=None,
3781 d948c101 Bernardo Dal Seno
                          ipolicy_spindle_ratio=None,
3782 d948c101 Bernardo Dal Seno
                          group_ipolicy=False,
3783 d948c101 Bernardo Dal Seno
                          allowed_values=None,
3784 d948c101 Bernardo Dal Seno
                          fill_all=False):
3785 d948c101 Bernardo Dal Seno
  """Creation of instance policy based on command line options.
3786 d948c101 Bernardo Dal Seno

3787 d948c101 Bernardo Dal Seno
  @param fill_all: whether for cluster policies we should ensure that
3788 d948c101 Bernardo Dal Seno
    all values are filled
3789 d948c101 Bernardo Dal Seno

3790 d948c101 Bernardo Dal Seno

3791 d948c101 Bernardo Dal Seno
  """
3792 d948c101 Bernardo Dal Seno
3793 d948c101 Bernardo Dal Seno
  ipolicy_out = objects.MakeEmptyIPolicy()
3794 d948c101 Bernardo Dal Seno
  _InitIspecsFromOpts(ipolicy_out, ispecs_mem_size, ispecs_cpu_count,
3795 d948c101 Bernardo Dal Seno
                      ispecs_disk_count, ispecs_disk_size, ispecs_nic_count,
3796 d948c101 Bernardo Dal Seno
                      group_ipolicy, allowed_values)
3797 703fa9ab Iustin Pop
3798 703fa9ab Iustin Pop
  if ipolicy_disk_templates is not None:
3799 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
3800 703fa9ab Iustin Pop
  if ipolicy_vcpu_ratio is not None:
3801 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
3802 ad5cc6bd René Nussbaumer
  if ipolicy_spindle_ratio is not None:
3803 ad5cc6bd René Nussbaumer
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
3804 703fa9ab Iustin Pop
3805 703fa9ab Iustin Pop
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
3806 703fa9ab Iustin Pop
3807 eeaa5f6c Bernardo Dal Seno
  if not group_ipolicy and fill_all:
3808 eeaa5f6c Bernardo Dal Seno
    ipolicy_out = objects.FillIPolicy(constants.IPOLICY_DEFAULTS, ipolicy_out)
3809 eeaa5f6c Bernardo Dal Seno
3810 703fa9ab Iustin Pop
  return ipolicy_out
3811 4d99964c Bernardo Dal Seno
3812 4d99964c Bernardo Dal Seno
3813 4d99964c Bernardo Dal Seno
def _SerializeGenericInfo(buf, data, level, afterkey=False):
3814 4d99964c Bernardo Dal Seno
  """Formatting core of L{PrintGenericInfo}.
3815 4d99964c Bernardo Dal Seno

3816 4d99964c Bernardo Dal Seno
  @param buf: (string) stream to accumulate the result into
3817 4d99964c Bernardo Dal Seno
  @param data: data to format
3818 4d99964c Bernardo Dal Seno
  @type level: int
3819 4d99964c Bernardo Dal Seno
  @param level: depth in the data hierarchy, used for indenting
3820 4d99964c Bernardo Dal Seno
  @type afterkey: bool
3821 4d99964c Bernardo Dal Seno
  @param afterkey: True when we are in the middle of a line after a key (used
3822 4d99964c Bernardo Dal Seno
      to properly add newlines or indentation)
3823 4d99964c Bernardo Dal Seno

3824 4d99964c Bernardo Dal Seno
  """
3825 4d99964c Bernardo Dal Seno
  baseind = "  "
3826 4d99964c Bernardo Dal Seno
  if isinstance(data, dict):
3827 4d99964c Bernardo Dal Seno
    if not data:
3828 4d99964c Bernardo Dal Seno
      buf.write("\n")
3829 4d99964c Bernardo Dal Seno
    else:
3830 4d99964c Bernardo Dal Seno
      if afterkey:
3831 4d99964c Bernardo Dal Seno
        buf.write("\n")
3832 4d99964c Bernardo Dal Seno
        doindent = True
3833 4d99964c Bernardo Dal Seno
      else:
3834 4d99964c Bernardo Dal Seno
        doindent = False
3835 4d99964c Bernardo Dal Seno
      for key in sorted(data):
3836 4d99964c Bernardo Dal Seno
        if doindent:
3837 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
3838 4d99964c Bernardo Dal Seno
        else:
3839 4d99964c Bernardo Dal Seno
          doindent = True
3840 4d99964c Bernardo Dal Seno
        buf.write(key)
3841 4d99964c Bernardo Dal Seno
        buf.write(": ")
3842 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, data[key], level + 1, afterkey=True)
3843 4d99964c Bernardo Dal Seno
  elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], tuple):
3844 4d99964c Bernardo Dal Seno
    # list of tuples (an ordered dictionary)
3845 4d99964c Bernardo Dal Seno
    if afterkey:
3846 4d99964c Bernardo Dal Seno
      buf.write("\n")
3847 4d99964c Bernardo Dal Seno
      doindent = True
3848 4d99964c Bernardo Dal Seno
    else:
3849 4d99964c Bernardo Dal Seno
      doindent = False
3850 4d99964c Bernardo Dal Seno
    for (key, val) in data:
3851 4d99964c Bernardo Dal Seno
      if doindent:
3852 4d99964c Bernardo Dal Seno
        buf.write(baseind * level)
3853 4d99964c Bernardo Dal Seno
      else:
3854 4d99964c Bernardo Dal Seno
        doindent = True
3855 4d99964c Bernardo Dal Seno
      buf.write(key)
3856 4d99964c Bernardo Dal Seno
      buf.write(": ")
3857 4d99964c Bernardo Dal Seno
      _SerializeGenericInfo(buf, val, level + 1, afterkey=True)
3858 4d99964c Bernardo Dal Seno
  elif isinstance(data, list):
3859 4d99964c Bernardo Dal Seno
    if not data:
3860 4d99964c Bernardo Dal Seno
      buf.write("\n")
3861 4d99964c Bernardo Dal Seno
    else:
3862 4d99964c Bernardo Dal Seno
      if afterkey:
3863 4d99964c Bernardo Dal Seno
        buf.write("\n")
3864 4d99964c Bernardo Dal Seno
        doindent = True
3865 4d99964c Bernardo Dal Seno
      else:
3866 4d99964c Bernardo Dal Seno
        doindent = False
3867 4d99964c Bernardo Dal Seno
      for item in data:
3868 4d99964c Bernardo Dal Seno
        if doindent:
3869 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
3870 4d99964c Bernardo Dal Seno
        else:
3871 4d99964c Bernardo Dal Seno
          doindent = True
3872 4d99964c Bernardo Dal Seno
        buf.write("-")
3873 4d99964c Bernardo Dal Seno
        buf.write(baseind[1:])
3874 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, item, level + 1)
3875 4d99964c Bernardo Dal Seno
  else:
3876 4d99964c Bernardo Dal Seno
    # This branch should be only taken for strings, but it's practically
3877 4d99964c Bernardo Dal Seno
    # impossible to guarantee that no other types are produced somewhere
3878 4d99964c Bernardo Dal Seno
    buf.write(str(data))
3879 4d99964c Bernardo Dal Seno
    buf.write("\n")
3880 4d99964c Bernardo Dal Seno
3881 4d99964c Bernardo Dal Seno
3882 4d99964c Bernardo Dal Seno
def PrintGenericInfo(data):
3883 4d99964c Bernardo Dal Seno
  """Print information formatted according to the hierarchy.
3884 4d99964c Bernardo Dal Seno

3885 4d99964c Bernardo Dal Seno
  The output is a valid YAML string.
3886 4d99964c Bernardo Dal Seno

3887 4d99964c Bernardo Dal Seno
  @param data: the data to print. It's a hierarchical structure whose elements
3888 4d99964c Bernardo Dal Seno
      can be:
3889 4d99964c Bernardo Dal Seno
        - dictionaries, where keys are strings and values are of any of the
3890 4d99964c Bernardo Dal Seno
          types listed here
3891 4d99964c Bernardo Dal Seno
        - lists of pairs (key, value), where key is a string and value is of
3892 4d99964c Bernardo Dal Seno
          any of the types listed here; it's a way to encode ordered
3893 4d99964c Bernardo Dal Seno
          dictionaries
3894 4d99964c Bernardo Dal Seno
        - lists of any of the types listed here
3895 4d99964c Bernardo Dal Seno
        - strings
3896 4d99964c Bernardo Dal Seno

3897 4d99964c Bernardo Dal Seno
  """
3898 4d99964c Bernardo Dal Seno
  buf = StringIO()
3899 4d99964c Bernardo Dal Seno
  _SerializeGenericInfo(buf, data, 0)
3900 4d99964c Bernardo Dal Seno
  ToStdout(buf.getvalue().rstrip("\n"))