Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 89c10241

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

359 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
360 863d7f46 Michael Hanselmann

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

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

378 863d7f46 Michael Hanselmann
  """
379 863d7f46 Michael Hanselmann
380 863d7f46 Michael Hanselmann
381 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
382 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
383 863d7f46 Michael Hanselmann

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

390 863d7f46 Michael Hanselmann
  """
391 863d7f46 Michael Hanselmann
392 863d7f46 Michael Hanselmann
393 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
394 863d7f46 Michael Hanselmann
  """Node argument.
395 863d7f46 Michael Hanselmann

396 863d7f46 Michael Hanselmann
  """
397 863d7f46 Michael Hanselmann
398 667dbd6b Adeodato Simo
399 9c784fb3 Dimitris Aragiorgis
class ArgNetwork(_Argument):
400 9c784fb3 Dimitris Aragiorgis
  """Network argument.
401 9c784fb3 Dimitris Aragiorgis

402 9c784fb3 Dimitris Aragiorgis
  """
403 9c784fb3 Dimitris Aragiorgis
404 3c286190 Dimitris Aragiorgis
405 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
406 667dbd6b Adeodato Simo
  """Node group argument.
407 667dbd6b Adeodato Simo

408 667dbd6b Adeodato Simo
  """
409 667dbd6b Adeodato Simo
410 667dbd6b Adeodato Simo
411 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
412 863d7f46 Michael Hanselmann
  """Job ID argument.
413 863d7f46 Michael Hanselmann

414 863d7f46 Michael Hanselmann
  """
415 863d7f46 Michael Hanselmann
416 863d7f46 Michael Hanselmann
417 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
418 863d7f46 Michael Hanselmann
  """File path argument.
419 863d7f46 Michael Hanselmann

420 863d7f46 Michael Hanselmann
  """
421 863d7f46 Michael Hanselmann
422 863d7f46 Michael Hanselmann
423 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
424 863d7f46 Michael Hanselmann
  """Command argument.
425 863d7f46 Michael Hanselmann

426 863d7f46 Michael Hanselmann
  """
427 863d7f46 Michael Hanselmann
428 863d7f46 Michael Hanselmann
429 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
430 83ec7961 Michael Hanselmann
  """Host argument.
431 83ec7961 Michael Hanselmann

432 83ec7961 Michael Hanselmann
  """
433 83ec7961 Michael Hanselmann
434 83ec7961 Michael Hanselmann
435 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
436 f9faf9c3 René Nussbaumer
  """OS argument.
437 f9faf9c3 René Nussbaumer

438 f9faf9c3 René Nussbaumer
  """
439 f9faf9c3 René Nussbaumer
440 f9faf9c3 René Nussbaumer
441 b954f097 Constantinos Venetsanopoulos
class ArgExtStorage(_Argument):
442 b954f097 Constantinos Venetsanopoulos
  """ExtStorage argument.
443 b954f097 Constantinos Venetsanopoulos

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

463 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
464 846baef9 Iustin Pop

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

488 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
489 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
490 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
491 810c50b7 Iustin Pop

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

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

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

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

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

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

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

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

579 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
580 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
581 726ae450 Bernardo Dal Seno
  will have the value=False and the prefix stripped, keys with the prefix
582 726ae450 Bernardo Dal Seno
  "-" will have value=None and the prefix stripped, and the others will
583 a8469393 Iustin Pop
  have value=True.
584 a8469393 Iustin Pop

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

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

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

633 a8469393 Iustin Pop
  """
634 a8469393 Iustin Pop
  if ":" not in value:
635 d0c8c01d Iustin Pop
    ident, rest = value, ""
636 a8469393 Iustin Pop
  else:
637 a8469393 Iustin Pop
    ident, rest = value.split(":", 1)
638 8b46606c Guido Trotter
639 726ae450 Bernardo Dal Seno
  if parse_prefixes and ident.startswith(NO_PREFIX):
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(NO_PREFIX):], False)
644 726ae450 Bernardo Dal Seno
  elif (parse_prefixes and ident.startswith(UN_PREFIX) and
645 726ae450 Bernardo Dal Seno
        (len(ident) <= len(UN_PREFIX) or not ident[len(UN_PREFIX)].isdigit())):
646 8b46606c Guido Trotter
    if rest:
647 8b46606c Guido Trotter
      msg = "Cannot pass options when removing parameter groups: %s" % value
648 8b46606c Guido Trotter
      raise errors.ParameterError(msg)
649 8b46606c Guido Trotter
    retval = (ident[len(UN_PREFIX):], None)
650 8b46606c Guido Trotter
  else:
651 726ae450 Bernardo Dal Seno
    kv_dict = _SplitKeyVal(opt, rest, parse_prefixes)
652 a8469393 Iustin Pop
    retval = (ident, kv_dict)
653 a8469393 Iustin Pop
  return retval
654 a8469393 Iustin Pop
655 a8469393 Iustin Pop
656 726ae450 Bernardo Dal Seno
def check_ident_key_val(option, opt, value):  # pylint: disable=W0613
657 726ae450 Bernardo Dal Seno
  """Custom parser for ident:key=val,key=val options.
658 726ae450 Bernardo Dal Seno

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

662 726ae450 Bernardo Dal Seno
  """
663 726ae450 Bernardo Dal Seno
  return _SplitIdentKeyVal(opt, value, True)
664 726ae450 Bernardo Dal Seno
665 726ae450 Bernardo Dal Seno
666 b459a848 Andrea Spadaccini
def check_key_val(option, opt, value):  # pylint: disable=W0613
667 552c8dff Michael Hanselmann
  """Custom parser class for key=val,key=val options.
668 552c8dff Michael Hanselmann

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

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

692 726ae450 Bernardo Dal Seno
  @rtype: list of dictionary
693 ef99e3e8 Bernardo Dal Seno
  @return: [{ident: {key: val, key: val}, ident: {key: val}}, {ident:..}]
694 726ae450 Bernardo Dal Seno

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

705 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
706 e7b61bb0 Iustin Pop

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

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

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

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

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

1714 d971402f Michael Hanselmann
  """
1715 d971402f Michael Hanselmann
  def __init__(self, exit_error):
1716 d971402f Michael Hanselmann
    """Initializes instances of this class.
1717 d971402f Michael Hanselmann

1718 d971402f Michael Hanselmann
    @type exit_error: bool
1719 d971402f Michael Hanselmann
    @param exit_error: Whether to report failure on exit
1720 d971402f Michael Hanselmann

1721 d971402f Michael Hanselmann
    """
1722 d971402f Michael Hanselmann
    Exception.__init__(self)
1723 d971402f Michael Hanselmann
    self.exit_error = exit_error
1724 d971402f Michael Hanselmann
1725 d971402f Michael Hanselmann
1726 d971402f Michael Hanselmann
class _ShowVersion(Exception):
1727 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1728 d971402f Michael Hanselmann

1729 d971402f Michael Hanselmann
  """
1730 d971402f Michael Hanselmann
1731 d971402f Michael Hanselmann
1732 d971402f Michael Hanselmann
def _ParseArgs(binary, argv, commands, aliases, env_override):
1733 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1734 a8083063 Iustin Pop

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

1738 d971402f Michael Hanselmann
  @param binary: Script name
1739 d971402f Michael Hanselmann
  @param argv: Command line arguments
1740 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1741 d971402f Michael Hanselmann
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1742 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1743 d971402f Michael Hanselmann
  @raise _ShowUsage: If usage description should be shown
1744 d971402f Michael Hanselmann
  @raise _ShowVersion: If version should be shown
1745 098c0958 Michael Hanselmann

1746 a8083063 Iustin Pop
  """
1747 ef9fa5b9 René Nussbaumer
  assert not (env_override - set(commands))
1748 d971402f Michael Hanselmann
  assert not (set(aliases.keys()) & set(commands.keys()))
1749 ef9fa5b9 René Nussbaumer
1750 d971402f Michael Hanselmann
  if len(argv) > 1:
1751 d971402f Michael Hanselmann
    cmd = argv[1]
1752 a8083063 Iustin Pop
  else:
1753 d971402f Michael Hanselmann
    # No option or command given
1754 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1755 a8083063 Iustin Pop
1756 d971402f Michael Hanselmann
  if cmd == "--version":
1757 d971402f Michael Hanselmann
    raise _ShowVersion()
1758 d971402f Michael Hanselmann
  elif cmd == "--help":
1759 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=False)
1760 d971402f Michael Hanselmann
  elif not (cmd in commands or cmd in aliases):
1761 d971402f Michael Hanselmann
    raise _ShowUsage(exit_error=True)
1762 de47cf8f Guido Trotter
1763 de47cf8f Guido Trotter
  # get command, unalias it, and look it up in commands
1764 de47cf8f Guido Trotter
  if cmd in aliases:
1765 de47cf8f Guido Trotter
    if aliases[cmd] not in commands:
1766 de47cf8f Guido Trotter
      raise errors.ProgrammerError("Alias '%s' maps to non-existing"
1767 de47cf8f Guido Trotter
                                   " command '%s'" % (cmd, aliases[cmd]))
1768 de47cf8f Guido Trotter
1769 de47cf8f Guido Trotter
    cmd = aliases[cmd]
1770 de47cf8f Guido Trotter
1771 ef9fa5b9 René Nussbaumer
  if cmd in env_override:
1772 ef9fa5b9 René Nussbaumer
    args_env_name = ("%s_%s" % (binary.replace("-", "_"), cmd)).upper()
1773 ef9fa5b9 René Nussbaumer
    env_args = os.environ.get(args_env_name)
1774 ef9fa5b9 René Nussbaumer
    if env_args:
1775 d971402f Michael Hanselmann
      argv = utils.InsertAtPos(argv, 2, shlex.split(env_args))
1776 ef9fa5b9 René Nussbaumer
1777 a8005e17 Michael Hanselmann
  func, args_def, parser_opts, usage, description = commands[cmd]
1778 bf5338b3 Michael Hanselmann
  parser = OptionParser(option_list=parser_opts + COMMON_OPTS,
1779 bf5338b3 Michael Hanselmann
                        description=description,
1780 bf5338b3 Michael Hanselmann
                        formatter=TitledHelpFormatter(),
1781 bf5338b3 Michael Hanselmann
                        usage="%%prog %s %s" % (cmd, usage))
1782 a8083063 Iustin Pop
  parser.disable_interspersed_args()
1783 d971402f Michael Hanselmann
  options, args = parser.parse_args(args=argv[2:])
1784 a8005e17 Michael Hanselmann
1785 a8005e17 Michael Hanselmann
  if not _CheckArguments(cmd, args_def, args):
1786 a8083063 Iustin Pop
    return None, None, None
1787 a8083063 Iustin Pop
1788 a8083063 Iustin Pop
  return func, options, args
1789 a8083063 Iustin Pop
1790 a8083063 Iustin Pop
1791 d971402f Michael Hanselmann
def _FormatUsage(binary, commands):
1792 d971402f Michael Hanselmann
  """Generates a nice description of all commands.
1793 d971402f Michael Hanselmann

1794 d971402f Michael Hanselmann
  @param binary: Script name
1795 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1796 d971402f Michael Hanselmann

1797 d971402f Michael Hanselmann
  """
1798 d971402f Michael Hanselmann
  # compute the max line length for cmd + usage
1799 d971402f Michael Hanselmann
  mlen = min(60, max(map(len, commands)))
1800 d971402f Michael Hanselmann
1801 d971402f Michael Hanselmann
  yield "Usage: %s {command} [options...] [argument...]" % binary
1802 d971402f Michael Hanselmann
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1803 d971402f Michael Hanselmann
  yield ""
1804 d971402f Michael Hanselmann
  yield "Commands:"
1805 d971402f Michael Hanselmann
1806 d971402f Michael Hanselmann
  # and format a nice command list
1807 d971402f Michael Hanselmann
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1808 d971402f Michael Hanselmann
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1809 d971402f Michael Hanselmann
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1810 d971402f Michael Hanselmann
    for line in help_lines:
1811 d971402f Michael Hanselmann
      yield " %-*s   %s" % (mlen, "", line)
1812 d971402f Michael Hanselmann
1813 d971402f Michael Hanselmann
  yield ""
1814 d971402f Michael Hanselmann
1815 d971402f Michael Hanselmann
1816 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1817 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1818 a8005e17 Michael Hanselmann

1819 a8005e17 Michael Hanselmann
  Algorithm:
1820 a8005e17 Michael Hanselmann

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

1823 a8005e17 Michael Hanselmann
    1. For each argument in definition
1824 a8005e17 Michael Hanselmann

1825 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1826 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1827 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1828 a8005e17 Michael Hanselmann

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

1831 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1832 a8005e17 Michael Hanselmann

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

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

1837 a8005e17 Michael Hanselmann
  """
1838 a8005e17 Michael Hanselmann
  if args and not args_def:
1839 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1840 a8005e17 Michael Hanselmann
    return False
1841 a8005e17 Michael Hanselmann
1842 a8005e17 Michael Hanselmann
  min_count = None
1843 a8005e17 Michael Hanselmann
  max_count = None
1844 a8005e17 Michael Hanselmann
  check_max = None
1845 a8005e17 Michael Hanselmann
1846 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1847 a8005e17 Michael Hanselmann
1848 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1849 a8005e17 Michael Hanselmann
    if min_count is None:
1850 a8005e17 Michael Hanselmann
      min_count = arg.min
1851 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1852 a8005e17 Michael Hanselmann
      min_count += arg.min
1853 a8005e17 Michael Hanselmann
1854 a8005e17 Michael Hanselmann
    if max_count is None:
1855 a8005e17 Michael Hanselmann
      max_count = arg.max
1856 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1857 a8005e17 Michael Hanselmann
      max_count += arg.max
1858 a8005e17 Michael Hanselmann
1859 a8005e17 Michael Hanselmann
    if idx == last_idx:
1860 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1861 a8005e17 Michael Hanselmann
1862 a8005e17 Michael Hanselmann
    elif arg.max is None:
1863 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1864 a8005e17 Michael Hanselmann
1865 a8005e17 Michael Hanselmann
  if check_max:
1866 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1867 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1868 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1869 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1870 a8005e17 Michael Hanselmann
      return False
1871 a8005e17 Michael Hanselmann
1872 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1873 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1874 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1875 a8005e17 Michael Hanselmann
               cmd, max_count)
1876 a8005e17 Michael Hanselmann
      return False
1877 a8005e17 Michael Hanselmann
1878 a8005e17 Michael Hanselmann
  # Command with some required arguments
1879 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1880 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1881 a8005e17 Michael Hanselmann
             cmd, min_count)
1882 a8005e17 Michael Hanselmann
    return False
1883 a8005e17 Michael Hanselmann
1884 a8005e17 Michael Hanselmann
  return True
1885 a8005e17 Michael Hanselmann
1886 a8005e17 Michael Hanselmann
1887 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1888 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1889 60d49723 Michael Hanselmann

1890 60d49723 Michael Hanselmann
  """
1891 d0c8c01d Iustin Pop
  if value and ":" in value:
1892 d0c8c01d Iustin Pop
    return value.split(":", 1)
1893 60d49723 Michael Hanselmann
  else:
1894 60d49723 Michael Hanselmann
    return (value, None)
1895 60d49723 Michael Hanselmann
1896 60d49723 Michael Hanselmann
1897 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1898 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1899 07150497 Guido Trotter

1900 07150497 Guido Trotter
  @type os_name: string
1901 07150497 Guido Trotter
  @param os_name: base name of the os
1902 07150497 Guido Trotter
  @type os_variants: list or None
1903 07150497 Guido Trotter
  @param os_variants: list of supported variants
1904 07150497 Guido Trotter
  @rtype: list
1905 07150497 Guido Trotter
  @return: list of valid names
1906 07150497 Guido Trotter

1907 07150497 Guido Trotter
  """
1908 07150497 Guido Trotter
  if os_variants:
1909 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1910 07150497 Guido Trotter
  else:
1911 07150497 Guido Trotter
    return [os_name]
1912 07150497 Guido Trotter
1913 07150497 Guido Trotter
1914 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1915 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1916 a4ebd726 Michael Hanselmann

1917 a4ebd726 Michael Hanselmann
  @type selected: string or None
1918 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1919 a4ebd726 Michael Hanselmann
  @type default: list
1920 a4ebd726 Michael Hanselmann
  @param default: Default fields
1921 a4ebd726 Michael Hanselmann

1922 a4ebd726 Michael Hanselmann
  """
1923 a4ebd726 Michael Hanselmann
  if selected is None:
1924 a4ebd726 Michael Hanselmann
    return default
1925 a4ebd726 Michael Hanselmann
1926 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1927 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1928 a4ebd726 Michael Hanselmann
1929 a4ebd726 Michael Hanselmann
  return selected.split(",")
1930 a4ebd726 Michael Hanselmann
1931 a4ebd726 Michael Hanselmann
1932 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1933 4331f6cd Michael Hanselmann
1934 4331f6cd Michael Hanselmann
1935 47988778 Iustin Pop
def AskUser(text, choices=None):
1936 47988778 Iustin Pop
  """Ask the user a question.
1937 a8083063 Iustin Pop

1938 c41eea6e Iustin Pop
  @param text: the question to ask
1939 a8083063 Iustin Pop

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

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

1949 a8083063 Iustin Pop
  """
1950 47988778 Iustin Pop
  if choices is None:
1951 d0c8c01d Iustin Pop
    choices = [("y", True, "Perform the operation"),
1952 d0c8c01d Iustin Pop
               ("n", False, "Do not perform the operation")]
1953 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1954 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1955 47988778 Iustin Pop
  for entry in choices:
