Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ b54ecf12

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

353 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
354 863d7f46 Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

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

457 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
458 846baef9 Iustin Pop

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

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

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

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

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

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

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

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

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

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

573 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
574 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
575 726ae450 Bernardo Dal Seno
  will have the value=False and the prefix stripped, keys with the prefix
576 726ae450 Bernardo Dal Seno
  "-" will have value=None and the prefix stripped, and the others will
577 a8469393 Iustin Pop
  have value=True.
578 a8469393 Iustin Pop

579 a8469393 Iustin Pop
  @type opt: string
580 a8469393 Iustin Pop
  @param opt: a string holding the option name for which we process the
581 a8469393 Iustin Pop
      data, used in building error messages
582 a8469393 Iustin Pop
  @type data: string
583 a8469393 Iustin Pop
  @param data: a string of the format key=val,key=val,...
584 726ae450 Bernardo Dal Seno
  @type parse_prefixes: bool
585 726ae450 Bernardo Dal Seno
  @param parse_prefixes: whether to handle prefixes specially
586 a8469393 Iustin Pop
  @rtype: dict
587 a8469393 Iustin Pop
  @return: {key=val, key=val}
588 a8469393 Iustin Pop
  @raises errors.ParameterError: if there are duplicate keys
589 a8469393 Iustin Pop

590 a8469393 Iustin Pop
  """
591 a8469393 Iustin Pop
  kv_dict = {}
592 4f31882e Guido Trotter
  if data:
593 1b3a7656 Iustin Pop
    for elem in utils.UnescapeAndSplit(data, sep=","):
594 4f31882e Guido Trotter
      if "=" in elem:
595 4f31882e Guido Trotter
        key, val = elem.split("=", 1)
596 726ae450 Bernardo Dal Seno
      elif parse_prefixes:
597 4f31882e Guido Trotter
        if elem.startswith(NO_PREFIX):
598 4f31882e Guido Trotter
          key, val = elem[len(NO_PREFIX):], False
599 4f31882e Guido Trotter
        elif elem.startswith(UN_PREFIX):
600 4f31882e Guido Trotter
          key, val = elem[len(UN_PREFIX):], None
601 4f31882e Guido Trotter
        else:
602 4f31882e Guido Trotter
          key, val = elem, True
603 726ae450 Bernardo Dal Seno
      else:
604 726ae450 Bernardo Dal Seno
        raise errors.ParameterError("Missing value for key '%s' in option %s" %
605 726ae450 Bernardo Dal Seno
                                    (elem, opt))
606 4f31882e Guido Trotter
      if key in kv_dict:
607 4f31882e Guido Trotter
        raise errors.ParameterError("Duplicate key '%s' in option %s" %
608 4f31882e Guido Trotter
                                    (key, opt))
609 4f31882e Guido Trotter
      kv_dict[key] = val
610 a8469393 Iustin Pop
  return kv_dict
611 a8469393 Iustin Pop
612 a8469393 Iustin Pop
613 726ae450 Bernardo Dal Seno
def _SplitIdentKeyVal(opt, value, parse_prefixes):
614 726ae450 Bernardo Dal Seno
  """Helper function to parse "ident:key=val,key=val" options.
615 552c8dff Michael Hanselmann

616 726ae450 Bernardo Dal Seno
  @type opt: string
617 726ae450 Bernardo Dal Seno
  @param opt: option name, used in error messages
618 726ae450 Bernardo Dal Seno
  @type value: string
619 726ae450 Bernardo Dal Seno
  @param value: expected to be in the format "ident:key=val,key=val,..."
620 726ae450 Bernardo Dal Seno
  @type parse_prefixes: bool
621 726ae450 Bernardo Dal Seno
  @param parse_prefixes: whether to handle prefixes specially (see
622 726ae450 Bernardo Dal Seno
      L{_SplitKeyVal})
623 726ae450 Bernardo Dal Seno
  @rtype: tuple
624 726ae450 Bernardo Dal Seno
  @return: (ident, {key=val, key=val})
625 726ae450 Bernardo Dal Seno
  @raises errors.ParameterError: in case of duplicates or other parsing errors
626 a8469393 Iustin Pop

627 a8469393 Iustin Pop
  """
628 a8469393 Iustin Pop
  if ":" not in value:
629 d0c8c01d Iustin Pop
    ident, rest = value, ""
630 a8469393 Iustin Pop
  else:
631 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
632 8b46606c Guido Trotter
633 726ae450 Bernardo Dal Seno
  if parse_prefixes and ident.startswith(NO_PREFIX):
634 8b46606c Guido Trotter
    if rest:
635 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
636 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
637 8b46606c Guido Trotter
    retval = (ident[len(NO_PREFIX):], False)
638 726ae450 Bernardo Dal Seno
  elif (parse_prefixes and ident.startswith(UN_PREFIX) and
639 726ae450 Bernardo Dal Seno
        (len(ident) <= len(UN_PREFIX) or not ident[len(UN_PREFIX)].isdigit())):
640 8b46606c Guido Trotter
    if rest:
641 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
642 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
643 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
644 8b46606c Guido Trotter
  else:
645 726ae450 Bernardo Dal Seno
    kv_dict = _SplitKeyVal(opt, rest, parse_prefixes)
646 a8469393 Iustin Pop
    retval = (ident, kv_dict)
647 a8469393 Iustin Pop
  return retval
648 a8469393 Iustin Pop
649 a8469393 Iustin Pop
650 726ae450 Bernardo Dal Seno
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
651 726ae450 Bernardo Dal Seno
  """Custom parser for ident:key=val,key=val options.
652 726ae450 Bernardo Dal Seno

653 726ae450 Bernardo Dal Seno
  This will store the parsed values as a tuple (ident, {key: val}). As such,
654 726ae450 Bernardo Dal Seno
  multiple uses of this option via action=append is possible.
655 726ae450 Bernardo Dal Seno

656 726ae450 Bernardo Dal Seno
  """
657 726ae450 Bernardo Dal Seno
  return _SplitIdentKeyVal(opt, value, True)
658 726ae450 Bernardo Dal Seno
659 726ae450 Bernardo Dal Seno
660 b459a848 Andrea Spadaccini
def check_key_val(option, opt, value):  # pylint: disable=W0613
661 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
662 552c8dff Michael Hanselmann

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

665 a8469393 Iustin Pop
  """
666 726ae450 Bernardo Dal Seno
  return _SplitKeyVal(opt, value, True)
667 726ae450 Bernardo Dal Seno
668 726ae450 Bernardo Dal Seno
669 726ae450 Bernardo Dal Seno
def _SplitListKeyVal(opt, value):
670 726ae450 Bernardo Dal Seno
  retval = {}
671 726ae450 Bernardo Dal Seno
  for elem in value.split("/"):
672 726ae450 Bernardo Dal Seno
    if not elem:
673 726ae450 Bernardo Dal Seno
      raise errors.ParameterError("Empty section in option '%s'" % opt)
674 726ae450 Bernardo Dal Seno
    (ident, valdict) = _SplitIdentKeyVal(opt, elem, False)
675 726ae450 Bernardo Dal Seno
    if ident in retval:
676 726ae450 Bernardo Dal Seno
      msg = ("Duplicated parameter '%s' in parsing %s: %s" %
677 726ae450 Bernardo Dal Seno
             (ident, opt, elem))
678 726ae450 Bernardo Dal Seno
      raise errors.ParameterError(msg)
679 726ae450 Bernardo Dal Seno
    retval[ident] = valdict
680 726ae450 Bernardo Dal Seno
  return retval
681 726ae450 Bernardo Dal Seno
682 726ae450 Bernardo Dal Seno
683 ef99e3e8 Bernardo Dal Seno
def check_multilist_ident_key_val(_, opt, value):
684 ef99e3e8 Bernardo Dal Seno
  """Custom parser for "ident:key=val,key=val/ident:key=val//ident:.." options.
685 726ae450 Bernardo Dal Seno

686 726ae450 Bernardo Dal Seno
  @rtype: list of dictionary
687 ef99e3e8 Bernardo Dal Seno
  @return: [{ident: {key: val, key: val}, ident: {key: val}}, {ident:..}]
688 726ae450 Bernardo Dal Seno

689 726ae450 Bernardo Dal Seno
  """
690 ef99e3e8 Bernardo Dal Seno
  retval = []
691 ef99e3e8 Bernardo Dal Seno
  for line in value.split("//"):
692 ef99e3e8 Bernardo Dal Seno
    retval.append(_SplitListKeyVal(opt, line))
693 ef99e3e8 Bernardo Dal Seno
  return retval
694 a8469393 Iustin Pop
695 a8469393 Iustin Pop
696 b459a848 Andrea Spadaccini
def check_bool(option, opt, value): # pylint: disable=W0613
697 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
698 e7b61bb0 Iustin Pop

699 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
700 e7b61bb0 Iustin Pop

701 e7b61bb0 Iustin Pop
  """
702 e7b61bb0 Iustin Pop
  value = value.lower()
703 e7b61bb0 Iustin Pop
  if value == constants.VALUE_FALSE or value == "no":
704 e7b61bb0 Iustin Pop
    return False
705 e7b61bb0 Iustin Pop
  elif value == constants.VALUE_TRUE or value == "yes":
706 e7b61bb0 Iustin Pop
    return True
707 e7b61bb0 Iustin Pop
  else:
708 e7b61bb0 Iustin Pop
    raise errors.ParameterError("Invalid boolean value '%s'" % value)
709 e7b61bb0 Iustin Pop
710 e7b61bb0 Iustin Pop
711 499eb088 Iustin Pop
def check_list(option, opt, value): # pylint: disable=W0613
712 499eb088 Iustin Pop
  """Custom parser for comma-separated lists.
713 499eb088 Iustin Pop

714 499eb088 Iustin Pop
  """
715 499eb088 Iustin Pop
  # we have to make this explicit check since "".split(",") is [""],
716 499eb088 Iustin Pop
  # not an empty list :(
717 499eb088 Iustin Pop
  if not value:
718 499eb088 Iustin Pop
    return []
719 499eb088 Iustin Pop
  else:
720 499eb088 Iustin Pop
    return utils.UnescapeAndSplit(value)
721 499eb088 Iustin Pop
722 499eb088 Iustin Pop
723 cd415612 René Nussbaumer
def check_maybefloat(option, opt, value): # pylint: disable=W0613
724 cd415612 René Nussbaumer
  """Custom parser for float numbers which might be also defaults.
725 cd415612 René Nussbaumer

726 cd415612 René Nussbaumer
  """
727 cd415612 René Nussbaumer
  value = value.lower()
728 cd415612 René Nussbaumer
729 cd415612 René Nussbaumer
  if value == constants.VALUE_DEFAULT:
730 cd415612 René Nussbaumer
    return value
731 cd415612 René Nussbaumer
  else:
732 cd415612 René Nussbaumer
    return float(value)
733 cd415612 René Nussbaumer
734 cd415612 René Nussbaumer
735 63d44c55 Michael Hanselmann
# completion_suggestion is normally a list. Using numeric values not evaluating
736 63d44c55 Michael Hanselmann
# to False for dynamic completion.
737 63d44c55 Michael Hanselmann
(OPT_COMPL_MANY_NODES,
738 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_NODE,
739 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_INSTANCE,
740 63d44c55 Michael Hanselmann
 OPT_COMPL_ONE_OS,
741 b954f097 Constantinos Venetsanopoulos
 OPT_COMPL_ONE_EXTSTORAGE,
742 2d3ed64b Michael Hanselmann
 OPT_COMPL_ONE_IALLOCATOR,
743 9c784fb3 Dimitris Aragiorgis
 OPT_COMPL_ONE_NETWORK,
744 36e247e1 Guido Trotter
 OPT_COMPL_INST_ADD_NODES,
745 b954f097 Constantinos Venetsanopoulos
 OPT_COMPL_ONE_NODEGROUP) = range(100, 109)
746 63d44c55 Michael Hanselmann
747 b8028dcf Michael Hanselmann
OPT_COMPL_ALL = compat.UniqueFrozenset([
748 63d44c55 Michael Hanselmann
  OPT_COMPL_MANY_NODES,
749 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_NODE,
750 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_INSTANCE,
751 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_OS,
752 b954f097 Constantinos Venetsanopoulos
  OPT_COMPL_ONE_EXTSTORAGE,
753 63d44c55 Michael Hanselmann
  OPT_COMPL_ONE_IALLOCATOR,
754 9c784fb3 Dimitris Aragiorgis
  OPT_COMPL_ONE_NETWORK,
755 2d3ed64b Michael Hanselmann
  OPT_COMPL_INST_ADD_NODES,
756 36e247e1 Guido Trotter
  OPT_COMPL_ONE_NODEGROUP,
757 63d44c55 Michael Hanselmann
  ])
758 63d44c55 Michael Hanselmann
759 63d44c55 Michael Hanselmann
760 552c8dff Michael Hanselmann
class CliOption(Option):
761 552c8dff Michael Hanselmann
  """Custom option class for optparse.
762 a8469393 Iustin Pop

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

