Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ 690e509d

History | View | Annotate | Download (136.4 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 7f5edc60 Iustin Pop
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Module dealing with command line parsing"""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
25 a8083063 Iustin Pop
import sys
26 a8083063 Iustin Pop
import textwrap
27 a8083063 Iustin Pop
import os.path
28 685ee993 Iustin Pop
import time
29 46fbdd04 Iustin Pop
import logging
30 225e2544 Iustin Pop
import errno
31 60452edf Michael Hanselmann
import itertools
32 ef9fa5b9 René Nussbaumer
import shlex
33 73702ee7 Iustin Pop
from cStringIO import StringIO
34 a8083063 Iustin Pop
35 a8083063 Iustin Pop
from ganeti import utils
36 a8083063 Iustin Pop
from ganeti import errors
37 a8083063 Iustin Pop
from ganeti import constants
38 846baef9 Iustin Pop
from ganeti import opcodes
39 ceab32dd Iustin Pop
from ganeti import luxi
40 b33e986b Iustin Pop
from ganeti import ssconf
41 4331f6cd Michael Hanselmann
from ganeti import rpc
42 7e49b6ce Michael Hanselmann
from ganeti import ssh
43 cea881e5 Michael Hanselmann
from ganeti import compat
44 a744b676 Manuel Franceschini
from ganeti import netutils
45 ee3aedff Michael Hanselmann
from ganeti import qlang
46 703fa9ab Iustin Pop
from ganeti import objects
47 ee4a14c0 Michael Hanselmann
from ganeti import pathutils
48 a8083063 Iustin Pop
49 bf5338b3 Michael Hanselmann
from optparse import (OptionParser, TitledHelpFormatter,
50 38206f3c Iustin Pop
                      Option, OptionValueError)
51 a8083063 Iustin Pop
52 03298ebe Michael Hanselmann
53 4abc4f1e Iustin Pop
__all__ = [
54 4abc4f1e Iustin Pop
  # Command line options
55 ef8270dc Iustin Pop
  "ABSOLUTE_OPT",
56 fdad8c4d Balazs Lecz
  "ADD_UIDS_OPT",
57 9c784fb3 Dimitris Aragiorgis
  "ADD_RESERVED_IPS_OPT",
58 e7e09483 Iustin Pop
  "ALLOCATABLE_OPT",
59 90e99856 Adeodato Simo
  "ALLOC_POLICY_OPT",
60 2d5e7ae1 Iustin Pop
  "ALL_OPT",
61 e9c487be René Nussbaumer
  "ALLOW_FAILOVER_OPT",
62 4c61d894 Iustin Pop
  "AUTO_PROMOTE_OPT",
63 e00f7a05 Iustin Pop
  "AUTO_REPLACE_OPT",
64 087ed2ed Iustin Pop
  "BACKEND_OPT",
65 61a14bb3 Iustin Pop
  "BLK_OS_OPT",
66 f91e255a Iustin Pop
  "CAPAB_MASTER_OPT",
67 53919782 Iustin Pop
  "CAPAB_VM_OPT",
68 baef337d Iustin Pop
  "CLEANUP_OPT",
69 3db3eb2a Michael Hanselmann
  "CLUSTER_DOMAIN_SECRET_OPT",
70 4abc4f1e Iustin Pop
  "CONFIRM_OPT",
71 e32df528 Iustin Pop
  "CP_SIZE_OPT",
72 4abc4f1e Iustin Pop
  "DEBUG_OPT",
73 a0c9776a Iustin Pop
  "DEBUG_SIMERR_OPT",
74 4b038a1e Iustin Pop
  "DISKIDX_OPT",
75 e3876ccb Iustin Pop
  "DISK_OPT",
76 bc5d0215 Andrea Spadaccini
  "DISK_PARAMS_OPT",
77 4b038a1e Iustin Pop
  "DISK_TEMPLATE_OPT",
78 771734c9 Iustin Pop
  "DRAINED_OPT",
79 a0a6ff34 Iustin Pop
  "DRY_RUN_OPT",
80 26591bfd Luca Bigliardi
  "DRBD_HELPER_OPT",
81 1b7761fd Apollon Oikonomopoulos
  "DST_NODE_OPT",
82 7ea7bcf6 Iustin Pop
  "EARLY_RELEASE_OPT",
83 383a3591 Iustin Pop
  "ENABLED_HV_OPT",
84 66af5ec5 Helga Velroyen
  "ENABLED_DISK_TEMPLATES_OPT",
85 14e9e7f3 Iustin Pop
  "ERROR_CODES_OPT",
86 d5b031dc Michael Hanselmann
  "FAILURE_ONLY_OPT",
87 4abc4f1e Iustin Pop
  "FIELDS_OPT",
88 4a25828c Iustin Pop
  "FILESTORE_DIR_OPT",
89 0f87c43e Iustin Pop
  "FILESTORE_DRIVER_OPT",
90 442587bf Michael Hanselmann
  "FORCE_FILTER_OPT",
91 06073e85 Guido Trotter
  "FORCE_OPT",
92 06073e85 Guido Trotter
  "FORCE_VARIANT_OPT",
93 9c784fb3 Dimitris Aragiorgis
  "GATEWAY_OPT",
94 9c784fb3 Dimitris Aragiorgis
  "GATEWAY6_OPT",
95 29392516 Iustin Pop
  "GLOBAL_FILEDIR_OPT",
96 61a14bb3 Iustin Pop
  "HID_OS_OPT",
97 4b97f902 Apollon Oikonomopoulos
  "GLOBAL_SHARED_FILEDIR_OPT",
98 073271f6 Iustin Pop
  "HVLIST_OPT",
99 48f212d7 Iustin Pop
  "HVOPTS_OPT",
100 236fd9c4 Iustin Pop
  "HYPERVISOR_OPT",
101 4eb62659 Iustin Pop
  "IALLOCATOR_OPT",
102 bf4af505 Apollon Oikonomopoulos
  "DEFAULT_IALLOCATOR_OPT",
103 e588764d Iustin Pop
  "IDENTIFY_DEFAULTS_OPT",
104 82a786d5 Iustin Pop
  "IGNORE_CONSIST_OPT",
105 93f2399e Andrea Spadaccini
  "IGNORE_ERRORS_OPT",
106 b6e841a8 Iustin Pop
  "IGNORE_FAILURES_OPT",
107 b44bd844 Michael Hanselmann
  "IGNORE_OFFLINE_OPT",
108 8d8d650c Michael Hanselmann
  "IGNORE_REMOVE_FAILURES_OPT",
109 ee3f9578 Iustin Pop
  "IGNORE_SECONDARIES_OPT",
110 05586c90 Iustin Pop
  "IGNORE_SIZE_OPT",
111 ea9d3b40 Bernardo Dal Seno
  "INCLUDEDEFAULTS_OPT",
112 19b9ba9a Michael Hanselmann
  "INTERVAL_OPT",
113 e3646f22 Iustin Pop
  "MAC_PREFIX_OPT",
114 3953242f Iustin Pop
  "MAINTAIN_NODE_HEALTH_OPT",
115 29392516 Iustin Pop
  "MASTER_NETDEV_OPT",
116 5a8648eb Andrea Spadaccini
  "MASTER_NETMASK_OPT",
117 771734c9 Iustin Pop
  "MC_OPT",
118 783a6c0b Iustin Pop
  "MIGRATION_MODE_OPT",
119 c89db623 Michele Tartara
  "MODIFY_ETCHOSTS_OPT",
120 7d3a9fab Iustin Pop
  "NET_OPT",
121 9c784fb3 Dimitris Aragiorgis
  "NETWORK_OPT",
122 9c784fb3 Dimitris Aragiorgis
  "NETWORK6_OPT",
123 6d4a1656 Michael Hanselmann
  "NEW_CLUSTER_CERT_OPT",
124 3db3eb2a Michael Hanselmann
  "NEW_CLUSTER_DOMAIN_SECRET_OPT",
125 6b7d5878 Michael Hanselmann
  "NEW_CONFD_HMAC_KEY_OPT",
126 6d4a1656 Michael Hanselmann
  "NEW_RAPI_CERT_OPT",
127 3438e1f8 Klaus Aehlig
  "NEW_PRIMARY_OPT",
128 a14db5ff Iustin Pop
  "NEW_SECONDARY_OPT",
129 b6267745 Andrea Spadaccini
  "NEW_SPICE_CERT_OPT",
130 4fbc93dd Iustin Pop
  "NIC_PARAMS_OPT",
131 9c784fb3 Dimitris Aragiorgis
  "NOCONFLICTSCHECK_OPT",
132 61413377 Stephen Shirley
  "NODE_FORCE_JOIN_OPT",
133 7edc4637 Iustin Pop
  "NODE_LIST_OPT",
134 990b7886 Iustin Pop
  "NODE_PLACEMENT_OPT",
135 5fbbd028 Guido Trotter
  "NODEGROUP_OPT",
136 a535cef7 René Nussbaumer
  "NODE_PARAMS_OPT",
137 dd94e9f6 René Nussbaumer
  "NODE_POWERED_OPT",
138 4abc4f1e Iustin Pop
  "NOHDR_OPT",
139 91e0748c Iustin Pop
  "NOIPCHECK_OPT",
140 25a8792c Iustin Pop
  "NO_INSTALL_OPT",
141 460d22be Iustin Pop
  "NONAMECHECK_OPT",
142 831040bf Iustin Pop
  "NOLVM_STORAGE_OPT",
143 29392516 Iustin Pop
  "NOMODIFY_ETCHOSTS_OPT",
144 b989b9d9 Ken Wehr
  "NOMODIFY_SSH_SETUP_OPT",
145 26023ecd Iustin Pop
  "NONICS_OPT",
146 f2a0828c Iustin Pop
  "NONLIVE_OPT",
147 14e9e7f3 Iustin Pop
  "NONPLUS1_OPT",
148 8c0b16f6 Guido Trotter
  "NORUNTIME_CHGS_OPT",
149 44c44832 Iustin Pop
  "NOSHUTDOWN_OPT",
150 edeb878a Iustin Pop
  "NOSTART_OPT",
151 fcdde7f2 Iustin Pop
  "NOSSH_KEYCHECK_OPT",
152 58371861 Iustin Pop
  "NOVOTING_OPT",
153 885a0fc4 Iustin Pop
  "NO_REMEMBER_OPT",
154 3f75b4f3 Iustin Pop
  "NWSYNC_OPT",
155 57de31c0 Agata Murawska
  "OFFLINE_INST_OPT",
156 57de31c0 Agata Murawska
  "ONLINE_INST_OPT",
157 a72d0a79 Iustin Pop
  "ON_PRIMARY_OPT",
158 feb09e6a Iustin Pop
  "ON_SECONDARY_OPT",
159 771734c9 Iustin Pop
  "OFFLINE_OPT",
160 062a7100 Iustin Pop
  "OSPARAMS_OPT",
161 d3ed23ff Iustin Pop
  "OS_OPT",
162 ff00c1a7 Iustin Pop
  "OS_SIZE_OPT",
163 41543d8b René Nussbaumer
  "OOB_TIMEOUT_OPT",
164 0c086a13 René Nussbaumer
  "POWER_DELAY_OPT",
165 b883637f René Nussbaumer
  "PREALLOC_WIPE_DISKS_OPT",
166 e7323b5e Manuel Franceschini
  "PRIMARY_IP_VERSION_OPT",
167 aafee533 Michael Hanselmann
  "PRIMARY_ONLY_OPT",
168 d6cd74dd Klaus Aehlig
  "PRINT_JOBID_OPT",
169 84a5b33c Michael Hanselmann
  "PRIORITY_OPT",
170 6d4a1656 Michael Hanselmann
  "RAPI_CERT_OPT",
171 b8d0f938 Iustin Pop
  "READD_OPT",
172 a59d5fa1 Michele Tartara
  "REASON_OPT",
173 12054861 Iustin Pop
  "REBOOT_TYPE_OPT",
174 8d8d650c Michael Hanselmann
  "REMOVE_INSTANCE_OPT",
175 9c784fb3 Dimitris Aragiorgis
  "REMOVE_RESERVED_IPS_OPT",
176 fdad8c4d Balazs Lecz
  "REMOVE_UIDS_OPT",
177 f38ea602 Iustin Pop
  "RESERVED_LVS_OPT",
178 2c0af7da Guido Trotter
  "RUNTIME_MEM_OPT",
179 31d97b2a Guido Trotter
  "ROMAN_OPT",
180 8d823629 Iustin Pop
  "SECONDARY_IP_OPT",
181 aafee533 Michael Hanselmann
  "SECONDARY_ONLY_OPT",
182 67840b40 Iustin Pop
  "SELECT_OS_OPT",
183 4abc4f1e Iustin Pop
  "SEP_OPT",
184 fdcf4d84 Iustin Pop
  "SHOWCMD_OPT",
185 f92ed8ab Michael Hanselmann
  "SHOW_MACHINE_OPT",
186 7e5eaaa8 Guido Trotter
  "SHUTDOWN_TIMEOUT_OPT",
187 f36d7d81 Iustin Pop
  "SINGLE_NODE_OPT",
188 32017174 Agata Murawska
  "SPECS_CPU_COUNT_OPT",
189 32017174 Agata Murawska
  "SPECS_DISK_COUNT_OPT",
190 32017174 Agata Murawska
  "SPECS_DISK_SIZE_OPT",
191 32017174 Agata Murawska
  "SPECS_MEM_SIZE_OPT",
192 32017174 Agata Murawska
  "SPECS_NIC_COUNT_OPT",
193 919db916 Bernardo Dal Seno
  "SPLIT_ISPECS_OPTS",
194 d2d3935a Bernardo Dal Seno
  "IPOLICY_STD_SPECS_OPT",
195 d04c9d45 Iustin Pop
  "IPOLICY_DISK_TEMPLATES",
196 976b78ba Iustin Pop
  "IPOLICY_VCPU_RATIO",
197 b6267745 Andrea Spadaccini
  "SPICE_CACERT_OPT",
198 b6267745 Andrea Spadaccini
  "SPICE_CERT_OPT",
199 df62e5db Iustin Pop
  "SRC_DIR_OPT",
200 df62e5db Iustin Pop
  "SRC_NODE_OPT",
201 4abc4f1e Iustin Pop
  "SUBMIT_OPT",
202 d6cd74dd Klaus Aehlig
  "SUBMIT_OPTS",
203 323f9095 Stephen Shirley
  "STARTUP_PAUSED_OPT",
204 99a8c799 Iustin Pop
  "STATIC_OPT",
205 4abc4f1e Iustin Pop
  "SYNC_OPT",
206 a57981c5 Apollon Oikonomopoulos
  "TAG_ADD_OPT",
207 4abc4f1e Iustin Pop
  "TAG_SRC_OPT",
208 b5762e2a Guido Trotter
  "TIMEOUT_OPT",
209 f6eb380d Michael Hanselmann
  "TO_GROUP_OPT",
210 1338f2b4 Balazs Lecz
  "UIDPOOL_OPT",
211 4abc4f1e Iustin Pop
  "USEUNITS_OPT",
212 bf689b7a Andrea Spadaccini
  "USE_EXTERNAL_MIP_SCRIPT",
213 74adc100 Iustin Pop
  "USE_REPL_NET_OPT",
214 9cdb9578 Iustin Pop
  "VERBOSE_OPT",
215 b58726e8 Iustin Pop
  "VG_NAME_OPT",
216 f30d8165 Iustin Pop
  "WFSYNC_OPT",
217 1f587d3d Iustin Pop
  "YES_DOIT_OPT",
218 38f29a36 René Nussbaumer
  "DISK_STATE_OPT",
219 38f29a36 René Nussbaumer
  "HV_STATE_OPT",
220 b6aaf437 René Nussbaumer
  "IGNORE_IPOLICY_OPT",
221 0ce212e5 Iustin Pop
  "INSTANCE_POLICY_OPTS",
222 4abc4f1e Iustin Pop
  # Generic functions for CLI programs
223 25bd815c René Nussbaumer
  "ConfirmOperation",
224 703fa9ab Iustin Pop
  "CreateIPolicyFromOpts",
225 4abc4f1e Iustin Pop
  "GenericMain",
226 d77490c5 Iustin Pop
  "GenericInstanceCreate",
227 ee3aedff Michael Hanselmann
  "GenericList",
228 ee3aedff Michael Hanselmann
  "GenericListFields",
229 4abc4f1e Iustin Pop
  "GetClient",
230 4abc4f1e Iustin Pop
  "GetOnlineNodes",
231 4abc4f1e Iustin Pop
  "JobExecutor",
232 4abc4f1e Iustin Pop
  "JobSubmittedException",
233 4abc4f1e Iustin Pop
  "ParseTimespec",
234 7e49b6ce Michael Hanselmann
  "RunWhileClusterStopped",
235 4abc4f1e Iustin Pop
  "SubmitOpCode",
236 4abc4f1e Iustin Pop
  "SubmitOrSend",
237 4abc4f1e Iustin Pop
  "UsesRPC",
238 4abc4f1e Iustin Pop
  # Formatting functions
239 4abc4f1e Iustin Pop
  "ToStderr", "ToStdout",
240 4abc4f1e Iustin Pop
  "FormatError",
241 ee3aedff Michael Hanselmann
  "FormatQueryResult",
242 4d99964c Bernardo Dal Seno
  "FormatParamsDictInfo",
243 d00884a2 Bernardo Dal Seno
  "FormatPolicyInfo",
244 ea9d3b40 Bernardo Dal Seno
  "PrintIPolicyCommand",
245 4d99964c Bernardo Dal Seno
  "PrintGenericInfo",
246 4abc4f1e Iustin Pop
  "GenerateTable",
247 4abc4f1e Iustin Pop
  "AskUser",
248 4abc4f1e Iustin Pop
  "FormatTimestamp",
249 8a7f1c61 Michael Hanselmann
  "FormatLogMessage",
250 4abc4f1e Iustin Pop
  # Tags functions
251 4abc4f1e Iustin Pop
  "ListTags",
252 4abc4f1e Iustin Pop
  "AddTags",
253 4abc4f1e Iustin Pop
  "RemoveTags",
254 4abc4f1e Iustin Pop
  # command line options support infrastructure
255 4abc4f1e Iustin Pop
  "ARGS_MANY_INSTANCES",
256 4abc4f1e Iustin Pop
  "ARGS_MANY_NODES",
257 667dbd6b Adeodato Simo
  "ARGS_MANY_GROUPS",
258 9c784fb3 Dimitris Aragiorgis
  "ARGS_MANY_NETWORKS",
259 4abc4f1e Iustin Pop
  "ARGS_NONE",
260 4abc4f1e Iustin Pop
  "ARGS_ONE_INSTANCE",
261 4abc4f1e Iustin Pop
  "ARGS_ONE_NODE",
262 667dbd6b Adeodato Simo
  "ARGS_ONE_GROUP",
263 f9faf9c3 René Nussbaumer
  "ARGS_ONE_OS",
264 9c784fb3 Dimitris Aragiorgis
  "ARGS_ONE_NETWORK",
265 4abc4f1e Iustin Pop
  "ArgChoice",
266 4abc4f1e Iustin Pop
  "ArgCommand",
267 4abc4f1e Iustin Pop
  "ArgFile",
268 667dbd6b Adeodato Simo
  "ArgGroup",
269 4abc4f1e Iustin Pop
  "ArgHost",
270 4abc4f1e Iustin Pop
  "ArgInstance",
271 4abc4f1e Iustin Pop
  "ArgJobId",
272 9c784fb3 Dimitris Aragiorgis
  "ArgNetwork",
273 4abc4f1e Iustin Pop
  "ArgNode",
274 f9faf9c3 René Nussbaumer
  "ArgOs",
275 b954f097 Constantinos Venetsanopoulos
  "ArgExtStorage",
276 4abc4f1e Iustin Pop
  "ArgSuggest",
277 4abc4f1e Iustin Pop
  "ArgUnknown",
278 4abc4f1e Iustin Pop
  "OPT_COMPL_INST_ADD_NODES",
279 4abc4f1e Iustin Pop
  "OPT_COMPL_MANY_NODES",
280 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_IALLOCATOR",
281 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_INSTANCE",
282 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_NODE",
283 36e247e1 Guido Trotter
  "OPT_COMPL_ONE_NODEGROUP",
284 9c784fb3 Dimitris Aragiorgis
  "OPT_COMPL_ONE_NETWORK",
285 4abc4f1e Iustin Pop
  "OPT_COMPL_ONE_OS",
286 b954f097 Constantinos Venetsanopoulos
  "OPT_COMPL_ONE_EXTSTORAGE",
287 4abc4f1e Iustin Pop
  "cli_option",
288 4abc4f1e Iustin Pop
  "SplitNodeOption",
289 07150497 Guido Trotter
  "CalculateOSNames",
290 a4ebd726 Michael Hanselmann
  "ParseFields",
291 eb28ecf6 Guido Trotter
  "COMMON_CREATE_OPTS",
292 4abc4f1e Iustin Pop
  ]
293 846baef9 Iustin Pop
294 8b46606c Guido Trotter
NO_PREFIX = "no_"
295 8b46606c Guido Trotter
UN_PREFIX = "-"
296 846baef9 Iustin Pop
297 84a5b33c Michael Hanselmann
#: Priorities (sorted)
298 84a5b33c Michael Hanselmann
_PRIORITY_NAMES = [
299 84a5b33c Michael Hanselmann
  ("low", constants.OP_PRIO_LOW),
300 84a5b33c Michael Hanselmann
  ("normal", constants.OP_PRIO_NORMAL),
301 84a5b33c Michael Hanselmann
  ("high", constants.OP_PRIO_HIGH),
302 84a5b33c Michael Hanselmann
  ]
303 84a5b33c Michael Hanselmann
304 84a5b33c Michael Hanselmann
#: Priority dictionary for easier lookup
305 84a5b33c Michael Hanselmann
# TODO: Replace this and _PRIORITY_NAMES with a single sorted dictionary once
306 84a5b33c Michael Hanselmann
# we migrate to Python 2.6
307 84a5b33c Michael Hanselmann
_PRIONAME_TO_VALUE = dict(_PRIORITY_NAMES)
308 84a5b33c Michael Hanselmann
309 ee3aedff Michael Hanselmann
# Query result status for clients
310 ee3aedff Michael Hanselmann
(QR_NORMAL,
311 ee3aedff Michael Hanselmann
 QR_UNKNOWN,
312 ee3aedff Michael Hanselmann
 QR_INCOMPLETE) = range(3)
313 ee3aedff Michael Hanselmann
314 11705e3d Iustin Pop
#: Maximum batch size for ChooseJob
315 11705e3d Iustin Pop
_CHOOSE_BATCH = 25
316 11705e3d Iustin Pop
317 03298ebe Michael Hanselmann
318 703fa9ab Iustin Pop
# constants used to create InstancePolicy dictionary
319 703fa9ab Iustin Pop
TISPECS_GROUP_TYPES = {
320 703fa9ab Iustin Pop
  constants.ISPECS_MIN: constants.VTYPE_INT,
321 703fa9ab Iustin Pop
  constants.ISPECS_MAX: constants.VTYPE_INT,
322 703fa9ab Iustin Pop
  }
323 703fa9ab Iustin Pop
324 703fa9ab Iustin Pop
TISPECS_CLUSTER_TYPES = {
325 703fa9ab Iustin Pop
  constants.ISPECS_MIN: constants.VTYPE_INT,
326 703fa9ab Iustin Pop
  constants.ISPECS_MAX: constants.VTYPE_INT,
327 703fa9ab Iustin Pop
  constants.ISPECS_STD: constants.VTYPE_INT,
328 703fa9ab Iustin Pop
  }
329 703fa9ab Iustin Pop
330 c1912a48 Michael Hanselmann
#: User-friendly names for query2 field types
331 c1912a48 Michael Hanselmann
_QFT_NAMES = {
332 c1912a48 Michael Hanselmann
  constants.QFT_UNKNOWN: "Unknown",
333 c1912a48 Michael Hanselmann
  constants.QFT_TEXT: "Text",
334 c1912a48 Michael Hanselmann
  constants.QFT_BOOL: "Boolean",
335 c1912a48 Michael Hanselmann
  constants.QFT_NUMBER: "Number",
336 c1912a48 Michael Hanselmann
  constants.QFT_UNIT: "Storage size",
337 c1912a48 Michael Hanselmann
  constants.QFT_TIMESTAMP: "Timestamp",
338 c1912a48 Michael Hanselmann
  constants.QFT_OTHER: "Custom",
339 c1912a48 Michael Hanselmann
  }
340 c1912a48 Michael Hanselmann
341 703fa9ab Iustin Pop
342 863d7f46 Michael Hanselmann
class _Argument:
343 b459a848 Andrea Spadaccini
  def __init__(self, min=0, max=None): # pylint: disable=W0622
344 863d7f46 Michael Hanselmann
    self.min = min
345 863d7f46 Michael Hanselmann
    self.max = max
346 863d7f46 Michael Hanselmann
347 863d7f46 Michael Hanselmann
  def __repr__(self):
348 863d7f46 Michael Hanselmann
    return ("<%s min=%s max=%s>" %
349 863d7f46 Michael Hanselmann
            (self.__class__.__name__, self.min, self.max))
350 863d7f46 Michael Hanselmann
351 863d7f46 Michael Hanselmann
352 863d7f46 Michael Hanselmann
class ArgSuggest(_Argument):
353 863d7f46 Michael Hanselmann
  """Suggesting argument.
354 863d7f46 Michael Hanselmann

355 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
356 863d7f46 Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

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

459 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
460 846baef9 Iustin Pop

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

701 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
702 e7b61bb0 Iustin Pop

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

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

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

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

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

1700 d971402f Michael Hanselmann
  """
1701 d971402f Michael Hanselmann
  def __init__(self, exit_error):
1702 d971402f Michael Hanselmann
    """Initializes instances of this class.
1703 d971402f Michael Hanselmann

1704 d971402f Michael Hanselmann
    @type exit_error: bool
1705 d971402f Michael Hanselmann
    @param exit_error: Whether to report failure on exit
1706 d971402f Michael Hanselmann

1707 d971402f Michael Hanselmann
    """
1708 d971402f Michael Hanselmann
    Exception.__init__(self)
1709 d971402f Michael Hanselmann
    self.exit_error = exit_error
1710 d971402f Michael Hanselmann
1711 d971402f Michael Hanselmann
1712 d971402f Michael Hanselmann
class _ShowVersion(Exception):
1713 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1714 d971402f Michael Hanselmann

1715 d971402f Michael Hanselmann
  """
1716 d971402f Michael Hanselmann
1717 d971402f Michael Hanselmann
1718 d971402f Michael Hanselmann
def _ParseArgs(binary, argv, commands, aliases, env_override):
1719 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1720 a8083063 Iustin Pop

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

1724 d971402f Michael Hanselmann
  @param binary: Script name
1725 d971402f Michael Hanselmann
  @param argv: Command line arguments
1726 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1727 d971402f Michael Hanselmann
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1728 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1729 d971402f Michael Hanselmann
  @raise _ShowUsage: If usage description should be shown
1730 d971402f Michael Hanselmann
  @raise _ShowVersion: If version should be shown
1731 098c0958 Michael Hanselmann

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

1780 d971402f Michael Hanselmann
  @param binary: Script name
1781 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1782 d971402f Michael Hanselmann

1783 d971402f Michael Hanselmann
  """
1784 d971402f Michael Hanselmann
  # compute the max line length for cmd + usage
1785 d971402f Michael Hanselmann
  mlen = min(60, max(map(len, commands)))
1786 d971402f Michael Hanselmann
1787 d971402f Michael Hanselmann
  yield "Usage: %s {command} [options...] [argument...]" % binary
1788 d971402f Michael Hanselmann
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1789 d971402f Michael Hanselmann
  yield ""
1790 d971402f Michael Hanselmann
  yield "Commands:"
1791 d971402f Michael Hanselmann
1792 d971402f Michael Hanselmann
  # and format a nice command list
1793 d971402f Michael Hanselmann
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1794 d971402f Michael Hanselmann
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1795 d971402f Michael Hanselmann
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1796 d971402f Michael Hanselmann
    for line in help_lines:
1797 d971402f Michael Hanselmann
      yield " %-*s   %s" % (mlen, "", line)
1798 d971402f Michael Hanselmann
1799 d971402f Michael Hanselmann
  yield ""
1800 d971402f Michael Hanselmann
1801 d971402f Michael Hanselmann
1802 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1803 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1804 a8005e17 Michael Hanselmann

1805 a8005e17 Michael Hanselmann
  Algorithm:
1806 a8005e17 Michael Hanselmann

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

1809 a8005e17 Michael Hanselmann
    1. For each argument in definition
1810 a8005e17 Michael Hanselmann

1811 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1812 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1813 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1814 a8005e17 Michael Hanselmann

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

1817 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1818 a8005e17 Michael Hanselmann

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

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

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

1876 60d49723 Michael Hanselmann
  """
1877 d0c8c01d Iustin Pop
  if value and ":" in value:
1878 d0c8c01d Iustin Pop
    return value.split(":", 1)
1879 60d49723 Michael Hanselmann
  else:
1880 60d49723 Michael Hanselmann
    return (value, None)
1881 60d49723 Michael Hanselmann
1882 60d49723 Michael Hanselmann
1883 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1884 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1885 07150497 Guido Trotter

1886 07150497 Guido Trotter
  @type os_name: string
1887 07150497 Guido Trotter
  @param os_name: base name of the os
1888 07150497 Guido Trotter
  @type os_variants: list or None
1889 07150497 Guido Trotter
  @param os_variants: list of supported variants
1890 07150497 Guido Trotter
  @rtype: list
1891 07150497 Guido Trotter
  @return: list of valid names
1892 07150497 Guido Trotter

1893 07150497 Guido Trotter
  """
1894 07150497 Guido Trotter
  if os_variants:
1895 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1896 07150497 Guido Trotter
  else:
1897 07150497 Guido Trotter
    return [os_name]
1898 07150497 Guido Trotter
1899 07150497 Guido Trotter
1900 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1901 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1902 a4ebd726 Michael Hanselmann

1903 a4ebd726 Michael Hanselmann
  @type selected: string or None
1904 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1905 a4ebd726 Michael Hanselmann
  @type default: list
1906 a4ebd726 Michael Hanselmann
  @param default: Default fields
1907 a4ebd726 Michael Hanselmann

1908 a4ebd726 Michael Hanselmann
  """
1909 a4ebd726 Michael Hanselmann
  if selected is None:
1910 a4ebd726 Michael Hanselmann
    return default
1911 a4ebd726 Michael Hanselmann
1912 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1913 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1914 a4ebd726 Michael Hanselmann
1915 a4ebd726 Michael Hanselmann
  return selected.split(",")
1916 a4ebd726 Michael Hanselmann
1917 a4ebd726 Michael Hanselmann
1918 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1919 4331f6cd Michael Hanselmann
1920 4331f6cd Michael Hanselmann
1921 47988778 Iustin Pop
def AskUser(text, choices=None):
1922 47988778 Iustin Pop
  """Ask the user a question.
1923 a8083063 Iustin Pop

1924 c41eea6e Iustin Pop
  @param text: the question to ask
1925 a8083063 Iustin Pop

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

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

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

1981 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1982 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1983 e9d741b6 Iustin Pop

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

1986 e9d741b6 Iustin Pop
  """
1987 e9d741b6 Iustin Pop
1988 e9d741b6 Iustin Pop
1989 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1990 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1991 a8083063 Iustin Pop

1992 0a1e74d9 Iustin Pop
  @type ops: list
1993 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1994 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1995 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1996 0a1e74d9 Iustin Pop
             if None, a new client will be created
1997 a8083063 Iustin Pop

1998 a8083063 Iustin Pop
  """
1999 e2212007 Iustin Pop
  if cl is None:
2000 b33e986b Iustin Pop
    cl = GetClient()
2001 685ee993 Iustin Pop
2002 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
2003 0a1e74d9 Iustin Pop
2004 0a1e74d9 Iustin Pop
  return job_id
2005 0a1e74d9 Iustin Pop
2006 0a1e74d9 Iustin Pop
2007 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
2008 4e338533 Michael Hanselmann
  """Generic job-polling function.
2009 0a1e74d9 Iustin Pop

2010 4e338533 Michael Hanselmann
  @type job_id: number
2011 4e338533 Michael Hanselmann
  @param job_id: Job ID
2012 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
2013 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
2014 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
2015 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
2016 0a1e74d9 Iustin Pop

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

2088 4e338533 Michael Hanselmann
  """
2089 4e338533 Michael Hanselmann
  def __init__(self):
2090 4e338533 Michael Hanselmann
    """Initializes this class.
2091 4e338533 Michael Hanselmann

2092 4e338533 Michael Hanselmann
    """
2093 4e338533 Michael Hanselmann
2094 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2095 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2096 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2097 4e338533 Michael Hanselmann

2098 4e338533 Michael Hanselmann
    """
2099 4e338533 Michael Hanselmann
    raise NotImplementedError()
2100 4e338533 Michael Hanselmann
2101 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2102 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2103 4e338533 Michael Hanselmann

2104 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
2105 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
2106 4e338533 Michael Hanselmann
    @type fields: list of strings
2107 4e338533 Michael Hanselmann
    @param fields: Fields
2108 4e338533 Michael Hanselmann

2109 4e338533 Michael Hanselmann
    """
2110 4e338533 Michael Hanselmann
    raise NotImplementedError()
2111 4e338533 Michael Hanselmann
2112 4e338533 Michael Hanselmann
2113 4e338533 Michael Hanselmann
class JobPollReportCbBase:
2114 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
2115 4e338533 Michael Hanselmann

2116 4e338533 Michael Hanselmann
  """
2117 4e338533 Michael Hanselmann
  def __init__(self):
2118 4e338533 Michael Hanselmann
    """Initializes this class.
2119 4e338533 Michael Hanselmann

2120 4e338533 Michael Hanselmann
    """
2121 4e338533 Michael Hanselmann
2122 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2123 4e338533 Michael Hanselmann
    """Handles a log message.
2124 4e338533 Michael Hanselmann

2125 4e338533 Michael Hanselmann
    """
2126 4e338533 Michael Hanselmann
    raise NotImplementedError()
2127 4e338533 Michael Hanselmann
2128 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2129 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
2130 4e338533 Michael Hanselmann

2131 4e338533 Michael Hanselmann
    @type job_id: number
2132 4e338533 Michael Hanselmann
    @param job_id: Job ID
2133 4e338533 Michael Hanselmann
    @type status: string or None
2134 4e338533 Michael Hanselmann
    @param status: Job status if available
2135 4e338533 Michael Hanselmann

2136 4e338533 Michael Hanselmann
    """
2137 4e338533 Michael Hanselmann
    raise NotImplementedError()
2138 4e338533 Michael Hanselmann
2139 4e338533 Michael Hanselmann
2140 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
2141 4e338533 Michael Hanselmann
  def __init__(self, cl):
2142 4e338533 Michael Hanselmann
    """Initializes this class.
2143 4e338533 Michael Hanselmann

2144 4e338533 Michael Hanselmann
    """
2145 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
2146 4e338533 Michael Hanselmann
    self.cl = cl
2147 4e338533 Michael Hanselmann
2148 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2149 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2150 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2151 4e338533 Michael Hanselmann

2152 4e338533 Michael Hanselmann
    """
2153 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2154 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
2155 4e338533 Michael Hanselmann
2156 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2157 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2158 4e338533 Michael Hanselmann

2159 4e338533 Michael Hanselmann
    """
2160 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
2161 4e338533 Michael Hanselmann
2162 4e338533 Michael Hanselmann
2163 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2164 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
2165 4e338533 Michael Hanselmann
    """Initializes this class.
2166 4e338533 Michael Hanselmann

2167 4e338533 Michael Hanselmann
    """
2168 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2169 4e338533 Michael Hanselmann
2170 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
2171 4e338533 Michael Hanselmann
2172 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
2173 4e338533 Michael Hanselmann
2174 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2175 4e338533 Michael Hanselmann
    """Handles a log message.
2176 4e338533 Michael Hanselmann

2177 4e338533 Michael Hanselmann
    """
2178 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
2179 4e338533 Michael Hanselmann
2180 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2181 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2182 4e338533 Michael Hanselmann

2183 4e338533 Michael Hanselmann
    """
2184 4e338533 Michael Hanselmann
    # Ignore
2185 4e338533 Michael Hanselmann
2186 4e338533 Michael Hanselmann
2187 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
2188 4e338533 Michael Hanselmann
  def __init__(self):
2189 4e338533 Michael Hanselmann
    """Initializes this class.
2190 4e338533 Michael Hanselmann

2191 4e338533 Michael Hanselmann
    """
2192 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2193 4e338533 Michael Hanselmann
2194 4e338533 Michael Hanselmann
    self.notified_queued = False
2195 4e338533 Michael Hanselmann
    self.notified_waitlock = False
2196 4e338533 Michael Hanselmann
2197 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2198 4e338533 Michael Hanselmann
    """Handles a log message.
2199 4e338533 Michael Hanselmann

2200 4e338533 Michael Hanselmann
    """
2201 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2202 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
2203 4e338533 Michael Hanselmann
2204 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2205 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2206 4e338533 Michael Hanselmann

2207 4e338533 Michael Hanselmann
    """
2208 4e338533 Michael Hanselmann
    if status is None:
2209 4e338533 Michael Hanselmann
      return
2210 4e338533 Michael Hanselmann
2211 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2212 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
2213 4e338533 Michael Hanselmann
      self.notified_queued = True
2214 4e338533 Michael Hanselmann
2215 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2216 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2217 4e338533 Michael Hanselmann
      self.notified_waitlock = True
2218 4e338533 Michael Hanselmann
2219 4e338533 Michael Hanselmann
2220 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
2221 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
2222 8a7f1c61 Michael Hanselmann

2223 8a7f1c61 Michael Hanselmann
  """
2224 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
2225 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
2226 8a7f1c61 Michael Hanselmann
2227 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
2228 8a7f1c61 Michael Hanselmann
2229 8a7f1c61 Michael Hanselmann
2230 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2231 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
2232 4e338533 Michael Hanselmann

2233 4e338533 Michael Hanselmann
  @type job_id: job identified
2234 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
2235 4e338533 Michael Hanselmann
  @type cl: luxi.Client
2236 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
2237 4e338533 Michael Hanselmann
             if None, a new client will be created
2238 4e338533 Michael Hanselmann

2239 4e338533 Michael Hanselmann
  """
2240 4e338533 Michael Hanselmann
  if cl is None:
2241 4e338533 Michael Hanselmann
    cl = GetClient()
2242 4e338533 Michael Hanselmann
2243 583163a6 Michael Hanselmann
  if reporter is None:
2244 583163a6 Michael Hanselmann
    if feedback_fn:
2245 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2246 583163a6 Michael Hanselmann
    else:
2247 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
2248 583163a6 Michael Hanselmann
  elif feedback_fn:
2249 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2250 4e338533 Michael Hanselmann
2251 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2252 ceab32dd Iustin Pop
2253 ceab32dd Iustin Pop
2254 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2255 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
2256 0a1e74d9 Iustin Pop

2257 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
2258 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
2259 0a1e74d9 Iustin Pop
  interaction functions.
2260 0a1e74d9 Iustin Pop

2261 0a1e74d9 Iustin Pop
  """
2262 0a1e74d9 Iustin Pop
  if cl is None:
2263 0a1e74d9 Iustin Pop
    cl = GetClient()
2264 0a1e74d9 Iustin Pop
2265 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
2266 293ba2d8 Iustin Pop
2267 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
2268 fe5a2780 Klaus Aehlig
  if hasattr(opts, "print_jobid") and opts.print_jobid:
2269 d6cd74dd Klaus Aehlig
    ToStdout("%d" % job_id)
2270 0a1e74d9 Iustin Pop
2271 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2272 583163a6 Michael Hanselmann
                       reporter=reporter)