1956 d0c8c01d Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1957 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1958 47988778 Iustin Pop
1959 47988778 Iustin Pop
  answer = choices[-1][1]
1960 47988778 Iustin Pop
  new_text = []
1961 47988778 Iustin Pop
  for line in text.splitlines():
1962 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1963 47988778 Iustin Pop
  text = "\n".join(new_text)
1964 a8083063 Iustin Pop
  try:
1965 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1966 a8083063 Iustin Pop
  except IOError:
1967 47988778 Iustin Pop
    return answer
1968 a8083063 Iustin Pop
  try:
1969 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1970 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1971 d0c8c01d Iustin Pop
    chars.append("?")
1972 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1973 47988778 Iustin Pop
    while True:
1974 47988778 Iustin Pop
      f.write(text)
1975 d0c8c01d Iustin Pop
      f.write("\n")
1976 47988778 Iustin Pop
      f.write("/".join(chars))
1977 47988778 Iustin Pop
      f.write(": ")
1978 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1979 47988778 Iustin Pop
      if line in maps:
1980 47988778 Iustin Pop
        answer = maps[line]
1981 47988778 Iustin Pop
        break
1982 d0c8c01d Iustin Pop
      elif line == "?":
1983 47988778 Iustin Pop
        for entry in choices:
1984 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1985 47988778 Iustin Pop
        f.write("\n")
1986 47988778 Iustin Pop
        continue
1987 a8083063 Iustin Pop
  finally:
1988 a8083063 Iustin Pop
    f.close()
1989 a8083063 Iustin Pop
  return answer
1990 a8083063 Iustin Pop
1991 a8083063 Iustin Pop
1992 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1993 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1994 e9d741b6 Iustin Pop

1995 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1996 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1997 e9d741b6 Iustin Pop

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

2000 e9d741b6 Iustin Pop
  """
2001 e9d741b6 Iustin Pop
2002 e9d741b6 Iustin Pop
2003 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
2004 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
2005 a8083063 Iustin Pop

2006 0a1e74d9 Iustin Pop
  @type ops: list
2007 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
2008 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
2009 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
2010 0a1e74d9 Iustin Pop
             if None, a new client will be created
2011 a8083063 Iustin Pop

2012 a8083063 Iustin Pop
  """
2013 e2212007 Iustin Pop
  if cl is None:
2014 b33e986b Iustin Pop
    cl = GetClient()
2015 685ee993 Iustin Pop
2016 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
2017 0a1e74d9 Iustin Pop
2018 0a1e74d9 Iustin Pop
  return job_id
2019 0a1e74d9 Iustin Pop
2020 0a1e74d9 Iustin Pop
2021 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
2022 4e338533 Michael Hanselmann
  """Generic job-polling function.
2023 0a1e74d9 Iustin Pop

2024 4e338533 Michael Hanselmann
  @type job_id: number
2025 4e338533 Michael Hanselmann
  @param job_id: Job ID
2026 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
2027 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
2028 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
2029 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
2030 0a1e74d9 Iustin Pop

2031 0a1e74d9 Iustin Pop
  """
2032 6c5a7090 Michael Hanselmann
  prev_job_info = None
2033 6c5a7090 Michael Hanselmann
  prev_logmsg_serial = None
2034 6c5a7090 Michael Hanselmann
2035 f4484122 Michael Hanselmann
  status = None
2036 f4484122 Michael Hanselmann
2037 685ee993 Iustin Pop
  while True:
2038 4e338533 Michael Hanselmann
    result = cbs.WaitForJobChangeOnce(job_id, ["status"], prev_job_info,
2039 4e338533 Michael Hanselmann
                                      prev_logmsg_serial)
2040 6c5a7090 Michael Hanselmann
    if not result:
2041 685ee993 Iustin Pop
      # job not found, go away!
2042 0bbe448c Michael Hanselmann
      raise errors.JobLost("Job with id %s lost" % job_id)
2043 4e338533 Michael Hanselmann
2044 4e338533 Michael Hanselmann
    if result == constants.JOB_NOTCHANGED:
2045 4e338533 Michael Hanselmann
      report_cbs.ReportNotChanged(job_id, status)
2046 f4484122 Michael Hanselmann
2047 f4484122 Michael Hanselmann
      # Wait again
2048 f4484122 Michael Hanselmann
      continue
2049 685ee993 Iustin Pop
2050 6c5a7090 Michael Hanselmann
    # Split result, a tuple of (field values, log entries)
2051 6c5a7090 Michael Hanselmann
    (job_info, log_entries) = result
2052 6c5a7090 Michael Hanselmann
    (status, ) = job_info
2053 6c5a7090 Michael Hanselmann
2054 6c5a7090 Michael Hanselmann
    if log_entries:
2055 6c5a7090 Michael Hanselmann
      for log_entry in log_entries:
2056 4e338533 Michael Hanselmann
        (serial, timestamp, log_type, message) = log_entry
2057 4e338533 Michael Hanselmann
        report_cbs.ReportLogMessage(job_id, serial, timestamp,
2058 4e338533 Michael Hanselmann
                                    log_type, message)
2059 6c5a7090 Michael Hanselmann
        prev_logmsg_serial = max(prev_logmsg_serial, serial)
2060 6c5a7090 Michael Hanselmann
2061 0bbe448c Michael Hanselmann
    # TODO: Handle canceled and archived jobs
2062 fbf0262f Michael Hanselmann
    elif status in (constants.JOB_STATUS_SUCCESS,
2063 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_ERROR,
2064 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELING,
2065 fbf0262f Michael Hanselmann
                    constants.JOB_STATUS_CANCELED):
2066 685ee993 Iustin Pop
      break
2067 6c5a7090 Michael Hanselmann
2068 6c5a7090 Michael Hanselmann
    prev_job_info = job_info
2069 685ee993 Iustin Pop
2070 4e338533 Michael Hanselmann
  jobs = cbs.QueryJobs([job_id], ["status", "opstatus", "opresult"])
2071 0bbe448c Michael Hanselmann
  if not jobs:
2072 0bbe448c Michael Hanselmann
    raise errors.JobLost("Job with id %s lost" % job_id)
2073 685ee993 Iustin Pop
2074 0e050889 Iustin Pop
  status, opstatus, result = jobs[0]
2075 4e338533 Michael Hanselmann
2076 0bbe448c Michael Hanselmann
  if status == constants.JOB_STATUS_SUCCESS:
2077 53c04d04 Iustin Pop
    return result
2078 4e338533 Michael Hanselmann
2079 4e338533 Michael Hanselmann
  if status in (constants.JOB_STATUS_CANCELING, constants.JOB_STATUS_CANCELED):
2080 fbf0262f Michael Hanselmann
    raise errors.OpExecError("Job was canceled")
2081 4e338533 Michael Hanselmann
2082 4e338533 Michael Hanselmann
  has_ok = False
2083 4e338533 Michael Hanselmann
  for idx, (status, msg) in enumerate(zip(opstatus, result)):
2084 4e338533 Michael Hanselmann
    if status == constants.OP_STATUS_SUCCESS:
2085 4e338533 Michael Hanselmann
      has_ok = True
2086 4e338533 Michael Hanselmann
    elif status == constants.OP_STATUS_ERROR:
2087 4e338533 Michael Hanselmann
      errors.MaybeRaise(msg)
2088 4e338533 Michael Hanselmann
2089 4e338533 Michael Hanselmann
      if has_ok:
2090 4e338533 Michael Hanselmann
        raise errors.OpExecError("partial failure (opcode %d): %s" %
2091 4e338533 Michael Hanselmann
                                 (idx, msg))
2092 4e338533 Michael Hanselmann
2093 4e338533 Michael Hanselmann
      raise errors.OpExecError(str(msg))
2094 4e338533 Michael Hanselmann
2095 4e338533 Michael Hanselmann
  # default failure mode
2096 4e338533 Michael Hanselmann
  raise errors.OpExecError(result)
2097 4e338533 Michael Hanselmann
2098 4e338533 Michael Hanselmann
2099 4e338533 Michael Hanselmann
class JobPollCbBase:
2100 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} callbacks.
2101 4e338533 Michael Hanselmann

2102 4e338533 Michael Hanselmann
  """
2103 4e338533 Michael Hanselmann
  def __init__(self):
2104 4e338533 Michael Hanselmann
    """Initializes this class.
2105 4e338533 Michael Hanselmann

2106 4e338533 Michael Hanselmann
    """
2107 4e338533 Michael Hanselmann
2108 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2109 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2110 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2111 4e338533 Michael Hanselmann

2112 4e338533 Michael Hanselmann
    """
2113 4e338533 Michael Hanselmann
    raise NotImplementedError()
2114 4e338533 Michael Hanselmann
2115 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2116 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2117 4e338533 Michael Hanselmann

2118 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
2119 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
2120 4e338533 Michael Hanselmann
    @type fields: list of strings
2121 4e338533 Michael Hanselmann
    @param fields: Fields
2122 4e338533 Michael Hanselmann

2123 4e338533 Michael Hanselmann
    """
2124 4e338533 Michael Hanselmann
    raise NotImplementedError()
2125 4e338533 Michael Hanselmann
2126 4e338533 Michael Hanselmann
2127 4e338533 Michael Hanselmann
class JobPollReportCbBase:
2128 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
2129 4e338533 Michael Hanselmann

2130 4e338533 Michael Hanselmann
  """
2131 4e338533 Michael Hanselmann
  def __init__(self):
2132 4e338533 Michael Hanselmann
    """Initializes this class.
2133 4e338533 Michael Hanselmann

2134 4e338533 Michael Hanselmann
    """
2135 4e338533 Michael Hanselmann
2136 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2137 4e338533 Michael Hanselmann
    """Handles a log message.
2138 4e338533 Michael Hanselmann

2139 4e338533 Michael Hanselmann
    """
2140 4e338533 Michael Hanselmann
    raise NotImplementedError()
2141 4e338533 Michael Hanselmann
2142 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2143 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
2144 4e338533 Michael Hanselmann

2145 4e338533 Michael Hanselmann
    @type job_id: number
2146 4e338533 Michael Hanselmann
    @param job_id: Job ID
2147 4e338533 Michael Hanselmann
    @type status: string or None
2148 4e338533 Michael Hanselmann
    @param status: Job status if available
2149 4e338533 Michael Hanselmann

2150 4e338533 Michael Hanselmann
    """
2151 4e338533 Michael Hanselmann
    raise NotImplementedError()
2152 4e338533 Michael Hanselmann
2153 4e338533 Michael Hanselmann
2154 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
2155 4e338533 Michael Hanselmann
  def __init__(self, cl):
2156 4e338533 Michael Hanselmann
    """Initializes this class.
2157 4e338533 Michael Hanselmann

2158 4e338533 Michael Hanselmann
    """
2159 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
2160 4e338533 Michael Hanselmann
    self.cl = cl
2161 4e338533 Michael Hanselmann
2162 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2163 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2164 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2165 4e338533 Michael Hanselmann

2166 4e338533 Michael Hanselmann
    """
2167 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2168 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
2169 4e338533 Michael Hanselmann
2170 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2171 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2172 4e338533 Michael Hanselmann

2173 4e338533 Michael Hanselmann
    """
2174 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
2175 4e338533 Michael Hanselmann
2176 4e338533 Michael Hanselmann
2177 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2178 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
2179 4e338533 Michael Hanselmann
    """Initializes this class.
2180 4e338533 Michael Hanselmann

2181 4e338533 Michael Hanselmann
    """
2182 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2183 4e338533 Michael Hanselmann
2184 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
2185 4e338533 Michael Hanselmann
2186 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
2187 4e338533 Michael Hanselmann
2188 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2189 4e338533 Michael Hanselmann
    """Handles a log message.
2190 4e338533 Michael Hanselmann

2191 4e338533 Michael Hanselmann
    """
2192 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
2193 4e338533 Michael Hanselmann
2194 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2195 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2196 4e338533 Michael Hanselmann

2197 4e338533 Michael Hanselmann
    """
2198 4e338533 Michael Hanselmann
    # Ignore
2199 4e338533 Michael Hanselmann
2200 4e338533 Michael Hanselmann
2201 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
2202 4e338533 Michael Hanselmann
  def __init__(self):
2203 4e338533 Michael Hanselmann
    """Initializes this class.
2204 4e338533 Michael Hanselmann

2205 4e338533 Michael Hanselmann
    """
2206 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2207 4e338533 Michael Hanselmann
2208 4e338533 Michael Hanselmann
    self.notified_queued = False
2209 4e338533 Michael Hanselmann
    self.notified_waitlock = False
2210 4e338533 Michael Hanselmann
2211 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2212 4e338533 Michael Hanselmann
    """Handles a log message.
2213 4e338533 Michael Hanselmann

2214 4e338533 Michael Hanselmann
    """
2215 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2216 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
2217 4e338533 Michael Hanselmann
2218 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2219 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2220 4e338533 Michael Hanselmann

2221 4e338533 Michael Hanselmann
    """
2222 4e338533 Michael Hanselmann
    if status is None:
2223 4e338533 Michael Hanselmann
      return
2224 4e338533 Michael Hanselmann
2225 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2226 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
2227 4e338533 Michael Hanselmann
      self.notified_queued = True
2228 4e338533 Michael Hanselmann
2229 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2230 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2231 4e338533 Michael Hanselmann
      self.notified_waitlock = True
2232 4e338533 Michael Hanselmann
2233 4e338533 Michael Hanselmann
2234 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
2235 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
2236 8a7f1c61 Michael Hanselmann

2237 8a7f1c61 Michael Hanselmann
  """
2238 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
2239 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
2240 8a7f1c61 Michael Hanselmann
2241 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
2242 8a7f1c61 Michael Hanselmann
2243 8a7f1c61 Michael Hanselmann
2244 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2245 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
2246 4e338533 Michael Hanselmann

2247 4e338533 Michael Hanselmann
  @type job_id: job identified
2248 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
2249 4e338533 Michael Hanselmann
  @type cl: luxi.Client
2250 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
2251 4e338533 Michael Hanselmann
             if None, a new client will be created
2252 4e338533 Michael Hanselmann

2253 4e338533 Michael Hanselmann
  """
2254 4e338533 Michael Hanselmann
  if cl is None:
2255 4e338533 Michael Hanselmann
    cl = GetClient()
2256 4e338533 Michael Hanselmann
2257 583163a6 Michael Hanselmann
  if reporter is None:
2258 583163a6 Michael Hanselmann
    if feedback_fn:
2259 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2260 583163a6 Michael Hanselmann
    else:
2261 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
2262 583163a6 Michael Hanselmann
  elif feedback_fn:
2263 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2264 4e338533 Michael Hanselmann
2265 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2266 ceab32dd Iustin Pop
2267 ceab32dd Iustin Pop
2268 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2269 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
2270 0a1e74d9 Iustin Pop

2271 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
2272 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
2273 0a1e74d9 Iustin Pop
  interaction functions.
2274 0a1e74d9 Iustin Pop

2275 0a1e74d9 Iustin Pop
  """
2276 0a1e74d9 Iustin Pop
  if cl is None:
2277 0a1e74d9 Iustin Pop
    cl = GetClient()
2278 0a1e74d9 Iustin Pop
2279 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
2280 293ba2d8 Iustin Pop
2281 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
2282 fe5a2780 Klaus Aehlig
  if hasattr(opts, "print_jobid") and opts.print_jobid:
2283 d6cd74dd Klaus Aehlig
    ToStdout("%d" % job_id)
2284 0a1e74d9 Iustin Pop
2285 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2286 583163a6 Michael Hanselmann
                       reporter=reporter)
2287 53c04d04 Iustin Pop
2288 53c04d04 Iustin Pop
  return op_results[0]
2289 0a1e74d9 Iustin Pop
2290 0a1e74d9 Iustin Pop
2291 346c3037 Klaus Aehlig
def SubmitOpCodeToDrainedQueue(op):
2292 346c3037 Klaus Aehlig
  """Forcefully insert a job in the queue, even if it is drained.
2293 346c3037 Klaus Aehlig

2294 346c3037 Klaus Aehlig
  """
2295 346c3037 Klaus Aehlig
  cl = GetClient()
2296 346c3037 Klaus Aehlig
  job_id = cl.SubmitJobToDrainedQueue([op])
2297 346c3037 Klaus Aehlig
  op_results = PollJob(job_id, cl=cl)
2298 346c3037 Klaus Aehlig
  return op_results[0]
2299 346c3037 Klaus Aehlig
2300 346c3037 Klaus Aehlig
2301 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2302 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
2303 94428652 Iustin Pop

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

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

2312 94428652 Iustin Pop
  """
2313 94428652 Iustin Pop
  if opts and opts.submit_only:
2314 293ba2d8 Iustin Pop
    job = [op]
2315 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
2316 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
2317 d6cd74dd Klaus Aehlig
    if opts.print_jobid:
2318 d6cd74dd Klaus Aehlig
      ToStdout("%d" % job_id)
2319 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
2320 94428652 Iustin Pop
  else:
2321 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2322 293ba2d8 Iustin Pop
2323 293ba2d8 Iustin Pop
2324 276e51bd Michele Tartara
def _InitReasonTrail(op, opts):
2325 276e51bd Michele Tartara
  """Builds the first part of the reason trail
2326 276e51bd Michele Tartara

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

2330 276e51bd Michele Tartara
  @param op: the opcode the reason trail will be added to
2331 276e51bd Michele Tartara
  @param opts: the command line options selected by the user
2332 276e51bd Michele Tartara