1483 552328b8 Michael Hanselmann
  """
1484 552328b8 Michael Hanselmann
  value = _PRIONAME_TO_VALUE[value]
1485 552328b8 Michael Hanselmann
1486 552328b8 Michael Hanselmann
  setattr(parser.values, option.dest, value)
1487 552328b8 Michael Hanselmann
1488 552328b8 Michael Hanselmann
1489 84a5b33c Michael Hanselmann
PRIORITY_OPT = cli_option("--priority", default=None, dest="priority",
1490 84a5b33c Michael Hanselmann
                          metavar="|".join(name for name, _ in _PRIORITY_NAMES),
1491 84a5b33c Michael Hanselmann
                          choices=_PRIONAME_TO_VALUE.keys(),
1492 552328b8 Michael Hanselmann
                          action="callback", type="choice",
1493 552328b8 Michael Hanselmann
                          callback=_PriorityOptionCb,
1494 aa06f8c6 Michael Hanselmann
                          help="Priority for opcode processing")
1495 84a5b33c Michael Hanselmann
1496 61a14bb3 Iustin Pop
HID_OS_OPT = cli_option("--hidden", dest="hidden",
1497 61a14bb3 Iustin Pop
                        type="bool", default=None, metavar=_YORNO,
1498 61a14bb3 Iustin Pop
                        help="Sets the hidden flag on the OS")
1499 61a14bb3 Iustin Pop
1500 61a14bb3 Iustin Pop
BLK_OS_OPT = cli_option("--blacklisted", dest="blacklisted",
1501 61a14bb3 Iustin Pop
                        type="bool", default=None, metavar=_YORNO,
1502 61a14bb3 Iustin Pop
                        help="Sets the blacklisted flag on the OS")
1503 61a14bb3 Iustin Pop
1504 b883637f René Nussbaumer
PREALLOC_WIPE_DISKS_OPT = cli_option("--prealloc-wipe-disks", default=None,
1505 b883637f René Nussbaumer
                                     type="bool", metavar=_YORNO,
1506 b883637f René Nussbaumer
                                     dest="prealloc_wipe_disks",
1507 b883637f René Nussbaumer
                                     help=("Wipe disks prior to instance"
1508 b883637f René Nussbaumer
                                           " creation"))
1509 b883637f René Nussbaumer
1510 a535cef7 René Nussbaumer
NODE_PARAMS_OPT = cli_option("--node-parameters", dest="ndparams",
1511 3c2b6a98 René Nussbaumer
                             type="keyval", default=None,
1512 a535cef7 René Nussbaumer
                             help="Node parameters")
1513 a535cef7 René Nussbaumer
1514 90e99856 Adeodato Simo
ALLOC_POLICY_OPT = cli_option("--alloc-policy", dest="alloc_policy",
1515 90e99856 Adeodato Simo
                              action="store", metavar="POLICY", default=None,
1516 90e99856 Adeodato Simo
                              help="Allocation policy for the node group")
1517 90e99856 Adeodato Simo
1518 d2881c71 René Nussbaumer
NODE_POWERED_OPT = cli_option("--node-powered", default=None,
1519 d2881c71 René Nussbaumer
                              type="bool", metavar=_YORNO,
1520 d2881c71 René Nussbaumer
                              dest="node_powered",
1521 d2881c71 René Nussbaumer
                              help="Specify if the SoR for node is powered")
1522 d2881c71 René Nussbaumer
1523 41543d8b René Nussbaumer
OOB_TIMEOUT_OPT = cli_option("--oob-timeout", dest="oob_timeout", type="int",
1524 5ae4945a Iustin Pop
                             default=constants.OOB_TIMEOUT,
1525 5ae4945a Iustin Pop
                             help="Maximum time to wait for out-of-band helper")
1526 41543d8b René Nussbaumer
1527 0c086a13 René Nussbaumer
POWER_DELAY_OPT = cli_option("--power-delay", dest="power_delay", type="float",
1528 0c086a13 René Nussbaumer
                             default=constants.OOB_POWER_DELAY,
1529 0c086a13 René Nussbaumer
                             help="Time in seconds to wait between power-ons")
1530 0c086a13 René Nussbaumer
1531 442587bf Michael Hanselmann
FORCE_FILTER_OPT = cli_option("-F", "--filter", dest="force_filter",
1532 442587bf Michael Hanselmann
                              action="store_true", default=False,
1533 442587bf Michael Hanselmann
                              help=("Whether command argument should be treated"
1534 442587bf Michael Hanselmann
                                    " as filter"))
1535 442587bf Michael Hanselmann
1536 885a0fc4 Iustin Pop
NO_REMEMBER_OPT = cli_option("--no-remember",
1537 885a0fc4 Iustin Pop
                             dest="no_remember",
1538 885a0fc4 Iustin Pop
                             action="store_true", default=False,
1539 885a0fc4 Iustin Pop
                             help="Perform but do not record the change"
1540 885a0fc4 Iustin Pop
                             " in the configuration")
1541 885a0fc4 Iustin Pop
1542 aafee533 Michael Hanselmann
PRIMARY_ONLY_OPT = cli_option("-p", "--primary-only",
1543 aafee533 Michael Hanselmann
                              default=False, action="store_true",
1544 aafee533 Michael Hanselmann
                              help="Evacuate primary instances only")
1545 aafee533 Michael Hanselmann
1546 aafee533 Michael Hanselmann
SECONDARY_ONLY_OPT = cli_option("-s", "--secondary-only",
1547 aafee533 Michael Hanselmann
                                default=False, action="store_true",
1548 aafee533 Michael Hanselmann
                                help="Evacuate secondary instances only"
1549 aafee533 Michael Hanselmann
                                     " (applies only to internally mirrored"
1550 aafee533 Michael Hanselmann
                                     " disk templates, e.g. %s)" %
1551 aafee533 Michael Hanselmann
                                     utils.CommaJoin(constants.DTS_INT_MIRROR))
1552 aafee533 Michael Hanselmann
1553 323f9095 Stephen Shirley
STARTUP_PAUSED_OPT = cli_option("--paused", dest="startup_paused",
1554 323f9095 Stephen Shirley
                                action="store_true", default=False,
1555 323f9095 Stephen Shirley
                                help="Pause instance at startup")
1556 323f9095 Stephen Shirley
1557 f6eb380d Michael Hanselmann
TO_GROUP_OPT = cli_option("--to", dest="to", metavar="<group>",
1558 f6eb380d Michael Hanselmann
                          help="Destination node group (name or uuid)",
1559 f6eb380d Michael Hanselmann
                          default=None, action="append",
1560 f6eb380d Michael Hanselmann
                          completion_suggest=OPT_COMPL_ONE_NODEGROUP)
1561 f6eb380d Michael Hanselmann
1562 93f2399e Andrea Spadaccini
IGNORE_ERRORS_OPT = cli_option("-I", "--ignore-errors", default=[],
1563 93f2399e Andrea Spadaccini
                               action="append", dest="ignore_errors",
1564 93f2399e Andrea Spadaccini
                               choices=list(constants.CV_ALL_ECODES_STRINGS),
1565 93f2399e Andrea Spadaccini
                               help="Error code to be ignored")
1566 93f2399e Andrea Spadaccini
1567 38f29a36 René Nussbaumer
DISK_STATE_OPT = cli_option("--disk-state", default=[], dest="disk_state",
1568 38f29a36 René Nussbaumer
                            action="append",
1569 a1cef552 Iustin Pop
                            help=("Specify disk state information in the"
1570 a1cef552 Iustin Pop
                                  " format"
1571 a1cef552 Iustin Pop
                                  " storage_type/identifier:option=value,...;"
1572 a1cef552 Iustin Pop
                                  " note this is unused for now"),
1573 38f29a36 René Nussbaumer
                            type="identkeyval")
1574 38f29a36 René Nussbaumer
1575 38f29a36 René Nussbaumer
HV_STATE_OPT = cli_option("--hypervisor-state", default=[], dest="hv_state",
1576 38f29a36 René Nussbaumer
                          action="append",
1577 38f29a36 René Nussbaumer
                          help=("Specify hypervisor state information in the"
1578 a1cef552 Iustin Pop
                                " format hypervisor:option=value,...;"
1579 a1cef552 Iustin Pop
                                " note this is unused for now"),
1580 38f29a36 René Nussbaumer
                          type="identkeyval")
1581 38f29a36 René Nussbaumer
1582 b6aaf437 René Nussbaumer
IGNORE_IPOLICY_OPT = cli_option("--ignore-ipolicy", dest="ignore_ipolicy",
1583 b6aaf437 René Nussbaumer
                                action="store_true", default=False,
1584 b6aaf437 René Nussbaumer
                                help="Ignore instance policy violations")
1585 b6aaf437 René Nussbaumer
1586 2c0af7da Guido Trotter
RUNTIME_MEM_OPT = cli_option("-m", "--runtime-memory", dest="runtime_mem",
1587 2c0af7da Guido Trotter
                             help="Sets the instance's runtime memory,"
1588 2c0af7da Guido Trotter
                             " ballooning it up or down to the new value",
1589 2c0af7da Guido Trotter
                             default=None, type="unit", metavar="<size>")
1590 61a14bb3 Iustin Pop
1591 ef8270dc Iustin Pop
ABSOLUTE_OPT = cli_option("--absolute", dest="absolute",
1592 ef8270dc Iustin Pop
                          action="store_true", default=False,
1593 ef8270dc Iustin Pop
                          help="Marks the grow as absolute instead of the"
1594 ef8270dc Iustin Pop
                          " (default) relative mode")
1595 ef8270dc Iustin Pop
1596 9c784fb3 Dimitris Aragiorgis
NETWORK_OPT = cli_option("--network",
1597 9c784fb3 Dimitris Aragiorgis
                         action="store", default=None, dest="network",
1598 9c784fb3 Dimitris Aragiorgis
                         help="IP network in CIDR notation")
1599 9c784fb3 Dimitris Aragiorgis
1600 9c784fb3 Dimitris Aragiorgis
GATEWAY_OPT = cli_option("--gateway",
1601 9c784fb3 Dimitris Aragiorgis
                         action="store", default=None, dest="gateway",
1602 9c784fb3 Dimitris Aragiorgis
                         help="IP address of the router (gateway)")
1603 9c784fb3 Dimitris Aragiorgis
1604 9c784fb3 Dimitris Aragiorgis
ADD_RESERVED_IPS_OPT = cli_option("--add-reserved-ips",
1605 9c784fb3 Dimitris Aragiorgis
                                  action="store", default=None,
1606 9c784fb3 Dimitris Aragiorgis
                                  dest="add_reserved_ips",
1607 9c784fb3 Dimitris Aragiorgis
                                  help="Comma-separated list of"
1608 9c784fb3 Dimitris Aragiorgis
                                  " reserved IPs to add")
1609 9c784fb3 Dimitris Aragiorgis
1610 9c784fb3 Dimitris Aragiorgis
REMOVE_RESERVED_IPS_OPT = cli_option("--remove-reserved-ips",
1611 9c784fb3 Dimitris Aragiorgis
                                     action="store", default=None,
1612 9c784fb3 Dimitris Aragiorgis
                                     dest="remove_reserved_ips",
1613 9c784fb3 Dimitris Aragiorgis
                                     help="Comma-delimited list of"
1614 9c784fb3 Dimitris Aragiorgis
                                     " reserved IPs to remove")
1615 9c784fb3 Dimitris Aragiorgis
1616 9c784fb3 Dimitris Aragiorgis
NETWORK6_OPT = cli_option("--network6",
1617 9c784fb3 Dimitris Aragiorgis
                          action="store", default=None, dest="network6",
1618 9c784fb3 Dimitris Aragiorgis
                          help="IP network in CIDR notation")
1619 9c784fb3 Dimitris Aragiorgis
1620 9c784fb3 Dimitris Aragiorgis
GATEWAY6_OPT = cli_option("--gateway6",
1621 9c784fb3 Dimitris Aragiorgis
                          action="store", default=None, dest="gateway6",
1622 9c784fb3 Dimitris Aragiorgis
                          help="IP6 address of the router (gateway)")
1623 9c784fb3 Dimitris Aragiorgis
1624 9c784fb3 Dimitris Aragiorgis
NOCONFLICTSCHECK_OPT = cli_option("--no-conflicts-check",
1625 9c784fb3 Dimitris Aragiorgis
                                  dest="conflicts_check",
1626 9c784fb3 Dimitris Aragiorgis
                                  default=True,
1627 9c784fb3 Dimitris Aragiorgis
                                  action="store_false",
1628 9c784fb3 Dimitris Aragiorgis
                                  help="Don't check for conflicting IPs")
1629 9c784fb3 Dimitris Aragiorgis
1630 ea9d3b40 Bernardo Dal Seno
INCLUDEDEFAULTS_OPT = cli_option("--include-defaults", dest="include_defaults",
1631 ea9d3b40 Bernardo Dal Seno
                                 default=False, action="store_true",
1632 ea9d3b40 Bernardo Dal Seno
                                 help="Include default values")
1633 ea9d3b40 Bernardo Dal Seno
1634 5786c087 Michael Hanselmann
#: Options provided by all commands
1635 aa4fff02 Michele Tartara
COMMON_OPTS = [DEBUG_OPT, REASON_OPT]
1636 5786c087 Michael Hanselmann
1637 eb28ecf6 Guido Trotter
# common options for creating instances. add and import then add their own
1638 eb28ecf6 Guido Trotter
# specific ones.
1639 eb28ecf6 Guido Trotter
COMMON_CREATE_OPTS = [
1640 eb28ecf6 Guido Trotter
  BACKEND_OPT,
1641 eb28ecf6 Guido Trotter
  DISK_OPT,
1642 eb28ecf6 Guido Trotter
  DISK_TEMPLATE_OPT,
1643 eb28ecf6 Guido Trotter
  FILESTORE_DIR_OPT,
1644 eb28ecf6 Guido Trotter
  FILESTORE_DRIVER_OPT,
1645 eb28ecf6 Guido Trotter
  HYPERVISOR_OPT,
1646 eb28ecf6 Guido Trotter
  IALLOCATOR_OPT,
1647 eb28ecf6 Guido Trotter
  NET_OPT,
1648 eb28ecf6 Guido Trotter
  NODE_PLACEMENT_OPT,
1649 eb28ecf6 Guido Trotter
  NOIPCHECK_OPT,
1650 9c784fb3 Dimitris Aragiorgis
  NOCONFLICTSCHECK_OPT,
1651 eb28ecf6 Guido Trotter
  NONAMECHECK_OPT,
1652 eb28ecf6 Guido Trotter
  NONICS_OPT,
1653 eb28ecf6 Guido Trotter
  NWSYNC_OPT,
1654 eb28ecf6 Guido Trotter
  OSPARAMS_OPT,
1655 eb28ecf6 Guido Trotter
  OS_SIZE_OPT,
1656 eb28ecf6 Guido Trotter
  SUBMIT_OPT,
1657 0f8810df Michael Hanselmann
  TAG_ADD_OPT,
1658 eb28ecf6 Guido Trotter
  DRY_RUN_OPT,
1659 eb28ecf6 Guido Trotter
  PRIORITY_OPT,
1660 eb28ecf6 Guido Trotter
  ]
1661 eb28ecf6 Guido Trotter
1662 0ce212e5 Iustin Pop
# common instance policy options
1663 0ce212e5 Iustin Pop
INSTANCE_POLICY_OPTS = [
1664 919db916 Bernardo Dal Seno
  IPOLICY_BOUNDS_SPECS_OPT,
1665 919db916 Bernardo Dal Seno
  IPOLICY_DISK_TEMPLATES,
1666 919db916 Bernardo Dal Seno
  IPOLICY_VCPU_RATIO,
1667 919db916 Bernardo Dal Seno
  IPOLICY_SPINDLE_RATIO,
1668 919db916 Bernardo Dal Seno
  ]
1669 919db916 Bernardo Dal Seno
1670 919db916 Bernardo Dal Seno
# instance policy split specs options
1671 919db916 Bernardo Dal Seno
SPLIT_ISPECS_OPTS = [
1672 0ce212e5 Iustin Pop
  SPECS_CPU_COUNT_OPT,
1673 0ce212e5 Iustin Pop
  SPECS_DISK_COUNT_OPT,
1674 0ce212e5 Iustin Pop
  SPECS_DISK_SIZE_OPT,
1675 0ce212e5 Iustin Pop
  SPECS_MEM_SIZE_OPT,
1676 0ce212e5 Iustin Pop
  SPECS_NIC_COUNT_OPT,
1677 0ce212e5 Iustin Pop
  ]
1678 0ce212e5 Iustin Pop
1679 771734c9 Iustin Pop
1680 d971402f Michael Hanselmann
class _ShowUsage(Exception):
1681 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1682 d971402f Michael Hanselmann

1683 d971402f Michael Hanselmann
  """
1684 d971402f Michael Hanselmann
  def __init__(self, exit_error):
1685 d971402f Michael Hanselmann
    """Initializes instances of this class.
1686 d971402f Michael Hanselmann

1687 d971402f Michael Hanselmann
    @type exit_error: bool
1688 d971402f Michael Hanselmann
    @param exit_error: Whether to report failure on exit
1689 d971402f Michael Hanselmann

1690 d971402f Michael Hanselmann
    """
1691 d971402f Michael Hanselmann
    Exception.__init__(self)
1692 d971402f Michael Hanselmann
    self.exit_error = exit_error
1693 d971402f Michael Hanselmann
1694 d971402f Michael Hanselmann
1695 d971402f Michael Hanselmann
class _ShowVersion(Exception):
1696 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1697 d971402f Michael Hanselmann

1698 d971402f Michael Hanselmann
  """
1699 d971402f Michael Hanselmann
1700 d971402f Michael Hanselmann
1701 d971402f Michael Hanselmann
def _ParseArgs(binary, argv, commands, aliases, env_override):
1702 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1703 a8083063 Iustin Pop

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

1707 d971402f Michael Hanselmann
  @param binary: Script name
1708 d971402f Michael Hanselmann
  @param argv: Command line arguments
1709 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1710 d971402f Michael Hanselmann
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1711 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1712 d971402f Michael Hanselmann
  @raise _ShowUsage: If usage description should be shown
1713 d971402f Michael Hanselmann
  @raise _ShowVersion: If version should be shown
1714 098c0958 Michael Hanselmann

1715 a8083063 Iustin Pop
  """
1716 ef9fa5b9 René Nussbaumer
  assert not (env_override - set(commands))
1717 d971402f Michael Hanselmann
  assert not (set(aliases.keys()) & set(commands.keys()))
1718 ef9fa5b9 René Nussbaumer
1719 d971402f Michael Hanselmann
  if len(argv) > 1:
1720 d971402f Michael Hanselmann
    cmd = argv[1]
1721 a8083063 Iustin Pop
  else:
1722 d971402f Michael Hanselmann
    # No option or command given
1723 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1724 a8083063 Iustin Pop
1725 d971402f Michael Hanselmann
  if cmd == "--version":
1726 d971402f Michael Hanselmann
    raise _ShowVersion()
1727 d971402f Michael Hanselmann
  elif cmd == "--help":
1728 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=False)
1729 d971402f Michael Hanselmann
  elif not (cmd in commands or cmd in aliases):
1730 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1731 de47cf8f Guido Trotter
1732 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1733 de47cf8f Guido Trotter
  if cmd in aliases:
1734 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1735 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1736 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1737 de47cf8f Guido Trotter
1738 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1739 de47cf8f Guido Trotter
1740 ef9fa5b9 René Nussbaumer
  if cmd in env_override:
1741 ef9fa5b9 René Nussbaumer
    args_env_name = ("%s_%s" % (binary.replace("-", "_"), cmd)).upper()
1742 ef9fa5b9 René Nussbaumer
    env_args = os.environ.get(args_env_name)
1743 ef9fa5b9 René Nussbaumer
    if env_args:
1744 d971402f Michael Hanselmann
      argv = utils.InsertAtPos(argv, 2, shlex.split(env_args))
1745 ef9fa5b9 René Nussbaumer
1746 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1747 bf5338b3 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1748 bf5338b3 Michael Hanselmann
                        description=description,
1749 bf5338b3 Michael Hanselmann
                        formatter=TitledHelpFormatter(),
1750 bf5338b3 Michael Hanselmann
                        usage="%%prog %s %s" % (cmd, usage))
1751 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1752 d971402f Michael Hanselmann
  options, args = parser.parse_args(args=argv[2:])
1753 a8005e17 Michael Hanselmann
1754 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1755 a8083063 Iustin Pop
    return None, None, None
1756 a8083063 Iustin Pop
1757 a8083063 Iustin Pop
  return func, options, args
1758 a8083063 Iustin Pop
1759 a8083063 Iustin Pop
1760 d971402f Michael Hanselmann
def _FormatUsage(binary, commands):
1761 d971402f Michael Hanselmann
  """Generates a nice description of all commands.
1762 d971402f Michael Hanselmann

1763 d971402f Michael Hanselmann
  @param binary: Script name
1764 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1765 d971402f Michael Hanselmann

1766 d971402f Michael Hanselmann
  """
1767 d971402f Michael Hanselmann
  # compute the max line length for cmd + usage
1768 d971402f Michael Hanselmann
  mlen = min(60, max(map(len, commands)))
1769 d971402f Michael Hanselmann
1770 d971402f Michael Hanselmann
  yield "Usage: %s {command} [options...] [argument...]" % binary
1771 d971402f Michael Hanselmann
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1772 d971402f Michael Hanselmann
  yield ""
1773 d971402f Michael Hanselmann
  yield "Commands:"
1774 d971402f Michael Hanselmann
1775 d971402f Michael Hanselmann
  # and format a nice command list
1776 d971402f Michael Hanselmann
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1777 d971402f Michael Hanselmann
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1778 d971402f Michael Hanselmann
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1779 d971402f Michael Hanselmann
    for line in help_lines:
1780 d971402f Michael Hanselmann
      yield " %-*s   %s" % (mlen, "", line)
1781 d971402f Michael Hanselmann
1782 d971402f Michael Hanselmann
  yield ""
1783 d971402f Michael Hanselmann
1784 d971402f Michael Hanselmann
1785 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1786 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1787 a8005e17 Michael Hanselmann

1788 a8005e17 Michael Hanselmann
  Algorithm:
1789 a8005e17 Michael Hanselmann

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

1792 a8005e17 Michael Hanselmann
    1. For each argument in definition
1793 a8005e17 Michael Hanselmann

1794 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1795 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1796 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1797 a8005e17 Michael Hanselmann

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

1800 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1801 a8005e17 Michael Hanselmann

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

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

1806 a8005e17 Michael Hanselmann
  """
1807 a8005e17 Michael Hanselmann
  if args and not args_def:
1808 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1809 a8005e17 Michael Hanselmann
    return False
1810 a8005e17 Michael Hanselmann
1811 a8005e17 Michael Hanselmann
  min_count = None
1812 a8005e17 Michael Hanselmann
  max_count = None
1813 a8005e17 Michael Hanselmann
  check_max = None
1814 a8005e17 Michael Hanselmann
1815 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1816 a8005e17 Michael Hanselmann
1817 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1818 a8005e17 Michael Hanselmann
    if min_count is None:
1819 a8005e17 Michael Hanselmann
      min_count = arg.min
1820 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1821 a8005e17 Michael Hanselmann
      min_count += arg.min
1822 a8005e17 Michael Hanselmann
1823 a8005e17 Michael Hanselmann
    if max_count is None:
1824 a8005e17 Michael Hanselmann
      max_count = arg.max
1825 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1826 a8005e17 Michael Hanselmann
      max_count += arg.max
1827 a8005e17 Michael Hanselmann
1828 a8005e17 Michael Hanselmann
    if idx == last_idx:
1829 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1830 a8005e17 Michael Hanselmann
1831 a8005e17 Michael Hanselmann
    elif arg.max is None:
1832 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1833 a8005e17 Michael Hanselmann
1834 a8005e17 Michael Hanselmann
  if check_max:
1835 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1836 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1837 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1838 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1839 a8005e17 Michael Hanselmann
      return False
1840 a8005e17 Michael Hanselmann
1841 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1842 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1843 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1844 a8005e17 Michael Hanselmann
               cmd, max_count)
1845 a8005e17 Michael Hanselmann
      return False
1846 a8005e17 Michael Hanselmann
1847 a8005e17 Michael Hanselmann
  # Command with some required arguments
1848 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1849 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1850 a8005e17 Michael Hanselmann
             cmd, min_count)
1851 a8005e17 Michael Hanselmann
    return False
1852 a8005e17 Michael Hanselmann
1853 a8005e17 Michael Hanselmann
  return True
1854 a8005e17 Michael Hanselmann
1855 a8005e17 Michael Hanselmann
1856 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1857 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1858 60d49723 Michael Hanselmann

1859 60d49723 Michael Hanselmann
  """