2273 53c04d04 Iustin Pop
2274 53c04d04 Iustin Pop
  return op_results[0]
2275 0a1e74d9 Iustin Pop
2276 0a1e74d9 Iustin Pop
2277 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2278 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
2279 94428652 Iustin Pop

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

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

2288 94428652 Iustin Pop
  """
2289 94428652 Iustin Pop
  if opts and opts.submit_only:
2290 293ba2d8 Iustin Pop
    job = [op]
2291 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
2292 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
2293 d6cd74dd Klaus Aehlig
    if opts.print_jobid:
2294 d6cd74dd Klaus Aehlig
      ToStdout("%d" % job_id)
2295 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
2296 94428652 Iustin Pop
  else:
2297 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2298 293ba2d8 Iustin Pop
2299 293ba2d8 Iustin Pop
2300 276e51bd Michele Tartara
def _InitReasonTrail(op, opts):
2301 276e51bd Michele Tartara
  """Builds the first part of the reason trail
2302 276e51bd Michele Tartara

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

2306 276e51bd Michele Tartara
  @param op: the opcode the reason trail will be added to
2307 276e51bd Michele Tartara
  @param opts: the command line options selected by the user
2308 276e51bd Michele Tartara

2309 276e51bd Michele Tartara
  """
2310 276e51bd Michele Tartara
  assert len(sys.argv) >= 2
2311 276e51bd Michele Tartara
  trail = []
2312 276e51bd Michele Tartara
2313 276e51bd Michele Tartara
  if opts.reason:
2314 276e51bd Michele Tartara
    trail.append((constants.OPCODE_REASON_SRC_USER,
2315 276e51bd Michele Tartara
                  opts.reason,
2316 276e51bd Michele Tartara
                  utils.EpochNano()))
2317 276e51bd Michele Tartara
2318 276e51bd Michele Tartara
  binary = os.path.basename(sys.argv[0])
2319 276e51bd Michele Tartara
  source = "%s:%s" % (constants.OPCODE_REASON_SRC_CLIENT, binary)
2320 276e51bd Michele Tartara
  command = sys.argv[1]
2321 276e51bd Michele Tartara
  trail.append((source, command, utils.EpochNano()))
2322 276e51bd Michele Tartara
  op.reason = trail
2323 276e51bd Michele Tartara
2324 276e51bd Michele Tartara
2325 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
2326 293ba2d8 Iustin Pop
  """Processor for generic options.