2333 276e51bd Michele Tartara
  """
2334 276e51bd Michele Tartara
  assert len(sys.argv) >= 2
2335 276e51bd Michele Tartara
  trail = []
2336 276e51bd Michele Tartara
2337 276e51bd Michele Tartara
  if opts.reason:
2338 276e51bd Michele Tartara
    trail.append((constants.OPCODE_REASON_SRC_USER,
2339 276e51bd Michele Tartara
                  opts.reason,
2340 276e51bd Michele Tartara
                  utils.EpochNano()))
2341 276e51bd Michele Tartara
2342 276e51bd Michele Tartara
  binary = os.path.basename(sys.argv[0])
2343 276e51bd Michele Tartara
  source = "%s:%s" % (constants.OPCODE_REASON_SRC_CLIENT, binary)
2344 276e51bd Michele Tartara
  command = sys.argv[1]
2345 276e51bd Michele Tartara
  trail.append((source, command, utils.EpochNano()))
2346 276e51bd Michele Tartara
  op.reason = trail
2347 276e51bd Michele Tartara
2348 276e51bd Michele Tartara
2349 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
2350 293ba2d8 Iustin Pop
  """Processor for generic options.
2351 293ba2d8 Iustin Pop

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

2355 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
2356 293ba2d8 Iustin Pop
  @param options: command line options or None
2357 293ba2d8 Iustin Pop
  @return: None (in-place modification)
2358 293ba2d8 Iustin Pop

2359 293ba2d8 Iustin Pop
  """
2360 293ba2d8 Iustin Pop
  if not options:
2361 293ba2d8 Iustin Pop
    return
2362 293ba2d8 Iustin Pop
  for op in opcode_list:
2363 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
2364 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
2365 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
2366 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
2367 552328b8 Michael Hanselmann
      op.priority = options.priority
2368 276e51bd Michele Tartara
    _InitReasonTrail(op, options)
2369 94428652 Iustin Pop
2370 94428652 Iustin Pop
2371 42ab9ac4 Iustin Pop
def GetClient(query=False):
2372 42ab9ac4 Iustin Pop
  """Connects to the a luxi socket and returns a client.
2373 42ab9ac4 Iustin Pop

2374 42ab9ac4 Iustin Pop
  @type query: boolean
2375 42ab9ac4 Iustin Pop
  @param query: this signifies that the client will only be
2376 42ab9ac4 Iustin Pop
      used for queries; if the build-time parameter
2377 42ab9ac4 Iustin Pop
      enable-split-queries is enabled, then the client will be
2378 42ab9ac4 Iustin Pop
      connected to the query socket instead of the masterd socket
2379 42ab9ac4 Iustin Pop

2380 42ab9ac4 Iustin Pop
  """
2381 055d6ac0 Iustin Pop
  override_socket = os.getenv(constants.LUXI_OVERRIDE, "")
2382 055d6ac0 Iustin Pop
  if override_socket:
2383 055d6ac0 Iustin Pop
    if override_socket == constants.LUXI_OVERRIDE_MASTER:
2384 055d6ac0 Iustin Pop
      address = pathutils.MASTER_SOCKET
2385 055d6ac0 Iustin Pop
    elif override_socket == constants.LUXI_OVERRIDE_QUERY:
2386 055d6ac0 Iustin Pop
      address = pathutils.QUERY_SOCKET
2387 055d6ac0 Iustin Pop
    else:
2388 055d6ac0 Iustin Pop
      address = override_socket
2389 055d6ac0 Iustin Pop
  elif query and constants.ENABLE_SPLIT_QUERY:
2390 ee4a14c0 Michael Hanselmann
    address = pathutils.QUERY_SOCKET
2391 42ab9ac4 Iustin Pop
  else:
2392 42ab9ac4 Iustin Pop
    address = None
2393 af30b2fd Michael Hanselmann
  # TODO: Cache object?
2394 b33e986b Iustin Pop
  try:
2395 42ab9ac4 Iustin Pop
    client = luxi.Client(address=address)
2396 b33e986b Iustin Pop
  except luxi.NoMasterError:
2397 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
2398 d9a51679 Michael Hanselmann
2399 d9a51679 Michael Hanselmann
    # Try to read ssconf file
2400 d9a51679 Michael Hanselmann
    try:
2401 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
2402 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
2403 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2404 2cfbc784 Iustin Pop
                                 " not part of a cluster",
2405 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2406 d9a51679 Michael Hanselmann
2407 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2408 b33e986b Iustin Pop
    if master != myself:
2409 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
2410 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
2411 2cfbc784 Iustin Pop
                                 master, errors.ECODE_INVAL)
2412 d9a51679 Michael Hanselmann
    raise
2413 b33e986b Iustin Pop
  return client
2414 af30b2fd Michael Hanselmann
2415 af30b2fd Michael Hanselmann
2416 73702ee7 Iustin Pop
def FormatError(err):
2417 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
2418 73702ee7 Iustin Pop

2419 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
2420 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
2421 73702ee7 Iustin Pop
  second, a string describing the error message (not
2422 73702ee7 Iustin Pop
  newline-terminated).
2423 73702ee7 Iustin Pop

2424 73702ee7 Iustin Pop
  """
2425 73702ee7 Iustin Pop
  retcode = 1
2426 73702ee7 Iustin Pop
  obuf = StringIO()
2427 e2e521d0 Iustin Pop
  msg = str(err)
2428 73702ee7 Iustin Pop
  if isinstance(err, errors.ConfigurationError):
2429 e2e521d0 Iustin Pop
    txt = "Corrupt configuration file: %s" % msg
2430 46fbdd04 Iustin Pop
    logging.error(txt)
2431 e2e521d0 Iustin Pop
    obuf.write(txt + "\n")
2432 73702ee7 Iustin Pop
    obuf.write("Aborting.")
2433 73702ee7 Iustin Pop
    retcode = 2
2434 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksAbort):
2435 73702ee7 Iustin Pop
    obuf.write("Failure: hooks execution failed:\n")
2436 73702ee7 Iustin Pop
    for node, script, out in err.args[0]:
2437 73702ee7 Iustin Pop
      if out:
2438 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s, output: %s\n" %
2439 73702ee7 Iustin Pop
                   (node, script, out))
2440 73702ee7 Iustin Pop
      else:
2441 73702ee7 Iustin Pop
        obuf.write("  node: %s, script: %s (no output)\n" %
2442 73702ee7 Iustin Pop
                   (node, script))
2443 73702ee7 Iustin Pop
  elif isinstance(err, errors.HooksFailure):
2444 e2e521d0 Iustin Pop
    obuf.write("Failure: hooks general failure: %s" % msg)
2445 73702ee7 Iustin Pop
  elif isinstance(err, errors.ResolverError):
2446 b705c7a6 Manuel Franceschini
    this_host = netutils.Hostname.GetSysName()
2447 73702ee7 Iustin Pop
    if err.args[0] == this_host:
2448 73702ee7 Iustin Pop
      msg = "Failure: can't resolve my own hostname ('%s')"
2449 73702ee7 Iustin Pop
    else:
2450 73702ee7 Iustin Pop
      msg = "Failure: can't resolve hostname '%s'"
2451 73702ee7 Iustin Pop
    obuf.write(msg % err.args[0])
2452 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpPrereqError):
2453 5c983ee5 Iustin Pop
    if len(err.args) == 2:
2454 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2455 5ae4945a Iustin Pop
                 " operation:\nerror type: %s, error details:\n%s" %
2456 5c983ee5 Iustin Pop
                 (err.args[1], err.args[0]))
2457 5c983ee5 Iustin Pop
    else:
2458 5c983ee5 Iustin Pop
      obuf.write("Failure: prerequisites not met for this"
2459 5c983ee5 Iustin Pop
                 " operation:\n%s" % msg)
2460 73702ee7 Iustin Pop
  elif isinstance(err, errors.OpExecError):
2461 e2e521d0 Iustin Pop
    obuf.write("Failure: command execution error:\n%s" % msg)
2462 73702ee7 Iustin Pop
  elif isinstance(err, errors.TagError):
2463 e2e521d0 Iustin Pop
    obuf.write("Failure: invalid tag(s) given:\n%s" % msg)
2464 686d7433 Iustin Pop
  elif isinstance(err, errors.JobQueueDrainError):
2465 686d7433 Iustin Pop
    obuf.write("Failure: the job queue is marked for drain and doesn't"
2466 686d7433 Iustin Pop
               " accept new requests\n")
2467 f87b405e Michael Hanselmann
  elif isinstance(err, errors.JobQueueFull):
2468 f87b405e Michael Hanselmann
    obuf.write("Failure: the job queue is full and doesn't accept new"
2469 f87b405e Michael Hanselmann
               " job submissions until old jobs are archived\n")
2470 a5728081 Guido Trotter
  elif isinstance(err, errors.TypeEnforcementError):
2471 a5728081 Guido Trotter
    obuf.write("Parameter Error: %s" % msg)
2472 c1ce76bb Iustin Pop
  elif isinstance(err, errors.ParameterError):
2473 c1ce76bb Iustin Pop
    obuf.write("Failure: unknown/wrong parameter name '%s'" % msg)
2474 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.NoMasterError):
2475 7f5edc60 Iustin Pop
    if err.args[0] == pathutils.MASTER_SOCKET:
2476 055d6ac0 Iustin Pop
      daemon = "the master daemon"
2477 055d6ac0 Iustin Pop
    elif err.args[0] == pathutils.QUERY_SOCKET:
2478 055d6ac0 Iustin Pop
      daemon = "the config daemon"
2479 7f5edc60 Iustin Pop
    else:
2480 055d6ac0 Iustin Pop
      daemon = "socket '%s'" % str(err.args[0])
2481 055d6ac0 Iustin Pop
    obuf.write("Cannot communicate with %s.\nIs the process running"
2482 7f5edc60 Iustin Pop
               " and listening for connections?" % daemon)
2483 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.TimeoutError):
2484 cd4c86a8 Michael Hanselmann
    obuf.write("Timeout while talking to the master daemon. Jobs might have"
2485 cd4c86a8 Michael Hanselmann
               " been submitted and will continue to run even if the call"
2486 cd4c86a8 Michael Hanselmann
               " timed out. Useful commands in this situation are \"gnt-job"
2487 cd4c86a8 Michael Hanselmann
               " list\", \"gnt-job cancel\" and \"gnt-job watch\". Error:\n")
2488 cd4c86a8 Michael Hanselmann
    obuf.write(msg)
2489 5a1c22fe Iustin Pop
  elif isinstance(err, luxi.PermissionError):
2490 5a1c22fe Iustin Pop
    obuf.write("It seems you don't have permissions to connect to the"
2491 5a1c22fe Iustin Pop
               " master daemon.\nPlease retry as a different user.")
2492 03a8dbdc Iustin Pop
  elif isinstance(err, luxi.ProtocolError):
2493 03a8dbdc Iustin Pop
    obuf.write("Unhandled protocol error while talking to the master daemon:\n"
2494 03a8dbdc Iustin Pop
               "%s" % msg)
2495 91c622a8 Iustin Pop
  elif isinstance(err, errors.JobLost):
2496 91c622a8 Iustin Pop
    obuf.write("Error checking job status: %s" % msg)
2497 cb1e6c3c Michael Hanselmann
  elif isinstance(err, errors.QueryFilterParseError):
2498 cb1e6c3c Michael Hanselmann
    obuf.write("Error while parsing query filter: %s\n" % err.args[0])
2499 cb1e6c3c Michael Hanselmann
    obuf.write("\n".join(err.GetDetails()))
2500 797506fc Michael Hanselmann
  elif isinstance(err, errors.GenericError):
2501 797506fc Michael Hanselmann
    obuf.write("Unhandled Ganeti error: %s" % msg)
2502 e9d741b6 Iustin Pop
  elif isinstance(err, JobSubmittedException):
2503 e9d741b6 Iustin Pop
    obuf.write("JobID: %s\n" % err.args[0])
2504 e9d741b6 Iustin Pop
    retcode = 0
2505 73702ee7 Iustin Pop
  else:
2506 e2e521d0 Iustin Pop
    obuf.write("Unhandled exception: %s" % msg)
2507 d0c8c01d Iustin Pop
  return retcode, obuf.getvalue().rstrip("\n")
2508 73702ee7 Iustin Pop
2509 73702ee7 Iustin Pop
2510 ef9fa5b9 René Nussbaumer
def GenericMain(commands, override=None, aliases=None,
2511 ef9fa5b9 René Nussbaumer
                env_override=frozenset()):
2512 a8083063 Iustin Pop
  """Generic main function for all the gnt-* commands.
2513 a8083063 Iustin Pop

2514 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2515 ef9fa5b9 René Nussbaumer
                   for command line handling.
2516 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2517 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2518 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2519 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2520 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2521 ef9fa5b9 René Nussbaumer
                       default args for commands
2522 a8083063 Iustin Pop

2523 a8083063 Iustin Pop
  """
2524 a8083063 Iustin Pop
  # save the program name and the entire command line for later logging
2525 a8083063 Iustin Pop
  if sys.argv:
2526 c1f19851 Michael Hanselmann
    binary = os.path.basename(sys.argv[0])
2527 c1f19851 Michael Hanselmann
    if not binary:
2528 c1f19851 Michael Hanselmann
      binary = sys.argv[0]
2529 c1f19851 Michael Hanselmann
2530 a8083063 Iustin Pop
    if len(sys.argv) >= 2:
2531 c1f19851 Michael Hanselmann
      logname = utils.ShellQuoteArgs([binary, sys.argv[1]])
2532 a8083063 Iustin Pop
    else:
2533 c1f19851 Michael Hanselmann
      logname = binary
2534 c1f19851 Michael Hanselmann
2535 c1f19851 Michael Hanselmann
    cmdline = utils.ShellQuoteArgs([binary] + sys.argv[1:])
2536 a8083063 Iustin Pop
  else:
2537 a8083063 Iustin Pop
    binary = "<unknown program>"
2538 c1f19851 Michael Hanselmann
    cmdline = "<unknown>"
2539 a8083063 Iustin Pop
2540 de47cf8f Guido Trotter
  if aliases is None:
2541 de47cf8f Guido Trotter
    aliases = {}
2542 de47cf8f Guido Trotter
2543 3126878d Guido Trotter
  try:
2544 d971402f Michael Hanselmann
    (func, options, args) = _ParseArgs(binary, sys.argv, commands, aliases,
2545 d971402f Michael Hanselmann
                                       env_override)
2546 d971402f Michael Hanselmann
  except _ShowVersion:
2547 d971402f Michael Hanselmann
    ToStdout("%s (ganeti %s) %s", binary, constants.VCS_VERSION,
2548 d971402f Michael Hanselmann
             constants.RELEASE_VERSION)
2549 d971402f Michael Hanselmann
    return constants.EXIT_SUCCESS
2550 d971402f Michael Hanselmann
  except _ShowUsage, err:
2551 d971402f Michael Hanselmann
    for line in _FormatUsage(binary, commands):
2552 d971402f Michael Hanselmann
      ToStdout(line)
2553 d971402f Michael Hanselmann
2554 d971402f Michael Hanselmann
    if err.exit_error:
2555 d971402f Michael Hanselmann
      return constants.EXIT_FAILURE
2556 d971402f Michael Hanselmann
    else:
2557 d971402f Michael Hanselmann
      return constants.EXIT_SUCCESS
2558 3126878d Guido Trotter
  except errors.ParameterError, err:
2559 3126878d Guido Trotter
    result, err_msg = FormatError(err)
2560 3126878d Guido Trotter
    ToStderr(err_msg)
2561 3126878d Guido Trotter
    return 1
2562 3126878d Guido Trotter
2563 a8083063 Iustin Pop
  if func is None: # parse error
2564 a8083063 Iustin Pop
    return 1
2565 a8083063 Iustin Pop
2566 334d1483 Iustin Pop
  if override is not None:
2567 334d1483 Iustin Pop
    for key, val in override.iteritems():
2568 334d1483 Iustin Pop
      setattr(options, key, val)
2569 334d1483 Iustin Pop
2570 ee4a14c0 Michael Hanselmann
  utils.SetupLogging(pathutils.LOG_COMMANDS, logname, debug=options.debug,
2571 cfcc79c6 Michael Hanselmann
                     stderr_logging=True)
2572 a8083063 Iustin Pop
2573 c1f19851 Michael Hanselmann
  logging.info("Command line: %s", cmdline)
2574 a8083063 Iustin Pop
2575 a8083063 Iustin Pop
  try:
2576 a4af651e Iustin Pop
    result = func(options, args)
2577 d8353c3a Iustin Pop
  except (errors.GenericError, luxi.ProtocolError,
2578 d8353c3a Iustin Pop
          JobSubmittedException), err:
2579 a4af651e Iustin Pop
    result, err_msg = FormatError(err)
2580 5bbd3f7f Michael Hanselmann
    logging.exception("Error during command processing")
2581 46fbdd04 Iustin Pop
    ToStderr(err_msg)
2582 8a53b55f Iustin Pop
  except KeyboardInterrupt:
2583 8a53b55f Iustin Pop
    result = constants.EXIT_FAILURE
2584 8a53b55f Iustin Pop
    ToStderr("Aborted. Note that if the operation created any jobs, they"
2585 8a53b55f Iustin Pop
             " might have been submitted and"
2586 8a53b55f Iustin Pop
             " will continue to run in the background.")
2587 225e2544 Iustin Pop
  except IOError, err:
2588 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
2589 225e2544 Iustin Pop
      # our terminal went away, we'll exit
2590 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
2591 225e2544 Iustin Pop
    else:
2592 225e2544 Iustin Pop
      raise