1860 d0c8c01d Iustin Pop
  if value and ":" in value:
1861 d0c8c01d Iustin Pop
    return value.split(":", 1)
1862 60d49723 Michael Hanselmann
  else:
1863 60d49723 Michael Hanselmann
    return (value, None)
1864 60d49723 Michael Hanselmann
1865 60d49723 Michael Hanselmann
1866 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1867 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1868 07150497 Guido Trotter

1869 07150497 Guido Trotter
  @type os_name: string
1870 07150497 Guido Trotter
  @param os_name: base name of the os
1871 07150497 Guido Trotter
  @type os_variants: list or None
1872 07150497 Guido Trotter
  @param os_variants: list of supported variants
1873 07150497 Guido Trotter
  @rtype: list
1874 07150497 Guido Trotter
  @return: list of valid names
1875 07150497 Guido Trotter

1876 07150497 Guido Trotter
  """
1877 07150497 Guido Trotter
  if os_variants:
1878 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1879 07150497 Guido Trotter
  else:
1880 07150497 Guido Trotter
    return [os_name]
1881 07150497 Guido Trotter
1882 07150497 Guido Trotter
1883 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1884 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1885 a4ebd726 Michael Hanselmann

1886 a4ebd726 Michael Hanselmann
  @type selected: string or None
1887 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1888 a4ebd726 Michael Hanselmann
  @type default: list
1889 a4ebd726 Michael Hanselmann
  @param default: Default fields
1890 a4ebd726 Michael Hanselmann

1891 a4ebd726 Michael Hanselmann
  """
1892 a4ebd726 Michael Hanselmann
  if selected is None:
1893 a4ebd726 Michael Hanselmann
    return default
1894 a4ebd726 Michael Hanselmann
1895 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1896 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1897 a4ebd726 Michael Hanselmann
1898 a4ebd726 Michael Hanselmann
  return selected.split(",")
1899 a4ebd726 Michael Hanselmann
1900 a4ebd726 Michael Hanselmann
1901 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1902 4331f6cd Michael Hanselmann
1903 4331f6cd Michael Hanselmann
1904 47988778 Iustin Pop
def AskUser(text, choices=None):
1905 47988778 Iustin Pop
  """Ask the user a question.
1906 a8083063 Iustin Pop

1907 c41eea6e Iustin Pop
  @param text: the question to ask
1908 a8083063 Iustin Pop

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

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

1918 a8083063 Iustin Pop
  """
1919 47988778 Iustin Pop
  if choices is None:
1920 d0c8c01d Iustin Pop
    choices = [("y", True, "Perform the operation"),
1921 d0c8c01d Iustin Pop
               ("n", False, "Do not perform the operation")]
1922 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1923 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1924 47988778 Iustin Pop
  for entry in choices:
1925 d0c8c01d Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1926 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1927 47988778 Iustin Pop
1928 47988778 Iustin Pop
  answer = choices[-1][1]
1929 47988778 Iustin Pop
  new_text = []
1930 47988778 Iustin Pop
  for line in text.splitlines():
1931 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1932 47988778 Iustin Pop
  text = "\n".join(new_text)
1933 a8083063 Iustin Pop
  try:
1934 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1935 a8083063 Iustin Pop
  except IOError:
1936 47988778 Iustin Pop
    return answer
1937 a8083063 Iustin Pop
  try:
1938 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1939 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1940 d0c8c01d Iustin Pop
    chars.append("?")
1941 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1942 47988778 Iustin Pop
    while True:
1943 47988778 Iustin Pop
      f.write(text)
1944 d0c8c01d Iustin Pop
      f.write("\n")
1945 47988778 Iustin Pop
      f.write("/".join(chars))
1946 47988778 Iustin Pop
      f.write(": ")
1947 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1948 47988778 Iustin Pop
      if line in maps:
1949 47988778 Iustin Pop
        answer = maps[line]
1950 47988778 Iustin Pop
        break
1951 d0c8c01d Iustin Pop
      elif line == "?":
1952 47988778 Iustin Pop
        for entry in choices:
1953 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1954 47988778 Iustin Pop
        f.write("\n")
1955 47988778 Iustin Pop
        continue
1956 a8083063 Iustin Pop
  finally:
1957 a8083063 Iustin Pop
    f.close()
1958 a8083063 Iustin Pop
  return answer
1959 a8083063 Iustin Pop
1960 a8083063 Iustin Pop
1961 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1962 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1963 e9d741b6 Iustin Pop

1964 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1965 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1966 e9d741b6 Iustin Pop

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

1969 e9d741b6 Iustin Pop
  """
1970 e9d741b6 Iustin Pop
1971 e9d741b6 Iustin Pop
1972 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1973 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1974 a8083063 Iustin Pop

1975 0a1e74d9 Iustin Pop
  @type ops: list
1976 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1977 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1978 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1979 0a1e74d9 Iustin Pop
             if None, a new client will be created
1980 a8083063 Iustin Pop

1981 a8083063 Iustin Pop
  """
1982 e2212007 Iustin Pop
  if cl is None:
1983 b33e986b Iustin Pop
    cl = GetClient()
1984 685ee993 Iustin Pop
1985 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1986 0a1e74d9 Iustin Pop
1987 0a1e74d9 Iustin Pop
  return job_id
1988 0a1e74d9 Iustin Pop
1989 0a1e74d9 Iustin Pop
1990 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1991 4e338533 Michael Hanselmann
  """Generic job-polling function.
1992 0a1e74d9 Iustin Pop

1993 4e338533 Michael Hanselmann
  @type job_id: number
1994 4e338533 Michael Hanselmann
  @param job_id: Job ID
1995 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1996 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1997 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1998 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1999 0a1e74d9 Iustin Pop

2000 0a1e74d9 Iustin Pop
  """
2001 6c5a7090 Michael Hanselmann
  prev_job_info = None
2002 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
2003 6c5a7090 Michael Hanselmann
2004 f4484122 Michael Hanselmann
  status = None
2005 f4484122 Michael Hanselmann
2006 685ee993 Iustin Pop
  while True:
2007 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
2008 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
2009 6c5a7090 Michael Hanselmann
    if not result:
2010 685ee993 Iustin Pop
      # job not found, go away!
2011 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
2012 4e338533 Michael Hanselmann
2013 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
2014 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
2015 f4484122 Michael Hanselmann
2016 f4484122 Michael Hanselmann
      # Wait again
2017 f4484122 Michael Hanselmann
      continue
2018 685ee993 Iustin Pop
2019 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
2020 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
2021 6c5a7090 Michael Hanselmann
    (status, ) = job_info
2022 6c5a7090 Michael Hanselmann
2023 6c5a7090 Michael Hanselmann
    if log_entries:
2024 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
2025 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
2026 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
2027 4e338533 Michael Hanselmann
                                    log_type, message)
2028 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
2029 6c5a7090 Michael Hanselmann
2030 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
2031 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
2032 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
2033 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
2034 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
2035 685ee993 Iustin Pop
      break
2036 6c5a7090 Michael Hanselmann
2037 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
2038 685ee993 Iustin Pop
2039 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
2040 0bbe448c Michael Hanselmann
  if not jobs:
2041 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
2042 685ee993 Iustin Pop
2043 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
2044 4e338533 Michael Hanselmann
2045 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
2046 53c04d04 Iustin Pop
    return result
2047 4e338533 Michael Hanselmann
2048 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
2049 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
2050 4e338533 Michael Hanselmann
2051 4e338533 Michael Hanselmann
  has_ok = False
2052 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
2053 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
2054 4e338533 Michael Hanselmann
      has_ok = True
2055 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
2056 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
2057 4e338533 Michael Hanselmann
2058 4e338533 Michael Hanselmann
      if has_ok:
2059 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
2060 4e338533 Michael Hanselmann
                                 (idx, msg))
2061 4e338533 Michael Hanselmann
2062 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
2063 4e338533 Michael Hanselmann
2064 4e338533 Michael Hanselmann
  # default failure mode
2065 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
2066 4e338533 Michael Hanselmann
2067 4e338533 Michael Hanselmann
2068 4e338533 Michael Hanselmann
class JobPollCbBase:
2069 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
2070 4e338533 Michael Hanselmann

2071 4e338533 Michael Hanselmann
  """
2072 4e338533 Michael Hanselmann
  def __init__(self):
2073 4e338533 Michael Hanselmann
    """Initializes this class.
2074 4e338533 Michael Hanselmann

2075 4e338533 Michael Hanselmann
    """
2076 4e338533 Michael Hanselmann
2077 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2078 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2079 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2080 4e338533 Michael Hanselmann

2081 4e338533 Michael Hanselmann
    """
2082 4e338533 Michael Hanselmann
    raise NotImplementedError()
2083 4e338533 Michael Hanselmann
2084 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2085 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2086 4e338533 Michael Hanselmann

2087 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
2088 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
2089 4e338533 Michael Hanselmann
    @type fields: list of strings
2090 4e338533 Michael Hanselmann
    @param fields: Fields
2091 4e338533 Michael Hanselmann

2092 4e338533 Michael Hanselmann
    """
2093 4e338533 Michael Hanselmann
    raise NotImplementedError()
2094 4e338533 Michael Hanselmann
2095 4e338533 Michael Hanselmann
2096 4e338533 Michael Hanselmann
class JobPollReportCbBase:
2097 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
2098 4e338533 Michael Hanselmann

2099 4e338533 Michael Hanselmann
  """
2100 4e338533 Michael Hanselmann
  def __init__(self):
2101 4e338533 Michael Hanselmann
    """Initializes this class.
2102 4e338533 Michael Hanselmann

2103 4e338533 Michael Hanselmann
    """
2104 4e338533 Michael Hanselmann
2105 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2106 4e338533 Michael Hanselmann
    """Handles a log message.
2107 4e338533 Michael Hanselmann

2108 4e338533 Michael Hanselmann
    """
2109 4e338533 Michael Hanselmann
    raise NotImplementedError()
2110 4e338533 Michael Hanselmann
2111 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2112 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
2113 4e338533 Michael Hanselmann

2114 4e338533 Michael Hanselmann
    @type job_id: number
2115 4e338533 Michael Hanselmann
    @param job_id: Job ID
2116 4e338533 Michael Hanselmann
    @type status: string or None
2117 4e338533 Michael Hanselmann
    @param status: Job status if available
2118 4e338533 Michael Hanselmann

2119 4e338533 Michael Hanselmann
    """
2120 4e338533 Michael Hanselmann
    raise NotImplementedError()
2121 4e338533 Michael Hanselmann
2122 4e338533 Michael Hanselmann
2123 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
2124 4e338533 Michael Hanselmann
  def __init__(self, cl):
2125 4e338533 Michael Hanselmann
    """Initializes this class.
2126 4e338533 Michael Hanselmann

2127 4e338533 Michael Hanselmann
    """
2128 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
2129 4e338533 Michael Hanselmann
    self.cl = cl
2130 4e338533 Michael Hanselmann
2131 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2132 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2133 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2134 4e338533 Michael Hanselmann

2135 4e338533 Michael Hanselmann
    """
2136 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2137 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
2138 4e338533 Michael Hanselmann
2139 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2140 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2141 4e338533 Michael Hanselmann

2142 4e338533 Michael Hanselmann
    """
2143 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
2144 4e338533 Michael Hanselmann
2145 4e338533 Michael Hanselmann
2146 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2147 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
2148 4e338533 Michael Hanselmann
    """Initializes this class.
2149 4e338533 Michael Hanselmann

2150 4e338533 Michael Hanselmann
    """
2151 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2152 4e338533 Michael Hanselmann
2153 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
2154 4e338533 Michael Hanselmann
2155 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
2156 4e338533 Michael Hanselmann
2157 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2158 4e338533 Michael Hanselmann
    """Handles a log message.
2159 4e338533 Michael Hanselmann

2160 4e338533 Michael Hanselmann
    """
2161 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
2162 4e338533 Michael Hanselmann
2163 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2164 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2165 4e338533 Michael Hanselmann

2166 4e338533 Michael Hanselmann
    """
2167 4e338533 Michael Hanselmann
    # Ignore
2168 4e338533 Michael Hanselmann
2169 4e338533 Michael Hanselmann
2170 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
2171 4e338533 Michael Hanselmann
  def __init__(self):
2172 4e338533 Michael Hanselmann
    """Initializes this class.
2173 4e338533 Michael Hanselmann

2174 4e338533 Michael Hanselmann
    """
2175 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2176 4e338533 Michael Hanselmann
2177 4e338533 Michael Hanselmann
    self.notified_queued = False
2178 4e338533 Michael Hanselmann
    self.notified_waitlock = False
2179 4e338533 Michael Hanselmann
2180 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2181 4e338533 Michael Hanselmann
    """Handles a log message.
2182 4e338533 Michael Hanselmann

2183 4e338533 Michael Hanselmann
    """
2184 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2185 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
2186 4e338533 Michael Hanselmann
2187 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2188 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2189 4e338533 Michael Hanselmann

2190 4e338533 Michael Hanselmann
    """
2191 4e338533 Michael Hanselmann
    if status is None:
2192 4e338533 Michael Hanselmann
      return
2193 4e338533 Michael Hanselmann
2194 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2195 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
2196 4e338533 Michael Hanselmann
      self.notified_queued = True
2197 4e338533 Michael Hanselmann
2198 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2199 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2200 4e338533 Michael Hanselmann
      self.notified_waitlock = True
2201 4e338533 Michael Hanselmann
2202 4e338533 Michael Hanselmann
2203 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
2204 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
2205 8a7f1c61 Michael Hanselmann

2206 8a7f1c61 Michael Hanselmann
  """
2207 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
2208 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
2209 8a7f1c61 Michael Hanselmann
2210 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
2211 8a7f1c61 Michael Hanselmann
2212 8a7f1c61 Michael Hanselmann
2213 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2214 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
2215 4e338533 Michael Hanselmann

2216 4e338533 Michael Hanselmann
  @type job_id: job identified
2217 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
2218 4e338533 Michael Hanselmann
  @type cl: luxi.Client
2219 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
2220 4e338533 Michael Hanselmann
             if None, a new client will be created
2221 4e338533 Michael Hanselmann

2222 4e338533 Michael Hanselmann
  """
2223 4e338533 Michael Hanselmann
  if cl is None:
2224 4e338533 Michael Hanselmann
    cl = GetClient()
2225 4e338533 Michael Hanselmann
2226 583163a6 Michael Hanselmann
  if reporter is None:
2227 583163a6 Michael Hanselmann
    if feedback_fn:
2228 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2229 583163a6 Michael Hanselmann
    else:
2230 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
2231 583163a6 Michael Hanselmann
  elif feedback_fn:
2232 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2233 4e338533 Michael Hanselmann
2234 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2235 ceab32dd Iustin Pop
2236 ceab32dd Iustin Pop
2237 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2238 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
2239 0a1e74d9 Iustin Pop

2240 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
2241 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
2242 0a1e74d9 Iustin Pop
  interaction functions.
2243 0a1e74d9 Iustin Pop

2244 0a1e74d9 Iustin Pop
  """
2245 0a1e74d9 Iustin Pop
  if cl is None:
2246 0a1e74d9 Iustin Pop
    cl = GetClient()
2247 0a1e74d9 Iustin Pop
2248 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
2249 293ba2d8 Iustin Pop
2250 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
2251 0a1e74d9 Iustin Pop
2252 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2253 583163a6 Michael Hanselmann
                       reporter=reporter)
2254 53c04d04 Iustin Pop
2255 53c04d04 Iustin Pop
  return op_results[0]
2256 0a1e74d9 Iustin Pop
2257 0a1e74d9 Iustin Pop
2258 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2259 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
2260 94428652 Iustin Pop

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

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

2269 94428652 Iustin Pop
  """
2270 94428652 Iustin Pop
  if opts and opts.submit_only:
2271 293ba2d8 Iustin Pop
    job = [op]
2272 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
2273 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
2274 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
2275 94428652 Iustin Pop
  else:
2276 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2277 293ba2d8 Iustin Pop
2278 293ba2d8 Iustin Pop
2279 276e51bd Michele Tartara
def _InitReasonTrail(op, opts):
2280 276e51bd Michele Tartara
  """Builds the first part of the reason trail
2281 276e51bd Michele Tartara

2282 276e51bd Michele Tartara
  Builds the initial part of the reason trail, adding the user provided reason
2283 276e51bd Michele Tartara
  (if it exists) and the name of the command starting the operation.
2284 276e51bd Michele Tartara

2285 276e51bd Michele Tartara
  @param op: the opcode the reason trail will be added to
2286 276e51bd Michele Tartara
  @param opts: the command line options selected by the user
2287 276e51bd Michele Tartara

2288 276e51bd Michele Tartara
  """
2289 276e51bd Michele Tartara
  assert len(sys.argv) >= 2
2290 276e51bd Michele Tartara
  trail = []
2291 276e51bd Michele Tartara
2292 276e51bd Michele Tartara
  if opts.reason:
2293 276e51bd Michele Tartara
    trail.append((constants.OPCODE_REASON_SRC_USER,
2294 276e51bd Michele Tartara
                  opts.reason,
2295 276e51bd Michele Tartara
                  utils.EpochNano()))
2296 276e51bd Michele Tartara
2297 276e51bd Michele Tartara
  binary = os.path.basename(sys.argv[0])
2298 276e51bd Michele Tartara
  source = "%s:%s" % (constants.OPCODE_REASON_SRC_CLIENT, binary)
2299 276e51bd Michele Tartara
  command = sys.argv[1]
2300 276e51bd Michele Tartara
  trail.append((source, command, utils.EpochNano()))
2301 276e51bd Michele Tartara
  op.reason = trail
2302 276e51bd Michele Tartara
2303 276e51bd Michele Tartara
2304 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
2305 293ba2d8 Iustin Pop
  """Processor for generic options.
2306 293ba2d8 Iustin Pop

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