2327 293ba2d8 Iustin Pop

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

2331 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
2332 293ba2d8 Iustin Pop
  @param options: command line options or None
2333 293ba2d8 Iustin Pop
  @return: None (in-place modification)
2334 293ba2d8 Iustin Pop

2335 293ba2d8 Iustin Pop
  """
2336 293ba2d8 Iustin Pop
  if not options:
2337 293ba2d8 Iustin Pop
    return
2338 293ba2d8 Iustin Pop
  for op in opcode_list:
2339 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
2340 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
2341 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
2342 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
2343 552328b8 Michael Hanselmann
      op.priority = options.priority
2344 276e51bd Michele Tartara
    _InitReasonTrail(op, options)
2345 94428652 Iustin Pop
2346 94428652 Iustin Pop
2347 42ab9ac4 Iustin Pop
def GetClient(query=False):
2348 42ab9ac4 Iustin Pop
  """Connects to the a luxi socket and returns a client.
2349 42ab9ac4 Iustin Pop

2350 42ab9ac4 Iustin Pop
  @type query: boolean
2351 42ab9ac4 Iustin Pop
  @param query: this signifies that the client will only be
2352 42ab9ac4 Iustin Pop
      used for queries; if the build-time parameter
2353 42ab9ac4 Iustin Pop
      enable-split-queries is enabled, then the client will be