2593 a8083063 Iustin Pop
2594 a8083063 Iustin Pop
  return result
2595 137161c9 Michael Hanselmann
2596 137161c9 Michael Hanselmann
2597 845c79d8 Michael Hanselmann
def ParseNicOption(optvalue):
2598 845c79d8 Michael Hanselmann
  """Parses the value of the --net option(s).
2599 845c79d8 Michael Hanselmann

2600 845c79d8 Michael Hanselmann
  """
2601 845c79d8 Michael Hanselmann
  try:
2602 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2603 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2604 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2605 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
2606 845c79d8 Michael Hanselmann
2607 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2608 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2609 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2610 845c79d8 Michael Hanselmann
2611 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2612 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2613 2cfbc784 Iustin Pop
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2614 845c79d8 Michael Hanselmann
2615 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2616 845c79d8 Michael Hanselmann
2617 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2618 845c79d8 Michael Hanselmann
2619 845c79d8 Michael Hanselmann
  return nics
2620 845c79d8 Michael Hanselmann
2621 845c79d8 Michael Hanselmann
2622 02a6b50a Michele Tartara
def FixHvParams(hvparams):
2623 02a6b50a Michele Tartara
  # In Ganeti 2.8.4 the separator for the usb_devices hvparam was changed from
2624 02a6b50a Michele Tartara
  # comma to space because commas cannot be accepted on the command line
2625 02a6b50a Michele Tartara
  # (they already act as the separator between different hvparams). Still,
2626 02a6b50a Michele Tartara
  # RAPI should be able to accept commas for backwards compatibility.
2627 02a6b50a Michele Tartara
  # Therefore, we convert spaces into commas here, and we keep the old
2628 02a6b50a Michele Tartara
  # parsing logic everywhere else.
2629 02a6b50a Michele Tartara
  try:
2630 02a6b50a Michele Tartara
    new_usb_devices = hvparams[constants.HV_USB_DEVICES].replace(" ", ",")
2631 02a6b50a Michele Tartara
    hvparams[constants.HV_USB_DEVICES] = new_usb_devices
2632 02a6b50a Michele Tartara
  except KeyError:
2633 02a6b50a Michele Tartara
    #No usb_devices, no modification required
2634 02a6b50a Michele Tartara
    pass
2635 02a6b50a Michele Tartara
2636 02a6b50a Michele Tartara
2637 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2638 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2639 d77490c5 Iustin Pop

2640 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2641 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2642 d77490c5 Iustin Pop
  @type args: list
2643 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2644 d77490c5 Iustin Pop
  @rtype: int
2645 d77490c5 Iustin Pop
  @return: the desired exit code
2646 d77490c5 Iustin Pop

2647 d77490c5 Iustin Pop
  """
2648 d77490c5 Iustin Pop
  instance = args[0]
2649 d77490c5 Iustin Pop
2650 d77490c5 Iustin Pop
  (pnode, snode) = SplitNodeOption(opts.node)
2651 d77490c5 Iustin Pop
2652 d77490c5 Iustin Pop
  hypervisor = None
2653 d77490c5 Iustin Pop
  hvparams = {}
2654 d77490c5 Iustin Pop
  if opts.hypervisor:
2655 d77490c5 Iustin Pop
    hypervisor, hvparams = opts.hypervisor
2656 d77490c5 Iustin Pop
2657 d77490c5 Iustin Pop
  if opts.nics:
2658 845c79d8 Michael Hanselmann
    nics = ParseNicOption(opts.nics)
2659 d77490c5 Iustin Pop
  elif opts.no_nics:
2660 d77490c5 Iustin Pop
    # no nics
2661 d77490c5 Iustin Pop
    nics = []
2662 0af0f641 Iustin Pop
  elif mode == constants.INSTANCE_CREATE:
2663 d77490c5 Iustin Pop
    # default of one nic, all auto
2664 d77490c5 Iustin Pop
    nics = [{}]
2665 0af0f641 Iustin Pop
  else:
2666 0af0f641 Iustin Pop
    # mode == import
2667 0af0f641 Iustin Pop
    nics = []
2668 d77490c5 Iustin Pop
2669 d77490c5 Iustin Pop
  if opts.disk_template == constants.DT_DISKLESS:
2670 d77490c5 Iustin Pop
    if opts.disks or opts.sd_size is not None:
2671 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Diskless instance but disk"
2672 2cfbc784 Iustin Pop
                                 " information passed", errors.ECODE_INVAL)
2673 d77490c5 Iustin Pop
    disks = []
2674 d77490c5 Iustin Pop
  else:
2675 9b12ed0f Iustin Pop
    if (not opts.disks and not opts.sd_size
2676 9b12ed0f Iustin Pop
        and mode == constants.INSTANCE_CREATE):
2677 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("No disk information specified",
2678 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2679 d77490c5 Iustin Pop
    if opts.disks and opts.sd_size is not None:
2680 d77490c5 Iustin Pop
      raise errors.OpPrereqError("Please use either the '--disk' or"
2681 2cfbc784 Iustin Pop
                                 " '-s' option", errors.ECODE_INVAL)
2682 d77490c5 Iustin Pop
    if opts.sd_size is not None:
2683 ccfa86ba Michael Hanselmann
      opts.disks = [(0, {constants.IDISK_SIZE: opts.sd_size})]
2684 9b12ed0f Iustin Pop
2685 9b12ed0f Iustin Pop
    if opts.disks:
2686 9b12ed0f Iustin Pop
      try:
2687 9b12ed0f Iustin Pop
        disk_max = max(int(didx[0]) + 1 for didx in opts.disks)
2688 9b12ed0f Iustin Pop
      except ValueError, err:
2689 2cfbc784 Iustin Pop
        raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err),
2690 2cfbc784 Iustin Pop
                                   errors.ECODE_INVAL)
2691 9b12ed0f Iustin Pop
      disks = [{}] * disk_max
2692 9b12ed0f Iustin Pop
    else:
2693 9b12ed0f Iustin Pop
      disks = []
2694 d77490c5 Iustin Pop
    for didx, ddict in opts.disks:
2695 d77490c5 Iustin Pop
      didx = int(didx)
2696 d77490c5 Iustin Pop
      if not isinstance(ddict, dict):
2697 d77490c5 Iustin Pop
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
2698 2cfbc784 Iustin Pop
        raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
2699 ccfa86ba Michael Hanselmann
      elif constants.IDISK_SIZE in ddict:
2700 ccfa86ba Michael Hanselmann
        if constants.IDISK_ADOPT in ddict:
2701 5029db65 Iustin Pop
          raise errors.OpPrereqError("Only one of 'size' and 'adopt' allowed"
2702 2cfbc784 Iustin Pop
                                     " (disk %d)" % didx, errors.ECODE_INVAL)
2703 5029db65 Iustin Pop
        try:
2704 ccfa86ba Michael Hanselmann
          ddict[constants.IDISK_SIZE] = \
2705 ccfa86ba Michael Hanselmann
            utils.ParseUnit(ddict[constants.IDISK_SIZE])
2706 5029db65 Iustin Pop
        except ValueError, err:
2707 5029db65 Iustin Pop
          raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
2708 2cfbc784 Iustin Pop
                                     (didx, err), errors.ECODE_INVAL)
2709 ccfa86ba Michael Hanselmann
      elif constants.IDISK_ADOPT in ddict:
2710 c615590c Bernardo Dal Seno
        if constants.IDISK_SPINDLES in ddict:
2711 c615590c Bernardo Dal Seno
          raise errors.OpPrereqError("spindles is not a valid option when"
2712 c615590c Bernardo Dal Seno
                                     " adopting a disk", errors.ECODE_INVAL)
2713 5029db65 Iustin Pop
        if mode == constants.INSTANCE_IMPORT:
2714 5029db65 Iustin Pop
          raise errors.OpPrereqError("Disk adoption not allowed for instance"
2715 2cfbc784 Iustin Pop
                                     " import", errors.ECODE_INVAL)
2716 ccfa86ba Michael Hanselmann
        ddict[constants.IDISK_SIZE] = 0
2717 5029db65 Iustin Pop
      else:
2718 5029db65 Iustin Pop
        raise errors.OpPrereqError("Missing size or adoption source for"
2719 2cfbc784 Iustin Pop
                                   " disk %d" % didx, errors.ECODE_INVAL)
2720 d77490c5 Iustin Pop
      disks[didx] = ddict
2721 d77490c5 Iustin Pop
2722 a57981c5 Apollon Oikonomopoulos
  if opts.tags is not None:
2723 0f8810df Michael Hanselmann
    tags = opts.tags.split(",")
2724 a57981c5 Apollon Oikonomopoulos
  else:
2725 a57981c5 Apollon Oikonomopoulos
    tags = []
2726 a57981c5 Apollon Oikonomopoulos
2727 b2e233a5 Guido Trotter
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_COMPAT)
2728 d77490c5 Iustin Pop
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
2729 02a6b50a Michele Tartara
  FixHvParams(hvparams)
2730 d77490c5 Iustin Pop
2731 d77490c5 Iustin Pop
  if mode == constants.INSTANCE_CREATE:
2732 d77490c5 Iustin Pop
    start = opts.start
2733 d77490c5 Iustin Pop
    os_type = opts.os
2734 1ee8e01a Guido Trotter
    force_variant = opts.force_variant
2735 d77490c5 Iustin Pop
    src_node = None
2736 d77490c5 Iustin Pop
    src_path = None
2737 25a8792c Iustin Pop
    no_install = opts.no_install
2738 e588764d Iustin Pop
    identify_defaults = False
2739 d77490c5 Iustin Pop
  elif mode == constants.INSTANCE_IMPORT:
2740 d77490c5 Iustin Pop
    start = False
2741 d77490c5 Iustin Pop
    os_type = None
2742 1ee8e01a Guido Trotter
    force_variant = False
2743 d77490c5 Iustin Pop
    src_node = opts.src_node
2744 d77490c5 Iustin Pop
    src_path = opts.src_dir
2745 25a8792c Iustin Pop
    no_install = None
2746 e588764d Iustin Pop
    identify_defaults = opts.identify_defaults
2747 d77490c5 Iustin Pop
  else:
2748 d77490c5 Iustin Pop
    raise errors.ProgrammerError("Invalid creation mode %s" % mode)
2749 d77490c5 Iustin Pop
2750 e1530b10 Iustin Pop
  op = opcodes.OpInstanceCreate(instance_name=instance,
2751 d77490c5 Iustin Pop
                                disks=disks,
2752 d77490c5 Iustin Pop
                                disk_template=opts.disk_template,
2753 d77490c5 Iustin Pop
                                nics=nics,
2754 d4117a72 Apollon Oikonomopoulos
                                conflicts_check=opts.conflicts_check,
2755 d77490c5 Iustin Pop
                                pnode=pnode, snode=snode,
2756 d77490c5 Iustin Pop
                                ip_check=opts.ip_check,
2757 460d22be Iustin Pop
                                name_check=opts.name_check,
2758 d77490c5 Iustin Pop
                                wait_for_sync=opts.wait_for_sync,
2759 d77490c5 Iustin Pop
                                file_storage_dir=opts.file_storage_dir,
2760 d77490c5 Iustin Pop
                                file_driver=opts.file_driver,
2761 d77490c5 Iustin Pop
                                iallocator=opts.iallocator,
2762 d77490c5 Iustin Pop
                                hypervisor=hypervisor,
2763 d77490c5 Iustin Pop
                                hvparams=hvparams,
2764 d77490c5 Iustin Pop
                                beparams=opts.beparams,
2765 062a7100 Iustin Pop
                                osparams=opts.osparams,
2766 d77490c5 Iustin Pop
                                mode=mode,
2767 d77490c5 Iustin Pop
                                start=start,
2768 d77490c5 Iustin Pop
                                os_type=os_type,
2769 1ee8e01a Guido Trotter
                                force_variant=force_variant,
2770 d77490c5 Iustin Pop
                                src_node=src_node,
2771 25a8792c Iustin Pop
                                src_path=src_path,
2772 a57981c5 Apollon Oikonomopoulos
                                tags=tags,
2773 e588764d Iustin Pop
                                no_install=no_install,
2774 10889e0c René Nussbaumer
                                identify_defaults=identify_defaults,
2775 10889e0c René Nussbaumer
                                ignore_ipolicy=opts.ignore_ipolicy)
2776 d77490c5 Iustin Pop
2777 d77490c5 Iustin Pop
  SubmitOrSend(op, opts)
2778 d77490c5 Iustin Pop
  return 0
2779 d77490c5 Iustin Pop
2780 d77490c5 Iustin Pop
2781 7e49b6ce Michael Hanselmann
class _RunWhileClusterStoppedHelper:
2782 7e49b6ce Michael Hanselmann
  """Helper class for L{RunWhileClusterStopped} to simplify state management
2783 7e49b6ce Michael Hanselmann

2784 7e49b6ce Michael Hanselmann
  """
2785 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2786 7e49b6ce Michael Hanselmann
    """Initializes this class.
2787 7e49b6ce Michael Hanselmann

2788 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2789 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2790 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2791 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2792 7e49b6ce Michael Hanselmann
    @type master_node: string
2793 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2794 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2795 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2796 7e49b6ce Michael Hanselmann

2797 7e49b6ce Michael Hanselmann
    """
2798 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2799 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2800 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2801 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2802 7e49b6ce Michael Hanselmann
2803 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2804 7e49b6ce Michael Hanselmann
2805 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2806 7e49b6ce Michael Hanselmann
                            if name != master_node]
2807 7e49b6ce Michael Hanselmann
2808 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2809 7e49b6ce Michael Hanselmann
2810 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2811 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2812 7e49b6ce Michael Hanselmann

2813 7e49b6ce Michael Hanselmann
    @type node_name: string
2814 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2815 7e49b6ce Michael Hanselmann
    @type cmd: list
2816 7e49b6ce Michael Hanselmann
    @param cmd: Command
2817 7e49b6ce Michael Hanselmann

2818 7e49b6ce Michael Hanselmann
    """
2819 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2820 7e49b6ce Michael Hanselmann
      # No need to use SSH
2821 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2822 7e49b6ce Michael Hanselmann
    else:
2823 052783ff Michael Hanselmann
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2824 052783ff Michael Hanselmann
                            utils.ShellQuoteArgs(cmd))
2825 7e49b6ce Michael Hanselmann
2826 7e49b6ce Michael Hanselmann
    if result.failed:
2827 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2828 7e49b6ce Michael Hanselmann
      if node_name:
2829 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2830 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2831 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2832 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2833 7e49b6ce Michael Hanselmann
2834 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2835 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2836 7e49b6ce Michael Hanselmann

2837 7e49b6ce Michael Hanselmann
    @type fn: callable
2838 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2839 7e49b6ce Michael Hanselmann

2840 7e49b6ce Michael Hanselmann
    """
2841 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2842 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2843 ee4a14c0 Michael Hanselmann
    watcher_block = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
2844 7e49b6ce Michael Hanselmann
    try:
2845 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2846 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2847 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2848 7e49b6ce Michael Hanselmann
2849 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2850 7e49b6ce Michael Hanselmann
      # ones are finished
2851 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2852 ee4a14c0 Michael Hanselmann
      self._RunCmd(None, [pathutils.DAEMON_UTIL, "stop-master"])
2853 7e49b6ce Michael Hanselmann
      try:
2854 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2855 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2856 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2857 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "stop-all"])
2858 7e49b6ce Michael Hanselmann
2859 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2860 7e49b6ce Michael Hanselmann
        try:
2861 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2862 d512e84b Michael Hanselmann
        except Exception, err:
2863 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2864 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2865 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2866 7e49b6ce Michael Hanselmann
          raise
2867 7e49b6ce Michael Hanselmann
      finally:
2868 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2869 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2870 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2871 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "start-all"])
2872 7e49b6ce Michael Hanselmann
    finally:
2873 7e49b6ce Michael Hanselmann
      # Resume watcher
2874 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2875 7e49b6ce Michael Hanselmann
2876 7e49b6ce Michael Hanselmann
2877 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2878 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2879 7e49b6ce Michael Hanselmann

2880 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2881 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2882 7e49b6ce Michael Hanselmann
  @type fn: callable
2883 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2884 7e49b6ce Michael Hanselmann

2885 7e49b6ce Michael Hanselmann
  """
2886 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2887 7e49b6ce Michael Hanselmann
2888 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2889 7e49b6ce Michael Hanselmann
  cl = GetClient()
2890 7e49b6ce Michael Hanselmann
2891 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2892 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2893 7e49b6ce Michael Hanselmann
2894 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2895 7e49b6ce Michael Hanselmann
2896 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2897 7e49b6ce Michael Hanselmann
  del cl
2898 7e49b6ce Michael Hanselmann
2899 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2900 7e49b6ce Michael Hanselmann
2901 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2902 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2903 7e49b6ce Michael Hanselmann
2904 7e49b6ce Michael Hanselmann
2905 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2906 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2907 9fbfbb7b Iustin Pop
                  units=None):
2908 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2909 137161c9 Michael Hanselmann

2910 9fbfbb7b Iustin Pop
  @type headers: dict
2911 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2912 9fbfbb7b Iustin Pop
      the table
2913 9fbfbb7b Iustin Pop
  @type fields: list
2914 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2915 9fbfbb7b Iustin Pop
      the data field
2916 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2917 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2918 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2919 9fbfbb7b Iustin Pop
      each field
2920 9fbfbb7b Iustin Pop
  @type data: list
2921 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2922 9fbfbb7b Iustin Pop
  @type numfields: list
2923 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2924 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2925 9fbfbb7b Iustin Pop
  @type unitfields: list