2310 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
2311 293ba2d8 Iustin Pop
  @param options: command line options or None
2312 293ba2d8 Iustin Pop
  @return: None (in-place modification)
2313 293ba2d8 Iustin Pop

2314 293ba2d8 Iustin Pop
  """
2315 293ba2d8 Iustin Pop
  if not options:
2316 293ba2d8 Iustin Pop
    return
2317 293ba2d8 Iustin Pop
  for op in opcode_list:
2318 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
2319 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
2320 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
2321 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
2322 552328b8 Michael Hanselmann
      op.priority = options.priority
2323 276e51bd Michele Tartara
    _InitReasonTrail(op, options)
2324 94428652 Iustin Pop
2325 94428652 Iustin Pop
2326 42ab9ac4 Iustin Pop
def GetClient(query=False):
2327 42ab9ac4 Iustin Pop
  """Connects to the a luxi socket and returns a client.
2328 42ab9ac4 Iustin Pop

2329 42ab9ac4 Iustin Pop
  @type query: boolean
2330 42ab9ac4 Iustin Pop
  @param query: this signifies that the client will only be
2331 42ab9ac4 Iustin Pop
      used for queries; if the build-time parameter
2332 42ab9ac4 Iustin Pop
      enable-split-queries is enabled, then the client will be
2333 42ab9ac4 Iustin Pop
      connected to the query socket instead of the masterd socket
2334 42ab9ac4 Iustin Pop

2335 42ab9ac4 Iustin Pop
  """
2336 055d6ac0 Iustin Pop
  override_socket = os.getenv(constants.LUXI_OVERRIDE, "")
2337 055d6ac0 Iustin Pop
  if override_socket:
2338 055d6ac0 Iustin Pop
    if override_socket == constants.LUXI_OVERRIDE_MASTER:
2339 055d6ac0 Iustin Pop
      address = pathutils.MASTER_SOCKET
2340 055d6ac0 Iustin Pop
    elif override_socket == constants.LUXI_OVERRIDE_QUERY:
2341 055d6ac0 Iustin Pop
      address = pathutils.QUERY_SOCKET
2342 055d6ac0 Iustin Pop
    else:
2343 055d6ac0 Iustin Pop
      address = override_socket
2344 055d6ac0 Iustin Pop
  elif query and constants.ENABLE_SPLIT_QUERY:
2345 ee4a14c0 Michael Hanselmann
    address = pathutils.QUERY_SOCKET
2346 42ab9ac4 Iustin Pop
  else:
2347 42ab9ac4 Iustin Pop
    address = None
2348 af30b2fd Michael Hanselmann
  # TODO: Cache object?
2349 b33e986b Iustin Pop
  try:
2350 42ab9ac4 Iustin Pop
    client = luxi.Client(address=address)
2351 b33e986b Iustin Pop
  except luxi.NoMasterError:
2352 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
2353 d9a51679 Michael Hanselmann
2354 d9a51679 Michael Hanselmann
    # Try to read ssconf file
2355 d9a51679 Michael Hanselmann
    try:
2356 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
2357 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
2358 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2359 2cfbc784 Iustin Pop
                                 " not part of a cluster",
2360 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2361 d9a51679 Michael Hanselmann
2362 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2363 b33e986b Iustin Pop
    if master != myself:
2364 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
2365 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
2366 2cfbc784 Iustin Pop
                                 master, errors.ECODE_INVAL)
2367 d9a51679 Michael Hanselmann
    raise
2368 b33e986b Iustin Pop
  return client
2369 af30b2fd Michael Hanselmann
2370 af30b2fd Michael Hanselmann
2371 73702ee7 Iustin Pop
def FormatError(err):
2372 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
2373 73702ee7 Iustin Pop

2374 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
2375 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
2376 73702ee7 Iustin Pop
  second, a string describing the error message (not
2377 73702ee7 Iustin Pop
  newline-terminated).
2378 73702ee7 Iustin Pop

2379 73702ee7 Iustin Pop
  """
2380 73702ee7 Iustin Pop
  retcode = 1
2381 73702ee7 Iustin Pop
  obuf = StringIO()
2382 e2e521d0 Iustin Pop
  msg = str(err)
2383 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
2384 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
2385 46fbdd04 Iustin Pop
    logging.error(txt)
2386 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
2387 73702ee7 Iustin Pop
    obuf.write("Aborting.")
2388 73702ee7 Iustin Pop
    retcode = 2
2389 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
2390 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
2391 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
2392 73702ee7 Iustin Pop
      if out:
2393 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
2394 73702ee7 Iustin Pop
                   (node, script, out))
2395 73702ee7 Iustin Pop
      else:
2396 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
2397 73702ee7 Iustin Pop
                   (node, script))
2398 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
2399 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
2400 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
2401 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
2402 73702ee7 Iustin Pop
    if err.args[0] == this_host:
2403 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
2404 73702ee7 Iustin Pop
    else:
2405 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
2406 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
2407 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
2408 5c983ee5 Iustin Pop
    if len(err.args) == 2:
2409 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2410 5ae4945a Iustin Pop
                 " operation:\nerror type: %s, error details:\n%s" %
2411 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
2412 5c983ee5 Iustin Pop
    else:
2413 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2414 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
2415 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
2416 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
2417 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
2418 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
2419 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
2420 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
2421 686d7433 Iustin Pop
               " accept new requests\n")
2422 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
2423 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
2424 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
2425 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
2426 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
2427 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
2428 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
2429 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
2430 7f5edc60 Iustin Pop
    if err.args[0] == pathutils.MASTER_SOCKET:
2431 055d6ac0 Iustin Pop
      daemon = "the master daemon"
2432 055d6ac0 Iustin Pop
    elif err.args[0] == pathutils.QUERY_SOCKET:
2433 055d6ac0 Iustin Pop
      daemon = "the config daemon"
2434 7f5edc60 Iustin Pop
    else:
2435 055d6ac0 Iustin Pop
      daemon = "socket '%s'" % str(err.args[0])
2436 055d6ac0 Iustin Pop
    obuf.write("Cannot communicate with %s.\nIs the process running"
2437 7f5edc60 Iustin Pop
               " and listening for connections?" % daemon)
2438 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
2439 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
2440 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
2441 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
2442 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
2443 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
2444 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
2445 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
2446 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
2447 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
2448 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
2449 03a8dbdc Iustin Pop
               "%s" % msg)
2450 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
2451 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
2452 cb1e6c3c Michael Hanselmann
  elif isinstance(err, errors.QueryFilterParseError):
2453 cb1e6c3c Michael Hanselmann
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
2454 cb1e6c3c Michael Hanselmann
    obuf.write("\n".join(err.GetDetails()))
2455 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
2456 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
2457 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
2458 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
2459 e9d741b6 Iustin Pop
    retcode = 0
2460 73702ee7 Iustin Pop
  else:
2461 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
2462 d0c8c01d Iustin Pop
  return retcode, obuf.getvalue().rstrip("\n")
2463 73702ee7 Iustin Pop
2464 73702ee7 Iustin Pop
2465 ef9fa5b9 René Nussbaumer
def GenericMain(commands, override=None, aliases=None,
2466 ef9fa5b9 René Nussbaumer
                env_override=frozenset()):
2467 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
2468 a8083063 Iustin Pop

2469 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2470 ef9fa5b9 René Nussbaumer
                   for command line handling.
2471 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2472 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2473 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2474 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2475 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2476 ef9fa5b9 René Nussbaumer
                       default args for commands
2477 a8083063 Iustin Pop

2478 a8083063 Iustin Pop
  """
2479 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
2480 a8083063 Iustin Pop
  if sys.argv:
2481 c1f19851 Michael Hanselmann
    binary = os.path.basename(sys.argv[0])
2482 c1f19851 Michael Hanselmann
    if not binary:
2483 c1f19851 Michael Hanselmann
      binary = sys.argv[0]
2484 c1f19851 Michael Hanselmann
2485 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
2486 c1f19851 Michael Hanselmann
      logname = utils.ShellQuoteArgs([binary, sys.argv[1]])
2487 a8083063 Iustin Pop
    else:
2488 c1f19851 Michael Hanselmann
      logname = binary
2489 c1f19851 Michael Hanselmann
2490 c1f19851 Michael Hanselmann
    cmdline = utils.ShellQuoteArgs([binary] + sys.argv[1:])
2491 a8083063 Iustin Pop
  else:
2492 a8083063 Iustin Pop
    binary = "<unknown program>"
2493 c1f19851 Michael Hanselmann
    cmdline = "<unknown>"
2494 a8083063 Iustin Pop
2495 de47cf8f Guido Trotter
  if aliases is None:
2496 de47cf8f Guido Trotter
    aliases = {}
2497 de47cf8f Guido Trotter
2498 3126878d Guido Trotter
  try:
2499 d971402f Michael Hanselmann
    (func, options, args) = _ParseArgs(binary, sys.argv, commands, aliases,
2500 d971402f Michael Hanselmann
                                       env_override)
2501 d971402f Michael Hanselmann
  except _ShowVersion:
2502 d971402f Michael Hanselmann
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
2503 d971402f Michael Hanselmann
             constants.RELEASE_VERSION)
2504 d971402f Michael Hanselmann
    return constants.EXIT_SUCCESS
2505 d971402f Michael Hanselmann
  except _ShowUsage, err:
2506 d971402f Michael Hanselmann
    for line in _FormatUsage(binary, commands):
2507 d971402f Michael Hanselmann
      ToStdout(line)
2508 d971402f Michael Hanselmann
2509 d971402f Michael Hanselmann
    if err.exit_error:
2510 d971402f Michael Hanselmann
      return constants.EXIT_FAILURE
2511 d971402f Michael Hanselmann
    else:
2512 d971402f Michael Hanselmann
      return constants.EXIT_SUCCESS
2513 3126878d Guido Trotter
  except errors.ParameterError, err:
2514 3126878d Guido Trotter
    result, err_msg = FormatError(err)
2515 3126878d Guido Trotter
    ToStderr(err_msg)
2516 3126878d Guido Trotter
    return 1
2517 3126878d Guido Trotter
2518 a8083063 Iustin Pop
  if func is None: # parse error
2519 a8083063 Iustin Pop
    return 1
2520 a8083063 Iustin Pop
2521 334d1483 Iustin Pop
  if override is not None:
2522 334d1483 Iustin Pop
    for key, val in override.iteritems():
2523 334d1483 Iustin Pop
      setattr(options, key, val)
2524 334d1483 Iustin Pop
2525 ee4a14c0 Michael Hanselmann
  utils.SetupLogging(pathutils.LOG_COMMANDS, logname, debug=options.debug,
2526 cfcc79c6 Michael Hanselmann
                     stderr_logging=True)
2527 a8083063 Iustin Pop
2528 c1f19851 Michael Hanselmann
  logging.info("Command line: %s", cmdline)
2529 a8083063 Iustin Pop
2530 a8083063 Iustin Pop
  try:
2531 a4af651e Iustin Pop
    result = func(options, args)
2532 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
2533 d8353c3a Iustin Pop
          JobSubmittedException), err:
2534 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
2535 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
2536 46fbdd04 Iustin Pop
    ToStderr(err_msg)
2537 8a53b55f Iustin Pop
  except KeyboardInterrupt:
2538 8a53b55f Iustin Pop
    result = constants.EXIT_FAILURE
2539 8a53b55f Iustin Pop
    ToStderr("Aborted. Note that if the operation created any jobs, they"
2540 8a53b55f Iustin Pop
             " might have been submitted and"
2541 8a53b55f Iustin Pop
             " will continue to run in the background.")
2542 225e2544 Iustin Pop
  except IOError, err:
2543 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
2544 225e2544 Iustin Pop
      # our terminal went away, we'll exit
2545 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
2546 225e2544 Iustin Pop
    else:
2547 225e2544 Iustin Pop
      raise
2548 a8083063 Iustin Pop
2549 a8083063 Iustin Pop
  return result
2550 137161c9 Michael Hanselmann
2551 137161c9 Michael Hanselmann
2552 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
2553 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
2554 845c79d8 Michael Hanselmann

2555 845c79d8 Michael Hanselmann
  """
2556 845c79d8 Michael Hanselmann
  try:
2557 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2558 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2559 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2560 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
2561 845c79d8 Michael Hanselmann
2562 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2563 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2564 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2565 845c79d8 Michael Hanselmann
2566 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2567 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2568 2cfbc784 Iustin Pop
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2569 845c79d8 Michael Hanselmann
2570 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2571 845c79d8 Michael Hanselmann
2572 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2573 845c79d8 Michael Hanselmann
2574 845c79d8 Michael Hanselmann
  return nics
2575 845c79d8 Michael Hanselmann
2576 845c79d8 Michael Hanselmann
2577 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2578 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2579 d77490c5 Iustin Pop

2580 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2581 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2582 d77490c5 Iustin Pop
  @type args: list
2583 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2584 d77490c5 Iustin Pop
  @rtype: int
2585 d77490c5 Iustin Pop
  @return: the desired exit code
2586 d77490c5 Iustin Pop

2587 d77490c5 Iustin Pop
  """
2588 d77490c5 Iustin Pop
  instance = args[0]
2589 d77490c5 Iustin Pop
2590 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
2591 d77490c5 Iustin Pop
2592 d77490c5 Iustin Pop
  hypervisor = None
2593 d77490c5 Iustin Pop
  hvparams = {}
2594 d77490c5 Iustin Pop
  if opts.hypervisor:
2595 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
2596 d77490c5 Iustin Pop
2597 d77490c5 Iustin Pop
  if opts.nics:
2598 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
2599 d77490c5 Iustin Pop
  elif opts.no_nics:
2600 d77490c5 Iustin Pop
    # no nics
2601 d77490c5 Iustin Pop
    nics = []
2602 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
2603 d77490c5 Iustin Pop
    # default of one nic, all auto
2604 d77490c5 Iustin Pop
    nics = [{}]
2605 0af0f641 Iustin Pop
  else:
2606 0af0f641 Iustin Pop
    # mode == import
2607 0af0f641 Iustin Pop
    nics = []
2608 d77490c5 Iustin Pop
2609 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
2610 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
2611 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
2612 2cfbc784 Iustin Pop
                                 " information passed", errors.ECODE_INVAL)
2613 d77490c5 Iustin Pop
    disks = []
2614 d77490c5 Iustin Pop
  else:
2615 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
2616 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
2617 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("No disk information specified",
2618 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2619 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
2620 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
2621 2cfbc784 Iustin Pop
                                 " '-s' option", errors.ECODE_INVAL)
2622 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2623 ccfa86ba Michael Hanselmann
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2624 9b12ed0f Iustin Pop
2625 9b12ed0f Iustin Pop
    if opts.disks:
2626 9b12ed0f Iustin Pop
      try:
2627 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2628 9b12ed0f Iustin Pop
      except ValueError, err:
2629 2cfbc784 Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
2630 2cfbc784 Iustin Pop
                                   errors.ECODE_INVAL)
2631 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2632 9b12ed0f Iustin Pop
    else:
2633 9b12ed0f Iustin Pop
      disks = []
2634 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2635 d77490c5 Iustin Pop
      didx = int(didx)
2636 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2637 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2638 2cfbc784 Iustin Pop
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
2639 ccfa86ba Michael Hanselmann
      elif constants.IDISK_SIZE in ddict:
2640 ccfa86ba Michael Hanselmann
        if constants.IDISK_ADOPT in ddict:
2641 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2642 2cfbc784 Iustin Pop
                                     " (disk %d)" % didx, errors.ECODE_INVAL)
2643 5029db65 Iustin Pop
        try:
2644 ccfa86ba Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
2645 ccfa86ba Michael Hanselmann
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2646 5029db65 Iustin Pop
        except ValueError, err:
2647 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2648 2cfbc784 Iustin Pop
                                     (didx, err), errors.ECODE_INVAL)
2649 ccfa86ba Michael Hanselmann
      elif constants.IDISK_ADOPT in ddict:
2650 c615590c Bernardo Dal Seno
        if constants.IDISK_SPINDLES in ddict:
2651 c615590c Bernardo Dal Seno
          raise errors.OpPrereqError("spindles is not a valid option when"
2652 c615590c Bernardo Dal Seno
                                     " adopting a disk", errors.ECODE_INVAL)
2653 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2654 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2655 2cfbc784 Iustin Pop
                                     " import", errors.ECODE_INVAL)
2656 ccfa86ba Michael Hanselmann
        ddict[constants.IDISK_SIZE] = 0
2657 5029db65 Iustin Pop
      else:
2658 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2659 2cfbc784 Iustin Pop
                                   " disk %d" % didx, errors.ECODE_INVAL)
2660 d77490c5 Iustin Pop
      disks[didx] = ddict
2661 d77490c5 Iustin Pop
2662 a57981c5 Apollon Oikonomopoulos
  if opts.tags is not None:
2663 0f8810df Michael Hanselmann
    tags = opts.tags.split(",")
2664 a57981c5 Apollon Oikonomopoulos
  else:
2665 a57981c5 Apollon Oikonomopoulos
    tags = []
2666 a57981c5 Apollon Oikonomopoulos
2667 b2e233a5 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT)
2668 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2669 d77490c5 Iustin Pop
2670 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2671 d77490c5 Iustin Pop
    start = opts.start
2672 d77490c5 Iustin Pop
    os_type = opts.os
2673 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2674 d77490c5 Iustin Pop
    src_node = None
2675 d77490c5 Iustin Pop
    src_path = None
2676 25a8792c Iustin Pop
    no_install = opts.no_install
2677 e588764d Iustin Pop
    identify_defaults = False
2678 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2679 d77490c5 Iustin Pop
    start = False
2680 d77490c5 Iustin Pop
    os_type = None
2681 1ee8e01a Guido Trotter
    force_variant = False
2682 d77490c5 Iustin Pop
    src_node = opts.src_node
2683 d77490c5 Iustin Pop
    src_path = opts.src_dir
2684 25a8792c Iustin Pop
    no_install = None
2685 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2686 d77490c5 Iustin Pop
  else:
2687 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2688 d77490c5 Iustin Pop
2689 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2690 d77490c5 Iustin Pop
                                disks=disks,
2691 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2692 d77490c5 Iustin Pop
                                nics=nics,
2693 d4117a72 Apollon Oikonomopoulos
                                conflicts_check=opts.conflicts_check,
2694 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2695 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2696 460d22be Iustin Pop
                                name_check=opts.name_check,
2697 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2698 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2699 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2700 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2701 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2702 d77490c5 Iustin Pop
                                hvparams=hvparams,
2703 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2704 062a7100 Iustin Pop
                                osparams=opts.osparams,
2705 d77490c5 Iustin Pop
                                mode=mode,
2706 d77490c5 Iustin Pop
                                start=start,
2707 d77490c5 Iustin Pop
                                os_type=os_type,
2708 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2709 d77490c5 Iustin Pop
                                src_node=src_node,
2710 25a8792c Iustin Pop
                                src_path=src_path,
2711 a57981c5 Apollon Oikonomopoulos
                                tags=tags,
2712 e588764d Iustin Pop
                                no_install=no_install,
2713 10889e0c René Nussbaumer
                                identify_defaults=identify_defaults,
2714 10889e0c René Nussbaumer
                                ignore_ipolicy=opts.ignore_ipolicy)
2715 d77490c5 Iustin Pop
2716 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2717 d77490c5 Iustin Pop
  return 0
2718 d77490c5 Iustin Pop
2719 d77490c5 Iustin Pop
2720 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2721 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2722 7e49b6ce Michael Hanselmann

2723 7e49b6ce Michael Hanselmann
  """