2354 42ab9ac4 Iustin Pop
      connected to the query socket instead of the masterd socket
2355 42ab9ac4 Iustin Pop

2356 42ab9ac4 Iustin Pop
  """
2357 055d6ac0 Iustin Pop
  override_socket = os.getenv(constants.LUXI_OVERRIDE, "")
2358 055d6ac0 Iustin Pop
  if override_socket:
2359 055d6ac0 Iustin Pop
    if override_socket == constants.LUXI_OVERRIDE_MASTER:
2360 055d6ac0 Iustin Pop
      address = pathutils.MASTER_SOCKET
2361 055d6ac0 Iustin Pop
    elif override_socket == constants.LUXI_OVERRIDE_QUERY:
2362 055d6ac0 Iustin Pop
      address = pathutils.QUERY_SOCKET
2363 055d6ac0 Iustin Pop
    else:
2364 055d6ac0 Iustin Pop
      address = override_socket
2365 055d6ac0 Iustin Pop
  elif query and constants.ENABLE_SPLIT_QUERY:
2366 ee4a14c0 Michael Hanselmann
    address = pathutils.QUERY_SOCKET
2367 42ab9ac4 Iustin Pop
  else:
2368 42ab9ac4 Iustin Pop
    address = None
2369 af30b2fd Michael Hanselmann
  # TODO: Cache object?
2370 b33e986b Iustin Pop
  try:
2371 42ab9ac4 Iustin Pop
    client = luxi.Client(address=address)
2372 b33e986b Iustin Pop
  except luxi.NoMasterError:
2373 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
2374 d9a51679 Michael Hanselmann
2375 d9a51679 Michael Hanselmann
    # Try to read ssconf file
2376 d9a51679 Michael Hanselmann
    try:
2377 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
2378 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
2379 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2380 2cfbc784 Iustin Pop
                                 " not part of a cluster",
2381 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2382 d9a51679 Michael Hanselmann
2383 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2384 b33e986b Iustin Pop
    if master != myself:
2385 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
2386 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
2387 2cfbc784 Iustin Pop
                                 master, errors.ECODE_INVAL)
2388 d9a51679 Michael Hanselmann
    raise
2389 b33e986b Iustin Pop
  return client
2390 af30b2fd Michael Hanselmann
2391 af30b2fd Michael Hanselmann
2392 73702ee7 Iustin Pop
def FormatError(err):
2393 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
2394 73702ee7 Iustin Pop

2395 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
2396 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
2397 73702ee7 Iustin Pop
  second, a string describing the error message (not
2398 73702ee7 Iustin Pop
  newline-terminated).
2399 73702ee7 Iustin Pop

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

2490 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2491 ef9fa5b9 René Nussbaumer
                   for command line handling.
2492 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2493 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2494 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2495 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2496 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2497 ef9fa5b9 René Nussbaumer
                       default args for commands
2498 a8083063 Iustin Pop

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

2576 845c79d8 Michael Hanselmann
  """
2577 845c79d8 Michael Hanselmann
  try:
2578 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2579 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2580 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2581 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
2582 845c79d8 Michael Hanselmann
2583 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2584 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2585 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2586 845c79d8 Michael Hanselmann
2587 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2588 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2589 2cfbc784 Iustin Pop
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2590 845c79d8 Michael Hanselmann
2591 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2592 845c79d8 Michael Hanselmann
2593 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2594 845c79d8 Michael Hanselmann
2595 845c79d8 Michael Hanselmann
  return nics
2596 845c79d8 Michael Hanselmann
2597 845c79d8 Michael Hanselmann
2598 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2599 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2600 d77490c5 Iustin Pop

2601 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2602 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2603 d77490c5 Iustin Pop
  @type args: list
2604 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2605 d77490c5 Iustin Pop
  @rtype: int
2606 d77490c5 Iustin Pop
  @return: the desired exit code
2607 d77490c5 Iustin Pop

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

2744 7e49b6ce Michael Hanselmann
  """
2745 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2746 7e49b6ce Michael Hanselmann
    """Initializes this class.
2747 7e49b6ce Michael Hanselmann

2748 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2749 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2750 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2751 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2752 7e49b6ce Michael Hanselmann
    @type master_node: string
2753 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2754 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2755 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2756 7e49b6ce Michael Hanselmann

2757 7e49b6ce Michael Hanselmann
    """
2758 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2759 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2760 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2761 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2762 7e49b6ce Michael Hanselmann
2763 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2764 7e49b6ce Michael Hanselmann
2765 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2766 7e49b6ce Michael Hanselmann
                            if name != master_node]
2767 7e49b6ce Michael Hanselmann
2768 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2769 7e49b6ce Michael Hanselmann
2770 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2771 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2772 7e49b6ce Michael Hanselmann

2773 7e49b6ce Michael Hanselmann
    @type node_name: string
2774 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2775 7e49b6ce Michael Hanselmann
    @type cmd: list
2776 7e49b6ce Michael Hanselmann
    @param cmd: Command
2777 7e49b6ce Michael Hanselmann

2778 7e49b6ce Michael Hanselmann
    """
2779 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2780 7e49b6ce Michael Hanselmann
      # No need to use SSH
2781 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2782 7e49b6ce Michael Hanselmann
    else:
2783 052783ff Michael Hanselmann
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2784 052783ff Michael Hanselmann
                            utils.ShellQuoteArgs(cmd))
2785 7e49b6ce Michael Hanselmann
2786 7e49b6ce Michael Hanselmann
    if result.failed:
2787 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2788 7e49b6ce Michael Hanselmann
      if node_name:
2789 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2790 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2791 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2792 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2793 7e49b6ce Michael Hanselmann
2794 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2795 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2796 7e49b6ce Michael Hanselmann

2797 7e49b6ce Michael Hanselmann
    @type fn: callable
2798 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2799 7e49b6ce Michael Hanselmann

2800 7e49b6ce Michael Hanselmann
    """
2801 7e49b6ce Michael Hanselmann
    # Pause watcher by acquiring an exclusive lock on watcher state file
2802 7e49b6ce Michael Hanselmann
    self.feedback_fn("Blocking watcher")
2803 ee4a14c0 Michael Hanselmann
    watcher_block = utils.FileLock.Open(pathutils.WATCHER_LOCK_FILE)
2804 7e49b6ce Michael Hanselmann
    try:
2805 7e49b6ce Michael Hanselmann
      # TODO: Currently, this just blocks. There's no timeout.
2806 7e49b6ce Michael Hanselmann
      # TODO: Should it be a shared lock?
2807 7e49b6ce Michael Hanselmann
      watcher_block.Exclusive(blocking=True)
2808 7e49b6ce Michael Hanselmann
2809 7e49b6ce Michael Hanselmann
      # Stop master daemons, so that no new jobs can come in and all running
2810 7e49b6ce Michael Hanselmann
      # ones are finished
2811 7e49b6ce Michael Hanselmann
      self.feedback_fn("Stopping master daemons")
2812 ee4a14c0 Michael Hanselmann
      self._RunCmd(None, [pathutils.DAEMON_UTIL, "stop-master"])
2813 7e49b6ce Michael Hanselmann
      try:
2814 7e49b6ce Michael Hanselmann
        # Stop daemons on all nodes
2815 7e49b6ce Michael Hanselmann
        for node_name in self.online_nodes:
2816 7e49b6ce Michael Hanselmann
          self.feedback_fn("Stopping daemons on %s" % node_name)
2817 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "stop-all"])
2818 7e49b6ce Michael Hanselmann
2819 7e49b6ce Michael Hanselmann
        # All daemons are shut down now
2820 7e49b6ce Michael Hanselmann
        try:
2821 7e49b6ce Michael Hanselmann
          return fn(self, *args)
2822 d512e84b Michael Hanselmann
        except Exception, err:
2823 d512e84b Michael Hanselmann
          _, errmsg = FormatError(err)
2824 7e49b6ce Michael Hanselmann
          logging.exception("Caught exception")
2825 d512e84b Michael Hanselmann
          self.feedback_fn(errmsg)
2826 7e49b6ce Michael Hanselmann
          raise
2827 7e49b6ce Michael Hanselmann
      finally:
2828 7e49b6ce Michael Hanselmann
        # Start cluster again, master node last
2829 7e49b6ce Michael Hanselmann
        for node_name in self.nonmaster_nodes + [self.master_node]:
2830 7e49b6ce Michael Hanselmann
          self.feedback_fn("Starting daemons on %s" % node_name)
2831 ee4a14c0 Michael Hanselmann
          self._RunCmd(node_name, [pathutils.DAEMON_UTIL, "start-all"])
2832 7e49b6ce Michael Hanselmann
    finally:
2833 7e49b6ce Michael Hanselmann
      # Resume watcher
2834 7e49b6ce Michael Hanselmann
      watcher_block.Close()
2835 7e49b6ce Michael Hanselmann
2836 7e49b6ce Michael Hanselmann
2837 7e49b6ce Michael Hanselmann
def RunWhileClusterStopped(feedback_fn, fn, *args):
2838 7e49b6ce Michael Hanselmann
  """Calls a function while all cluster daemons are stopped.
2839 7e49b6ce Michael Hanselmann

2840 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2841 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2842 7e49b6ce Michael Hanselmann
  @type fn: callable
2843 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2844 7e49b6ce Michael Hanselmann

2845 7e49b6ce Michael Hanselmann
  """
2846 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2847 7e49b6ce Michael Hanselmann
2848 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2849 7e49b6ce Michael Hanselmann
  cl = GetClient()
2850 7e49b6ce Michael Hanselmann
2851 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2852 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2853 7e49b6ce Michael Hanselmann
2854 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2855 7e49b6ce Michael Hanselmann
2856 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2857 7e49b6ce Michael Hanselmann
  del cl
2858 7e49b6ce Michael Hanselmann
2859 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2860 7e49b6ce Michael Hanselmann
2861 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2862 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2863 7e49b6ce Michael Hanselmann
2864 7e49b6ce Michael Hanselmann
2865 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2866 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2867 9fbfbb7b Iustin Pop
                  units=None):
2868 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2869 137161c9 Michael Hanselmann

2870 9fbfbb7b Iustin Pop
  @type headers: dict
2871 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2872 9fbfbb7b Iustin Pop
      the table
2873 9fbfbb7b Iustin Pop
  @type fields: list
2874 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2875 9fbfbb7b Iustin Pop
      the data field
2876 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2877 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2878 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2879 9fbfbb7b Iustin Pop
      each field
2880 9fbfbb7b Iustin Pop
  @type data: list
2881 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2882 9fbfbb7b Iustin Pop
  @type numfields: list
2883 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2884 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2885 9fbfbb7b Iustin Pop
  @type unitfields: list
2886 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2887 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2888 9fbfbb7b Iustin Pop
  @type units: string or None
2889 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2890 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2891 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2892 137161c9 Michael Hanselmann

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

2976 ee3aedff Michael Hanselmann
  """
2977 ee3aedff Michael Hanselmann
  if value:
2978 ee3aedff Michael Hanselmann
    return "Y"
2979 ee3aedff Michael Hanselmann
  return "N"
2980 ee3aedff Michael Hanselmann
2981 ee3aedff Michael Hanselmann
2982 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2983 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2984 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2985 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2986 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2987 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2988 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2989 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2990 ee3aedff Michael Hanselmann
  }
2991 ee3aedff Michael Hanselmann
2992 ee3aedff Michael Hanselmann
2993 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2994 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2995 ee3aedff Michael Hanselmann