2926 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2927 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2928 9fbfbb7b Iustin Pop
  @type units: string or None
2929 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2930 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2931 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2932 137161c9 Michael Hanselmann

2933 137161c9 Michael Hanselmann
  """
2934 9fbfbb7b Iustin Pop
  if units is None:
2935 9fbfbb7b Iustin Pop
    if separator:
2936 9fbfbb7b Iustin Pop
      units = "m"
2937 9fbfbb7b Iustin Pop
    else:
2938 9fbfbb7b Iustin Pop
      units = "h"
2939 9fbfbb7b Iustin Pop
2940 137161c9 Michael Hanselmann
  if numfields is None:
2941 137161c9 Michael Hanselmann
    numfields = []
2942 137161c9 Michael Hanselmann
  if unitfields is None:
2943 137161c9 Michael Hanselmann
    unitfields = []
2944 137161c9 Michael Hanselmann
2945 b459a848 Andrea Spadaccini
  numfields = utils.FieldSet(*numfields)   # pylint: disable=W0142
2946 b459a848 Andrea Spadaccini
  unitfields = utils.FieldSet(*unitfields) # pylint: disable=W0142
2947 00430f8e Iustin Pop
2948 137161c9 Michael Hanselmann
  format_fields = []
2949 137161c9 Michael Hanselmann
  for field in fields:
2950 01ca31ae Iustin Pop
    if headers and field not in headers:
2951 ea5a5b74 Guido Trotter
      # TODO: handle better unknown fields (either revert to old
2952 71c1af58 Iustin Pop
      # style of raising exception, or deal more intelligently with
2953 71c1af58 Iustin Pop
      # variable fields)
2954 71c1af58 Iustin Pop
      headers[field] = field
2955 137161c9 Michael Hanselmann
    if separator is not None:
2956 137161c9 Michael Hanselmann
      format_fields.append("%s")
2957 00430f8e Iustin Pop
    elif numfields.Matches(field):
2958 137161c9 Michael Hanselmann
      format_fields.append("%*s")
2959 137161c9 Michael Hanselmann
    else:
2960 137161c9 Michael Hanselmann
      format_fields.append("%-*s")
2961 137161c9 Michael Hanselmann
2962 137161c9 Michael Hanselmann
  if separator is None:
2963 137161c9 Michael Hanselmann
    mlens = [0 for name in fields]
2964 d0c8c01d Iustin Pop
    format_str = " ".join(format_fields)
2965 137161c9 Michael Hanselmann
  else:
2966 c04bc777 Iustin Pop
    format_str = separator.replace("%", "%%").join(format_fields)
2967 137161c9 Michael Hanselmann
2968 137161c9 Michael Hanselmann
  for row in data:
2969 dcbd6288 Guido Trotter
    if row is None:
2970 dcbd6288 Guido Trotter
      continue
2971 137161c9 Michael Hanselmann
    for idx, val in enumerate(row):
2972 00430f8e Iustin Pop
      if unitfields.Matches(fields[idx]):
2973 137161c9 Michael Hanselmann
        try:
2974 137161c9 Michael Hanselmann
          val = int(val)
2975 691744c4 Iustin Pop
        except (TypeError, ValueError):
2976 137161c9 Michael Hanselmann
          pass
2977 137161c9 Michael Hanselmann
        else:
2978 9fbfbb7b Iustin Pop
          val = row[idx] = utils.FormatUnit(val, units)
2979 01ca31ae Iustin Pop
      val = row[idx] = str(val)
2980 137161c9 Michael Hanselmann
      if separator is None:
2981 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(val))
2982 137161c9 Michael Hanselmann
2983 16be8703 Iustin Pop
  result = []
2984 137161c9 Michael Hanselmann
  if headers:
2985 137161c9 Michael Hanselmann
    args = []
2986 137161c9 Michael Hanselmann
    for idx, name in enumerate(fields):
2987 137161c9 Michael Hanselmann
      hdr = headers[name]
2988 137161c9 Michael Hanselmann
      if separator is None:
2989 137161c9 Michael Hanselmann
        mlens[idx] = max(mlens[idx], len(hdr))
2990 137161c9 Michael Hanselmann
        args.append(mlens[idx])
2991 137161c9 Michael Hanselmann
      args.append(hdr)
2992 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
2993 137161c9 Michael Hanselmann
2994 ec39d63c Michael Hanselmann
  if separator is None:
2995 ec39d63c Michael Hanselmann
    assert len(mlens) == len(fields)
2996 ec39d63c Michael Hanselmann
2997 ec39d63c Michael Hanselmann
    if fields and not numfields.Matches(fields[-1]):
2998 ec39d63c Michael Hanselmann
      mlens[-1] = 0
2999 ec39d63c Michael Hanselmann
3000 137161c9 Michael Hanselmann
  for line in data:
3001 137161c9 Michael Hanselmann
    args = []
3002 dcbd6288 Guido Trotter
    if line is None:
3003 d0c8c01d Iustin Pop
      line = ["-" for _ in fields]
3004 f1501b3f Michael Hanselmann
    for idx in range(len(fields)):
3005 137161c9 Michael Hanselmann
      if separator is None:
3006 137161c9 Michael Hanselmann
        args.append(mlens[idx])
3007 137161c9 Michael Hanselmann
      args.append(line[idx])
3008 c04bc777 Iustin Pop
    result.append(format_str % tuple(args))
3009 16be8703 Iustin Pop
3010 16be8703 Iustin Pop
  return result
3011 3386e7a9 Iustin Pop
3012 3386e7a9 Iustin Pop
3013 ee3aedff Michael Hanselmann
def _FormatBool(value):
3014 ee3aedff Michael Hanselmann
  """Formats a boolean value as a string.
3015 ee3aedff Michael Hanselmann

3016 ee3aedff Michael Hanselmann
  """
3017 ee3aedff Michael Hanselmann
  if value:
3018 ee3aedff Michael Hanselmann
    return "Y"
3019 ee3aedff Michael Hanselmann
  return "N"
3020 ee3aedff Michael Hanselmann
3021 ee3aedff Michael Hanselmann
3022 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
3023 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
3024 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
3025 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
3026 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
3027 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
3028 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
3029 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
3030 ee3aedff Michael Hanselmann
  }
3031 ee3aedff Michael Hanselmann
3032 ee3aedff Michael Hanselmann
3033 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
3034 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
3035 ee3aedff Michael Hanselmann

3036 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
3037 ee3aedff Michael Hanselmann
  @type override: dict
3038 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
3039 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3040 ee3aedff Michael Hanselmann
  @type unit: string
3041 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
3042 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
3043 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
3044 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
3045 ee3aedff Michael Hanselmann

3046 ee3aedff Michael Hanselmann
  """
3047 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
3048 ee3aedff Michael Hanselmann
  if fmt is not None:
3049 ee3aedff Michael Hanselmann
    return fmt
3050 ee3aedff Michael Hanselmann
3051 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
3052 ee3aedff Michael Hanselmann
3053 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
3054 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
3055 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
3056 ee3aedff Michael Hanselmann
3057 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
3058 ee3aedff Michael Hanselmann
  if fmt is not None:
3059 ee3aedff Michael Hanselmann
    return fmt
3060 ee3aedff Michael Hanselmann
3061 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
3062 ee3aedff Michael Hanselmann
3063 ee3aedff Michael Hanselmann
3064 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
3065 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
3066 ee3aedff Michael Hanselmann

3067 ee3aedff Michael Hanselmann
  """
3068 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
3069 ee3aedff Michael Hanselmann
    """Initializes this class.
3070 ee3aedff Michael Hanselmann

3071 ee3aedff Michael Hanselmann
    @type fn: callable
3072 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3073 ee3aedff Michael Hanselmann
    @type status_fn: callable
3074 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
3075 f0b1bafe Iustin Pop
    @type verbose: boolean
3076 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
3077 ee3aedff Michael Hanselmann

3078 ee3aedff Michael Hanselmann
    """
3079 ee3aedff Michael Hanselmann
    self._fn = fn
3080 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
3081 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
3082 ee3aedff Michael Hanselmann
3083 ee3aedff Michael Hanselmann
  def __call__(self, data):
3084 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
3085 ee3aedff Michael Hanselmann

3086 ee3aedff Michael Hanselmann
    """
3087 ee3aedff Michael Hanselmann
    (status, value) = data
3088 ee3aedff Michael Hanselmann
3089 ee3aedff Michael Hanselmann
    # Report status
3090 ee3aedff Michael Hanselmann
    self._status_fn(status)
3091 ee3aedff Michael Hanselmann
3092 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
3093 ee3aedff Michael Hanselmann
      return self._fn(value)
3094 ee3aedff Michael Hanselmann
3095 ee3aedff Michael Hanselmann
    assert value is None, \
3096 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
3097 ee3aedff Michael Hanselmann
3098 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
3099 ee3aedff Michael Hanselmann
3100 ee3aedff Michael Hanselmann
3101 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
3102 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
3103 ee3aedff Michael Hanselmann

3104 ae95e419 René Nussbaumer
  @param status: The result status
3105 f2c6673d Michael Hanselmann
  @type verbose: boolean
3106 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
3107 ae95e419 René Nussbaumer
  @return: Text of result status
3108 a6070ef7 Michael Hanselmann

3109 ae95e419 René Nussbaumer
  """
3110 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
3111 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
3112 ae95e419 René Nussbaumer
  try:
3113 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
3114 ae95e419 René Nussbaumer
  except KeyError:
3115 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
3116 cbfa4f0f Michael Hanselmann
  else:
3117 cbfa4f0f Michael Hanselmann
    if verbose:
3118 cbfa4f0f Michael Hanselmann
      return verbose_text
3119 cbfa4f0f Michael Hanselmann
    return normal_text
3120 ee3aedff Michael Hanselmann
3121 ee3aedff Michael Hanselmann
3122 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
3123 f0b1bafe Iustin Pop
                      header=False, verbose=False):
3124 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
3125 ee3aedff Michael Hanselmann

3126 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
3127 ee3aedff Michael Hanselmann
  @param result: result of query operation
3128 ee3aedff Michael Hanselmann
  @type unit: string
3129 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
3130 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
3131 ee3aedff Michael Hanselmann
  @type format_override: dict
3132 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3133 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3134 ee3aedff Michael Hanselmann
  @type separator: string or None
3135 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3136 ee3aedff Michael Hanselmann
  @type header: bool
3137 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
3138 f0b1bafe Iustin Pop
  @type verbose: boolean
3139 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3140 ee3aedff Michael Hanselmann

3141 ee3aedff Michael Hanselmann
  """
3142 ee3aedff Michael Hanselmann
  if unit is None:
3143 ee3aedff Michael Hanselmann
    if separator:
3144 ee3aedff Michael Hanselmann
      unit = "m"
3145 ee3aedff Michael Hanselmann
    else:
3146 ee3aedff Michael Hanselmann
      unit = "h"
3147 ee3aedff Michael Hanselmann
3148 ee3aedff Michael Hanselmann
  if format_override is None:
3149 ee3aedff Michael Hanselmann
    format_override = {}
3150 ee3aedff Michael Hanselmann
3151 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
3152 ee3aedff Michael Hanselmann
3153 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
3154 ee3aedff Michael Hanselmann
    if status in stats:
3155 ee3aedff Michael Hanselmann
      stats[status] += 1
3156 ee3aedff Michael Hanselmann
3157 ee3aedff Michael Hanselmann
  columns = []
3158 ee3aedff Michael Hanselmann
  for fdef in result.fields:
3159 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
3160 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
3161 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
3162 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
3163 f0b1bafe Iustin Pop
                                                     verbose),
3164 ee3aedff Michael Hanselmann
                               align_right))
3165 ee3aedff Michael Hanselmann
3166 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
3167 ee3aedff Michael Hanselmann
3168 ee3aedff Michael Hanselmann
  # Collect statistics
3169 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
3170 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
3171 ee3aedff Michael Hanselmann
3172 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
3173 ee3aedff Michael Hanselmann
  # detected via the field definitions.
3174 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
3175 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
3176 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
3177 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
3178 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
3179 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
3180 ee3aedff Michael Hanselmann
  else:
3181 ee3aedff Michael Hanselmann
    status = QR_NORMAL
3182 ee3aedff Michael Hanselmann
3183 ee3aedff Michael Hanselmann
  return (status, table)
3184 ee3aedff Michael Hanselmann
3185 ee3aedff Michael Hanselmann
3186 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
3187 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
3188 ee3aedff Michael Hanselmann

3189 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3190 ee3aedff Michael Hanselmann

3191 ee3aedff Michael Hanselmann
  """
3192 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
3193 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
3194 ee3aedff Michael Hanselmann
3195 ee3aedff Michael Hanselmann
3196 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
3197 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
3198 ee3aedff Michael Hanselmann

3199 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3200 ee3aedff Michael Hanselmann

3201 ee3aedff Michael Hanselmann
  """
3202 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
3203 ee3aedff Michael Hanselmann
  if unknown:
3204 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
3205 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
3206 ee3aedff Michael Hanselmann
    return True
3207 ee3aedff Michael Hanselmann
3208 ee3aedff Michael Hanselmann
  return False
3209 ee3aedff Michael Hanselmann
3210 ee3aedff Michael Hanselmann
3211 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
3212 03ec545a Michael Hanselmann
                format_override=None, verbose=False, force_filter=False,
3213 6f287cf3 Iustin Pop
                namefield=None, qfilter=None, isnumeric=False):
3214 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
3215 ee3aedff Michael Hanselmann

3216 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3217 ee3aedff Michael Hanselmann
  @type fields: list of strings
3218 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3219 ee3aedff Michael Hanselmann
  @type names: list of strings
3220 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
3221 ee3aedff Michael Hanselmann
  @type unit: string or None
3222 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3223 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
3224 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
3225 ee3aedff Michael Hanselmann
  @type separator: string or None
3226 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3227 ee3aedff Michael Hanselmann
  @type header: bool
3228 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3229 2928de47 Michael Hanselmann
  @type force_filter: bool
3230 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
3231 ee3aedff Michael Hanselmann
  @type format_override: dict
3232 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3233 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3234 f0b1bafe Iustin Pop
  @type verbose: boolean
3235 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3236 03ec545a Michael Hanselmann
  @type namefield: string
3237 03ec545a Michael Hanselmann
  @param namefield: Name of field to use for simple filters (see
3238 03ec545a Michael Hanselmann
    L{qlang.MakeFilter} for details)
3239 f037e9d7 Michael Hanselmann
  @type qfilter: list or None
3240 f037e9d7 Michael Hanselmann
  @param qfilter: Query filter (in addition to names)
3241 6f287cf3 Iustin Pop
  @param isnumeric: bool
3242 6f287cf3 Iustin Pop
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3243 6f287cf3 Iustin Pop
    any simple filters built by namefield should use integer values to
3244 6f287cf3 Iustin Pop
    reflect that
3245 ee3aedff Michael Hanselmann

3246 ee3aedff Michael Hanselmann
  """
3247 ee3aedff Michael Hanselmann
  if not names:
3248 ee3aedff Michael Hanselmann
    names = None
3249 ee3aedff Michael Hanselmann
3250 6f287cf3 Iustin Pop
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3251 6f287cf3 Iustin Pop
                                isnumeric=isnumeric)
3252 f037e9d7 Michael Hanselmann
3253 f037e9d7 Michael Hanselmann
  if qfilter is None:
3254 f037e9d7 Michael Hanselmann
    qfilter = namefilter
3255 f037e9d7 Michael Hanselmann
  elif namefilter is not None:
3256 f037e9d7 Michael Hanselmann
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3257 2928de47 Michael Hanselmann
3258 727274dd Iustin Pop
  if cl is None:
3259 727274dd Iustin Pop
    cl = GetClient()
3260 727274dd Iustin Pop
3261 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
3262 ee3aedff Michael Hanselmann
3263 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3264 ee3aedff Michael Hanselmann
3265 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3266 ee3aedff Michael Hanselmann
                                     header=header,
3267 f0b1bafe Iustin Pop
                                     format_override=format_override,
3268 f0b1bafe Iustin Pop
                                     verbose=verbose)
3269 ee3aedff Michael Hanselmann
3270 ee3aedff Michael Hanselmann
  for line in data:
3271 ee3aedff Michael Hanselmann
    ToStdout(line)
3272 ee3aedff Michael Hanselmann
3273 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
3274 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
3275 ee3aedff Michael Hanselmann
3276 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
3277 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3278 ee3aedff Michael Hanselmann
3279 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
3280 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3281 ee3aedff Michael Hanselmann
3282 ee3aedff Michael Hanselmann
3283 c1912a48 Michael Hanselmann
def _FieldDescValues(fdef):
3284 c1912a48 Michael Hanselmann
  """Helper function for L{GenericListFields} to get query field description.
3285 c1912a48 Michael Hanselmann

3286 c1912a48 Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
3287 c1912a48 Michael Hanselmann
  @rtype: list
3288 c1912a48 Michael Hanselmann

3289 c1912a48 Michael Hanselmann
  """
3290 c1912a48 Michael Hanselmann
  return [
3291 c1912a48 Michael Hanselmann
    fdef.name,
3292 c1912a48 Michael Hanselmann
    _QFT_NAMES.get(fdef.kind, fdef.kind),
3293 c1912a48 Michael Hanselmann
    fdef.title,
3294 c1912a48 Michael Hanselmann
    fdef.doc,
3295 c1912a48 Michael Hanselmann
    ]
3296 c1912a48 Michael Hanselmann
3297 c1912a48 Michael Hanselmann
3298 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
3299 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
3300 ee3aedff Michael Hanselmann

3301 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3302 ee3aedff Michael Hanselmann
  @type fields: list of strings
3303 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3304 ee3aedff Michael Hanselmann
  @type separator: string or None
3305 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3306 ee3aedff Michael Hanselmann
  @type header: bool
3307 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3308 ee3aedff Michael Hanselmann

3309 ee3aedff Michael Hanselmann
  """