2724 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2725 7e49b6ce Michael Hanselmann
    """Initializes this class.
2726 7e49b6ce Michael Hanselmann

2727 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2728 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2729 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2730 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2731 7e49b6ce Michael Hanselmann
    @type master_node: string
2732 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2733 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2734 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2735 7e49b6ce Michael Hanselmann

2736 7e49b6ce Michael Hanselmann
    """
2737 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2738 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2739 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2740 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2741 7e49b6ce Michael Hanselmann
2742 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2743 7e49b6ce Michael Hanselmann
2744 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2745 7e49b6ce Michael Hanselmann
                            if name != master_node]
2746 7e49b6ce Michael Hanselmann
2747 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2748 7e49b6ce Michael Hanselmann
2749 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2750 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2751 7e49b6ce Michael Hanselmann

2752 7e49b6ce Michael Hanselmann
    @type node_name: string
2753 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2754 7e49b6ce Michael Hanselmann
    @type cmd: list
2755 7e49b6ce Michael Hanselmann
    @param cmd: Command
2756 7e49b6ce Michael Hanselmann

2757 7e49b6ce Michael Hanselmann
    """
2758 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2759 7e49b6ce Michael Hanselmann
      # No need to use SSH
2760 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2761 7e49b6ce Michael Hanselmann
    else:
2762 052783ff Michael Hanselmann
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2763 052783ff Michael Hanselmann
                            utils.ShellQuoteArgs(cmd))
2764 7e49b6ce Michael Hanselmann
2765 7e49b6ce Michael Hanselmann
    if result.failed:
2766 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2767 7e49b6ce Michael Hanselmann
      if node_name:
2768 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2769 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2770 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2771 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2772 7e49b6ce Michael Hanselmann
2773 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2774 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2775 7e49b6ce Michael Hanselmann

2776 7e49b6ce Michael Hanselmann
    @type fn: callable
2777 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2778 7e49b6ce Michael Hanselmann

2779 7e49b6ce Michael Hanselmann
    """
2780 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2781 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2782 ee4a14c0 Michael Hanselmann
    watcher_block = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
2783 7e49b6ce Michael Hanselmann
    try:
2784 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2785 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2786 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2787 7e49b6ce Michael Hanselmann
2788 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2789 7e49b6ce Michael Hanselmann
      # ones are finished
2790 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2791 ee4a14c0 Michael Hanselmann
      self._RunCmd(None, [pathutils.DAEMON_UTIL, "stop-master"])
2792 7e49b6ce Michael Hanselmann
      try:
2793 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2794 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2795 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2796 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "stop-all"])
2797 7e49b6ce Michael Hanselmann
2798 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2799 7e49b6ce Michael Hanselmann
        try:
2800 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2801 d512e84b Michael Hanselmann
        except Exception, err:
2802 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2803 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2804 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2805 7e49b6ce Michael Hanselmann
          raise
2806 7e49b6ce Michael Hanselmann
      finally:
2807 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2808 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2809 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2810 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "start-all"])
2811 7e49b6ce Michael Hanselmann
    finally:
2812 7e49b6ce Michael Hanselmann
      # Resume watcher
2813 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2814 7e49b6ce Michael Hanselmann
2815 7e49b6ce Michael Hanselmann
2816 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2817 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2818 7e49b6ce Michael Hanselmann

2819 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2820 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2821 7e49b6ce Michael Hanselmann
  @type fn: callable
2822 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2823 7e49b6ce Michael Hanselmann

2824 7e49b6ce Michael Hanselmann
  """
2825 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2826 7e49b6ce Michael Hanselmann
2827 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2828 7e49b6ce Michael Hanselmann
  cl = GetClient()
2829 7e49b6ce Michael Hanselmann
2830 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2831 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2832 7e49b6ce Michael Hanselmann
2833 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2834 7e49b6ce Michael Hanselmann
2835 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2836 7e49b6ce Michael Hanselmann
  del cl
2837 7e49b6ce Michael Hanselmann
2838 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2839 7e49b6ce Michael Hanselmann
2840 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2841 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2842 7e49b6ce Michael Hanselmann
2843 7e49b6ce Michael Hanselmann
2844 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2845 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2846 9fbfbb7b Iustin Pop
                  units=None):
2847 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2848 137161c9 Michael Hanselmann

2849 9fbfbb7b Iustin Pop
  @type headers: dict
2850 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2851 9fbfbb7b Iustin Pop
      the table
2852 9fbfbb7b Iustin Pop
  @type fields: list
2853 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2854 9fbfbb7b Iustin Pop
      the data field
2855 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2856 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2857 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2858 9fbfbb7b Iustin Pop
      each field
2859 9fbfbb7b Iustin Pop
  @type data: list
2860 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2861 9fbfbb7b Iustin Pop
  @type numfields: list
2862 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2863 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2864 9fbfbb7b Iustin Pop
  @type unitfields: list
2865 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2866 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2867 9fbfbb7b Iustin Pop
  @type units: string or None
2868 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2869 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2870 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2871 137161c9 Michael Hanselmann

2872 137161c9 Michael Hanselmann
  """
2873 9fbfbb7b Iustin Pop
  if units is None:
2874 9fbfbb7b Iustin Pop
    if separator:
2875 9fbfbb7b Iustin Pop
      units = "m"
2876 9fbfbb7b Iustin Pop
    else:
2877 9fbfbb7b Iustin Pop
      units = "h"
2878 9fbfbb7b Iustin Pop
2879 137161c9 Michael Hanselmann
  if numfields is None:
2880 137161c9 Michael Hanselmann
    numfields = []
2881 137161c9 Michael Hanselmann
  if unitfields is None:
2882 137161c9 Michael Hanselmann
    unitfields = []
2883 137161c9 Michael Hanselmann
2884 b459a848 Andrea Spadaccini
  numfields = utils.FieldSet(*numfields)   # pylint: disable=W0142
2885 b459a848 Andrea Spadaccini
  unitfields = utils.FieldSet(*unitfields) # pylint: disable=W0142
2886 00430f8e Iustin Pop
2887 137161c9 Michael Hanselmann
  format_fields = []
2888 137161c9 Michael Hanselmann
  for field in fields:
2889 01ca31ae Iustin Pop
    if headers and field not in headers:
2890 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2891 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2892 71c1af58 Iustin Pop
      # variable fields)
2893 71c1af58 Iustin Pop
      headers[field] = field
2894 137161c9 Michael Hanselmann
    if separator is not None:
2895 137161c9 Michael Hanselmann
      format_fields.append("%s")
2896 00430f8e Iustin Pop
    elif numfields.Matches(field):
2897 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2898 137161c9 Michael Hanselmann
    else:
2899 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2900 137161c9 Michael Hanselmann
2901 137161c9 Michael Hanselmann
  if separator is None:
2902 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2903 d0c8c01d Iustin Pop
    format_str = " ".join(format_fields)
2904 137161c9 Michael Hanselmann
  else:
2905 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2906 137161c9 Michael Hanselmann
2907 137161c9 Michael Hanselmann
  for row in data:
2908 dcbd6288 Guido Trotter
    if row is None:
2909 dcbd6288 Guido Trotter
      continue
2910 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2911 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2912 137161c9 Michael Hanselmann
        try:
2913 137161c9 Michael Hanselmann
          val = int(val)
2914 691744c4 Iustin Pop
        except (TypeError, ValueError):
2915 137161c9 Michael Hanselmann
          pass
2916 137161c9 Michael Hanselmann
        else:
2917 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2918 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2919 137161c9 Michael Hanselmann
      if separator is None:
2920 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2921 137161c9 Michael Hanselmann
2922 16be8703 Iustin Pop
  result = []
2923 137161c9 Michael Hanselmann
  if headers:
2924 137161c9 Michael Hanselmann
    args = []
2925 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2926 137161c9 Michael Hanselmann
      hdr = headers[name]
2927 137161c9 Michael Hanselmann
      if separator is None:
2928 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2929 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2930 137161c9 Michael Hanselmann
      args.append(hdr)
2931 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2932 137161c9 Michael Hanselmann
2933 ec39d63c Michael Hanselmann
  if separator is None:
2934 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2935 ec39d63c Michael Hanselmann
2936 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2937 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2938 ec39d63c Michael Hanselmann
2939 137161c9 Michael Hanselmann
  for line in data:
2940 137161c9 Michael Hanselmann
    args = []
2941 dcbd6288 Guido Trotter
    if line is None:
2942 d0c8c01d Iustin Pop
      line = ["-" for _ in fields]
2943 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
2944 137161c9 Michael Hanselmann
      if separator is None:
2945 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2946 137161c9 Michael Hanselmann
      args.append(line[idx])
2947 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2948 16be8703 Iustin Pop
2949 16be8703 Iustin Pop
  return result
2950 3386e7a9 Iustin Pop
2951 3386e7a9 Iustin Pop
2952 ee3aedff Michael Hanselmann
def _FormatBool(value):
2953 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
2954 ee3aedff Michael Hanselmann

2955 ee3aedff Michael Hanselmann
  """
2956 ee3aedff Michael Hanselmann
  if value:
2957 ee3aedff Michael Hanselmann
    return "Y"
2958 ee3aedff Michael Hanselmann
  return "N"
2959 ee3aedff Michael Hanselmann
2960 ee3aedff Michael Hanselmann
2961 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2962 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2963 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2964 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2965 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2966 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2967 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2968 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2969 ee3aedff Michael Hanselmann
  }
2970 ee3aedff Michael Hanselmann
2971 ee3aedff Michael Hanselmann
2972 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2973 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2974 ee3aedff Michael Hanselmann

2975 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2976 ee3aedff Michael Hanselmann
  @type override: dict
2977 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2978 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2979 ee3aedff Michael Hanselmann
  @type unit: string
2980 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2981 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2982 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2983 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2984 ee3aedff Michael Hanselmann

2985 ee3aedff Michael Hanselmann
  """
2986 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2987 ee3aedff Michael Hanselmann
  if fmt is not None:
2988 ee3aedff Michael Hanselmann
    return fmt
2989 ee3aedff Michael Hanselmann
2990 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2991 ee3aedff Michael Hanselmann
2992 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2993 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2994 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2995 ee3aedff Michael Hanselmann
2996 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2997 ee3aedff Michael Hanselmann
  if fmt is not None:
2998 ee3aedff Michael Hanselmann
    return fmt
2999 ee3aedff Michael Hanselmann
3000 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
3001 ee3aedff Michael Hanselmann
3002 ee3aedff Michael Hanselmann
3003 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
3004 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
3005 ee3aedff Michael Hanselmann

3006 ee3aedff Michael Hanselmann
  """
3007 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
3008 ee3aedff Michael Hanselmann
    """Initializes this class.
3009 ee3aedff Michael Hanselmann

3010 ee3aedff Michael Hanselmann
    @type fn: callable
3011 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3012 ee3aedff Michael Hanselmann
    @type status_fn: callable
3013 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
3014 f0b1bafe Iustin Pop
    @type verbose: boolean
3015 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
3016 ee3aedff Michael Hanselmann

3017 ee3aedff Michael Hanselmann
    """
3018 ee3aedff Michael Hanselmann
    self._fn = fn
3019 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
3020 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
3021 ee3aedff Michael Hanselmann
3022 ee3aedff Michael Hanselmann
  def __call__(self, data):
3023 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
3024 ee3aedff Michael Hanselmann

3025 ee3aedff Michael Hanselmann
    """
3026 ee3aedff Michael Hanselmann
    (status, value) = data
3027 ee3aedff Michael Hanselmann
3028 ee3aedff Michael Hanselmann
    # Report status
3029 ee3aedff Michael Hanselmann
    self._status_fn(status)
3030 ee3aedff Michael Hanselmann
3031 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
3032 ee3aedff Michael Hanselmann
      return self._fn(value)
3033 ee3aedff Michael Hanselmann
3034 ee3aedff Michael Hanselmann
    assert value is None, \
3035 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
3036 ee3aedff Michael Hanselmann
3037 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
3038 ee3aedff Michael Hanselmann
3039 ee3aedff Michael Hanselmann
3040 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
3041 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
3042 ee3aedff Michael Hanselmann

3043 ae95e419 René Nussbaumer
  @param status: The result status
3044 f2c6673d Michael Hanselmann
  @type verbose: boolean
3045 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
3046 ae95e419 René Nussbaumer
  @return: Text of result status
3047 a6070ef7 Michael Hanselmann

3048 ae95e419 René Nussbaumer
  """
3049 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
3050 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
3051 ae95e419 René Nussbaumer
  try:
3052 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
3053 ae95e419 René Nussbaumer
  except KeyError:
3054 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
3055 cbfa4f0f Michael Hanselmann
  else:
3056 cbfa4f0f Michael Hanselmann
    if verbose:
3057 cbfa4f0f Michael Hanselmann
      return verbose_text
3058 cbfa4f0f Michael Hanselmann
    return normal_text
3059 ee3aedff Michael Hanselmann
3060 ee3aedff Michael Hanselmann
3061 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
3062 f0b1bafe Iustin Pop
                      header=False, verbose=False):
3063 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
3064 ee3aedff Michael Hanselmann

3065 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
3066 ee3aedff Michael Hanselmann
  @param result: result of query operation
3067 ee3aedff Michael Hanselmann
  @type unit: string
3068 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
3069 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
3070 ee3aedff Michael Hanselmann
  @type format_override: dict
3071 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3072 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3073 ee3aedff Michael Hanselmann
  @type separator: string or None
3074 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3075 ee3aedff Michael Hanselmann
  @type header: bool
3076 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
3077 f0b1bafe Iustin Pop
  @type verbose: boolean
3078 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3079 ee3aedff Michael Hanselmann

3080 ee3aedff Michael Hanselmann
  """
3081 ee3aedff Michael Hanselmann
  if unit is None:
3082 ee3aedff Michael Hanselmann
    if separator:
3083 ee3aedff Michael Hanselmann
      unit = "m"
3084 ee3aedff Michael Hanselmann
    else:
3085 ee3aedff Michael Hanselmann
      unit = "h"
3086 ee3aedff Michael Hanselmann
3087 ee3aedff Michael Hanselmann
  if format_override is None:
3088 ee3aedff Michael Hanselmann
    format_override = {}
3089 ee3aedff Michael Hanselmann
3090 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
3091 ee3aedff Michael Hanselmann
3092 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
3093 ee3aedff Michael Hanselmann
    if status in stats:
3094 ee3aedff Michael Hanselmann
      stats[status] += 1
3095 ee3aedff Michael Hanselmann
3096 ee3aedff Michael Hanselmann
  columns = []
3097 ee3aedff Michael Hanselmann
  for fdef in result.fields:
3098 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
3099 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
3100 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
3101 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
3102 f0b1bafe Iustin Pop
                                                     verbose),
3103 ee3aedff Michael Hanselmann
                               align_right))
3104 ee3aedff Michael Hanselmann
3105 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
3106 ee3aedff Michael Hanselmann
3107 ee3aedff Michael Hanselmann
  # Collect statistics
3108 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
3109 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
3110 ee3aedff Michael Hanselmann
3111 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
3112 ee3aedff Michael Hanselmann
  # detected via the field definitions.
3113 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
3114 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
3115 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
3116 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
3117 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
3118 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
3119 ee3aedff Michael Hanselmann
  else:
3120 ee3aedff Michael Hanselmann
    status = QR_NORMAL
3121 ee3aedff Michael Hanselmann
3122 ee3aedff Michael Hanselmann
  return (status, table)
3123 ee3aedff Michael Hanselmann
3124 ee3aedff Michael Hanselmann
3125 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
3126 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
3127 ee3aedff Michael Hanselmann

3128 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3129 ee3aedff Michael Hanselmann

3130 ee3aedff Michael Hanselmann
  """
3131 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
3132 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
3133 ee3aedff Michael Hanselmann
3134 ee3aedff Michael Hanselmann
3135 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
3136 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
3137 ee3aedff Michael Hanselmann

3138 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3139 ee3aedff Michael Hanselmann

3140 ee3aedff Michael Hanselmann
  """
3141 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
3142 ee3aedff Michael Hanselmann
  if unknown:
3143 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
3144 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
3145 ee3aedff Michael Hanselmann
    return True
3146 ee3aedff Michael Hanselmann
3147 ee3aedff Michael Hanselmann
  return False
3148 ee3aedff Michael Hanselmann
3149 ee3aedff Michael Hanselmann
3150 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
3151 03ec545a Michael Hanselmann
                format_override=None, verbose=False, force_filter=False,
3152 6f287cf3 Iustin Pop
                namefield=None, qfilter=None, isnumeric=False):
3153 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
3154 ee3aedff Michael Hanselmann

3155 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3156 ee3aedff Michael Hanselmann
  @type fields: list of strings
3157 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3158 ee3aedff Michael Hanselmann
  @type names: list of strings
3159 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
3160 ee3aedff Michael Hanselmann
  @type unit: string or None
3161 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3162 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
3163 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
3164 ee3aedff Michael Hanselmann
  @type separator: string or None
3165 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3166 ee3aedff Michael Hanselmann
  @type header: bool
3167 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3168 2928de47 Michael Hanselmann
  @type force_filter: bool
3169 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
3170 ee3aedff Michael Hanselmann
  @type format_override: dict
3171 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3172 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3173 f0b1bafe Iustin Pop
  @type verbose: boolean
3174 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3175 03ec545a Michael Hanselmann
  @type namefield: string
3176 03ec545a Michael Hanselmann
  @param namefield: Name of field to use for simple filters (see
3177 03ec545a Michael Hanselmann
    L{qlang.MakeFilter} for details)