2996 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2997 ee3aedff Michael Hanselmann
  @type override: dict
2998 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2999 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3000 ee3aedff Michael Hanselmann
  @type unit: string
3001 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
3002 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
3003 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
3004 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
3005 ee3aedff Michael Hanselmann

3006 ee3aedff Michael Hanselmann
  """
3007 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
3008 ee3aedff Michael Hanselmann
  if fmt is not None:
3009 ee3aedff Michael Hanselmann
    return fmt
3010 ee3aedff Michael Hanselmann
3011 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
3012 ee3aedff Michael Hanselmann
3013 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
3014 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
3015 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
3016 ee3aedff Michael Hanselmann
3017 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
3018 ee3aedff Michael Hanselmann
  if fmt is not None:
3019 ee3aedff Michael Hanselmann
    return fmt
3020 ee3aedff Michael Hanselmann
3021 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
3022 ee3aedff Michael Hanselmann
3023 ee3aedff Michael Hanselmann
3024 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
3025 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
3026 ee3aedff Michael Hanselmann

3027 ee3aedff Michael Hanselmann
  """
3028 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
3029 ee3aedff Michael Hanselmann
    """Initializes this class.
3030 ee3aedff Michael Hanselmann

3031 ee3aedff Michael Hanselmann
    @type fn: callable
3032 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3033 ee3aedff Michael Hanselmann
    @type status_fn: callable
3034 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
3035 f0b1bafe Iustin Pop
    @type verbose: boolean
3036 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
3037 ee3aedff Michael Hanselmann

3038 ee3aedff Michael Hanselmann
    """
3039 ee3aedff Michael Hanselmann
    self._fn = fn
3040 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
3041 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
3042 ee3aedff Michael Hanselmann
3043 ee3aedff Michael Hanselmann
  def __call__(self, data):
3044 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
3045 ee3aedff Michael Hanselmann

3046 ee3aedff Michael Hanselmann
    """
3047 ee3aedff Michael Hanselmann
    (status, value) = data
3048 ee3aedff Michael Hanselmann
3049 ee3aedff Michael Hanselmann
    # Report status
3050 ee3aedff Michael Hanselmann
    self._status_fn(status)
3051 ee3aedff Michael Hanselmann
3052 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
3053 ee3aedff Michael Hanselmann
      return self._fn(value)
3054 ee3aedff Michael Hanselmann
3055 ee3aedff Michael Hanselmann
    assert value is None, \
3056 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
3057 ee3aedff Michael Hanselmann
3058 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
3059 ee3aedff Michael Hanselmann
3060 ee3aedff Michael Hanselmann
3061 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
3062 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
3063 ee3aedff Michael Hanselmann

3064 ae95e419 René Nussbaumer
  @param status: The result status
3065 f2c6673d Michael Hanselmann
  @type verbose: boolean
3066 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
3067 ae95e419 René Nussbaumer
  @return: Text of result status
3068 a6070ef7 Michael Hanselmann

3069 ae95e419 René Nussbaumer
  """
3070 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
3071 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
3072 ae95e419 René Nussbaumer
  try:
3073 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
3074 ae95e419 René Nussbaumer
  except KeyError:
3075 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
3076 cbfa4f0f Michael Hanselmann
  else:
3077 cbfa4f0f Michael Hanselmann
    if verbose:
3078 cbfa4f0f Michael Hanselmann
      return verbose_text
3079 cbfa4f0f Michael Hanselmann
    return normal_text
3080 ee3aedff Michael Hanselmann
3081 ee3aedff Michael Hanselmann
3082 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
3083 f0b1bafe Iustin Pop
                      header=False, verbose=False):
3084 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
3085 ee3aedff Michael Hanselmann

3086 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
3087 ee3aedff Michael Hanselmann
  @param result: result of query operation
3088 ee3aedff Michael Hanselmann
  @type unit: string
3089 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
3090 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
3091 ee3aedff Michael Hanselmann
  @type format_override: dict
3092 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3093 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3094 ee3aedff Michael Hanselmann
  @type separator: string or None
3095 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3096 ee3aedff Michael Hanselmann
  @type header: bool
3097 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
3098 f0b1bafe Iustin Pop
  @type verbose: boolean
3099 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3100 ee3aedff Michael Hanselmann

3101 ee3aedff Michael Hanselmann
  """
3102 ee3aedff Michael Hanselmann
  if unit is None:
3103 ee3aedff Michael Hanselmann
    if separator:
3104 ee3aedff Michael Hanselmann
      unit = "m"
3105 ee3aedff Michael Hanselmann
    else:
3106 ee3aedff Michael Hanselmann
      unit = "h"
3107 ee3aedff Michael Hanselmann
3108 ee3aedff Michael Hanselmann
  if format_override is None:
3109 ee3aedff Michael Hanselmann
    format_override = {}
3110 ee3aedff Michael Hanselmann
3111 cfb084ae René Nussbaumer
  stats = dict.fromkeys(constants.RS_ALL, 0)
3112 ee3aedff Michael Hanselmann
3113 ee3aedff Michael Hanselmann
  def _RecordStatus(status):
3114 ee3aedff Michael Hanselmann
    if status in stats:
3115 ee3aedff Michael Hanselmann
      stats[status] += 1
3116 ee3aedff Michael Hanselmann
3117 ee3aedff Michael Hanselmann
  columns = []
3118 ee3aedff Michael Hanselmann
  for fdef in result.fields:
3119 ee3aedff Michael Hanselmann
    assert fdef.title and fdef.name
3120 ee3aedff Michael Hanselmann
    (fn, align_right) = _GetColumnFormatter(fdef, format_override, unit)
3121 ee3aedff Michael Hanselmann
    columns.append(TableColumn(fdef.title,
3122 f0b1bafe Iustin Pop
                               _QueryColumnFormatter(fn, _RecordStatus,
3123 f0b1bafe Iustin Pop
                                                     verbose),
3124 ee3aedff Michael Hanselmann
                               align_right))
3125 ee3aedff Michael Hanselmann
3126 ee3aedff Michael Hanselmann
  table = FormatTable(result.data, columns, header, separator)
3127 ee3aedff Michael Hanselmann
3128 ee3aedff Michael Hanselmann
  # Collect statistics
3129 cfb084ae René Nussbaumer
  assert len(stats) == len(constants.RS_ALL)
3130 ee3aedff Michael Hanselmann
  assert compat.all(count >= 0 for count in stats.values())
3131 ee3aedff Michael Hanselmann
3132 ee3aedff Michael Hanselmann
  # Determine overall status. If there was no data, unknown fields must be
3133 ee3aedff Michael Hanselmann
  # detected via the field definitions.
3134 cfb084ae René Nussbaumer
  if (stats[constants.RS_UNKNOWN] or
3135 ee3aedff Michael Hanselmann
      (not result.data and _GetUnknownFields(result.fields))):
3136 ee3aedff Michael Hanselmann
    status = QR_UNKNOWN
3137 ee3aedff Michael Hanselmann
  elif compat.any(count > 0 for key, count in stats.items()
3138 cfb084ae René Nussbaumer
                  if key != constants.RS_NORMAL):
3139 ee3aedff Michael Hanselmann
    status = QR_INCOMPLETE
3140 ee3aedff Michael Hanselmann
  else:
3141 ee3aedff Michael Hanselmann
    status = QR_NORMAL
3142 ee3aedff Michael Hanselmann
3143 ee3aedff Michael Hanselmann
  return (status, table)
3144 ee3aedff Michael Hanselmann
3145 ee3aedff Michael Hanselmann
3146 ee3aedff Michael Hanselmann
def _GetUnknownFields(fdefs):
3147 ee3aedff Michael Hanselmann
  """Returns list of unknown fields included in C{fdefs}.
3148 ee3aedff Michael Hanselmann

3149 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3150 ee3aedff Michael Hanselmann

3151 ee3aedff Michael Hanselmann
  """
3152 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
3153 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
3154 ee3aedff Michael Hanselmann
3155 ee3aedff Michael Hanselmann
3156 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
3157 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
3158 ee3aedff Michael Hanselmann

3159 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3160 ee3aedff Michael Hanselmann

3161 ee3aedff Michael Hanselmann
  """
3162 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
3163 ee3aedff Michael Hanselmann
  if unknown:
3164 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
3165 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
3166 ee3aedff Michael Hanselmann
    return True
3167 ee3aedff Michael Hanselmann
3168 ee3aedff Michael Hanselmann
  return False
3169 ee3aedff Michael Hanselmann
3170 ee3aedff Michael Hanselmann
3171 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
3172 03ec545a Michael Hanselmann
                format_override=None, verbose=False, force_filter=False,
3173 6f287cf3 Iustin Pop
                namefield=None, qfilter=None, isnumeric=False):
3174 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
3175 ee3aedff Michael Hanselmann

3176 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3177 ee3aedff Michael Hanselmann
  @type fields: list of strings
3178 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3179 ee3aedff Michael Hanselmann
  @type names: list of strings
3180 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
3181 ee3aedff Michael Hanselmann
  @type unit: string or None
3182 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3183 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
3184 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
3185 ee3aedff Michael Hanselmann
  @type separator: string or None
3186 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3187 ee3aedff Michael Hanselmann
  @type header: bool
3188 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3189 2928de47 Michael Hanselmann
  @type force_filter: bool
3190 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
3191 ee3aedff Michael Hanselmann
  @type format_override: dict
3192 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3193 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3194 f0b1bafe Iustin Pop
  @type verbose: boolean
3195 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3196 03ec545a Michael Hanselmann
  @type namefield: string
3197 03ec545a Michael Hanselmann
  @param namefield: Name of field to use for simple filters (see
3198 03ec545a Michael Hanselmann
    L{qlang.MakeFilter} for details)
3199 f037e9d7 Michael Hanselmann
  @type qfilter: list or None
3200 f037e9d7 Michael Hanselmann
  @param qfilter: Query filter (in addition to names)
3201 6f287cf3 Iustin Pop
  @param isnumeric: bool
3202 6f287cf3 Iustin Pop
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3203 6f287cf3 Iustin Pop
    any simple filters built by namefield should use integer values to
3204 6f287cf3 Iustin Pop
    reflect that
3205 ee3aedff Michael Hanselmann

3206 ee3aedff Michael Hanselmann
  """
3207 ee3aedff Michael Hanselmann
  if not names:
3208 ee3aedff Michael Hanselmann
    names = None
3209 ee3aedff Michael Hanselmann
3210 6f287cf3 Iustin Pop
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3211 6f287cf3 Iustin Pop
                                isnumeric=isnumeric)
3212 f037e9d7 Michael Hanselmann
3213 f037e9d7 Michael Hanselmann
  if qfilter is None:
3214 f037e9d7 Michael Hanselmann
    qfilter = namefilter
3215 f037e9d7 Michael Hanselmann
  elif namefilter is not None:
3216 f037e9d7 Michael Hanselmann
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3217 2928de47 Michael Hanselmann
3218 727274dd Iustin Pop
  if cl is None:
3219 727274dd Iustin Pop
    cl = GetClient()
3220 727274dd Iustin Pop
3221 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
3222 ee3aedff Michael Hanselmann
3223 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3224 ee3aedff Michael Hanselmann
3225 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3226 ee3aedff Michael Hanselmann
                                     header=header,
3227 f0b1bafe Iustin Pop
                                     format_override=format_override,
3228 f0b1bafe Iustin Pop
                                     verbose=verbose)
3229 ee3aedff Michael Hanselmann
3230 ee3aedff Michael Hanselmann
  for line in data:
3231 ee3aedff Michael Hanselmann
    ToStdout(line)
3232 ee3aedff Michael Hanselmann
3233 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
3234 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
3235 ee3aedff Michael Hanselmann
3236 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
3237 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3238 ee3aedff Michael Hanselmann
3239 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
3240 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3241 ee3aedff Michael Hanselmann
3242 ee3aedff Michael Hanselmann
3243 c1912a48 Michael Hanselmann
def _FieldDescValues(fdef):
3244 c1912a48 Michael Hanselmann
  """Helper function for L{GenericListFields} to get query field description.
3245 c1912a48 Michael Hanselmann

3246 c1912a48 Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
3247 c1912a48 Michael Hanselmann
  @rtype: list
3248 c1912a48 Michael Hanselmann

3249 c1912a48 Michael Hanselmann
  """
3250 c1912a48 Michael Hanselmann
  return [
3251 c1912a48 Michael Hanselmann
    fdef.name,
3252 c1912a48 Michael Hanselmann
    _QFT_NAMES.get(fdef.kind, fdef.kind),
3253 c1912a48 Michael Hanselmann
    fdef.title,
3254 c1912a48 Michael Hanselmann
    fdef.doc,
3255 c1912a48 Michael Hanselmann
    ]
3256 c1912a48 Michael Hanselmann
3257 c1912a48 Michael Hanselmann
3258 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
3259 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
3260 ee3aedff Michael Hanselmann

3261 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3262 ee3aedff Michael Hanselmann
  @type fields: list of strings
3263 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3264 ee3aedff Michael Hanselmann
  @type separator: string or None
3265 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3266 ee3aedff Michael Hanselmann
  @type header: bool
3267 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3268 ee3aedff Michael Hanselmann

3269 ee3aedff Michael Hanselmann
  """
3270 ee3aedff Michael Hanselmann
  if cl is None:
3271 ee3aedff Michael Hanselmann
    cl = GetClient()
3272 ee3aedff Michael Hanselmann
3273 ee3aedff Michael Hanselmann
  if not fields:
3274 ee3aedff Michael Hanselmann
    fields = None
3275 ee3aedff Michael Hanselmann
3276 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
3277 ee3aedff Michael Hanselmann
3278 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3279 ee3aedff Michael Hanselmann
3280 ee3aedff Michael Hanselmann
  columns = [
3281 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
3282 c1912a48 Michael Hanselmann
    TableColumn("Type", str, False),
3283 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
3284 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
3285 ee3aedff Michael Hanselmann
    ]