3310 ee3aedff Michael Hanselmann
  if cl is None:
3311 ee3aedff Michael Hanselmann
    cl = GetClient()
3312 ee3aedff Michael Hanselmann
3313 ee3aedff Michael Hanselmann
  if not fields:
3314 ee3aedff Michael Hanselmann
    fields = None
3315 ee3aedff Michael Hanselmann
3316 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
3317 ee3aedff Michael Hanselmann
3318 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3319 ee3aedff Michael Hanselmann
3320 ee3aedff Michael Hanselmann
  columns = [
3321 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
3322 c1912a48 Michael Hanselmann
    TableColumn("Type", str, False),
3323 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
3324 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
3325 ee3aedff Michael Hanselmann
    ]
3326 ee3aedff Michael Hanselmann
3327 c1912a48 Michael Hanselmann
  rows = map(_FieldDescValues, response.fields)
3328 ee3aedff Michael Hanselmann
3329 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
3330 ee3aedff Michael Hanselmann
    ToStdout(line)
3331 ee3aedff Michael Hanselmann
3332 ee3aedff Michael Hanselmann
  if found_unknown:
3333 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3334 ee3aedff Michael Hanselmann
3335 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3336 ee3aedff Michael Hanselmann
3337 ee3aedff Michael Hanselmann
3338 ee3aedff Michael Hanselmann
class TableColumn:
3339 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
3340 ee3aedff Michael Hanselmann

3341 ee3aedff Michael Hanselmann
  """
3342 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
3343 ee3aedff Michael Hanselmann
    """Initializes this class.
3344 ee3aedff Michael Hanselmann

3345 ee3aedff Michael Hanselmann
    @type title: string
3346 ee3aedff Michael Hanselmann
    @param title: Column title
3347 ee3aedff Michael Hanselmann
    @type fn: callable
3348 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3349 ee3aedff Michael Hanselmann
    @type align_right: bool
3350 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
3351 ee3aedff Michael Hanselmann

3352 ee3aedff Michael Hanselmann
    """
3353 ee3aedff Michael Hanselmann
    self.title = title
3354 ee3aedff Michael Hanselmann
    self.format = fn
3355 ee3aedff Michael Hanselmann
    self.align_right = align_right
3356 ee3aedff Michael Hanselmann
3357 ee3aedff Michael Hanselmann
3358 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
3359 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
3360 ee3aedff Michael Hanselmann

3361 ee3aedff Michael Hanselmann
  """
3362 ee3aedff Michael Hanselmann
  if align_right:
3363 ee3aedff Michael Hanselmann
    sign = ""
3364 ee3aedff Michael Hanselmann
  else:
3365 ee3aedff Michael Hanselmann
    sign = "-"
3366 ee3aedff Michael Hanselmann
3367 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
3368 ee3aedff Michael Hanselmann
3369 ee3aedff Michael Hanselmann
3370 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
3371 ee3aedff Michael Hanselmann
  """Formats data as a table.
3372 ee3aedff Michael Hanselmann

3373 ee3aedff Michael Hanselmann
  @type rows: list of lists
3374 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
3375 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
3376 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
3377 ee3aedff Michael Hanselmann
  @type header: bool
3378 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3379 ee3aedff Michael Hanselmann
  @type separator: string or None
3380 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
3381 ee3aedff Michael Hanselmann

3382 ee3aedff Michael Hanselmann
  """
3383 ee3aedff Michael Hanselmann
  if header:
3384 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
3385 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
3386 ee3aedff Michael Hanselmann
  else:
3387 ee3aedff Michael Hanselmann
    data = []
3388 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
3389 ee3aedff Michael Hanselmann
3390 ee3aedff Michael Hanselmann
  # Format row data
3391 ee3aedff Michael Hanselmann
  for row in rows:
3392 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
3393 ee3aedff Michael Hanselmann
3394 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
3395 ee3aedff Michael Hanselmann
3396 ee3aedff Michael Hanselmann
    if separator is None:
3397 ee3aedff Michael Hanselmann
      # Update column widths
3398 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3399 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
3400 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
3401 ee3aedff Michael Hanselmann
3402 ee3aedff Michael Hanselmann
    data.append(formatted)
3403 ee3aedff Michael Hanselmann
3404 ee3aedff Michael Hanselmann
  if separator is not None:
3405 ee3aedff Michael Hanselmann
    # Return early if a separator is used
3406 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
3407 ee3aedff Michael Hanselmann
3408 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
3409 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
3410 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
3411 ee3aedff Michael Hanselmann
3412 ee3aedff Michael Hanselmann
  # Build format string
3413 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3414 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
3415 ee3aedff Michael Hanselmann
3416 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
3417 ee3aedff Michael Hanselmann
3418 ee3aedff Michael Hanselmann
3419 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
3420 3386e7a9 Iustin Pop
  """Formats a given timestamp.
3421 3386e7a9 Iustin Pop

3422 3386e7a9 Iustin Pop
  @type ts: timestamp
3423 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3424 3386e7a9 Iustin Pop

3425 3386e7a9 Iustin Pop
  @rtype: string
3426 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
3427 3386e7a9 Iustin Pop

3428 3386e7a9 Iustin Pop
  """
3429 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3430 d0c8c01d Iustin Pop
    return "?"
3431 26a72a48 Michael Hanselmann
3432 26a72a48 Michael Hanselmann
  (sec, usecs) = ts
3433 26a72a48 Michael Hanselmann
  return utils.FormatTime(sec, usecs=usecs)
3434 2241e2b9 Iustin Pop
3435 2241e2b9 Iustin Pop
3436 2241e2b9 Iustin Pop
def ParseTimespec(value):
3437 2241e2b9 Iustin Pop
  """Parse a time specification.
3438 2241e2b9 Iustin Pop

3439 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
3440 2241e2b9 Iustin Pop

3441 2241e2b9 Iustin Pop
    - s: seconds
3442 2241e2b9 Iustin Pop
    - m: minutes
3443 2241e2b9 Iustin Pop
    - h: hours
3444 2241e2b9 Iustin Pop
    - d: day
3445 2241e2b9 Iustin Pop
    - w: weeks
3446 2241e2b9 Iustin Pop

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

3449 2241e2b9 Iustin Pop
  """
3450 2241e2b9 Iustin Pop
  value = str(value)
3451 2241e2b9 Iustin Pop
  if not value:
3452 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed",
3453 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
3454 2241e2b9 Iustin Pop
  suffix_map = {
3455 d0c8c01d Iustin Pop
    "s": 1,
3456 d0c8c01d Iustin Pop
    "m": 60,
3457 d0c8c01d Iustin Pop
    "h": 3600,
3458 d0c8c01d Iustin Pop
    "d": 86400,
3459 d0c8c01d Iustin Pop
    "w": 604800,
3460 2241e2b9 Iustin Pop
    }
3461 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
3462 2241e2b9 Iustin Pop
    try:
3463 2241e2b9 Iustin Pop
      value = int(value)
3464 691744c4 Iustin Pop
    except (TypeError, ValueError):
3465 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3466 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3467 2241e2b9 Iustin Pop
  else:
3468 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
3469 2241e2b9 Iustin Pop
    value = value[:-1]
3470 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
3471 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
3472 2cfbc784 Iustin Pop
                                 " suffix passed)", errors.ECODE_INVAL)
3473 2241e2b9 Iustin Pop
    try:
3474 2241e2b9 Iustin Pop
      value = int(value) * multiplier
3475 691744c4 Iustin Pop
    except (TypeError, ValueError):
3476 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3477 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3478 2241e2b9 Iustin Pop
  return value
3479 46fbdd04 Iustin Pop
3480 46fbdd04 Iustin Pop
3481 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3482 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
3483 4040a784 Iustin Pop
  """Returns the names of online nodes.
3484 4040a784 Iustin Pop

3485 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
3486 4040a784 Iustin Pop
  the online nodes.
3487 4040a784 Iustin Pop

3488 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
3489 4040a784 Iustin Pop
      offline ones)
3490 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
3491 4040a784 Iustin Pop
  @type nowarn: boolean
3492 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
3493 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
3494 4040a784 Iustin Pop
      note is not displayed
3495 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
3496 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
3497 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
3498 e9e26bb3 Iustin Pop
      (if any)
3499 e9e26bb3 Iustin Pop
  @type filter_master: boolean
3500 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
3501 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
3502 e9e26bb3 Iustin Pop
      node name against the list)
3503 05484a24 Michael Hanselmann
  @type nodegroup: string
3504 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
3505 4040a784 Iustin Pop

3506 4040a784 Iustin Pop
  """
3507 4040a784 Iustin Pop
  if cl is None:
3508 4040a784 Iustin Pop
    cl = GetClient()
3509 4040a784 Iustin Pop
3510 2e5c33db Iustin Pop
  qfilter = []
3511 05484a24 Michael Hanselmann
3512 05484a24 Michael Hanselmann
  if nodes:
3513 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3514 05484a24 Michael Hanselmann
3515 05484a24 Michael Hanselmann
  if nodegroup is not None:
3516 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3517 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3518 e9e26bb3 Iustin Pop
3519 e9e26bb3 Iustin Pop
  if filter_master:
3520 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3521 05484a24 Michael Hanselmann
3522 2e5c33db Iustin Pop
  if qfilter:
3523 2e5c33db Iustin Pop
    if len(qfilter) > 1:
3524 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
3525 05484a24 Michael Hanselmann
    else:
3526 2e5c33db Iustin Pop
      assert len(qfilter) == 1
3527 2e5c33db Iustin Pop
      final_filter = qfilter[0]
3528 e9e26bb3 Iustin Pop
  else:
3529 05484a24 Michael Hanselmann
    final_filter = None
3530 05484a24 Michael Hanselmann
3531 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3532 05484a24 Michael Hanselmann
3533 05484a24 Michael Hanselmann
  def _IsOffline(row):
3534 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
3535 05484a24 Michael Hanselmann
    return offline
3536 05484a24 Michael Hanselmann
3537 05484a24 Michael Hanselmann
  def _GetName(row):
3538 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
3539 05484a24 Michael Hanselmann
    return name
3540 05484a24 Michael Hanselmann
3541 05484a24 Michael Hanselmann
  def _GetSip(row):
3542 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
3543 05484a24 Michael Hanselmann
    return sip
3544 05484a24 Michael Hanselmann
3545 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
3546 e9e26bb3 Iustin Pop
3547 4040a784 Iustin Pop
  if offline and not nowarn:
3548 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
3549 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
3550 05484a24 Michael Hanselmann
3551 05484a24 Michael Hanselmann
  if secondary_ips:
3552 05484a24 Michael Hanselmann
    fn = _GetSip
3553 05484a24 Michael Hanselmann
  else:
3554 05484a24 Michael Hanselmann
    fn = _GetName
3555 05484a24 Michael Hanselmann
3556 05484a24 Michael Hanselmann
  return map(fn, online)
3557 4040a784 Iustin Pop
3558 4040a784 Iustin Pop
3559 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3560 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3561 46fbdd04 Iustin Pop

3562 46fbdd04 Iustin Pop
  @type stream: file object
3563 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3564 46fbdd04 Iustin Pop
  @type txt: str
3565 46fbdd04 Iustin Pop
  @param txt: the message
3566 46fbdd04 Iustin Pop

3567 46fbdd04 Iustin Pop
  """
3568 225e2544 Iustin Pop
  try:
3569 225e2544 Iustin Pop
    if args:
3570 225e2544 Iustin Pop
      args = tuple(args)
3571 225e2544 Iustin Pop
      stream.write(txt % args)
3572 225e2544 Iustin Pop
    else:
3573 225e2544 Iustin Pop
      stream.write(txt)
3574 d0c8c01d Iustin Pop
    stream.write("\n")
3575 225e2544 Iustin Pop
    stream.flush()
3576 225e2544 Iustin Pop
  except IOError, err:
3577 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3578 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3579 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3580 225e2544 Iustin Pop
    else:
3581 225e2544 Iustin Pop
      raise
3582 46fbdd04 Iustin Pop
3583 46fbdd04 Iustin Pop
3584 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3585 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3586 46fbdd04 Iustin Pop

3587 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3588 46fbdd04 Iustin Pop

3589 46fbdd04 Iustin Pop
  @type txt: str
3590 46fbdd04 Iustin Pop
  @param txt: the message
3591 46fbdd04 Iustin Pop

3592 46fbdd04 Iustin Pop
  """
3593 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3594 46fbdd04 Iustin Pop
3595 46fbdd04 Iustin Pop
3596 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3597 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3598 46fbdd04 Iustin Pop

3599 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3600 46fbdd04 Iustin Pop

3601 46fbdd04 Iustin Pop
  @type txt: str
3602 46fbdd04 Iustin Pop
  @param txt: the message
3603 46fbdd04 Iustin Pop

3604 46fbdd04 Iustin Pop
  """
3605 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3606 479636a3 Iustin Pop
3607 479636a3 Iustin Pop
3608 479636a3 Iustin Pop
class JobExecutor(object):
3609 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3610 479636a3 Iustin Pop

3611 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3612 479636a3 Iustin Pop
  GetResults() calls.
3613 479636a3 Iustin Pop

3614 479636a3 Iustin Pop
  """
3615 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3616 479636a3 Iustin Pop
    self.queue = []
3617 479636a3 Iustin Pop
    if cl is None:
3618 479636a3 Iustin Pop
      cl = GetClient()
3619 479636a3 Iustin Pop
    self.cl = cl
3620 479636a3 Iustin Pop
    self.verbose = verbose
3621 23b4b983 Iustin Pop
    self.jobs = []
3622 cff5fa7f Iustin Pop
    self.opts = opts
3623 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3624 60452edf Michael Hanselmann
    self._counter = itertools.count()
3625 479636a3 Iustin Pop
3626 8d99a8bf Michael Hanselmann
  @staticmethod
3627 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3628 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3629 8d99a8bf Michael Hanselmann

3630 8d99a8bf Michael Hanselmann
    """
3631 8d99a8bf Michael Hanselmann
    if name:
3632 8d99a8bf Michael Hanselmann
      return fmt % name
3633 8d99a8bf Michael Hanselmann
3634 8d99a8bf Michael Hanselmann
    return ""
3635 8d99a8bf Michael Hanselmann
3636 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3637 23b4b983 Iustin Pop
    """Record a job for later submit.
3638 479636a3 Iustin Pop

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

3642 479636a3 Iustin Pop
    """
3643 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3644 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3645 23b4b983 Iustin Pop
3646 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3647 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3648 8d99a8bf Michael Hanselmann

3649 8d99a8bf Michael Hanselmann
    """
3650 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3651 8d99a8bf Michael Hanselmann
3652 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3653 23b4b983 Iustin Pop
    """Submit all pending jobs.
3654 23b4b983 Iustin Pop

3655 23b4b983 Iustin Pop
    """
3656 66ecc479 Guido Trotter
    if each:
3657 66ecc479 Guido Trotter
      results = []
3658 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3659 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3660 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3661 519fafa1 Andrea Spadaccini
        results.append([True, self.cl.SubmitJob(ops)[0]])
3662 66ecc479 Guido Trotter
    else:
3663 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3664 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3665 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3666 5299e61f Iustin Pop
3667 5299e61f Iustin Pop
  def _ChooseJob(self):
3668 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3669 5299e61f Iustin Pop

3670 5299e61f Iustin Pop
    """
3671 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3672 5299e61f Iustin Pop
3673 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3674 11705e3d Iustin Pop
                               ["status"])
3675 5299e61f Iustin Pop
    assert result
3676 5299e61f Iustin Pop
3677 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3678 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3679 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3680 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3681 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3682 91c622a8 Iustin Pop
        # job is still present and waiting
3683 5299e61f Iustin Pop
        continue
3684 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3685 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3686 5299e61f Iustin Pop
      return job_data
3687 5299e61f Iustin Pop
3688 5299e61f Iustin Pop
    # no job found
3689 5299e61f Iustin Pop
    return self.jobs.pop(0)
3690 479636a3 Iustin Pop
3691 479636a3 Iustin Pop
  def GetResults(self):
3692 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3693 479636a3 Iustin Pop

3694 479636a3 Iustin Pop
    @rtype: list
3695 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3696 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3697 479636a3 Iustin Pop
        there will be the error message
3698 479636a3 Iustin Pop

3699 479636a3 Iustin Pop
    """
3700 23b4b983 Iustin Pop
    if not self.jobs:
3701 23b4b983 Iustin Pop
      self.SubmitPending()
3702 479636a3 Iustin Pop
    results = []
3703 479636a3 Iustin Pop
    if self.verbose:
3704 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3705 23b4b983 Iustin Pop
      if ok_jobs:
3706 4474f112 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3707 5299e61f Iustin Pop
3708 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
3709 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3710 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
3711 4474f112 Iustin Pop
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3712 c63355f2 Iustin Pop
      results.append((idx, False, jid))
3713 5299e61f Iustin Pop
3714 5299e61f Iustin Pop
    while self.jobs:
3715 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
3716 4474f112 Iustin Pop
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3717 479636a3 Iustin Pop
      try:
3718 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3719 479636a3 Iustin Pop
        success = True
3720 91c622a8 Iustin Pop
      except errors.JobLost, err:
3721 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3722 4474f112 Iustin Pop
        ToStderr("Job %s%s has been archived, cannot check its result",
3723 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"))
3724 91c622a8 Iustin Pop
        success = False
3725 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3726 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3727 479636a3 Iustin Pop
        success = False
3728 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3729 4474f112 Iustin Pop
        ToStderr("Job %s%s has failed: %s",
3730 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"), job_result)
3731 479636a3 Iustin Pop
3732 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3733 5299e61f Iustin Pop
3734 5299e61f Iustin Pop
    # sort based on the index, then drop it
3735 5299e61f Iustin Pop
    results.sort()
3736 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3737 5299e61f Iustin Pop
3738 479636a3 Iustin Pop
    return results
3739 479636a3 Iustin Pop
3740 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3741 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3742 479636a3 Iustin Pop

3743 479636a3 Iustin Pop
    @type wait: boolean
3744 479636a3 Iustin Pop
    @param wait: whether to wait or not
3745 479636a3 Iustin Pop

3746 479636a3 Iustin Pop
    """
3747 479636a3 Iustin Pop
    if wait:
3748 479636a3 Iustin Pop
      return self.GetResults()
3749 479636a3 Iustin Pop
    else:
3750 23b4b983 Iustin Pop
      if not self.jobs:
3751 23b4b983 Iustin Pop
        self.SubmitPending()
3752 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3753 23b4b983 Iustin Pop
        if status:
3754 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3755 23b4b983 Iustin Pop
        else:
3756 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3757 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3758 acd19189 René Nussbaumer
3759 acd19189 René Nussbaumer
3760 4d99964c Bernardo Dal Seno
def FormatParamsDictInfo(param_dict, actual):
3761 4d99964c Bernardo Dal Seno
  """Formats a parameter dictionary.
3762 4d99964c Bernardo Dal Seno

3763 4d99964c Bernardo Dal Seno
  @type param_dict: dict
3764 4d99964c Bernardo Dal Seno
  @param param_dict: the own parameters
3765 4d99964c Bernardo Dal Seno
  @type actual: dict
3766 4d99964c Bernardo Dal Seno
  @param actual: the current parameter set (including defaults)
3767 4d99964c Bernardo Dal Seno
  @rtype: dict
3768 4d99964c Bernardo Dal Seno
  @return: dictionary where the value of each parameter is either a fully
3769 4d99964c Bernardo Dal Seno
      formatted string or a dictionary containing formatted strings
3770 4d99964c Bernardo Dal Seno

3771 4d99964c Bernardo Dal Seno
  """
3772 4d99964c Bernardo Dal Seno
  ret = {}
3773 4d99964c Bernardo Dal Seno
  for (key, data) in actual.items():
3774 4d99964c Bernardo Dal Seno
    if isinstance(data, dict) and data:
3775 4d99964c Bernardo Dal Seno
      ret[key] = FormatParamsDictInfo(param_dict.get(key, {}), data)
3776 4d99964c Bernardo Dal Seno
    else:
3777 4d99964c Bernardo Dal Seno
      ret[key] = str(param_dict.get(key, "default (%s)" % data))
3778 4d99964c Bernardo Dal Seno
  return ret
3779 4d99964c Bernardo Dal Seno
3780 4d99964c Bernardo Dal Seno
3781 d00884a2 Bernardo Dal Seno
def _FormatListInfoDefault(data, def_data):
3782 d00884a2 Bernardo Dal Seno
  if data is not None:
3783 d00884a2 Bernardo Dal Seno
    ret = utils.CommaJoin(data)
3784 d00884a2 Bernardo Dal Seno
  else:
3785 d00884a2 Bernardo Dal Seno
    ret = "default (%s)" % utils.CommaJoin(def_data)
3786 d00884a2 Bernardo Dal Seno
  return ret
3787 d00884a2 Bernardo Dal Seno
3788 d00884a2 Bernardo Dal Seno
3789 d00884a2 Bernardo Dal Seno
def FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster):
3790 d00884a2 Bernardo Dal Seno
  """Formats an instance policy.
3791 d00884a2 Bernardo Dal Seno

3792 d00884a2 Bernardo Dal Seno
  @type custom_ipolicy: dict
3793 d00884a2 Bernardo Dal Seno
  @param custom_ipolicy: own policy
3794 d00884a2 Bernardo Dal Seno
  @type eff_ipolicy: dict
3795 d00884a2 Bernardo Dal Seno
  @param eff_ipolicy: effective policy (including defaults); ignored for
3796 d00884a2 Bernardo Dal Seno
      cluster
3797 d00884a2 Bernardo Dal Seno
  @type iscluster: bool
3798 d00884a2 Bernardo Dal Seno
  @param iscluster: the policy is at cluster level
3799 d00884a2 Bernardo Dal Seno
  @rtype: list of pairs
3800 d00884a2 Bernardo Dal Seno
  @return: formatted data, suitable for L{PrintGenericInfo}
3801 d00884a2 Bernardo Dal Seno

3802 d00884a2 Bernardo Dal Seno
  """
3803 d00884a2 Bernardo Dal Seno
  if iscluster:
3804 d00884a2 Bernardo Dal Seno
    eff_ipolicy = custom_ipolicy
3805 d00884a2 Bernardo Dal Seno
3806 41044e04 Bernardo Dal Seno
  minmax_out = []
3807 41044e04 Bernardo Dal Seno
  custom_minmax = custom_ipolicy.get(constants.ISPECS_MINMAX)
3808 41044e04 Bernardo Dal Seno
  if custom_minmax:
3809 41044e04 Bernardo Dal Seno
    for (k, minmax) in enumerate(custom_minmax):
3810 41044e04 Bernardo Dal Seno
      minmax_out.append([
3811 41044e04 Bernardo Dal Seno
        ("%s/%s" % (key, k),
3812 41044e04 Bernardo Dal Seno
         FormatParamsDictInfo(minmax[key], minmax[key]))
3813 41044e04 Bernardo Dal Seno
        for key in constants.ISPECS_MINMAX_KEYS
3814 41044e04 Bernardo Dal Seno
        ])
3815 41044e04 Bernardo Dal Seno
  else:
3816 41044e04 Bernardo Dal Seno
    for (k, minmax) in enumerate(eff_ipolicy[constants.ISPECS_MINMAX]):
3817 41044e04 Bernardo Dal Seno
      minmax_out.append([
3818 41044e04 Bernardo Dal Seno
        ("%s/%s" % (key, k),
3819 41044e04 Bernardo Dal Seno
         FormatParamsDictInfo({}, minmax[key]))
3820 41044e04 Bernardo Dal Seno
        for key in constants.ISPECS_MINMAX_KEYS
3821 41044e04 Bernardo Dal Seno
        ])
3822 41044e04 Bernardo Dal Seno
  ret = [("bounds specs", minmax_out)]
3823 41044e04 Bernardo Dal Seno
3824 d00884a2 Bernardo Dal Seno
  if iscluster:
3825 d00884a2 Bernardo Dal Seno
    stdspecs = custom_ipolicy[constants.ISPECS_STD]
3826 d00884a2 Bernardo Dal Seno
    ret.append(
3827 d00884a2 Bernardo Dal Seno
      (constants.ISPECS_STD,
3828 d00884a2 Bernardo Dal Seno
       FormatParamsDictInfo(stdspecs, stdspecs))
3829 d00884a2 Bernardo Dal Seno
      )
3830 d00884a2 Bernardo Dal Seno
3831 d00884a2 Bernardo Dal Seno
  ret.append(
3832 9db0b351 Bernardo Dal Seno
    ("allowed disk templates",
3833 d00884a2 Bernardo Dal Seno
     _FormatListInfoDefault(custom_ipolicy.get(constants.IPOLICY_DTS),
3834 d00884a2 Bernardo Dal Seno
                            eff_ipolicy[constants.IPOLICY_DTS]))
3835 d00884a2 Bernardo Dal Seno
    )
3836 d00884a2 Bernardo Dal Seno
  ret.extend([
3837 d00884a2 Bernardo Dal Seno
    (key, str(custom_ipolicy.get(key, "default (%s)" % eff_ipolicy[key])))
3838 d00884a2 Bernardo Dal Seno
    for key in constants.IPOLICY_PARAMETERS
3839 d00884a2 Bernardo Dal Seno
    ])
3840 d00884a2 Bernardo Dal Seno
  return ret
3841 d00884a2 Bernardo Dal Seno
3842 d00884a2 Bernardo Dal Seno
3843 ea9d3b40 Bernardo Dal Seno
def _PrintSpecsParameters(buf, specs):
3844 ea9d3b40 Bernardo Dal Seno
  values = ("%s=%s" % (par, val) for (par, val) in sorted(specs.items()))
3845 ea9d3b40 Bernardo Dal Seno
  buf.write(",".join(values))
3846 ea9d3b40 Bernardo Dal Seno
3847 ea9d3b40 Bernardo Dal Seno
3848 ea9d3b40 Bernardo Dal Seno
def PrintIPolicyCommand(buf, ipolicy, isgroup):
3849 ea9d3b40 Bernardo Dal Seno
  """Print the command option used to generate the given instance policy.
3850 ea9d3b40 Bernardo Dal Seno

3851 ea9d3b40 Bernardo Dal Seno
  Currently only the parts dealing with specs are supported.
3852 ea9d3b40 Bernardo Dal Seno

3853 ea9d3b40 Bernardo Dal Seno
  @type buf: StringIO
3854 ea9d3b40 Bernardo Dal Seno
  @param buf: stream to write into
3855 ea9d3b40 Bernardo Dal Seno
  @type ipolicy: dict
3856 ea9d3b40 Bernardo Dal Seno
  @param ipolicy: instance policy
3857 ea9d3b40 Bernardo Dal Seno
  @type isgroup: bool
3858 ea9d3b40 Bernardo Dal Seno
  @param isgroup: whether the policy is at group level
3859 ea9d3b40 Bernardo Dal Seno

3860 ea9d3b40 Bernardo Dal Seno
  """
3861 ea9d3b40 Bernardo Dal Seno
  if not isgroup:
3862 ea9d3b40 Bernardo Dal Seno
    stdspecs = ipolicy.get("std")
3863 ea9d3b40 Bernardo Dal Seno
    if stdspecs:
3864 ea9d3b40 Bernardo Dal Seno
      buf.write(" %s " % IPOLICY_STD_SPECS_STR)
3865 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, stdspecs)
3866 ef99e3e8 Bernardo Dal Seno
  minmaxes = ipolicy.get("minmax", [])
3867 ef99e3e8 Bernardo Dal Seno
  first = True
3868 ef99e3e8 Bernardo Dal Seno
  for minmax in minmaxes:
3869 ef99e3e8 Bernardo Dal Seno
    minspecs = minmax.get("min")
3870 ef99e3e8 Bernardo Dal Seno
    maxspecs = minmax.get("max")
3871 ea9d3b40 Bernardo Dal Seno
    if minspecs and maxspecs:
3872 ef99e3e8 Bernardo Dal Seno
      if first:
3873 ef99e3e8 Bernardo Dal Seno
        buf.write(" %s " % IPOLICY_BOUNDS_SPECS_STR)
3874 ef99e3e8 Bernardo Dal Seno
        first = False
3875 ef99e3e8 Bernardo Dal Seno
      else:
3876 ef99e3e8 Bernardo Dal Seno
        buf.write("//")
3877 ea9d3b40 Bernardo Dal Seno
      buf.write("min:")
3878 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, minspecs)
3879 ea9d3b40 Bernardo Dal Seno
      buf.write("/max:")
3880 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, maxspecs)
3881 ea9d3b40 Bernardo Dal Seno
3882 ea9d3b40 Bernardo Dal Seno
3883 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3884 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3885 25bd815c René Nussbaumer

3886 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3887 25bd815c René Nussbaumer
  on a given list of list_type.
3888 25bd815c René Nussbaumer

3889 25bd815c René Nussbaumer
  @type names: list
3890 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3891 25bd815c René Nussbaumer
      we ask for confirmation
3892 25bd815c René Nussbaumer
  @type list_type: str
3893 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3894 25bd815c René Nussbaumer
  @type text: str
3895 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3896 25bd815c René Nussbaumer
  @rtype: boolean
3897 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3898 25bd815c René Nussbaumer

3899 25bd815c René Nussbaumer
  """
3900 25bd815c René Nussbaumer
  count = len(names)
3901 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3902 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3903 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3904 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3905 25bd815c René Nussbaumer
3906 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3907 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3908 25bd815c René Nussbaumer
3909 25bd815c René Nussbaumer
  if count > 20:
3910 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3911 25bd815c René Nussbaumer
    question = msg
3912 25bd815c René Nussbaumer
  else:
3913 25bd815c René Nussbaumer
    question = msg + affected
3914 25bd815c René Nussbaumer
3915 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3916 25bd815c René Nussbaumer
  if choice == "v":
3917 25bd815c René Nussbaumer
    choices.pop(1)
3918 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3919 25bd815c René Nussbaumer
  return choice
3920 703fa9ab Iustin Pop
3921 703fa9ab Iustin Pop
3922 cd415612 René Nussbaumer
def _MaybeParseUnit(elements):
3923 cd415612 René Nussbaumer
  """Parses and returns an array of potential values with units.
3924 cd415612 René Nussbaumer

3925 cd415612 René Nussbaumer
  """
3926 ef40c537 René Nussbaumer
  parsed = {}
3927 ef40c537 René Nussbaumer
  for k, v in elements.items():
3928 ef40c537 René Nussbaumer
    if v == constants.VALUE_DEFAULT:
3929 ef40c537 René Nussbaumer
      parsed[k] = v
3930 cd415612 René Nussbaumer
    else:
3931 ef40c537 René Nussbaumer
      parsed[k] = utils.ParseUnit(v)
3932 cd415612 René Nussbaumer
  return parsed
3933 cd415612 René Nussbaumer
3934 cd415612 René Nussbaumer
3935 d2d3935a Bernardo Dal Seno
def _InitISpecsFromSplitOpts(ipolicy, ispecs_mem_size, ispecs_cpu_count,
3936 d2d3935a Bernardo Dal Seno
                             ispecs_disk_count, ispecs_disk_size,
3937 919db916 Bernardo Dal Seno
                             ispecs_nic_count, group_ipolicy, fill_all):
3938 d67e0a94 Iustin Pop
  try:
3939 d67e0a94 Iustin Pop
    if ispecs_mem_size:
3940 cd415612 René Nussbaumer
      ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
3941 d67e0a94 Iustin Pop
    if ispecs_disk_size:
3942 cd415612 René Nussbaumer
      ispecs_disk_size = _MaybeParseUnit(ispecs_disk_size)
3943 d67e0a94 Iustin Pop
  except (TypeError, ValueError, errors.UnitParseError), err:
3944 d67e0a94 Iustin Pop
    raise errors.OpPrereqError("Invalid disk (%s) or memory (%s) size"
3945 d67e0a94 Iustin Pop
                               " in policy: %s" %
3946 d67e0a94 Iustin Pop
                               (ispecs_disk_size, ispecs_mem_size, err),
3947 d67e0a94 Iustin Pop
                               errors.ECODE_INVAL)
3948 d67e0a94 Iustin Pop
3949 703fa9ab Iustin Pop
  # prepare ipolicy dict
3950 d948c101 Bernardo Dal Seno
  ispecs_transposed = {
3951 703fa9ab Iustin Pop
    constants.ISPEC_MEM_SIZE: ispecs_mem_size,
3952 703fa9ab Iustin Pop
    constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
3953 703fa9ab Iustin Pop
    constants.ISPEC_DISK_COUNT: ispecs_disk_count,
3954 703fa9ab Iustin Pop
    constants.ISPEC_DISK_SIZE: ispecs_disk_size,
3955 703fa9ab Iustin Pop
    constants.ISPEC_NIC_COUNT: ispecs_nic_count,
3956 703fa9ab Iustin Pop
    }
3957 703fa9ab Iustin Pop
3958 703fa9ab Iustin Pop
  # first, check that the values given are correct
3959 703fa9ab Iustin Pop
  if group_ipolicy:
3960 703fa9ab Iustin Pop
    forced_type = TISPECS_GROUP_TYPES
3961 703fa9ab Iustin Pop
  else:
3962 703fa9ab Iustin Pop
    forced_type = TISPECS_CLUSTER_TYPES
3963 d948c101 Bernardo Dal Seno
  for specs in ispecs_transposed.values():
3964 d2d3935a Bernardo Dal Seno
    assert type(specs) is dict
3965 919db916 Bernardo Dal Seno
    utils.ForceDictType(specs, forced_type)
3966 703fa9ab Iustin Pop
3967 703fa9ab Iustin Pop
  # then transpose
3968 da5f09ef Bernardo Dal Seno
  ispecs = {
3969 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MIN: {},
3970 da5f09ef Bernardo Dal Seno
    constants.ISPECS_MAX: {},
3971 da5f09ef Bernardo Dal Seno
    constants.ISPECS_STD: {},
3972 da5f09ef Bernardo Dal Seno
    }
3973 d948c101 Bernardo Dal Seno
  for (name, specs) in ispecs_transposed.iteritems():
3974 703fa9ab Iustin Pop
    assert name in constants.ISPECS_PARAMETERS
3975 703fa9ab Iustin Pop
    for key, val in specs.items(): # {min: .. ,max: .., std: ..}
3976 da5f09ef Bernardo Dal Seno
      assert key in ispecs
3977 da5f09ef Bernardo Dal Seno
      ispecs[key][name] = val
3978 41044e04 Bernardo Dal Seno
  minmax_out = {}
3979 da5f09ef Bernardo Dal Seno
  for key in constants.ISPECS_MINMAX_KEYS:
3980 919db916 Bernardo Dal Seno
    if fill_all:
3981 41044e04 Bernardo Dal Seno
      minmax_out[key] = \
3982 919db916 Bernardo Dal Seno
        objects.FillDict(constants.ISPECS_MINMAX_DEFAULTS[key], ispecs[key])
3983 919db916 Bernardo Dal Seno
    else:
3984 41044e04 Bernardo Dal Seno
      minmax_out[key] = ispecs[key]
3985 41044e04 Bernardo Dal Seno
  ipolicy[constants.ISPECS_MINMAX] = [minmax_out]
3986 919db916 Bernardo Dal Seno
  if fill_all:
3987 919db916 Bernardo Dal Seno
    ipolicy[constants.ISPECS_STD] = \
3988 919db916 Bernardo Dal Seno
        objects.FillDict(constants.IPOLICY_DEFAULTS[constants.ISPECS_STD],
3989 919db916 Bernardo Dal Seno
                         ispecs[constants.ISPECS_STD])
3990 919db916 Bernardo Dal Seno
  else:
3991 919db916 Bernardo Dal Seno
    ipolicy[constants.ISPECS_STD] = ispecs[constants.ISPECS_STD]
3992 d948c101 Bernardo Dal Seno
3993 d948c101 Bernardo Dal Seno
3994 d2d3935a Bernardo Dal Seno
def _ParseSpecUnit(spec, keyname):
3995 d2d3935a Bernardo Dal Seno
  ret = spec.copy()
3996 d2d3935a Bernardo Dal Seno
  for k in [constants.ISPEC_DISK_SIZE, constants.ISPEC_MEM_SIZE]:
3997 919db916 Bernardo Dal Seno
    if k in ret:
3998 d2d3935a Bernardo Dal Seno
      try:
3999 d2d3935a Bernardo Dal Seno
        ret[k] = utils.ParseUnit(ret[k])
4000 d2d3935a Bernardo Dal Seno
      except (TypeError, ValueError, errors.UnitParseError), err:
4001 d2d3935a Bernardo Dal Seno
        raise errors.OpPrereqError(("Invalid parameter %s (%s) in %s instance"
4002 d2d3935a Bernardo Dal Seno
                                    " specs: %s" % (k, ret[k], keyname, err)),
4003 d2d3935a Bernardo Dal Seno
                                   errors.ECODE_INVAL)
4004 d2d3935a Bernardo Dal Seno
  return ret
4005 d2d3935a Bernardo Dal Seno
4006 d2d3935a Bernardo Dal Seno
4007 919db916 Bernardo Dal Seno
def _ParseISpec(spec, keyname, required):
4008 d2d3935a Bernardo Dal Seno
  ret = _ParseSpecUnit(spec, keyname)
4009 919db916 Bernardo Dal Seno
  utils.ForceDictType(ret, constants.ISPECS_PARAMETER_TYPES)
4010 919db916 Bernardo Dal Seno
  missing = constants.ISPECS_PARAMETERS - frozenset(ret.keys())
4011 919db916 Bernardo Dal Seno
  if required and missing:
4012 919db916 Bernardo Dal Seno
    raise errors.OpPrereqError("Missing parameters in ipolicy spec %s: %s" %
4013 919db916 Bernardo Dal Seno
                               (keyname, utils.CommaJoin(missing)),
4014 919db916 Bernardo Dal Seno
                               errors.ECODE_INVAL)
4015 919db916 Bernardo Dal Seno
  return ret
4016 919db916 Bernardo Dal Seno
4017 919db916 Bernardo Dal Seno
4018 919db916 Bernardo Dal Seno
def _GetISpecsInAllowedValues(minmax_ispecs, allowed_values):
4019 919db916 Bernardo Dal Seno
  ret = None
4020 ef99e3e8 Bernardo Dal Seno
  if (minmax_ispecs and allowed_values and len(minmax_ispecs) == 1 and
4021 ef99e3e8 Bernardo Dal Seno
      len(minmax_ispecs[0]) == 1):
4022 ef99e3e8 Bernardo Dal Seno
    for (key, spec) in minmax_ispecs[0].items():
4023 919db916 Bernardo Dal Seno
      # This loop is executed exactly once
4024 919db916 Bernardo Dal Seno
      if key in allowed_values and not spec:
4025 919db916 Bernardo Dal Seno
        ret = key
4026 d2d3935a Bernardo Dal Seno
  return ret
4027 d2d3935a Bernardo Dal Seno
4028 d2d3935a Bernardo Dal Seno
4029 d2d3935a Bernardo Dal Seno
def _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
4030 d2d3935a Bernardo Dal Seno
                            group_ipolicy, allowed_values):
4031 919db916 Bernardo Dal Seno
  found_allowed = _GetISpecsInAllowedValues(minmax_ispecs, allowed_values)
4032 919db916 Bernardo Dal Seno
  if found_allowed is not None:
4033 919db916 Bernardo Dal Seno
    ipolicy_out[constants.ISPECS_MINMAX] = found_allowed
4034 919db916 Bernardo Dal Seno
  elif minmax_ispecs is not None:
4035 ef99e3e8 Bernardo Dal Seno
    minmax_out = []
4036 ef99e3e8 Bernardo Dal Seno
    for mmpair in minmax_ispecs:
4037 ef99e3e8 Bernardo Dal Seno
      mmpair_out = {}
4038 ef99e3e8 Bernardo Dal Seno
      for (key, spec) in mmpair.items():
4039 ef99e3e8 Bernardo Dal Seno
        if key not in constants.ISPECS_MINMAX_KEYS:
4040 ef99e3e8 Bernardo Dal Seno
          msg = "Invalid key in bounds instance specifications: %s" % key
4041 ef99e3e8 Bernardo Dal Seno
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
4042 ef99e3e8 Bernardo Dal Seno
        mmpair_out[key] = _ParseISpec(spec, key, True)
4043 ef99e3e8 Bernardo Dal Seno
      minmax_out.append(mmpair_out)
4044 ef99e3e8 Bernardo Dal Seno
    ipolicy_out[constants.ISPECS_MINMAX] = minmax_out
4045 d2d3935a Bernardo Dal Seno
  if std_ispecs is not None:
4046 d2d3935a Bernardo Dal Seno
    assert not group_ipolicy # This is not an option for gnt-group
4047 919db916 Bernardo Dal Seno
    ipolicy_out[constants.ISPECS_STD] = _ParseISpec(std_ispecs, "std", False)
4048 d2d3935a Bernardo Dal Seno
4049 d2d3935a Bernardo Dal Seno
4050 d948c101 Bernardo Dal Seno
def CreateIPolicyFromOpts(ispecs_mem_size=None,
4051 d948c101 Bernardo Dal Seno
                          ispecs_cpu_count=None,
4052 d948c101 Bernardo Dal Seno
                          ispecs_disk_count=None,
4053 d948c101 Bernardo Dal Seno
                          ispecs_disk_size=None,
4054 d948c101 Bernardo Dal Seno
                          ispecs_nic_count=None,
4055 d2d3935a Bernardo Dal Seno
                          minmax_ispecs=None,
4056 d2d3935a Bernardo Dal Seno
                          std_ispecs=None,
4057 d948c101 Bernardo Dal Seno
                          ipolicy_disk_templates=None,
4058 d948c101 Bernardo Dal Seno
                          ipolicy_vcpu_ratio=None,
4059 d948c101 Bernardo Dal Seno
                          ipolicy_spindle_ratio=None,
4060 d948c101 Bernardo Dal Seno
                          group_ipolicy=False,
4061 d948c101 Bernardo Dal Seno
                          allowed_values=None,
4062 d948c101 Bernardo Dal Seno
                          fill_all=False):
4063 d948c101 Bernardo Dal Seno
  """Creation of instance policy based on command line options.
4064 d948c101 Bernardo Dal Seno

4065 d948c101 Bernardo Dal Seno
  @param fill_all: whether for cluster policies we should ensure that
4066 d948c101 Bernardo Dal Seno
    all values are filled
4067 d948c101 Bernardo Dal Seno

4068 d948c101 Bernardo Dal Seno
  """
4069 919db916 Bernardo Dal Seno
  assert not (fill_all and allowed_values)
4070 919db916 Bernardo Dal Seno
4071 919db916 Bernardo Dal Seno
  split_specs = (ispecs_mem_size or ispecs_cpu_count or ispecs_disk_count or
4072 919db916 Bernardo Dal Seno
                 ispecs_disk_size or ispecs_nic_count)
4073 919db916 Bernardo Dal Seno
  if (split_specs and (minmax_ispecs is not None or std_ispecs is not None)):
4074 d2d3935a Bernardo Dal Seno
    raise errors.OpPrereqError("A --specs-xxx option cannot be specified"
4075 d2d3935a Bernardo Dal Seno
                               " together with any --ipolicy-xxx-specs option",
4076 d2d3935a Bernardo Dal Seno
                               errors.ECODE_INVAL)
4077 d948c101 Bernardo Dal Seno
4078 d948c101 Bernardo Dal Seno
  ipolicy_out = objects.MakeEmptyIPolicy()
4079 919db916 Bernardo Dal Seno
  if split_specs:
4080 919db916 Bernardo Dal Seno
    assert fill_all
4081 d2d3935a Bernardo Dal Seno
    _InitISpecsFromSplitOpts(ipolicy_out, ispecs_mem_size, ispecs_cpu_count,
4082 d2d3935a Bernardo Dal Seno
                             ispecs_disk_count, ispecs_disk_size,
4083 919db916 Bernardo Dal Seno
                             ispecs_nic_count, group_ipolicy, fill_all)
4084 919db916 Bernardo Dal Seno
  elif (minmax_ispecs is not None or std_ispecs is not None):
4085 d2d3935a Bernardo Dal Seno
    _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
4086 d2d3935a Bernardo Dal Seno
                            group_ipolicy, allowed_values)