3178 f037e9d7 Michael Hanselmann
  @type qfilter: list or None
3179 f037e9d7 Michael Hanselmann
  @param qfilter: Query filter (in addition to names)
3180 6f287cf3 Iustin Pop
  @param isnumeric: bool
3181 6f287cf3 Iustin Pop
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3182 6f287cf3 Iustin Pop
    any simple filters built by namefield should use integer values to
3183 6f287cf3 Iustin Pop
    reflect that
3184 ee3aedff Michael Hanselmann

3185 ee3aedff Michael Hanselmann
  """
3186 ee3aedff Michael Hanselmann
  if not names:
3187 ee3aedff Michael Hanselmann
    names = None
3188 ee3aedff Michael Hanselmann
3189 6f287cf3 Iustin Pop
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3190 6f287cf3 Iustin Pop
                                isnumeric=isnumeric)
3191 f037e9d7 Michael Hanselmann
3192 f037e9d7 Michael Hanselmann
  if qfilter is None:
3193 f037e9d7 Michael Hanselmann
    qfilter = namefilter
3194 f037e9d7 Michael Hanselmann
  elif namefilter is not None:
3195 f037e9d7 Michael Hanselmann
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3196 2928de47 Michael Hanselmann
3197 727274dd Iustin Pop
  if cl is None:
3198 727274dd Iustin Pop
    cl = GetClient()
3199 727274dd Iustin Pop
3200 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
3201 ee3aedff Michael Hanselmann
3202 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3203 ee3aedff Michael Hanselmann
3204 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3205 ee3aedff Michael Hanselmann
                                     header=header,
3206 f0b1bafe Iustin Pop
                                     format_override=format_override,
3207 f0b1bafe Iustin Pop
                                     verbose=verbose)
3208 ee3aedff Michael Hanselmann
3209 ee3aedff Michael Hanselmann
  for line in data:
3210 ee3aedff Michael Hanselmann
    ToStdout(line)
3211 ee3aedff Michael Hanselmann
3212 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
3213 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
3214 ee3aedff Michael Hanselmann
3215 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
3216 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3217 ee3aedff Michael Hanselmann
3218 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
3219 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3220 ee3aedff Michael Hanselmann
3221 ee3aedff Michael Hanselmann
3222 c1912a48 Michael Hanselmann
def _FieldDescValues(fdef):
3223 c1912a48 Michael Hanselmann
  """Helper function for L{GenericListFields} to get query field description.
3224 c1912a48 Michael Hanselmann

3225 c1912a48 Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
3226 c1912a48 Michael Hanselmann
  @rtype: list
3227 c1912a48 Michael Hanselmann

3228 c1912a48 Michael Hanselmann
  """
3229 c1912a48 Michael Hanselmann
  return [
3230 c1912a48 Michael Hanselmann
    fdef.name,
3231 c1912a48 Michael Hanselmann
    _QFT_NAMES.get(fdef.kind, fdef.kind),
3232 c1912a48 Michael Hanselmann
    fdef.title,
3233 c1912a48 Michael Hanselmann
    fdef.doc,
3234 c1912a48 Michael Hanselmann
    ]
3235 c1912a48 Michael Hanselmann
3236 c1912a48 Michael Hanselmann
3237 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
3238 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
3239 ee3aedff Michael Hanselmann

3240 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3241 ee3aedff Michael Hanselmann
  @type fields: list of strings
3242 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3243 ee3aedff Michael Hanselmann
  @type separator: string or None
3244 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3245 ee3aedff Michael Hanselmann
  @type header: bool
3246 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3247 ee3aedff Michael Hanselmann

3248 ee3aedff Michael Hanselmann
  """
3249 ee3aedff Michael Hanselmann
  if cl is None:
3250 ee3aedff Michael Hanselmann
    cl = GetClient()
3251 ee3aedff Michael Hanselmann
3252 ee3aedff Michael Hanselmann
  if not fields:
3253 ee3aedff Michael Hanselmann
    fields = None
3254 ee3aedff Michael Hanselmann
3255 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
3256 ee3aedff Michael Hanselmann
3257 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3258 ee3aedff Michael Hanselmann
3259 ee3aedff Michael Hanselmann
  columns = [
3260 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
3261 c1912a48 Michael Hanselmann
    TableColumn("Type", str, False),
3262 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
3263 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
3264 ee3aedff Michael Hanselmann
    ]
3265 ee3aedff Michael Hanselmann
3266 c1912a48 Michael Hanselmann
  rows = map(_FieldDescValues, response.fields)
3267 ee3aedff Michael Hanselmann
3268 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
3269 ee3aedff Michael Hanselmann
    ToStdout(line)
3270 ee3aedff Michael Hanselmann
3271 ee3aedff Michael Hanselmann
  if found_unknown:
3272 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3273 ee3aedff Michael Hanselmann
3274 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3275 ee3aedff Michael Hanselmann
3276 ee3aedff Michael Hanselmann
3277 ee3aedff Michael Hanselmann
class TableColumn:
3278 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
3279 ee3aedff Michael Hanselmann

3280 ee3aedff Michael Hanselmann
  """
3281 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
3282 ee3aedff Michael Hanselmann
    """Initializes this class.
3283 ee3aedff Michael Hanselmann

3284 ee3aedff Michael Hanselmann
    @type title: string
3285 ee3aedff Michael Hanselmann
    @param title: Column title
3286 ee3aedff Michael Hanselmann
    @type fn: callable
3287 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3288 ee3aedff Michael Hanselmann
    @type align_right: bool
3289 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
3290 ee3aedff Michael Hanselmann

3291 ee3aedff Michael Hanselmann
    """
3292 ee3aedff Michael Hanselmann
    self.title = title
3293 ee3aedff Michael Hanselmann
    self.format = fn
3294 ee3aedff Michael Hanselmann
    self.align_right = align_right
3295 ee3aedff Michael Hanselmann
3296 ee3aedff Michael Hanselmann
3297 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
3298 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
3299 ee3aedff Michael Hanselmann

3300 ee3aedff Michael Hanselmann
  """
3301 ee3aedff Michael Hanselmann
  if align_right:
3302 ee3aedff Michael Hanselmann
    sign = ""
3303 ee3aedff Michael Hanselmann
  else:
3304 ee3aedff Michael Hanselmann
    sign = "-"
3305 ee3aedff Michael Hanselmann
3306 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
3307 ee3aedff Michael Hanselmann
3308 ee3aedff Michael Hanselmann
3309 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
3310 ee3aedff Michael Hanselmann
  """Formats data as a table.
3311 ee3aedff Michael Hanselmann

3312 ee3aedff Michael Hanselmann
  @type rows: list of lists
3313 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
3314 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
3315 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
3316 ee3aedff Michael Hanselmann
  @type header: bool
3317 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3318 ee3aedff Michael Hanselmann
  @type separator: string or None
3319 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
3320 ee3aedff Michael Hanselmann

3321 ee3aedff Michael Hanselmann
  """
3322 ee3aedff Michael Hanselmann
  if header:
3323 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
3324 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
3325 ee3aedff Michael Hanselmann
  else:
3326 ee3aedff Michael Hanselmann
    data = []
3327 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
3328 ee3aedff Michael Hanselmann
3329 ee3aedff Michael Hanselmann
  # Format row data
3330 ee3aedff Michael Hanselmann
  for row in rows:
3331 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
3332 ee3aedff Michael Hanselmann
3333 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
3334 ee3aedff Michael Hanselmann
3335 ee3aedff Michael Hanselmann
    if separator is None:
3336 ee3aedff Michael Hanselmann
      # Update column widths
3337 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3338 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
3339 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
3340 ee3aedff Michael Hanselmann
3341 ee3aedff Michael Hanselmann
    data.append(formatted)
3342 ee3aedff Michael Hanselmann
3343 ee3aedff Michael Hanselmann
  if separator is not None:
3344 ee3aedff Michael Hanselmann
    # Return early if a separator is used
3345 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
3346 ee3aedff Michael Hanselmann
3347 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
3348 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
3349 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
3350 ee3aedff Michael Hanselmann
3351 ee3aedff Michael Hanselmann
  # Build format string
3352 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3353 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
3354 ee3aedff Michael Hanselmann
3355 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
3356 ee3aedff Michael Hanselmann
3357 ee3aedff Michael Hanselmann
3358 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
3359 3386e7a9 Iustin Pop
  """Formats a given timestamp.
3360 3386e7a9 Iustin Pop

3361 3386e7a9 Iustin Pop
  @type ts: timestamp
3362 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3363 3386e7a9 Iustin Pop

3364 3386e7a9 Iustin Pop
  @rtype: string
3365 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
3366 3386e7a9 Iustin Pop

3367 3386e7a9 Iustin Pop
  """
3368 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3369 d0c8c01d Iustin Pop
    return "?"
3370 26a72a48 Michael Hanselmann
3371 26a72a48 Michael Hanselmann
  (sec, usecs) = ts
3372 26a72a48 Michael Hanselmann
  return utils.FormatTime(sec, usecs=usecs)
3373 2241e2b9 Iustin Pop
3374 2241e2b9 Iustin Pop
3375 2241e2b9 Iustin Pop
def ParseTimespec(value):
3376 2241e2b9 Iustin Pop
  """Parse a time specification.
3377 2241e2b9 Iustin Pop

3378 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
3379 2241e2b9 Iustin Pop

3380 2241e2b9 Iustin Pop
    - s: seconds
3381 2241e2b9 Iustin Pop
    - m: minutes
3382 2241e2b9 Iustin Pop
    - h: hours
3383 2241e2b9 Iustin Pop
    - d: day
3384 2241e2b9 Iustin Pop
    - w: weeks
3385 2241e2b9 Iustin Pop

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

3388 2241e2b9 Iustin Pop
  """
3389 2241e2b9 Iustin Pop
  value = str(value)
3390 2241e2b9 Iustin Pop
  if not value:
3391 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed",
3392 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
3393 2241e2b9 Iustin Pop
  suffix_map = {
3394 d0c8c01d Iustin Pop
    "s": 1,
3395 d0c8c01d Iustin Pop
    "m": 60,
3396 d0c8c01d Iustin Pop
    "h": 3600,
3397 d0c8c01d Iustin Pop
    "d": 86400,
3398 d0c8c01d Iustin Pop
    "w": 604800,
3399 2241e2b9 Iustin Pop
    }
3400 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
3401 2241e2b9 Iustin Pop
    try:
3402 2241e2b9 Iustin Pop
      value = int(value)
3403 691744c4 Iustin Pop
    except (TypeError, ValueError):
3404 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3405 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3406 2241e2b9 Iustin Pop
  else:
3407 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
3408 2241e2b9 Iustin Pop
    value = value[:-1]
3409 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
3410 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
3411 2cfbc784 Iustin Pop
                                 " suffix passed)", errors.ECODE_INVAL)
3412 2241e2b9 Iustin Pop
    try:
3413 2241e2b9 Iustin Pop
      value = int(value) * multiplier
3414 691744c4 Iustin Pop
    except (TypeError, ValueError):
3415 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3416 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3417 2241e2b9 Iustin Pop
  return value
3418 46fbdd04 Iustin Pop
3419 46fbdd04 Iustin Pop
3420 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3421 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
3422 4040a784 Iustin Pop
  """Returns the names of online nodes.
3423 4040a784 Iustin Pop

3424 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
3425 4040a784 Iustin Pop
  the online nodes.
3426 4040a784 Iustin Pop

3427 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
3428 4040a784 Iustin Pop
      offline ones)
3429 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
3430 4040a784 Iustin Pop
  @type nowarn: boolean
3431 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
3432 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
3433 4040a784 Iustin Pop
      note is not displayed
3434 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
3435 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
3436 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
3437 e9e26bb3 Iustin Pop
      (if any)
3438 e9e26bb3 Iustin Pop
  @type filter_master: boolean
3439 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
3440 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
3441 e9e26bb3 Iustin Pop
      node name against the list)
3442 05484a24 Michael Hanselmann
  @type nodegroup: string
3443 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
3444 4040a784 Iustin Pop

3445 4040a784 Iustin Pop
  """
3446 4040a784 Iustin Pop
  if cl is None:
3447 4040a784 Iustin Pop
    cl = GetClient()
3448 4040a784 Iustin Pop
3449 2e5c33db Iustin Pop
  qfilter = []
3450 05484a24 Michael Hanselmann
3451 05484a24 Michael Hanselmann
  if nodes:
3452 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3453 05484a24 Michael Hanselmann
3454 05484a24 Michael Hanselmann
  if nodegroup is not None:
3455 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3456 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3457 e9e26bb3 Iustin Pop
3458 e9e26bb3 Iustin Pop
  if filter_master:
3459 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3460 05484a24 Michael Hanselmann
3461 2e5c33db Iustin Pop
  if qfilter:
3462 2e5c33db Iustin Pop
    if len(qfilter) > 1:
3463 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
3464 05484a24 Michael Hanselmann
    else:
3465 2e5c33db Iustin Pop
      assert len(qfilter) == 1
3466 2e5c33db Iustin Pop
      final_filter = qfilter[0]
3467 e9e26bb3 Iustin Pop
  else:
3468 05484a24 Michael Hanselmann
    final_filter = None
3469 05484a24 Michael Hanselmann
3470 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3471 05484a24 Michael Hanselmann
3472 05484a24 Michael Hanselmann
  def _IsOffline(row):
3473 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
3474 05484a24 Michael Hanselmann
    return offline
3475 05484a24 Michael Hanselmann
3476 05484a24 Michael Hanselmann
  def _GetName(row):
3477 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
3478 05484a24 Michael Hanselmann
    return name
3479 05484a24 Michael Hanselmann
3480 05484a24 Michael Hanselmann
  def _GetSip(row):
3481 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
3482 05484a24 Michael Hanselmann
    return sip
3483 05484a24 Michael Hanselmann
3484 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
3485 e9e26bb3 Iustin Pop
3486 4040a784 Iustin Pop
  if offline and not nowarn:
3487 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
3488 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
3489 05484a24 Michael Hanselmann
3490 05484a24 Michael Hanselmann
  if secondary_ips:
3491 05484a24 Michael Hanselmann
    fn = _GetSip
3492 05484a24 Michael Hanselmann
  else:
3493 05484a24 Michael Hanselmann
    fn = _GetName
3494 05484a24 Michael Hanselmann
3495 05484a24 Michael Hanselmann
  return map(fn, online)
3496 4040a784 Iustin Pop
3497 4040a784 Iustin Pop
3498 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3499 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3500 46fbdd04 Iustin Pop

3501 46fbdd04 Iustin Pop
  @type stream: file object
3502 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3503 46fbdd04 Iustin Pop
  @type txt: str
3504 46fbdd04 Iustin Pop
  @param txt: the message
3505 46fbdd04 Iustin Pop

3506 46fbdd04 Iustin Pop
  """
3507 225e2544 Iustin Pop
  try:
3508 225e2544 Iustin Pop
    if args:
3509 225e2544 Iustin Pop
      args = tuple(args)
3510 225e2544 Iustin Pop
      stream.write(txt % args)
3511 225e2544 Iustin Pop
    else:
3512 225e2544 Iustin Pop
      stream.write(txt)
3513 d0c8c01d Iustin Pop
    stream.write("\n")
3514 225e2544 Iustin Pop
    stream.flush()
3515 225e2544 Iustin Pop
  except IOError, err:
3516 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3517 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3518 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3519 225e2544 Iustin Pop
    else:
3520 225e2544 Iustin Pop
      raise
3521 46fbdd04 Iustin Pop
3522 46fbdd04 Iustin Pop
3523 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3524 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3525 46fbdd04 Iustin Pop

3526 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3527 46fbdd04 Iustin Pop

3528 46fbdd04 Iustin Pop
  @type txt: str
3529 46fbdd04 Iustin Pop
  @param txt: the message
3530 46fbdd04 Iustin Pop

3531 46fbdd04 Iustin Pop
  """
3532 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3533 46fbdd04 Iustin Pop
3534 46fbdd04 Iustin Pop
3535 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3536 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3537 46fbdd04 Iustin Pop

3538 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3539 46fbdd04 Iustin Pop

3540 46fbdd04 Iustin Pop
  @type txt: str
3541 46fbdd04 Iustin Pop
  @param txt: the message
3542 46fbdd04 Iustin Pop

3543 46fbdd04 Iustin Pop
  """
3544 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3545 479636a3 Iustin Pop
3546 479636a3 Iustin Pop
3547 479636a3 Iustin Pop
class JobExecutor(object):
3548 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3549 479636a3 Iustin Pop

3550 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3551 479636a3 Iustin Pop
  GetResults() calls.
3552 479636a3 Iustin Pop

3553 479636a3 Iustin Pop
  """
3554 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3555 479636a3 Iustin Pop
    self.queue = []
3556 479636a3 Iustin Pop
    if cl is None:
3557 479636a3 Iustin Pop
      cl = GetClient()
3558 479636a3 Iustin Pop
    self.cl = cl
3559 479636a3 Iustin Pop
    self.verbose = verbose
3560 23b4b983 Iustin Pop
    self.jobs = []
3561 cff5fa7f Iustin Pop
    self.opts = opts
3562 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3563 60452edf Michael Hanselmann
    self._counter = itertools.count()
3564 479636a3 Iustin Pop
3565 8d99a8bf Michael Hanselmann
  @staticmethod
3566 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3567 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3568 8d99a8bf Michael Hanselmann

3569 8d99a8bf Michael Hanselmann
    """
3570 8d99a8bf Michael Hanselmann
    if name:
3571 8d99a8bf Michael Hanselmann
      return fmt % name
3572 8d99a8bf Michael Hanselmann
3573 8d99a8bf Michael Hanselmann
    return ""
3574 8d99a8bf Michael Hanselmann
3575 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3576 23b4b983 Iustin Pop
    """Record a job for later submit.
3577 479636a3 Iustin Pop

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

3581 479636a3 Iustin Pop
    """
3582 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3583 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3584 23b4b983 Iustin Pop
3585 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3586 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3587 8d99a8bf Michael Hanselmann

3588 8d99a8bf Michael Hanselmann
    """
3589 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3590 8d99a8bf Michael Hanselmann
3591 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3592 23b4b983 Iustin Pop
    """Submit all pending jobs.
3593 23b4b983 Iustin Pop

3594 23b4b983 Iustin Pop
    """
3595 66ecc479 Guido Trotter
    if each:
3596 66ecc479 Guido Trotter
      results = []
3597 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3598 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3599 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3600 519fafa1 Andrea Spadaccini
        results.append([True, self.cl.SubmitJob(ops)[0]])
3601 66ecc479 Guido Trotter
    else:
3602 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3603 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3604 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3605 5299e61f Iustin Pop
3606 5299e61f Iustin Pop
  def _ChooseJob(self):
3607 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3608 5299e61f Iustin Pop

3609 5299e61f Iustin Pop
    """
3610 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3611 5299e61f Iustin Pop
3612 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3613 11705e3d Iustin Pop
                               ["status"])
3614 5299e61f Iustin Pop
    assert result
3615 5299e61f Iustin Pop
3616 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3617 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3618 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3619 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3620 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3621 91c622a8 Iustin Pop
        # job is still present and waiting
3622 5299e61f Iustin Pop
        continue
3623 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3624 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3625 5299e61f Iustin Pop
      return job_data
3626 5299e61f Iustin Pop
3627 5299e61f Iustin Pop
    # no job found
3628 5299e61f Iustin Pop
    return self.jobs.pop(0)
3629 479636a3 Iustin Pop
3630 479636a3 Iustin Pop
  def GetResults(self):
3631 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3632 479636a3 Iustin Pop

3633 479636a3 Iustin Pop
    @rtype: list
3634 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3635 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3636 479636a3 Iustin Pop
        there will be the error message
3637 479636a3 Iustin Pop

3638 479636a3 Iustin Pop
    """
3639 23b4b983 Iustin Pop
    if not self.jobs:
3640 23b4b983 Iustin Pop
      self.SubmitPending()
3641 479636a3 Iustin Pop
    results = []
3642 479636a3 Iustin Pop
    if self.verbose:
3643 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3644 23b4b983 Iustin Pop
      if ok_jobs:
3645 4474f112 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3646 5299e61f Iustin Pop
3647 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
3648 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3649 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
3650 4474f112 Iustin Pop
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3651 c63355f2 Iustin Pop
      results.append((idx, False, jid))
3652 5299e61f Iustin Pop
3653 5299e61f Iustin Pop
    while self.jobs:
3654 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
3655 4474f112 Iustin Pop
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3656 479636a3 Iustin Pop
      try:
3657 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3658 479636a3 Iustin Pop
        success = True
3659 91c622a8 Iustin Pop
      except errors.JobLost, err:
3660 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3661 4474f112 Iustin Pop
        ToStderr("Job %s%s has been archived, cannot check its result",
3662 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"))
3663 91c622a8 Iustin Pop
        success = False
3664 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3665 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3666 479636a3 Iustin Pop
        success = False
3667 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3668 4474f112 Iustin Pop
        ToStderr("Job %s%s has failed: %s",
3669 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"), job_result)
3670 479636a3 Iustin Pop
3671 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3672 5299e61f Iustin Pop
3673 5299e61f Iustin Pop
    # sort based on the index, then drop it
3674 5299e61f Iustin Pop
    results.sort()
3675 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3676 5299e61f Iustin Pop
3677 479636a3 Iustin Pop
    return results
3678 479636a3 Iustin Pop
3679 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3680 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3681 479636a3 Iustin Pop

3682 479636a3 Iustin Pop
    @type wait: boolean
3683 479636a3 Iustin Pop
    @param wait: whether to wait or not
3684 479636a3 Iustin Pop

3685 479636a3 Iustin Pop
    """
3686 479636a3 Iustin Pop
    if wait:
3687 479636a3 Iustin Pop
      return self.GetResults()
3688 479636a3 Iustin Pop
    else:
3689 23b4b983 Iustin Pop
      if not self.jobs:
3690 23b4b983 Iustin Pop
        self.SubmitPending()
3691 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3692 23b4b983 Iustin Pop
        if status:
3693 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3694 23b4b983 Iustin Pop
        else:
3695 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3696 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3697 acd19189 René Nussbaumer
3698 acd19189 René Nussbaumer
3699 4d99964c Bernardo Dal Seno
def FormatParamsDictInfo(param_dict, actual):
3700 4d99964c Bernardo Dal Seno
  """Formats a parameter dictionary.
3701 4d99964c Bernardo Dal Seno

3702 4d99964c Bernardo Dal Seno
  @type param_dict: dict
3703 4d99964c Bernardo Dal Seno
  @param param_dict: the own parameters
3704 4d99964c Bernardo Dal Seno
  @type actual: dict
3705 4d99964c Bernardo Dal Seno
  @param actual: the current parameter set (including defaults)
3706 4d99964c Bernardo Dal Seno
  @rtype: dict
3707 4d99964c Bernardo Dal Seno
  @return: dictionary where the value of each parameter is either a fully
3708 4d99964c Bernardo Dal Seno
      formatted string or a dictionary containing formatted strings
3709 4d99964c Bernardo Dal Seno

3710 4d99964c Bernardo Dal Seno
  """
3711 4d99964c Bernardo Dal Seno
  ret = {}
3712 4d99964c Bernardo Dal Seno
  for (key, data) in actual.items():
3713 4d99964c Bernardo Dal Seno
    if isinstance(data, dict) and data:
3714 4d99964c Bernardo Dal Seno
      ret[key] = FormatParamsDictInfo(param_dict.get(key, {}), data)
3715 4d99964c Bernardo Dal Seno
    else:
3716 4d99964c Bernardo Dal Seno
      ret[key] = str(param_dict.get(key, "default (%s)" % data))
3717 4d99964c Bernardo Dal Seno
  return ret
3718 4d99964c Bernardo Dal Seno
3719 4d99964c Bernardo Dal Seno
3720 d00884a2 Bernardo Dal Seno
def _FormatListInfoDefault(data, def_data):
3721 d00884a2 Bernardo Dal Seno
  if data is not None:
3722 d00884a2 Bernardo Dal Seno
    ret = utils.CommaJoin(data)
3723 d00884a2 Bernardo Dal Seno
  else:
3724 d00884a2 Bernardo Dal Seno
    ret = "default (%s)" % utils.CommaJoin(def_data)
3725 d00884a2 Bernardo Dal Seno
  return ret
3726 d00884a2 Bernardo Dal Seno
3727 d00884a2 Bernardo Dal Seno
3728 d00884a2 Bernardo Dal Seno
def FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster):
3729 d00884a2 Bernardo Dal Seno
  """Formats an instance policy.
3730 d00884a2 Bernardo Dal Seno

3731 d00884a2 Bernardo Dal Seno
  @type custom_ipolicy: dict
3732 d00884a2 Bernardo Dal Seno
  @param custom_ipolicy: own policy
3733 d00884a2 Bernardo Dal Seno
  @type eff_ipolicy: dict
3734 d00884a2 Bernardo Dal Seno
  @param eff_ipolicy: effective policy (including defaults); ignored for
3735 d00884a2 Bernardo Dal Seno
      cluster
3736 d00884a2 Bernardo Dal Seno
  @type iscluster: bool
3737 d00884a2 Bernardo Dal Seno
  @param iscluster: the policy is at cluster level
3738 d00884a2 Bernardo Dal Seno
  @rtype: list of pairs
3739 d00884a2 Bernardo Dal Seno
  @return: formatted data, suitable for L{PrintGenericInfo}
3740 d00884a2 Bernardo Dal Seno

3741 d00884a2 Bernardo Dal Seno
  """
3742 d00884a2 Bernardo Dal Seno
  if iscluster:
3743 d00884a2 Bernardo Dal Seno
    eff_ipolicy = custom_ipolicy
3744 d00884a2 Bernardo Dal Seno
3745 41044e04 Bernardo Dal Seno
  minmax_out = []
3746 41044e04 Bernardo Dal Seno
  custom_minmax = custom_ipolicy.get(constants.ISPECS_MINMAX)
3747 41044e04 Bernardo Dal Seno
  if custom_minmax:
3748 41044e04 Bernardo Dal Seno
    for (k, minmax) in enumerate(custom_minmax):
3749 41044e04 Bernardo Dal Seno
      minmax_out.append([
3750 41044e04 Bernardo Dal Seno
        ("%s/%s" % (key, k),
3751 41044e04 Bernardo Dal Seno
         FormatParamsDictInfo(minmax[key], minmax[key]))
3752 41044e04 Bernardo Dal Seno
        for key in constants.ISPECS_MINMAX_KEYS
3753 41044e04 Bernardo Dal Seno
        ])
3754 41044e04 Bernardo Dal Seno
  else:
3755 41044e04 Bernardo Dal Seno
    for (k, minmax) in enumerate(eff_ipolicy[constants.ISPECS_MINMAX]):
3756 41044e04 Bernardo Dal Seno
      minmax_out.append([
3757 41044e04 Bernardo Dal Seno
        ("%s/%s" % (key, k),
3758 41044e04 Bernardo Dal Seno
         FormatParamsDictInfo({}, minmax[key]))
3759 41044e04 Bernardo Dal Seno
        for key in constants.ISPECS_MINMAX_KEYS
3760 41044e04 Bernardo Dal Seno
        ])
3761 41044e04 Bernardo Dal Seno
  ret = [("bounds specs", minmax_out)]
3762 41044e04 Bernardo Dal Seno
3763 d00884a2 Bernardo Dal Seno
  if iscluster:
3764 d00884a2 Bernardo Dal Seno
    stdspecs = custom_ipolicy[constants.ISPECS_STD]
3765 d00884a2 Bernardo Dal Seno
    ret.append(
3766 d00884a2 Bernardo Dal Seno
      (constants.ISPECS_STD,
3767 d00884a2 Bernardo Dal Seno
       FormatParamsDictInfo(stdspecs, stdspecs))
3768 d00884a2 Bernardo Dal Seno
      )
3769 d00884a2 Bernardo Dal Seno
3770 d00884a2 Bernardo Dal Seno
  ret.append(
3771 9db0b351 Bernardo Dal Seno
    ("allowed disk templates",
3772 d00884a2 Bernardo Dal Seno
     _FormatListInfoDefault(custom_ipolicy.get(constants.IPOLICY_DTS),
3773 d00884a2 Bernardo Dal Seno
                            eff_ipolicy[constants.IPOLICY_DTS]))
3774 d00884a2 Bernardo Dal Seno
    )
3775 d00884a2 Bernardo Dal Seno
  ret.extend([
3776 d00884a2 Bernardo Dal Seno
    (key, str(custom_ipolicy.get(key, "default (%s)" % eff_ipolicy[key])))
3777 d00884a2 Bernardo Dal Seno
    for key in constants.IPOLICY_PARAMETERS
3778 d00884a2 Bernardo Dal Seno
    ])
3779 d00884a2 Bernardo Dal Seno
  return ret
3780 d00884a2 Bernardo Dal Seno
3781 d00884a2 Bernardo Dal Seno
3782 ea9d3b40 Bernardo Dal Seno
def _PrintSpecsParameters(buf, specs):
3783 ea9d3b40 Bernardo Dal Seno
  values = ("%s=%s" % (par, val) for (par, val) in sorted(specs.items()))
3784 ea9d3b40 Bernardo Dal Seno
  buf.write(",".join(values))
3785 ea9d3b40 Bernardo Dal Seno
3786 ea9d3b40 Bernardo Dal Seno
3787 ea9d3b40 Bernardo Dal Seno
def PrintIPolicyCommand(buf, ipolicy, isgroup):
3788 ea9d3b40 Bernardo Dal Seno
  """Print the command option used to generate the given instance policy.
3789 ea9d3b40 Bernardo Dal Seno

3790 ea9d3b40 Bernardo Dal Seno
  Currently only the parts dealing with specs are supported.
3791 ea9d3b40 Bernardo Dal Seno

3792 ea9d3b40 Bernardo Dal Seno
  @type buf: StringIO
3793 ea9d3b40 Bernardo Dal Seno
  @param buf: stream to write into
3794 ea9d3b40 Bernardo Dal Seno
  @type ipolicy: dict
3795 ea9d3b40 Bernardo Dal Seno
  @param ipolicy: instance policy
3796 ea9d3b40 Bernardo Dal Seno
  @type isgroup: bool
3797 ea9d3b40 Bernardo Dal Seno
  @param isgroup: whether the policy is at group level
3798 ea9d3b40 Bernardo Dal Seno

3799 ea9d3b40 Bernardo Dal Seno
  """
3800 ea9d3b40 Bernardo Dal Seno
  if not isgroup:
3801 ea9d3b40 Bernardo Dal Seno
    stdspecs = ipolicy.get("std")
3802 ea9d3b40 Bernardo Dal Seno
    if stdspecs:
3803 ea9d3b40 Bernardo Dal Seno
      buf.write(" %s " % IPOLICY_STD_SPECS_STR)
3804 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, stdspecs)
3805 ef99e3e8 Bernardo Dal Seno
  minmaxes = ipolicy.get("minmax", [])
3806 ef99e3e8 Bernardo Dal Seno
  first = True
3807 ef99e3e8 Bernardo Dal Seno
  for minmax in minmaxes:
3808 ef99e3e8 Bernardo Dal Seno
    minspecs = minmax.get("min")
3809 ef99e3e8 Bernardo Dal Seno
    maxspecs = minmax.get("max")
3810 ea9d3b40 Bernardo Dal Seno
    if minspecs and maxspecs:
3811 ef99e3e8 Bernardo Dal Seno
      if first:
3812 ef99e3e8 Bernardo Dal Seno
        buf.write(" %s " % IPOLICY_BOUNDS_SPECS_STR)
3813 ef99e3e8 Bernardo Dal Seno
        first = False
3814 ef99e3e8 Bernardo Dal Seno
      else:
3815 ef99e3e8 Bernardo Dal Seno
        buf.write("//")
3816 ea9d3b40 Bernardo Dal Seno
      buf.write("min:")
3817 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, minspecs)
3818 ea9d3b40 Bernardo Dal Seno
      buf.write("/max:")
3819 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, maxspecs)
3820 ea9d3b40 Bernardo Dal Seno
3821 ea9d3b40 Bernardo Dal Seno
3822 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3823 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3824 25bd815c René Nussbaumer

3825 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3826 25bd815c René Nussbaumer
  on a given list of list_type.
3827 25bd815c René Nussbaumer

3828 25bd815c René Nussbaumer
  @type names: list
3829 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3830 25bd815c René Nussbaumer
      we ask for confirmation
3831 25bd815c René Nussbaumer
  @type list_type: str
3832 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3833 25bd815c René Nussbaumer
  @type text: str
3834 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3835 25bd815c René Nussbaumer
  @rtype: boolean
3836 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3837 25bd815c René Nussbaumer

3838 25bd815c René Nussbaumer
  """
3839 25bd815c René Nussbaumer
  count = len(names)
3840 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3841 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3842 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3843 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3844 25bd815c René Nussbaumer
3845 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3846 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3847 25bd815c René Nussbaumer
3848 25bd815c René Nussbaumer
  if count > 20:
3849 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3850 25bd815c René Nussbaumer
    question = msg
3851 25bd815c René Nussbaumer
  else:
3852 25bd815c René Nussbaumer
    question = msg + affected
3853 25bd815c René Nussbaumer
3854 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3855 25bd815c René Nussbaumer
  if choice == "v":
3856 25bd815c René Nussbaumer
    choices.pop(1)
3857 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3858 25bd815c René Nussbaumer
  return choice
3859 703fa9ab Iustin Pop
3860 703fa9ab Iustin Pop
3861 cd415612 René Nussbaumer
def _MaybeParseUnit(elements):
3862 cd415612 René Nussbaumer
  """Parses and returns an array of potential values with units.
3863 cd415612 René Nussbaumer

3864 cd415612 René Nussbaumer
  """
3865 ef40c537 René Nussbaumer
  parsed = {}
3866 ef40c537 René Nussbaumer
  for k, v in elements.items():
3867 ef40c537 René Nussbaumer
    if v == constants.VALUE_DEFAULT:
3868 ef40c537 René Nussbaumer
      parsed[k] = v
3869 cd415612 René Nussbaumer
    else:
3870 ef40c537 René Nussbaumer
      parsed[k] = utils.ParseUnit(v)
3871 cd415612 René Nussbaumer
  return parsed
3872 cd415612 René Nussbaumer
3873 cd415612 René Nussbaumer
3874 d2d3935a Bernardo Dal Seno
def _InitISpecsFromSplitOpts(ipolicy, ispecs_mem_size, ispecs_cpu_count,
3875 d2d3935a Bernardo Dal Seno
                             ispecs_disk_count, ispecs_disk_size,
3876 919db916 Bernardo Dal Seno
                             ispecs_nic_count, group_ipolicy, fill_all):
3877 d67e0a94 Iustin Pop
  try:
3878 d67e0a94 Iustin Pop
    if ispecs_mem_size:
3879 cd415612 René Nussbaumer
      ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
3880 d67e0a94 Iustin Pop
    if ispecs_disk_size:
3881 cd415612 René Nussbaumer
      ispecs_disk_size = _MaybeParseUnit(ispecs_disk_size)
3882 d67e0a94 Iustin Pop
  except (TypeError, ValueError, errors.UnitParseError), err:
3883 d67e0a94 Iustin Pop
    raise errors.OpPrereqError("Invalid disk (%s) or memory (%s) size"
3884 d67e0a94 Iustin Pop
                               " in policy: %s" %
3885 d67e0a94 Iustin Pop
                               (ispecs_disk_size, ispecs_mem_size, err),
3886 d67e0a94 Iustin Pop
                               errors.ECODE_INVAL)
3887 d67e0a94 Iustin Pop
3888 703fa9ab Iustin Pop
  # prepare ipolicy dict
3889 d948c101 Bernardo Dal Seno
  ispecs_transposed = {
3890 703fa9ab Iustin Pop
    constants.ISPEC_MEM_SIZE: ispecs_mem_size,
3891 703fa9ab Iustin Pop
    constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
3892 703fa9ab Iustin Pop
    constants.ISPEC_DISK_COUNT: ispecs_disk_count,
3893 703fa9ab Iustin Pop
    constants.ISPEC_DISK_SIZE: ispecs_disk_size,
3894 703fa9ab Iustin Pop
    constants.ISPEC_NIC_COUNT: ispecs_nic_count,
3895 703fa9ab Iustin Pop
    }
3896 703fa9ab Iustin Pop
3897 703fa9ab Iustin Pop
  # first, check that the values given are correct
3898 703fa9ab Iustin Pop
  if group_ipolicy:
3899 703fa9ab Iustin Pop
    forced_type = TISPECS_GROUP_TYPES
3900 703fa9ab Iustin Pop
  else:
3901 703fa9ab Iustin Pop
    forced_type = TISPECS_CLUSTER_TYPES
3902 d948c101 Bernardo Dal Seno
  for specs in ispecs_transposed.values():
3903 d2d3935a Bernardo Dal Seno
    assert type(specs) is dict
3904 919db916 Bernardo Dal Seno
    utils.ForceDictType(specs, forced_type)
3905 703fa9ab Iustin Pop
3906 703fa9ab Iustin Pop
  # then transpose
3907 da5f09ef Bernardo Dal Seno
  ispecs = {
3908 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MIN: {},
3909 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MAX: {},
3910 da5f09ef Bernardo Dal Seno
    constants.ISPECS_STD: {},
3911 da5f09ef Bernardo Dal Seno
    }
3912 d948c101 Bernardo Dal Seno
  for (name, specs) in ispecs_transposed.iteritems():
3913 703fa9ab Iustin Pop
    assert name in constants.ISPECS_PARAMETERS
3914 703fa9ab Iustin Pop
    for key, val in specs.items(): # {min: .. ,max: .., std: ..}
3915 da5f09ef Bernardo Dal Seno
      assert key in ispecs
3916 da5f09ef Bernardo Dal Seno
      ispecs[key][name] = val
3917 41044e04 Bernardo Dal Seno
  minmax_out = {}
3918 da5f09ef Bernardo Dal Seno
  for key in constants.ISPECS_MINMAX_KEYS:
3919 919db916 Bernardo Dal Seno
    if fill_all:
3920 41044e04 Bernardo Dal Seno
      minmax_out[key] = \
3921 919db916 Bernardo Dal Seno
        objects.FillDict(constants.ISPECS_MINMAX_DEFAULTS[key], ispecs[key])
3922 919db916 Bernardo Dal Seno
    else:
3923 41044e04 Bernardo Dal Seno
      minmax_out[key] = ispecs[key]
3924 41044e04 Bernardo Dal Seno
  ipolicy[constants.ISPECS_MINMAX] = [minmax_out]
3925 919db916 Bernardo Dal Seno
  if fill_all:
3926 919db916 Bernardo Dal Seno
    ipolicy[constants.ISPECS_STD] = \
3927 919db916 Bernardo Dal Seno
        objects.FillDict(constants.IPOLICY_DEFAULTS[constants.ISPECS_STD],
3928 919db916 Bernardo Dal Seno
                         ispecs[constants.ISPECS_STD])
3929 919db916 Bernardo Dal Seno
  else:
3930 919db916 Bernardo Dal Seno
    ipolicy[constants.ISPECS_STD] = ispecs[constants.ISPECS_STD]
3931 d948c101 Bernardo Dal Seno
3932 d948c101 Bernardo Dal Seno
3933 d2d3935a Bernardo Dal Seno
def _ParseSpecUnit(spec, keyname):
3934 d2d3935a Bernardo Dal Seno
  ret = spec.copy()
3935 d2d3935a Bernardo Dal Seno
  for k in [constants.ISPEC_DISK_SIZE, constants.ISPEC_MEM_SIZE]:
3936 919db916 Bernardo Dal Seno
    if k in ret:
3937 d2d3935a Bernardo Dal Seno
      try:
3938 d2d3935a Bernardo Dal Seno
        ret[k] = utils.ParseUnit(ret[k])
3939 d2d3935a Bernardo Dal Seno
      except (TypeError, ValueError, errors.UnitParseError), err:
3940 d2d3935a Bernardo Dal Seno
        raise errors.OpPrereqError(("Invalid parameter %s (%s) in %s instance"
3941 d2d3935a Bernardo Dal Seno
                                    " specs: %s" % (k, ret[k], keyname, err)),
3942 d2d3935a Bernardo Dal Seno
                                   errors.ECODE_INVAL)
3943 d2d3935a Bernardo Dal Seno
  return ret
3944 d2d3935a Bernardo Dal Seno
3945 d2d3935a Bernardo Dal Seno
3946 919db916 Bernardo Dal Seno
def _ParseISpec(spec, keyname, required):
3947 d2d3935a Bernardo Dal Seno
  ret = _ParseSpecUnit(spec, keyname)
3948 919db916 Bernardo Dal Seno
  utils.ForceDictType(ret, constants.ISPECS_PARAMETER_TYPES)
3949 919db916 Bernardo Dal Seno
  missing = constants.ISPECS_PARAMETERS - frozenset(ret.keys())
3950 919db916 Bernardo Dal Seno
  if required and missing:
3951 919db916 Bernardo Dal Seno
    raise errors.OpPrereqError("Missing parameters in ipolicy spec %s: %s" %
3952 919db916 Bernardo Dal Seno
                               (keyname, utils.CommaJoin(missing)),
3953 919db916 Bernardo Dal Seno
                               errors.ECODE_INVAL)
3954 919db916 Bernardo Dal Seno
  return ret
3955 919db916 Bernardo Dal Seno
3956 919db916 Bernardo Dal Seno
3957 919db916 Bernardo Dal Seno
def _GetISpecsInAllowedValues(minmax_ispecs, allowed_values):
3958 919db916 Bernardo Dal Seno
  ret = None
3959 ef99e3e8 Bernardo Dal Seno
  if (minmax_ispecs and allowed_values and len(minmax_ispecs) == 1 and
3960 ef99e3e8 Bernardo Dal Seno
      len(minmax_ispecs[0]) == 1):
3961 ef99e3e8 Bernardo Dal Seno
    for (key, spec) in minmax_ispecs[0].items():
3962 919db916 Bernardo Dal Seno
      # This loop is executed exactly once
3963 919db916 Bernardo Dal Seno
      if key in allowed_values and not spec:
3964 919db916 Bernardo Dal Seno
        ret = key
3965 d2d3935a Bernardo Dal Seno
  return ret
3966 d2d3935a Bernardo Dal Seno
3967 d2d3935a Bernardo Dal Seno
3968 d2d3935a Bernardo Dal Seno
def _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
3969 d2d3935a Bernardo Dal Seno
                            group_ipolicy, allowed_values):
3970 919db916 Bernardo Dal Seno
  found_allowed = _GetISpecsInAllowedValues(minmax_ispecs, allowed_values)
3971 919db916 Bernardo Dal Seno
  if found_allowed is not None:
3972 919db916 Bernardo Dal Seno
    ipolicy_out[constants.ISPECS_MINMAX] = found_allowed
3973 919db916 Bernardo Dal Seno
  elif minmax_ispecs is not None:
3974 ef99e3e8 Bernardo Dal Seno
    minmax_out = []
3975 ef99e3e8 Bernardo Dal Seno
    for mmpair in minmax_ispecs:
3976 ef99e3e8 Bernardo Dal Seno
      mmpair_out = {}
3977 ef99e3e8 Bernardo Dal Seno
      for (key, spec) in mmpair.items():
3978 ef99e3e8 Bernardo Dal Seno
        if key not in constants.ISPECS_MINMAX_KEYS:
3979 ef99e3e8 Bernardo Dal Seno
          msg = "Invalid key in bounds instance specifications: %s" % key
3980 ef99e3e8 Bernardo Dal Seno
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
3981 ef99e3e8 Bernardo Dal Seno
        mmpair_out[key] = _ParseISpec(spec, key, True)
3982 ef99e3e8 Bernardo Dal Seno
      minmax_out.append(mmpair_out)
3983 ef99e3e8 Bernardo Dal Seno
    ipolicy_out[constants.ISPECS_MINMAX] = minmax_out
3984 d2d3935a Bernardo Dal Seno
  if std_ispecs is not None:
3985 d2d3935a Bernardo Dal Seno
    assert not group_ipolicy # This is not an option for gnt-group
3986 919db916 Bernardo Dal Seno
    ipolicy_out[constants.ISPECS_STD] = _ParseISpec(std_ispecs, "std", False)
3987 d2d3935a Bernardo Dal Seno
3988 d2d3935a Bernardo Dal Seno
3989 d948c101 Bernardo Dal Seno
def CreateIPolicyFromOpts(ispecs_mem_size=None,
3990 d948c101 Bernardo Dal Seno
                          ispecs_cpu_count=None,
3991 d948c101 Bernardo Dal Seno
                          ispecs_disk_count=None,
3992 d948c101 Bernardo Dal Seno
                          ispecs_disk_size=None,
3993 d948c101 Bernardo Dal Seno
                          ispecs_nic_count=None,
3994 d2d3935a Bernardo Dal Seno
                          minmax_ispecs=None,
3995 d2d3935a Bernardo Dal Seno
                          std_ispecs=None,
3996 d948c101 Bernardo Dal Seno
                          ipolicy_disk_templates=None,
3997 d948c101 Bernardo Dal Seno
                          ipolicy_vcpu_ratio=None,
3998 d948c101 Bernardo Dal Seno
                          ipolicy_spindle_ratio=None,
3999 d948c101 Bernardo Dal Seno
                          group_ipolicy=False,
4000 d948c101 Bernardo Dal Seno
                          allowed_values=None,
4001 d948c101 Bernardo Dal Seno
                          fill_all=False):
4002 d948c101 Bernardo Dal Seno
  """Creation of instance policy based on command line options.
4003 d948c101 Bernardo Dal Seno

4004 d948c101 Bernardo Dal Seno
  @param fill_all: whether for cluster policies we should ensure that
4005 d948c101 Bernardo Dal Seno
    all values are filled
4006 d948c101 Bernardo Dal Seno

4007 d948c101 Bernardo Dal Seno
  """
4008 919db916 Bernardo Dal Seno
  assert not (fill_all and allowed_values)
4009 919db916 Bernardo Dal Seno
4010 919db916 Bernardo Dal Seno
  split_specs = (ispecs_mem_size or ispecs_cpu_count or ispecs_disk_count or
4011 919db916 Bernardo Dal Seno
                 ispecs_disk_size or ispecs_nic_count)
4012 919db916 Bernardo Dal Seno
  if (split_specs and (minmax_ispecs is not None or std_ispecs is not None)):
4013 d2d3935a Bernardo Dal Seno
    raise errors.OpPrereqError("A --specs-xxx option cannot be specified"
4014 d2d3935a Bernardo Dal Seno
                               " together with any --ipolicy-xxx-specs option",
4015 d2d3935a Bernardo Dal Seno
                               errors.ECODE_INVAL)
4016 d948c101 Bernardo Dal Seno
4017 d948c101 Bernardo Dal Seno
  ipolicy_out = objects.MakeEmptyIPolicy()
4018 919db916 Bernardo Dal Seno
  if split_specs:
4019 919db916 Bernardo Dal Seno
    assert fill_all
4020 d2d3935a Bernardo Dal Seno
    _InitISpecsFromSplitOpts(ipolicy_out, ispecs_mem_size, ispecs_cpu_count,
4021 d2d3935a Bernardo Dal Seno
                             ispecs_disk_count, ispecs_disk_size,
4022 919db916 Bernardo Dal Seno
                             ispecs_nic_count, group_ipolicy, fill_all)
4023 919db916 Bernardo Dal Seno
  elif (minmax_ispecs is not None or std_ispecs is not None):
4024 d2d3935a Bernardo Dal Seno
    _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
4025 d2d3935a Bernardo Dal Seno
                            group_ipolicy, allowed_values)