3286 ee3aedff Michael Hanselmann
3287 c1912a48 Michael Hanselmann
  rows = map(_FieldDescValues, response.fields)
3288 ee3aedff Michael Hanselmann
3289 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
3290 ee3aedff Michael Hanselmann
    ToStdout(line)
3291 ee3aedff Michael Hanselmann
3292 ee3aedff Michael Hanselmann
  if found_unknown:
3293 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3294 ee3aedff Michael Hanselmann
3295 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3296 ee3aedff Michael Hanselmann
3297 ee3aedff Michael Hanselmann
3298 ee3aedff Michael Hanselmann
class TableColumn:
3299 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
3300 ee3aedff Michael Hanselmann

3301 ee3aedff Michael Hanselmann
  """
3302 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
3303 ee3aedff Michael Hanselmann
    """Initializes this class.
3304 ee3aedff Michael Hanselmann

3305 ee3aedff Michael Hanselmann
    @type title: string
3306 ee3aedff Michael Hanselmann
    @param title: Column title
3307 ee3aedff Michael Hanselmann
    @type fn: callable
3308 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3309 ee3aedff Michael Hanselmann
    @type align_right: bool
3310 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
3311 ee3aedff Michael Hanselmann

3312 ee3aedff Michael Hanselmann
    """
3313 ee3aedff Michael Hanselmann
    self.title = title
3314 ee3aedff Michael Hanselmann
    self.format = fn
3315 ee3aedff Michael Hanselmann
    self.align_right = align_right
3316 ee3aedff Michael Hanselmann
3317 ee3aedff Michael Hanselmann
3318 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
3319 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
3320 ee3aedff Michael Hanselmann

3321 ee3aedff Michael Hanselmann
  """
3322 ee3aedff Michael Hanselmann
  if align_right:
3323 ee3aedff Michael Hanselmann
    sign = ""
3324 ee3aedff Michael Hanselmann
  else:
3325 ee3aedff Michael Hanselmann
    sign = "-"
3326 ee3aedff Michael Hanselmann
3327 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
3328 ee3aedff Michael Hanselmann
3329 ee3aedff Michael Hanselmann
3330 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
3331 ee3aedff Michael Hanselmann
  """Formats data as a table.
3332 ee3aedff Michael Hanselmann

3333 ee3aedff Michael Hanselmann
  @type rows: list of lists
3334 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
3335 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
3336 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
3337 ee3aedff Michael Hanselmann
  @type header: bool
3338 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3339 ee3aedff Michael Hanselmann
  @type separator: string or None
3340 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
3341 ee3aedff Michael Hanselmann

3342 ee3aedff Michael Hanselmann
  """
3343 ee3aedff Michael Hanselmann
  if header:
3344 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
3345 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
3346 ee3aedff Michael Hanselmann
  else:
3347 ee3aedff Michael Hanselmann
    data = []
3348 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
3349 ee3aedff Michael Hanselmann
3350 ee3aedff Michael Hanselmann
  # Format row data
3351 ee3aedff Michael Hanselmann
  for row in rows:
3352 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
3353 ee3aedff Michael Hanselmann
3354 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
3355 ee3aedff Michael Hanselmann
3356 ee3aedff Michael Hanselmann
    if separator is None:
3357 ee3aedff Michael Hanselmann
      # Update column widths
3358 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3359 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
3360 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
3361 ee3aedff Michael Hanselmann
3362 ee3aedff Michael Hanselmann
    data.append(formatted)
3363 ee3aedff Michael Hanselmann
3364 ee3aedff Michael Hanselmann
  if separator is not None:
3365 ee3aedff Michael Hanselmann
    # Return early if a separator is used
3366 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
3367 ee3aedff Michael Hanselmann
3368 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
3369 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
3370 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
3371 ee3aedff Michael Hanselmann
3372 ee3aedff Michael Hanselmann
  # Build format string
3373 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3374 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
3375 ee3aedff Michael Hanselmann
3376 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
3377 ee3aedff Michael Hanselmann
3378 ee3aedff Michael Hanselmann
3379 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
3380 3386e7a9 Iustin Pop
  """Formats a given timestamp.
3381 3386e7a9 Iustin Pop

3382 3386e7a9 Iustin Pop
  @type ts: timestamp
3383 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3384 3386e7a9 Iustin Pop

3385 3386e7a9 Iustin Pop
  @rtype: string
3386 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
3387 3386e7a9 Iustin Pop

3388 3386e7a9 Iustin Pop
  """
3389 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3390 d0c8c01d Iustin Pop
    return "?"
3391 26a72a48 Michael Hanselmann
3392 26a72a48 Michael Hanselmann
  (sec, usecs) = ts
3393 26a72a48 Michael Hanselmann
  return utils.FormatTime(sec, usecs=usecs)
3394 2241e2b9 Iustin Pop
3395 2241e2b9 Iustin Pop
3396 2241e2b9 Iustin Pop
def ParseTimespec(value):
3397 2241e2b9 Iustin Pop
  """Parse a time specification.
3398 2241e2b9 Iustin Pop

3399 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
3400 2241e2b9 Iustin Pop

3401 2241e2b9 Iustin Pop
    - s: seconds
3402 2241e2b9 Iustin Pop
    - m: minutes
3403 2241e2b9 Iustin Pop
    - h: hours
3404 2241e2b9 Iustin Pop
    - d: day
3405 2241e2b9 Iustin Pop
    - w: weeks
3406 2241e2b9 Iustin Pop

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

3409 2241e2b9 Iustin Pop
  """
3410 2241e2b9 Iustin Pop
  value = str(value)
3411 2241e2b9 Iustin Pop
  if not value:
3412 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed",
3413 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
3414 2241e2b9 Iustin Pop
  suffix_map = {
3415 d0c8c01d Iustin Pop
    "s": 1,
3416 d0c8c01d Iustin Pop
    "m": 60,
3417 d0c8c01d Iustin Pop
    "h": 3600,
3418 d0c8c01d Iustin Pop
    "d": 86400,
3419 d0c8c01d Iustin Pop
    "w": 604800,
3420 2241e2b9 Iustin Pop
    }
3421 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
3422 2241e2b9 Iustin Pop
    try:
3423 2241e2b9 Iustin Pop
      value = int(value)
3424 691744c4 Iustin Pop
    except (TypeError, ValueError):
3425 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3426 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3427 2241e2b9 Iustin Pop
  else:
3428 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
3429 2241e2b9 Iustin Pop
    value = value[:-1]
3430 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
3431 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
3432 2cfbc784 Iustin Pop
                                 " suffix passed)", errors.ECODE_INVAL)
3433 2241e2b9 Iustin Pop
    try:
3434 2241e2b9 Iustin Pop
      value = int(value) * multiplier
3435 691744c4 Iustin Pop
    except (TypeError, ValueError):
3436 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3437 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3438 2241e2b9 Iustin Pop
  return value
3439 46fbdd04 Iustin Pop
3440 46fbdd04 Iustin Pop
3441 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3442 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
3443 4040a784 Iustin Pop
  """Returns the names of online nodes.
3444 4040a784 Iustin Pop

3445 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
3446 4040a784 Iustin Pop
  the online nodes.
3447 4040a784 Iustin Pop

3448 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
3449 4040a784 Iustin Pop
      offline ones)
3450 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
3451 4040a784 Iustin Pop
  @type nowarn: boolean
3452 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
3453 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
3454 4040a784 Iustin Pop
      note is not displayed
3455 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
3456 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
3457 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
3458 e9e26bb3 Iustin Pop
      (if any)
3459 e9e26bb3 Iustin Pop
  @type filter_master: boolean
3460 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
3461 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
3462 e9e26bb3 Iustin Pop
      node name against the list)
3463 05484a24 Michael Hanselmann
  @type nodegroup: string
3464 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
3465 4040a784 Iustin Pop

3466 4040a784 Iustin Pop
  """
3467 4040a784 Iustin Pop
  if cl is None:
3468 4040a784 Iustin Pop
    cl = GetClient()
3469 4040a784 Iustin Pop
3470 2e5c33db Iustin Pop
  qfilter = []
3471 05484a24 Michael Hanselmann
3472 05484a24 Michael Hanselmann
  if nodes:
3473 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3474 05484a24 Michael Hanselmann
3475 05484a24 Michael Hanselmann
  if nodegroup is not None:
3476 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3477 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3478 e9e26bb3 Iustin Pop
3479 e9e26bb3 Iustin Pop
  if filter_master:
3480 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3481 05484a24 Michael Hanselmann
3482 2e5c33db Iustin Pop
  if qfilter:
3483 2e5c33db Iustin Pop
    if len(qfilter) > 1:
3484 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
3485 05484a24 Michael Hanselmann
    else:
3486 2e5c33db Iustin Pop
      assert len(qfilter) == 1
3487 2e5c33db Iustin Pop
      final_filter = qfilter[0]
3488 e9e26bb3 Iustin Pop
  else:
3489 05484a24 Michael Hanselmann
    final_filter = None
3490 05484a24 Michael Hanselmann
3491 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3492 05484a24 Michael Hanselmann
3493 05484a24 Michael Hanselmann
  def _IsOffline(row):
3494 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
3495 05484a24 Michael Hanselmann
    return offline
3496 05484a24 Michael Hanselmann
3497 05484a24 Michael Hanselmann
  def _GetName(row):
3498 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
3499 05484a24 Michael Hanselmann
    return name
3500 05484a24 Michael Hanselmann
3501 05484a24 Michael Hanselmann
  def _GetSip(row):
3502 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
3503 05484a24 Michael Hanselmann
    return sip
3504 05484a24 Michael Hanselmann
3505 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
3506 e9e26bb3 Iustin Pop
3507 4040a784 Iustin Pop
  if offline and not nowarn:
3508 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
3509 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
3510 05484a24 Michael Hanselmann
3511 05484a24 Michael Hanselmann
  if secondary_ips:
3512 05484a24 Michael Hanselmann
    fn = _GetSip
3513 05484a24 Michael Hanselmann
  else:
3514 05484a24 Michael Hanselmann
    fn = _GetName
3515 05484a24 Michael Hanselmann
3516 05484a24 Michael Hanselmann
  return map(fn, online)
3517 4040a784 Iustin Pop
3518 4040a784 Iustin Pop
3519 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3520 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3521 46fbdd04 Iustin Pop

3522 46fbdd04 Iustin Pop
  @type stream: file object
3523 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3524 46fbdd04 Iustin Pop
  @type txt: str
3525 46fbdd04 Iustin Pop
  @param txt: the message
3526 46fbdd04 Iustin Pop

3527 46fbdd04 Iustin Pop
  """
3528 225e2544 Iustin Pop
  try:
3529 225e2544 Iustin Pop
    if args:
3530 225e2544 Iustin Pop
      args = tuple(args)
3531 225e2544 Iustin Pop
      stream.write(txt % args)
3532 225e2544 Iustin Pop
    else:
3533 225e2544 Iustin Pop
      stream.write(txt)
3534 d0c8c01d Iustin Pop
    stream.write("\n")
3535 225e2544 Iustin Pop
    stream.flush()
3536 225e2544 Iustin Pop
  except IOError, err:
3537 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3538 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3539 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3540 225e2544 Iustin Pop
    else:
3541 225e2544 Iustin Pop
      raise
3542 46fbdd04 Iustin Pop
3543 46fbdd04 Iustin Pop
3544 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3545 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3546 46fbdd04 Iustin Pop

3547 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3548 46fbdd04 Iustin Pop

3549 46fbdd04 Iustin Pop
  @type txt: str
3550 46fbdd04 Iustin Pop
  @param txt: the message
3551 46fbdd04 Iustin Pop

3552 46fbdd04 Iustin Pop
  """
3553 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3554 46fbdd04 Iustin Pop
3555 46fbdd04 Iustin Pop
3556 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3557 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3558 46fbdd04 Iustin Pop

3559 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3560 46fbdd04 Iustin Pop

3561 46fbdd04 Iustin Pop
  @type txt: str
3562 46fbdd04 Iustin Pop
  @param txt: the message
3563 46fbdd04 Iustin Pop

3564 46fbdd04 Iustin Pop
  """
3565 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3566 479636a3 Iustin Pop
3567 479636a3 Iustin Pop
3568 479636a3 Iustin Pop
class JobExecutor(object):
3569 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3570 479636a3 Iustin Pop

3571 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3572 479636a3 Iustin Pop
  GetResults() calls.
3573 479636a3 Iustin Pop

3574 479636a3 Iustin Pop
  """
3575 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3576 479636a3 Iustin Pop
    self.queue = []
3577 479636a3 Iustin Pop
    if cl is None:
3578 479636a3 Iustin Pop
      cl = GetClient()
3579 479636a3 Iustin Pop
    self.cl = cl
3580 479636a3 Iustin Pop
    self.verbose = verbose
3581 23b4b983 Iustin Pop
    self.jobs = []
3582 cff5fa7f Iustin Pop
    self.opts = opts
3583 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3584 60452edf Michael Hanselmann
    self._counter = itertools.count()
3585 479636a3 Iustin Pop
3586 8d99a8bf Michael Hanselmann
  @staticmethod
3587 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3588 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3589 8d99a8bf Michael Hanselmann

3590 8d99a8bf Michael Hanselmann
    """
3591 8d99a8bf Michael Hanselmann
    if name:
3592 8d99a8bf Michael Hanselmann
      return fmt % name
3593 8d99a8bf Michael Hanselmann
3594 8d99a8bf Michael Hanselmann
    return ""
3595 8d99a8bf Michael Hanselmann
3596 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3597 23b4b983 Iustin Pop
    """Record a job for later submit.
3598 479636a3 Iustin Pop

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

3602 479636a3 Iustin Pop
    """
3603 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3604 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3605 23b4b983 Iustin Pop
3606 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3607 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3608 8d99a8bf Michael Hanselmann

3609 8d99a8bf Michael Hanselmann
    """