4087 703fa9ab Iustin Pop
4088 703fa9ab Iustin Pop
  if ipolicy_disk_templates is not None:
4089 f824ae42 Bernardo Dal Seno
    if allowed_values and ipolicy_disk_templates in allowed_values:
4090 f824ae42 Bernardo Dal Seno
      ipolicy_out[constants.IPOLICY_DTS] = ipolicy_disk_templates
4091 f824ae42 Bernardo Dal Seno
    else:
4092 f824ae42 Bernardo Dal Seno
      ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
4093 703fa9ab Iustin Pop
  if ipolicy_vcpu_ratio is not None:
4094 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
4095 ad5cc6bd René Nussbaumer
  if ipolicy_spindle_ratio is not None:
4096 ad5cc6bd René Nussbaumer
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
4097 703fa9ab Iustin Pop
4098 703fa9ab Iustin Pop
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
4099 703fa9ab Iustin Pop
4100 eeaa5f6c Bernardo Dal Seno
  if not group_ipolicy and fill_all:
4101 eeaa5f6c Bernardo Dal Seno
    ipolicy_out = objects.FillIPolicy(constants.IPOLICY_DEFAULTS, ipolicy_out)
4102 eeaa5f6c Bernardo Dal Seno
4103 703fa9ab Iustin Pop
  return ipolicy_out
4104 4d99964c Bernardo Dal Seno
4105 4d99964c Bernardo Dal Seno
4106 4d99964c Bernardo Dal Seno
def _SerializeGenericInfo(buf, data, level, afterkey=False):
4107 4d99964c Bernardo Dal Seno
  """Formatting core of L{PrintGenericInfo}.
4108 4d99964c Bernardo Dal Seno

4109 4d99964c Bernardo Dal Seno
  @param buf: (string) stream to accumulate the result into
4110 4d99964c Bernardo Dal Seno
  @param data: data to format
4111 4d99964c Bernardo Dal Seno
  @type level: int
4112 4d99964c Bernardo Dal Seno
  @param level: depth in the data hierarchy, used for indenting
4113 4d99964c Bernardo Dal Seno
  @type afterkey: bool
4114 4d99964c Bernardo Dal Seno
  @param afterkey: True when we are in the middle of a line after a key (used
4115 4d99964c Bernardo Dal Seno
      to properly add newlines or indentation)
4116 4d99964c Bernardo Dal Seno

4117 4d99964c Bernardo Dal Seno
  """
4118 4d99964c Bernardo Dal Seno
  baseind = "  "
4119 4d99964c Bernardo Dal Seno
  if isinstance(data, dict):
4120 4d99964c Bernardo Dal Seno
    if not data:
4121 4d99964c Bernardo Dal Seno
      buf.write("\n")
4122 4d99964c Bernardo Dal Seno
    else:
4123 4d99964c Bernardo Dal Seno
      if afterkey:
4124 4d99964c Bernardo Dal Seno
        buf.write("\n")
4125 4d99964c Bernardo Dal Seno
        doindent = True
4126 4d99964c Bernardo Dal Seno
      else:
4127 4d99964c Bernardo Dal Seno
        doindent = False
4128 4d99964c Bernardo Dal Seno
      for key in sorted(data):
4129 4d99964c Bernardo Dal Seno
        if doindent:
4130 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
4131 4d99964c Bernardo Dal Seno
        else:
4132 4d99964c Bernardo Dal Seno
          doindent = True
4133 4d99964c Bernardo Dal Seno
        buf.write(key)
4134 4d99964c Bernardo Dal Seno
        buf.write(": ")
4135 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, data[key], level + 1, afterkey=True)
4136 4d99964c Bernardo Dal Seno
  elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], tuple):
4137 4d99964c Bernardo Dal Seno
    # list of tuples (an ordered dictionary)
4138 4d99964c Bernardo Dal Seno
    if afterkey:
4139 4d99964c Bernardo Dal Seno
      buf.write("\n")
4140 4d99964c Bernardo Dal Seno
      doindent = True
4141 4d99964c Bernardo Dal Seno
    else:
4142 4d99964c Bernardo Dal Seno
      doindent = False
4143 4d99964c Bernardo Dal Seno
    for (key, val) in data:
4144 4d99964c Bernardo Dal Seno
      if doindent:
4145 4d99964c Bernardo Dal Seno
        buf.write(baseind * level)
4146 4d99964c Bernardo Dal Seno
      else:
4147 4d99964c Bernardo Dal Seno
        doindent = True
4148 4d99964c Bernardo Dal Seno
      buf.write(key)
4149 4d99964c Bernardo Dal Seno
      buf.write(": ")
4150 4d99964c Bernardo Dal Seno
      _SerializeGenericInfo(buf, val, level + 1, afterkey=True)
4151 4d99964c Bernardo Dal Seno
  elif isinstance(data, list):
4152 4d99964c Bernardo Dal Seno
    if not data:
4153 4d99964c Bernardo Dal Seno
      buf.write("\n")
4154 4d99964c Bernardo Dal Seno
    else:
4155 4d99964c Bernardo Dal Seno
      if afterkey:
4156 4d99964c Bernardo Dal Seno
        buf.write("\n")
4157 4d99964c Bernardo Dal Seno
        doindent = True
4158 4d99964c Bernardo Dal Seno
      else:
4159 4d99964c Bernardo Dal Seno
        doindent = False
4160 4d99964c Bernardo Dal Seno
      for item in data:
4161 4d99964c Bernardo Dal Seno
        if doindent:
4162 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
4163 4d99964c Bernardo Dal Seno
        else:
4164 4d99964c Bernardo Dal Seno
          doindent = True
4165 4d99964c Bernardo Dal Seno
        buf.write("-")
4166 4d99964c Bernardo Dal Seno
        buf.write(baseind[1:])
4167 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, item, level + 1)
4168 4d99964c Bernardo Dal Seno
  else:
4169 4d99964c Bernardo Dal Seno
    # This branch should be only taken for strings, but it's practically
4170 4d99964c Bernardo Dal Seno
    # impossible to guarantee that no other types are produced somewhere
4171 4d99964c Bernardo Dal Seno
    buf.write(str(data))
4172 4d99964c Bernardo Dal Seno
    buf.write("\n")
4173 4d99964c Bernardo Dal Seno
4174 4d99964c Bernardo Dal Seno
4175 4d99964c Bernardo Dal Seno
def PrintGenericInfo(data):
4176 4d99964c Bernardo Dal Seno
  """Print information formatted according to the hierarchy.
4177 4d99964c Bernardo Dal Seno

4178 4d99964c Bernardo Dal Seno
  The output is a valid YAML string.
4179 4d99964c Bernardo Dal Seno

4180 4d99964c Bernardo Dal Seno
  @param data: the data to print. It's a hierarchical structure whose elements
4181 4d99964c Bernardo Dal Seno
      can be:
4182 4d99964c Bernardo Dal Seno
        - dictionaries, where keys are strings and values are of any of the
4183 4d99964c Bernardo Dal Seno
          types listed here
4184 4d99964c Bernardo Dal Seno
        - lists of pairs (key, value), where key is a string and value is of
4185 4d99964c Bernardo Dal Seno
          any of the types listed here; it's a way to encode ordered
4186 4d99964c Bernardo Dal Seno
          dictionaries
4187 4d99964c Bernardo Dal Seno
        - lists of any of the types listed here
4188 4d99964c Bernardo Dal Seno
        - strings
4189 4d99964c Bernardo Dal Seno

4190 4d99964c Bernardo Dal Seno
  """
4191 4d99964c Bernardo Dal Seno
  buf = StringIO()
4192 4d99964c Bernardo Dal Seno
  _SerializeGenericInfo(buf, data, 0)
4193 4d99964c Bernardo Dal Seno
  ToStdout(buf.getvalue().rstrip("\n"))