4026 703fa9ab Iustin Pop
4027 703fa9ab Iustin Pop
  if ipolicy_disk_templates is not None:
4028 f824ae42 Bernardo Dal Seno
    if allowed_values and ipolicy_disk_templates in allowed_values:
4029 f824ae42 Bernardo Dal Seno
      ipolicy_out[constants.IPOLICY_DTS] = ipolicy_disk_templates
4030 f824ae42 Bernardo Dal Seno
    else:
4031 f824ae42 Bernardo Dal Seno
      ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
4032 703fa9ab Iustin Pop
  if ipolicy_vcpu_ratio is not None:
4033 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
4034 ad5cc6bd René Nussbaumer
  if ipolicy_spindle_ratio is not None:
4035 ad5cc6bd René Nussbaumer
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
4036 703fa9ab Iustin Pop
4037 703fa9ab Iustin Pop
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
4038 703fa9ab Iustin Pop
4039 eeaa5f6c Bernardo Dal Seno
  if not group_ipolicy and fill_all:
4040 eeaa5f6c Bernardo Dal Seno
    ipolicy_out = objects.FillIPolicy(constants.IPOLICY_DEFAULTS, ipolicy_out)
4041 eeaa5f6c Bernardo Dal Seno
4042 703fa9ab Iustin Pop
  return ipolicy_out
4043 4d99964c Bernardo Dal Seno
4044 4d99964c Bernardo Dal Seno
4045 4d99964c Bernardo Dal Seno
def _SerializeGenericInfo(buf, data, level, afterkey=False):
4046 4d99964c Bernardo Dal Seno
  """Formatting core of L{PrintGenericInfo}.
4047 4d99964c Bernardo Dal Seno

4048 4d99964c Bernardo Dal Seno
  @param buf: (string) stream to accumulate the result into
4049 4d99964c Bernardo Dal Seno
  @param data: data to format
4050 4d99964c Bernardo Dal Seno
  @type level: int
4051 4d99964c Bernardo Dal Seno
  @param level: depth in the data hierarchy, used for indenting
4052 4d99964c Bernardo Dal Seno
  @type afterkey: bool
4053 4d99964c Bernardo Dal Seno
  @param afterkey: True when we are in the middle of a line after a key (used
4054 4d99964c Bernardo Dal Seno
      to properly add newlines or indentation)
4055 4d99964c Bernardo Dal Seno

4056 4d99964c Bernardo Dal Seno
  """
4057 4d99964c Bernardo Dal Seno
  baseind = "  "
4058 4d99964c Bernardo Dal Seno
  if isinstance(data, dict):
4059 4d99964c Bernardo Dal Seno
    if not data:
4060 4d99964c Bernardo Dal Seno
      buf.write("\n")
4061 4d99964c Bernardo Dal Seno
    else:
4062 4d99964c Bernardo Dal Seno
      if afterkey:
4063 4d99964c Bernardo Dal Seno
        buf.write("\n")
4064 4d99964c Bernardo Dal Seno
        doindent = True
4065 4d99964c Bernardo Dal Seno
      else:
4066 4d99964c Bernardo Dal Seno
        doindent = False
4067 4d99964c Bernardo Dal Seno
      for key in sorted(data):
4068 4d99964c Bernardo Dal Seno
        if doindent:
4069 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
4070 4d99964c Bernardo Dal Seno
        else:
4071 4d99964c Bernardo Dal Seno
          doindent = True
4072 4d99964c Bernardo Dal Seno
        buf.write(key)
4073 4d99964c Bernardo Dal Seno
        buf.write(": ")
4074 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, data[key], level + 1, afterkey=True)
4075 4d99964c Bernardo Dal Seno
  elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], tuple):
4076 4d99964c Bernardo Dal Seno
    # list of tuples (an ordered dictionary)
4077 4d99964c Bernardo Dal Seno
    if afterkey:
4078 4d99964c Bernardo Dal Seno
      buf.write("\n")
4079 4d99964c Bernardo Dal Seno
      doindent = True
4080 4d99964c Bernardo Dal Seno
    else:
4081 4d99964c Bernardo Dal Seno
      doindent = False
4082 4d99964c Bernardo Dal Seno
    for (key, val) in data:
4083 4d99964c Bernardo Dal Seno
      if doindent:
4084 4d99964c Bernardo Dal Seno
        buf.write(baseind * level)
4085 4d99964c Bernardo Dal Seno
      else:
4086 4d99964c Bernardo Dal Seno
        doindent = True
4087 4d99964c Bernardo Dal Seno
      buf.write(key)
4088 4d99964c Bernardo Dal Seno
      buf.write(": ")
4089 4d99964c Bernardo Dal Seno
      _SerializeGenericInfo(buf, val, level + 1, afterkey=True)
4090 4d99964c Bernardo Dal Seno
  elif isinstance(data, list):
4091 4d99964c Bernardo Dal Seno
    if not data:
4092 4d99964c Bernardo Dal Seno
      buf.write("\n")
4093 4d99964c Bernardo Dal Seno
    else:
4094 4d99964c Bernardo Dal Seno
      if afterkey:
4095 4d99964c Bernardo Dal Seno
        buf.write("\n")
4096 4d99964c Bernardo Dal Seno
        doindent = True
4097 4d99964c Bernardo Dal Seno
      else:
4098 4d99964c Bernardo Dal Seno
        doindent = False
4099 4d99964c Bernardo Dal Seno
      for item in data:
4100 4d99964c Bernardo Dal Seno
        if doindent:
4101 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
4102 4d99964c Bernardo Dal Seno
        else:
4103 4d99964c Bernardo Dal Seno
          doindent = True
4104 4d99964c Bernardo Dal Seno
        buf.write("-")
4105 4d99964c Bernardo Dal Seno
        buf.write(baseind[1:])
4106 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, item, level + 1)
4107 4d99964c Bernardo Dal Seno
  else:
4108 4d99964c Bernardo Dal Seno
    # This branch should be only taken for strings, but it's practically
4109 4d99964c Bernardo Dal Seno
    # impossible to guarantee that no other types are produced somewhere
4110 4d99964c Bernardo Dal Seno
    buf.write(str(data))
4111 4d99964c Bernardo Dal Seno
    buf.write("\n")
4112 4d99964c Bernardo Dal Seno
4113 4d99964c Bernardo Dal Seno
4114 4d99964c Bernardo Dal Seno
def PrintGenericInfo(data):
4115 4d99964c Bernardo Dal Seno
  """Print information formatted according to the hierarchy.
4116 4d99964c Bernardo Dal Seno

4117 4d99964c Bernardo Dal Seno
  The output is a valid YAML string.
4118 4d99964c Bernardo Dal Seno

4119 4d99964c Bernardo Dal Seno
  @param data: the data to print. It's a hierarchical structure whose elements
4120 4d99964c Bernardo Dal Seno
      can be:
4121 4d99964c Bernardo Dal Seno
        - dictionaries, where keys are strings and values are of any of the
4122 4d99964c Bernardo Dal Seno
          types listed here
4123 4d99964c Bernardo Dal Seno
        - lists of pairs (key, value), where key is a string and value is of
4124 4d99964c Bernardo Dal Seno
          any of the types listed here; it's a way to encode ordered
4125 4d99964c Bernardo Dal Seno
          dictionaries
4126 4d99964c Bernardo Dal Seno
        - lists of any of the types listed here
4127 4d99964c Bernardo Dal Seno
        - strings
4128 4d99964c Bernardo Dal Seno

4129 4d99964c Bernardo Dal Seno
  """
4130 4d99964c Bernardo Dal Seno
  buf = StringIO()
4131 4d99964c Bernardo Dal Seno
  _SerializeGenericInfo(buf, data, 0)
4132 4d99964c Bernardo Dal Seno
  ToStdout(buf.getvalue().rstrip("\n"))