3610 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3611 8d99a8bf Michael Hanselmann
3612 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3613 23b4b983 Iustin Pop
    """Submit all pending jobs.
3614 23b4b983 Iustin Pop

3615 23b4b983 Iustin Pop
    """
3616 66ecc479 Guido Trotter
    if each:
3617 66ecc479 Guido Trotter
      results = []
3618 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3619 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3620 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3621 519fafa1 Andrea Spadaccini
        results.append([True, self.cl.SubmitJob(ops)[0]])
3622 66ecc479 Guido Trotter
    else:
3623 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3624 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3625 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3626 5299e61f Iustin Pop
3627 5299e61f Iustin Pop
  def _ChooseJob(self):
3628 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3629 5299e61f Iustin Pop

3630 5299e61f Iustin Pop
    """
3631 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3632 5299e61f Iustin Pop
3633 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3634 11705e3d Iustin Pop
                               ["status"])
3635 5299e61f Iustin Pop
    assert result
3636 5299e61f Iustin Pop
3637 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3638 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3639 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3640 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3641 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3642 91c622a8 Iustin Pop
        # job is still present and waiting
3643 5299e61f Iustin Pop
        continue
3644 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3645 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3646 5299e61f Iustin Pop
      return job_data
3647 5299e61f Iustin Pop
3648 5299e61f Iustin Pop
    # no job found
3649 5299e61f Iustin Pop
    return self.jobs.pop(0)
3650 479636a3 Iustin Pop
3651 479636a3 Iustin Pop
  def GetResults(self):
3652 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3653 479636a3 Iustin Pop

3654 479636a3 Iustin Pop
    @rtype: list
3655 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3656 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3657 479636a3 Iustin Pop
        there will be the error message
3658 479636a3 Iustin Pop

3659 479636a3 Iustin Pop
    """
3660 23b4b983 Iustin Pop
    if not self.jobs:
3661 23b4b983 Iustin Pop
      self.SubmitPending()
3662 479636a3 Iustin Pop
    results = []
3663 479636a3 Iustin Pop
    if self.verbose:
3664 5299e61f Iustin Pop
      ok_jobs = [row[2] for row in self.jobs if row[1]]
3665 23b4b983 Iustin Pop
      if ok_jobs:
3666 4474f112 Iustin Pop
        ToStdout("Submitted jobs %s", utils.CommaJoin(ok_jobs))
3667 5299e61f Iustin Pop
3668 5299e61f Iustin Pop
    # first, remove any non-submitted jobs
3669 cea881e5 Michael Hanselmann
    self.jobs, failures = compat.partition(self.jobs, lambda x: x[1])
3670 5299e61f Iustin Pop
    for idx, _, jid, name in failures:
3671 4474f112 Iustin Pop
      ToStderr("Failed to submit job%s: %s", self._IfName(name, " for %s"), jid)
3672 c63355f2 Iustin Pop
      results.append((idx, False, jid))
3673 5299e61f Iustin Pop
3674 5299e61f Iustin Pop
    while self.jobs:
3675 5299e61f Iustin Pop
      (idx, _, jid, name) = self._ChooseJob()
3676 4474f112 Iustin Pop
      ToStdout("Waiting for job %s%s ...", jid, self._IfName(name, " for %s"))
3677 479636a3 Iustin Pop
      try:
3678 919ca415 Iustin Pop
        job_result = PollJob(jid, cl=self.cl, feedback_fn=self.feedback_fn)
3679 479636a3 Iustin Pop
        success = True
3680 91c622a8 Iustin Pop
      except errors.JobLost, err:
3681 91c622a8 Iustin Pop
        _, job_result = FormatError(err)
3682 4474f112 Iustin Pop
        ToStderr("Job %s%s has been archived, cannot check its result",
3683 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"))
3684 91c622a8 Iustin Pop
        success = False
3685 479636a3 Iustin Pop
      except (errors.GenericError, luxi.ProtocolError), err:
3686 479636a3 Iustin Pop
        _, job_result = FormatError(err)
3687 479636a3 Iustin Pop
        success = False
3688 479636a3 Iustin Pop
        # the error message will always be shown, verbose or not
3689 4474f112 Iustin Pop
        ToStderr("Job %s%s has failed: %s",
3690 4474f112 Iustin Pop
                 jid, self._IfName(name, " for %s"), job_result)
3691 479636a3 Iustin Pop
3692 5299e61f Iustin Pop
      results.append((idx, success, job_result))
3693 5299e61f Iustin Pop
3694 5299e61f Iustin Pop
    # sort based on the index, then drop it
3695 5299e61f Iustin Pop
    results.sort()
3696 5299e61f Iustin Pop
    results = [i[1:] for i in results]
3697 5299e61f Iustin Pop
3698 479636a3 Iustin Pop
    return results
3699 479636a3 Iustin Pop
3700 479636a3 Iustin Pop
  def WaitOrShow(self, wait):
3701 479636a3 Iustin Pop
    """Wait for job results or only print the job IDs.
3702 479636a3 Iustin Pop

3703 479636a3 Iustin Pop
    @type wait: boolean
3704 479636a3 Iustin Pop
    @param wait: whether to wait or not
3705 479636a3 Iustin Pop

3706 479636a3 Iustin Pop
    """
3707 479636a3 Iustin Pop
    if wait:
3708 479636a3 Iustin Pop
      return self.GetResults()
3709 479636a3 Iustin Pop
    else:
3710 23b4b983 Iustin Pop
      if not self.jobs:
3711 23b4b983 Iustin Pop
        self.SubmitPending()
3712 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3713 23b4b983 Iustin Pop
        if status:
3714 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3715 23b4b983 Iustin Pop
        else:
3716 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3717 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3718 acd19189 René Nussbaumer
3719 acd19189 René Nussbaumer
3720 4d99964c Bernardo Dal Seno
def FormatParamsDictInfo(param_dict, actual):
3721 4d99964c Bernardo Dal Seno
  """Formats a parameter dictionary.
3722 4d99964c Bernardo Dal Seno

3723 4d99964c Bernardo Dal Seno
  @type param_dict: dict
3724 4d99964c Bernardo Dal Seno
  @param param_dict: the own parameters
3725 4d99964c Bernardo Dal Seno
  @type actual: dict
3726 4d99964c Bernardo Dal Seno
  @param actual: the current parameter set (including defaults)
3727 4d99964c Bernardo Dal Seno
  @rtype: dict
3728 4d99964c Bernardo Dal Seno
  @return: dictionary where the value of each parameter is either a fully
3729 4d99964c Bernardo Dal Seno
      formatted string or a dictionary containing formatted strings
3730 4d99964c Bernardo Dal Seno

3731 4d99964c Bernardo Dal Seno
  """
3732 4d99964c Bernardo Dal Seno
  ret = {}
3733 4d99964c Bernardo Dal Seno
  for (key, data) in actual.items():
3734 4d99964c Bernardo Dal Seno
    if isinstance(data, dict) and data:
3735 4d99964c Bernardo Dal Seno
      ret[key] = FormatParamsDictInfo(param_dict.get(key, {}), data)
3736 4d99964c Bernardo Dal Seno
    else:
3737 4d99964c Bernardo Dal Seno
      ret[key] = str(param_dict.get(key, "default (%s)" % data))
3738 4d99964c Bernardo Dal Seno
  return ret
3739 4d99964c Bernardo Dal Seno
3740 4d99964c Bernardo Dal Seno
3741 d00884a2 Bernardo Dal Seno
def _FormatListInfoDefault(data, def_data):
3742 d00884a2 Bernardo Dal Seno
  if data is not None:
3743 d00884a2 Bernardo Dal Seno
    ret = utils.CommaJoin(data)
3744 d00884a2 Bernardo Dal Seno
  else:
3745 d00884a2 Bernardo Dal Seno
    ret = "default (%s)" % utils.CommaJoin(def_data)
3746 d00884a2 Bernardo Dal Seno
  return ret
3747 d00884a2 Bernardo Dal Seno
3748 d00884a2 Bernardo Dal Seno
3749 d00884a2 Bernardo Dal Seno
def FormatPolicyInfo(custom_ipolicy, eff_ipolicy, iscluster):
3750 d00884a2 Bernardo Dal Seno
  """Formats an instance policy.
3751 d00884a2 Bernardo Dal Seno

3752 d00884a2 Bernardo Dal Seno
  @type custom_ipolicy: dict
3753 d00884a2 Bernardo Dal Seno
  @param custom_ipolicy: own policy
3754 d00884a2 Bernardo Dal Seno
  @type eff_ipolicy: dict
3755 d00884a2 Bernardo Dal Seno
  @param eff_ipolicy: effective policy (including defaults); ignored for
3756 d00884a2 Bernardo Dal Seno
      cluster
3757 d00884a2 Bernardo Dal Seno
  @type iscluster: bool
3758 d00884a2 Bernardo Dal Seno
  @param iscluster: the policy is at cluster level
3759 d00884a2 Bernardo Dal Seno
  @rtype: list of pairs
3760 d00884a2 Bernardo Dal Seno
  @return: formatted data, suitable for L{PrintGenericInfo}
3761 d00884a2 Bernardo Dal Seno

3762 d00884a2 Bernardo Dal Seno
  """
3763 d00884a2 Bernardo Dal Seno
  if iscluster:
3764 d00884a2 Bernardo Dal Seno
    eff_ipolicy = custom_ipolicy
3765 d00884a2 Bernardo Dal Seno
3766 41044e04 Bernardo Dal Seno
  minmax_out = []
3767 41044e04 Bernardo Dal Seno
  custom_minmax = custom_ipolicy.get(constants.ISPECS_MINMAX)
3768 41044e04 Bernardo Dal Seno
  if custom_minmax:
3769 41044e04 Bernardo Dal Seno
    for (k, minmax) in enumerate(custom_minmax):
3770 41044e04 Bernardo Dal Seno
      minmax_out.append([
3771 41044e04 Bernardo Dal Seno
        ("%s/%s" % (key, k),
3772 41044e04 Bernardo Dal Seno
         FormatParamsDictInfo(minmax[key], minmax[key]))
3773 41044e04 Bernardo Dal Seno
        for key in constants.ISPECS_MINMAX_KEYS
3774 41044e04 Bernardo Dal Seno
        ])
3775 41044e04 Bernardo Dal Seno
  else:
3776 41044e04 Bernardo Dal Seno
    for (k, minmax) in enumerate(eff_ipolicy[constants.ISPECS_MINMAX]):
3777 41044e04 Bernardo Dal Seno
      minmax_out.append([
3778 41044e04 Bernardo Dal Seno
        ("%s/%s" % (key, k),
3779 41044e04 Bernardo Dal Seno
         FormatParamsDictInfo({}, minmax[key]))
3780 41044e04 Bernardo Dal Seno
        for key in constants.ISPECS_MINMAX_KEYS
3781 41044e04 Bernardo Dal Seno
        ])
3782 41044e04 Bernardo Dal Seno
  ret = [("bounds specs", minmax_out)]
3783 41044e04 Bernardo Dal Seno
3784 d00884a2 Bernardo Dal Seno
  if iscluster:
3785 d00884a2 Bernardo Dal Seno
    stdspecs = custom_ipolicy[constants.ISPECS_STD]
3786 d00884a2 Bernardo Dal Seno
    ret.append(
3787 d00884a2 Bernardo Dal Seno
      (constants.ISPECS_STD,
3788 d00884a2 Bernardo Dal Seno
       FormatParamsDictInfo(stdspecs, stdspecs))
3789 d00884a2 Bernardo Dal Seno
      )
3790 d00884a2 Bernardo Dal Seno
3791 d00884a2 Bernardo Dal Seno
  ret.append(
3792 9db0b351 Bernardo Dal Seno
    ("allowed disk templates",
3793 d00884a2 Bernardo Dal Seno
     _FormatListInfoDefault(custom_ipolicy.get(constants.IPOLICY_DTS),
3794 d00884a2 Bernardo Dal Seno
                            eff_ipolicy[constants.IPOLICY_DTS]))
3795 d00884a2 Bernardo Dal Seno
    )
3796 d00884a2 Bernardo Dal Seno
  ret.extend([
3797 d00884a2 Bernardo Dal Seno
    (key, str(custom_ipolicy.get(key, "default (%s)" % eff_ipolicy[key])))
3798 d00884a2 Bernardo Dal Seno
    for key in constants.IPOLICY_PARAMETERS
3799 d00884a2 Bernardo Dal Seno
    ])
3800 d00884a2 Bernardo Dal Seno
  return ret
3801 d00884a2 Bernardo Dal Seno
3802 d00884a2 Bernardo Dal Seno
3803 ea9d3b40 Bernardo Dal Seno
def _PrintSpecsParameters(buf, specs):
3804 ea9d3b40 Bernardo Dal Seno
  values = ("%s=%s" % (par, val) for (par, val) in sorted(specs.items()))
3805 ea9d3b40 Bernardo Dal Seno
  buf.write(",".join(values))
3806 ea9d3b40 Bernardo Dal Seno
3807 ea9d3b40 Bernardo Dal Seno
3808 ea9d3b40 Bernardo Dal Seno
def PrintIPolicyCommand(buf, ipolicy, isgroup):
3809 ea9d3b40 Bernardo Dal Seno
  """Print the command option used to generate the given instance policy.
3810 ea9d3b40 Bernardo Dal Seno

3811 ea9d3b40 Bernardo Dal Seno
  Currently only the parts dealing with specs are supported.
3812 ea9d3b40 Bernardo Dal Seno

3813 ea9d3b40 Bernardo Dal Seno
  @type buf: StringIO
3814 ea9d3b40 Bernardo Dal Seno
  @param buf: stream to write into
3815 ea9d3b40 Bernardo Dal Seno
  @type ipolicy: dict
3816 ea9d3b40 Bernardo Dal Seno
  @param ipolicy: instance policy
3817 ea9d3b40 Bernardo Dal Seno
  @type isgroup: bool
3818 ea9d3b40 Bernardo Dal Seno
  @param isgroup: whether the policy is at group level
3819 ea9d3b40 Bernardo Dal Seno

3820 ea9d3b40 Bernardo Dal Seno
  """
3821 ea9d3b40 Bernardo Dal Seno
  if not isgroup:
3822 ea9d3b40 Bernardo Dal Seno
    stdspecs = ipolicy.get("std")
3823 ea9d3b40 Bernardo Dal Seno
    if stdspecs:
3824 ea9d3b40 Bernardo Dal Seno
      buf.write(" %s " % IPOLICY_STD_SPECS_STR)
3825 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, stdspecs)
3826 ef99e3e8 Bernardo Dal Seno
  minmaxes = ipolicy.get("minmax", [])
3827 ef99e3e8 Bernardo Dal Seno
  first = True
3828 ef99e3e8 Bernardo Dal Seno
  for minmax in minmaxes:
3829 ef99e3e8 Bernardo Dal Seno
    minspecs = minmax.get("min")
3830 ef99e3e8 Bernardo Dal Seno
    maxspecs = minmax.get("max")
3831 ea9d3b40 Bernardo Dal Seno
    if minspecs and maxspecs:
3832 ef99e3e8 Bernardo Dal Seno
      if first:
3833 ef99e3e8 Bernardo Dal Seno
        buf.write(" %s " % IPOLICY_BOUNDS_SPECS_STR)
3834 ef99e3e8 Bernardo Dal Seno
        first = False
3835 ef99e3e8 Bernardo Dal Seno
      else:
3836 ef99e3e8 Bernardo Dal Seno
        buf.write("//")
3837 ea9d3b40 Bernardo Dal Seno
      buf.write("min:")
3838 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, minspecs)
3839 ea9d3b40 Bernardo Dal Seno
      buf.write("/max:")
3840 ea9d3b40 Bernardo Dal Seno
      _PrintSpecsParameters(buf, maxspecs)
3841 ea9d3b40 Bernardo Dal Seno
3842 ea9d3b40 Bernardo Dal Seno
3843 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3844 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3845 25bd815c René Nussbaumer

3846 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3847 25bd815c René Nussbaumer
  on a given list of list_type.
3848 25bd815c René Nussbaumer

3849 25bd815c René Nussbaumer
  @type names: list
3850 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3851 25bd815c René Nussbaumer
      we ask for confirmation
3852 25bd815c René Nussbaumer
  @type list_type: str
3853 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3854 25bd815c René Nussbaumer
  @type text: str
3855 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3856 25bd815c René Nussbaumer
  @rtype: boolean
3857 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3858 25bd815c René Nussbaumer

3859 25bd815c René Nussbaumer
  """
3860 25bd815c René Nussbaumer
  count = len(names)
3861 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3862 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3863 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3864 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3865 25bd815c René Nussbaumer
3866 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3867 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3868 25bd815c René Nussbaumer
3869 25bd815c René Nussbaumer
  if count > 20:
3870 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3871 25bd815c René Nussbaumer
    question = msg
3872 25bd815c René Nussbaumer
  else:
3873 25bd815c René Nussbaumer
    question = msg + affected
3874 25bd815c René Nussbaumer
3875 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3876 25bd815c René Nussbaumer
  if choice == "v":
3877 25bd815c René Nussbaumer
    choices.pop(1)
3878 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3879 25bd815c René Nussbaumer
  return choice
3880 703fa9ab Iustin Pop
3881 703fa9ab Iustin Pop
3882 cd415612 René Nussbaumer
def _MaybeParseUnit(elements):
3883 cd415612 René Nussbaumer
  """Parses and returns an array of potential values with units.
3884 cd415612 René Nussbaumer

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

4025 d948c101 Bernardo Dal Seno
  @param fill_all: whether for cluster policies we should ensure that
4026 d948c101 Bernardo Dal Seno
    all values are filled
4027 d948c101 Bernardo Dal Seno

4028 d948c101 Bernardo Dal Seno
  """
4029 919db916 Bernardo Dal Seno
  assert not (fill_all and allowed_values)
4030 919db916 Bernardo Dal Seno
4031 919db916 Bernardo Dal Seno
  split_specs = (ispecs_mem_size or ispecs_cpu_count or ispecs_disk_count or
4032 919db916 Bernardo Dal Seno
                 ispecs_disk_size or ispecs_nic_count)
4033 919db916 Bernardo Dal Seno
  if (split_specs and (minmax_ispecs is not None or std_ispecs is not None)):
4034 d2d3935a Bernardo Dal Seno
    raise errors.OpPrereqError("A --specs-xxx option cannot be specified"
4035 d2d3935a Bernardo Dal Seno
                               " together with any --ipolicy-xxx-specs option",
4036 d2d3935a Bernardo Dal Seno
                               errors.ECODE_INVAL)
4037 d948c101 Bernardo Dal Seno
4038 d948c101 Bernardo Dal Seno
  ipolicy_out = objects.MakeEmptyIPolicy()
4039 919db916 Bernardo Dal Seno
  if split_specs:
4040 919db916 Bernardo Dal Seno
    assert fill_all
4041 d2d3935a Bernardo Dal Seno
    _InitISpecsFromSplitOpts(ipolicy_out, ispecs_mem_size, ispecs_cpu_count,
4042 d2d3935a Bernardo Dal Seno
                             ispecs_disk_count, ispecs_disk_size,
4043 919db916 Bernardo Dal Seno
                             ispecs_nic_count, group_ipolicy, fill_all)
4044 919db916 Bernardo Dal Seno
  elif (minmax_ispecs is not None or std_ispecs is not None):
4045 d2d3935a Bernardo Dal Seno
    _InitISpecsFromFullOpts(ipolicy_out, minmax_ispecs, std_ispecs,
4046 d2d3935a Bernardo Dal Seno
                            group_ipolicy, allowed_values)
4047 703fa9ab Iustin Pop
4048 703fa9ab Iustin Pop
  if ipolicy_disk_templates is not None:
4049 f824ae42 Bernardo Dal Seno
    if allowed_values and ipolicy_disk_templates in allowed_values:
4050 f824ae42 Bernardo Dal Seno
      ipolicy_out[constants.IPOLICY_DTS] = ipolicy_disk_templates
4051 f824ae42 Bernardo Dal Seno
    else:
4052 f824ae42 Bernardo Dal Seno
      ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
4053 703fa9ab Iustin Pop
  if ipolicy_vcpu_ratio is not None:
4054 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
4055 ad5cc6bd René Nussbaumer
  if ipolicy_spindle_ratio is not None:
4056 ad5cc6bd René Nussbaumer
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
4057 703fa9ab Iustin Pop
4058 703fa9ab Iustin Pop
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
4059 703fa9ab Iustin Pop
4060 eeaa5f6c Bernardo Dal Seno
  if not group_ipolicy and fill_all:
4061 eeaa5f6c Bernardo Dal Seno
    ipolicy_out = objects.FillIPolicy(constants.IPOLICY_DEFAULTS, ipolicy_out)
4062 eeaa5f6c Bernardo Dal Seno
4063 703fa9ab Iustin Pop
  return ipolicy_out
4064 4d99964c Bernardo Dal Seno
4065 4d99964c Bernardo Dal Seno
4066 4d99964c Bernardo Dal Seno
def _SerializeGenericInfo(buf, data, level, afterkey=False):
4067 4d99964c Bernardo Dal Seno
  """Formatting core of L{PrintGenericInfo}.
4068 4d99964c Bernardo Dal Seno

4069 4d99964c Bernardo Dal Seno
  @param buf: (string) stream to accumulate the result into
4070 4d99964c Bernardo Dal Seno
  @param data: data to format
4071 4d99964c Bernardo Dal Seno
  @type level: int
4072 4d99964c Bernardo Dal Seno
  @param level: depth in the data hierarchy, used for indenting
4073 4d99964c Bernardo Dal Seno
  @type afterkey: bool
4074 4d99964c Bernardo Dal Seno
  @param afterkey: True when we are in the middle of a line after a key (used
4075 4d99964c Bernardo Dal Seno
      to properly add newlines or indentation)
4076 4d99964c Bernardo Dal Seno

4077 4d99964c Bernardo Dal Seno
  """
4078 4d99964c Bernardo Dal Seno
  baseind = "  "
4079 4d99964c Bernardo Dal Seno
  if isinstance(data, dict):
4080 4d99964c Bernardo Dal Seno
    if not data:
4081 4d99964c Bernardo Dal Seno
      buf.write("\n")
4082 4d99964c Bernardo Dal Seno
    else:
4083 4d99964c Bernardo Dal Seno
      if afterkey:
4084 4d99964c Bernardo Dal Seno
        buf.write("\n")
4085 4d99964c Bernardo Dal Seno
        doindent = True
4086 4d99964c Bernardo Dal Seno
      else:
4087 4d99964c Bernardo Dal Seno
        doindent = False
4088 4d99964c Bernardo Dal Seno
      for key in sorted(data):
4089 4d99964c Bernardo Dal Seno
        if doindent:
4090 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
4091 4d99964c Bernardo Dal Seno
        else:
4092 4d99964c Bernardo Dal Seno
          doindent = True
4093 4d99964c Bernardo Dal Seno
        buf.write(key)
4094 4d99964c Bernardo Dal Seno
        buf.write(": ")
4095 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, data[key], level + 1, afterkey=True)
4096 4d99964c Bernardo Dal Seno
  elif isinstance(data, list) and len(data) > 0 and isinstance(data[0], tuple):
4097 4d99964c Bernardo Dal Seno
    # list of tuples (an ordered dictionary)
4098 4d99964c Bernardo Dal Seno
    if afterkey:
4099 4d99964c Bernardo Dal Seno
      buf.write("\n")
4100 4d99964c Bernardo Dal Seno
      doindent = True
4101 4d99964c Bernardo Dal Seno
    else:
4102 4d99964c Bernardo Dal Seno
      doindent = False
4103 4d99964c Bernardo Dal Seno
    for (key, val) in data:
4104 4d99964c Bernardo Dal Seno
      if doindent:
4105 4d99964c Bernardo Dal Seno
        buf.write(baseind * level)
4106 4d99964c Bernardo Dal Seno
      else:
4107 4d99964c Bernardo Dal Seno
        doindent = True
4108 4d99964c Bernardo Dal Seno
      buf.write(key)
4109 4d99964c Bernardo Dal Seno
      buf.write(": ")
4110 4d99964c Bernardo Dal Seno
      _SerializeGenericInfo(buf, val, level + 1, afterkey=True)
4111 4d99964c Bernardo Dal Seno
  elif isinstance(data, list):
4112 4d99964c Bernardo Dal Seno
    if not data:
4113 4d99964c Bernardo Dal Seno
      buf.write("\n")
4114 4d99964c Bernardo Dal Seno
    else:
4115 4d99964c Bernardo Dal Seno
      if afterkey:
4116 4d99964c Bernardo Dal Seno
        buf.write("\n")
4117 4d99964c Bernardo Dal Seno
        doindent = True
4118 4d99964c Bernardo Dal Seno
      else:
4119 4d99964c Bernardo Dal Seno
        doindent = False
4120 4d99964c Bernardo Dal Seno
      for item in data:
4121 4d99964c Bernardo Dal Seno
        if doindent:
4122 4d99964c Bernardo Dal Seno
          buf.write(baseind * level)
4123 4d99964c Bernardo Dal Seno
        else:
4124 4d99964c Bernardo Dal Seno
          doindent = True
4125 4d99964c Bernardo Dal Seno
        buf.write("-")
4126 4d99964c Bernardo Dal Seno
        buf.write(baseind[1:])
4127 4d99964c Bernardo Dal Seno
        _SerializeGenericInfo(buf, item, level + 1)
4128 4d99964c Bernardo Dal Seno
  else:
4129 4d99964c Bernardo Dal Seno
    # This branch should be only taken for strings, but it's practically
4130 4d99964c Bernardo Dal Seno
    # impossible to guarantee that no other types are produced somewhere
4131 4d99964c Bernardo Dal Seno
    buf.write(str(data))
4132 4d99964c Bernardo Dal Seno
    buf.write("\n")
4133 4d99964c Bernardo Dal Seno
4134 4d99964c Bernardo Dal Seno
4135 4d99964c Bernardo Dal Seno
def PrintGenericInfo(data):
4136 4d99964c Bernardo Dal Seno
  """Print information formatted according to the hierarchy.
4137 4d99964c Bernardo Dal Seno

4138 4d99964c Bernardo Dal Seno
  The output is a valid YAML string.
4139 4d99964c Bernardo Dal Seno

4140 4d99964c Bernardo Dal Seno
  @param data: the data to print. It's a hierarchical structure whose elements
4141 4d99964c Bernardo Dal Seno
      can be:
4142 4d99964c Bernardo Dal Seno
        - dictionaries, where keys are strings and values are of any of the
4143 4d99964c Bernardo Dal Seno
          types listed here
4144 4d99964c Bernardo Dal Seno
        - lists of pairs (key, value), where key is a string and value is of
4145 4d99964c Bernardo Dal Seno
          any of the types listed here; it's a way to encode ordered
4146 4d99964c Bernardo Dal Seno
          dictionaries
4147 4d99964c Bernardo Dal Seno
        - lists of any of the types listed here
4148 4d99964c Bernardo Dal Seno
        - strings
4149 4d99964c Bernardo Dal Seno

4150 4d99964c Bernardo Dal Seno
  """
4151 4d99964c Bernardo Dal Seno
  buf = StringIO()
4152 4d99964c Bernardo Dal Seno
  _SerializeGenericInfo(buf, data, 0)
4153 4d99964c Bernardo Dal Seno
  ToStdout(buf.getvalue().rstrip("\n"))