Statistics
| Branch: | Tag: | Revision:

root / lib / cli.py @ c270ee07

History | View | Annotate | Download (122.6 kB)

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

346 863d7f46 Michael Hanselmann
  Value can be any of the ones passed to the constructor.
347 863d7f46 Michael Hanselmann

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

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

365 863d7f46 Michael Hanselmann
  """
366 863d7f46 Michael Hanselmann
367 863d7f46 Michael Hanselmann
368 863d7f46 Michael Hanselmann
class ArgUnknown(_Argument):
369 863d7f46 Michael Hanselmann
  """Unknown argument to program (e.g. determined at runtime).
370 863d7f46 Michael Hanselmann

371 863d7f46 Michael Hanselmann
  """
372 863d7f46 Michael Hanselmann
373 863d7f46 Michael Hanselmann
374 863d7f46 Michael Hanselmann
class ArgInstance(_Argument):
375 863d7f46 Michael Hanselmann
  """Instances argument.
376 863d7f46 Michael Hanselmann

377 863d7f46 Michael Hanselmann
  """
378 863d7f46 Michael Hanselmann
379 863d7f46 Michael Hanselmann
380 863d7f46 Michael Hanselmann
class ArgNode(_Argument):
381 863d7f46 Michael Hanselmann
  """Node argument.
382 863d7f46 Michael Hanselmann

383 863d7f46 Michael Hanselmann
  """
384 863d7f46 Michael Hanselmann
385 667dbd6b Adeodato Simo
386 9c784fb3 Dimitris Aragiorgis
class ArgNetwork(_Argument):
387 9c784fb3 Dimitris Aragiorgis
  """Network argument.
388 9c784fb3 Dimitris Aragiorgis

389 9c784fb3 Dimitris Aragiorgis
  """
390 9c784fb3 Dimitris Aragiorgis
391 3c286190 Dimitris Aragiorgis
392 667dbd6b Adeodato Simo
class ArgGroup(_Argument):
393 667dbd6b Adeodato Simo
  """Node group argument.
394 667dbd6b Adeodato Simo

395 667dbd6b Adeodato Simo
  """
396 667dbd6b Adeodato Simo
397 667dbd6b Adeodato Simo
398 863d7f46 Michael Hanselmann
class ArgJobId(_Argument):
399 863d7f46 Michael Hanselmann
  """Job ID argument.
400 863d7f46 Michael Hanselmann

401 863d7f46 Michael Hanselmann
  """
402 863d7f46 Michael Hanselmann
403 863d7f46 Michael Hanselmann
404 863d7f46 Michael Hanselmann
class ArgFile(_Argument):
405 863d7f46 Michael Hanselmann
  """File path argument.
406 863d7f46 Michael Hanselmann

407 863d7f46 Michael Hanselmann
  """
408 863d7f46 Michael Hanselmann
409 863d7f46 Michael Hanselmann
410 863d7f46 Michael Hanselmann
class ArgCommand(_Argument):
411 863d7f46 Michael Hanselmann
  """Command argument.
412 863d7f46 Michael Hanselmann

413 863d7f46 Michael Hanselmann
  """
414 863d7f46 Michael Hanselmann
415 863d7f46 Michael Hanselmann
416 83ec7961 Michael Hanselmann
class ArgHost(_Argument):
417 83ec7961 Michael Hanselmann
  """Host argument.
418 83ec7961 Michael Hanselmann

419 83ec7961 Michael Hanselmann
  """
420 83ec7961 Michael Hanselmann
421 83ec7961 Michael Hanselmann
422 f9faf9c3 René Nussbaumer
class ArgOs(_Argument):
423 f9faf9c3 René Nussbaumer
  """OS argument.
424 f9faf9c3 René Nussbaumer

425 f9faf9c3 René Nussbaumer
  """
426 f9faf9c3 René Nussbaumer
427 f9faf9c3 René Nussbaumer
428 b954f097 Constantinos Venetsanopoulos
class ArgExtStorage(_Argument):
429 b954f097 Constantinos Venetsanopoulos
  """ExtStorage argument.
430 b954f097 Constantinos Venetsanopoulos

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

450 846baef9 Iustin Pop
  Note that this function will modify its args parameter.
451 846baef9 Iustin Pop

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

475 810c50b7 Iustin Pop
  This function will extend the tags with the contents of the file
476 810c50b7 Iustin Pop
  passed in the 'tags_source' attribute of the opts parameter. A file
477 810c50b7 Iustin Pop
  named '-' will be replaced by stdin.
478 810c50b7 Iustin Pop

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

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

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

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

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

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

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

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

566 a8469393 Iustin Pop
  This function will convert a key=val[,...] string into a dict. Empty
567 a8469393 Iustin Pop
  values will be converted specially: keys which have the prefix 'no_'
568 a8469393 Iustin Pop
  will have the value=False and the prefix stripped, the others will
569 a8469393 Iustin Pop
  have value=True.
570 a8469393 Iustin Pop

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

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

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

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

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

635 a8469393 Iustin Pop
  """
636 a8469393 Iustin Pop
  return _SplitKeyVal(opt, value)
637 a8469393 Iustin Pop
638 a8469393 Iustin Pop
639 b459a848 Andrea Spadaccini
def check_bool(option, opt, value): # pylint: disable=W0613
640 e7b61bb0 Iustin Pop
  """Custom parser for yes/no options.
641 e7b61bb0 Iustin Pop

642 e7b61bb0 Iustin Pop
  This will store the parsed value as either True or False.
643 e7b61bb0 Iustin Pop

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

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

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

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

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

1599 d971402f Michael Hanselmann
  """
1600 d971402f Michael Hanselmann
  def __init__(self, exit_error):
1601 d971402f Michael Hanselmann
    """Initializes instances of this class.
1602 d971402f Michael Hanselmann

1603 d971402f Michael Hanselmann
    @type exit_error: bool
1604 d971402f Michael Hanselmann
    @param exit_error: Whether to report failure on exit
1605 d971402f Michael Hanselmann

1606 d971402f Michael Hanselmann
    """
1607 d971402f Michael Hanselmann
    Exception.__init__(self)
1608 d971402f Michael Hanselmann
    self.exit_error = exit_error
1609 d971402f Michael Hanselmann
1610 d971402f Michael Hanselmann
1611 d971402f Michael Hanselmann
class _ShowVersion(Exception):
1612 d971402f Michael Hanselmann
  """Exception class for L{_ParseArgs}.
1613 d971402f Michael Hanselmann

1614 d971402f Michael Hanselmann
  """
1615 d971402f Michael Hanselmann
1616 d971402f Michael Hanselmann
1617 d971402f Michael Hanselmann
def _ParseArgs(binary, argv, commands, aliases, env_override):
1618 c41eea6e Iustin Pop
  """Parser for the command line arguments.
1619 a8083063 Iustin Pop

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

1623 d971402f Michael Hanselmann
  @param binary: Script name
1624 d971402f Michael Hanselmann
  @param argv: Command line arguments
1625 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1626 d971402f Michael Hanselmann
  @param aliases: dictionary with command aliases {"alias": "target", ...}
1627 ef9fa5b9 René Nussbaumer
  @param env_override: list of env variables allowed for default args
1628 d971402f Michael Hanselmann
  @raise _ShowUsage: If usage description should be shown
1629 d971402f Michael Hanselmann
  @raise _ShowVersion: If version should be shown
1630 098c0958 Michael Hanselmann

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

1679 d971402f Michael Hanselmann
  @param binary: Script name
1680 d971402f Michael Hanselmann
  @param commands: Dictionary containing command definitions
1681 d971402f Michael Hanselmann

1682 d971402f Michael Hanselmann
  """
1683 d971402f Michael Hanselmann
  # compute the max line length for cmd + usage
1684 d971402f Michael Hanselmann
  mlen = min(60, max(map(len, commands)))
1685 d971402f Michael Hanselmann
1686 d971402f Michael Hanselmann
  yield "Usage: %s {command} [options...] [argument...]" % binary
1687 d971402f Michael Hanselmann
  yield "%s <command> --help to see details, or man %s" % (binary, binary)
1688 d971402f Michael Hanselmann
  yield ""
1689 d971402f Michael Hanselmann
  yield "Commands:"
1690 d971402f Michael Hanselmann
1691 d971402f Michael Hanselmann
  # and format a nice command list
1692 d971402f Michael Hanselmann
  for (cmd, (_, _, _, _, help_text)) in sorted(commands.items()):
1693 d971402f Michael Hanselmann
    help_lines = textwrap.wrap(help_text, 79 - 3 - mlen)
1694 d971402f Michael Hanselmann
    yield " %-*s - %s" % (mlen, cmd, help_lines.pop(0))
1695 d971402f Michael Hanselmann
    for line in help_lines:
1696 d971402f Michael Hanselmann
      yield " %-*s   %s" % (mlen, "", line)
1697 d971402f Michael Hanselmann
1698 d971402f Michael Hanselmann
  yield ""
1699 d971402f Michael Hanselmann
1700 d971402f Michael Hanselmann
1701 a8005e17 Michael Hanselmann
def _CheckArguments(cmd, args_def, args):
1702 a8005e17 Michael Hanselmann
  """Verifies the arguments using the argument definition.
1703 a8005e17 Michael Hanselmann

1704 a8005e17 Michael Hanselmann
  Algorithm:
1705 a8005e17 Michael Hanselmann

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

1708 a8005e17 Michael Hanselmann
    1. For each argument in definition
1709 a8005e17 Michael Hanselmann

1710 a8005e17 Michael Hanselmann
      1. Keep running count of minimum number of values (min_count)
1711 a8005e17 Michael Hanselmann
      1. Keep running count of maximum number of values (max_count)
1712 a8005e17 Michael Hanselmann
      1. If it has an unlimited number of values
1713 a8005e17 Michael Hanselmann

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

1716 a8005e17 Michael Hanselmann
    1. If last argument has limited number of values
1717 a8005e17 Michael Hanselmann

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

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

1722 a8005e17 Michael Hanselmann
  """
1723 a8005e17 Michael Hanselmann
  if args and not args_def:
1724 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects no arguments", cmd)
1725 a8005e17 Michael Hanselmann
    return False
1726 a8005e17 Michael Hanselmann
1727 a8005e17 Michael Hanselmann
  min_count = None
1728 a8005e17 Michael Hanselmann
  max_count = None
1729 a8005e17 Michael Hanselmann
  check_max = None
1730 a8005e17 Michael Hanselmann
1731 a8005e17 Michael Hanselmann
  last_idx = len(args_def) - 1
1732 a8005e17 Michael Hanselmann
1733 a8005e17 Michael Hanselmann
  for idx, arg in enumerate(args_def):
1734 a8005e17 Michael Hanselmann
    if min_count is None:
1735 a8005e17 Michael Hanselmann
      min_count = arg.min
1736 a8005e17 Michael Hanselmann
    elif arg.min is not None:
1737 a8005e17 Michael Hanselmann
      min_count += arg.min
1738 a8005e17 Michael Hanselmann
1739 a8005e17 Michael Hanselmann
    if max_count is None:
1740 a8005e17 Michael Hanselmann
      max_count = arg.max
1741 a8005e17 Michael Hanselmann
    elif arg.max is not None:
1742 a8005e17 Michael Hanselmann
      max_count += arg.max
1743 a8005e17 Michael Hanselmann
1744 a8005e17 Michael Hanselmann
    if idx == last_idx:
1745 a8005e17 Michael Hanselmann
      check_max = (arg.max is not None)
1746 a8005e17 Michael Hanselmann
1747 a8005e17 Michael Hanselmann
    elif arg.max is None:
1748 a8005e17 Michael Hanselmann
      raise errors.ProgrammerError("Only the last argument can have max=None")
1749 a8005e17 Michael Hanselmann
1750 a8005e17 Michael Hanselmann
  if check_max:
1751 a8005e17 Michael Hanselmann
    # Command with exact number of arguments
1752 a8005e17 Michael Hanselmann
    if (min_count is not None and max_count is not None and
1753 a8005e17 Michael Hanselmann
        min_count == max_count and len(args) != min_count):
1754 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects %d argument(s)", cmd, min_count)
1755 a8005e17 Michael Hanselmann
      return False
1756 a8005e17 Michael Hanselmann
1757 a8005e17 Michael Hanselmann
    # Command with limited number of arguments
1758 a8005e17 Michael Hanselmann
    if max_count is not None and len(args) > max_count:
1759 a8005e17 Michael Hanselmann
      ToStderr("Error: Command %s expects only %d argument(s)",
1760 a8005e17 Michael Hanselmann
               cmd, max_count)
1761 a8005e17 Michael Hanselmann
      return False
1762 a8005e17 Michael Hanselmann
1763 a8005e17 Michael Hanselmann
  # Command with some required arguments
1764 a8005e17 Michael Hanselmann
  if min_count is not None and len(args) < min_count:
1765 a8005e17 Michael Hanselmann
    ToStderr("Error: Command %s expects at least %d argument(s)",
1766 a8005e17 Michael Hanselmann
             cmd, min_count)
1767 a8005e17 Michael Hanselmann
    return False
1768 a8005e17 Michael Hanselmann
1769 a8005e17 Michael Hanselmann
  return True
1770 a8005e17 Michael Hanselmann
1771 a8005e17 Michael Hanselmann
1772 60d49723 Michael Hanselmann
def SplitNodeOption(value):
1773 60d49723 Michael Hanselmann
  """Splits the value of a --node option.
1774 60d49723 Michael Hanselmann

1775 60d49723 Michael Hanselmann
  """
1776 d0c8c01d Iustin Pop
  if value and ":" in value:
1777 d0c8c01d Iustin Pop
    return value.split(":", 1)
1778 60d49723 Michael Hanselmann
  else:
1779 60d49723 Michael Hanselmann
    return (value, None)
1780 60d49723 Michael Hanselmann
1781 60d49723 Michael Hanselmann
1782 07150497 Guido Trotter
def CalculateOSNames(os_name, os_variants):
1783 07150497 Guido Trotter
  """Calculates all the names an OS can be called, according to its variants.
1784 07150497 Guido Trotter

1785 07150497 Guido Trotter
  @type os_name: string
1786 07150497 Guido Trotter
  @param os_name: base name of the os
1787 07150497 Guido Trotter
  @type os_variants: list or None
1788 07150497 Guido Trotter
  @param os_variants: list of supported variants
1789 07150497 Guido Trotter
  @rtype: list
1790 07150497 Guido Trotter
  @return: list of valid names
1791 07150497 Guido Trotter

1792 07150497 Guido Trotter
  """
1793 07150497 Guido Trotter
  if os_variants:
1794 d0c8c01d Iustin Pop
    return ["%s+%s" % (os_name, v) for v in os_variants]
1795 07150497 Guido Trotter
  else:
1796 07150497 Guido Trotter
    return [os_name]
1797 07150497 Guido Trotter
1798 07150497 Guido Trotter
1799 a4ebd726 Michael Hanselmann
def ParseFields(selected, default):
1800 a4ebd726 Michael Hanselmann
  """Parses the values of "--field"-like options.
1801 a4ebd726 Michael Hanselmann

1802 a4ebd726 Michael Hanselmann
  @type selected: string or None
1803 a4ebd726 Michael Hanselmann
  @param selected: User-selected options
1804 a4ebd726 Michael Hanselmann
  @type default: list
1805 a4ebd726 Michael Hanselmann
  @param default: Default fields
1806 a4ebd726 Michael Hanselmann

1807 a4ebd726 Michael Hanselmann
  """
1808 a4ebd726 Michael Hanselmann
  if selected is None:
1809 a4ebd726 Michael Hanselmann
    return default
1810 a4ebd726 Michael Hanselmann
1811 a4ebd726 Michael Hanselmann
  if selected.startswith("+"):
1812 a4ebd726 Michael Hanselmann
    return default + selected[1:].split(",")
1813 a4ebd726 Michael Hanselmann
1814 a4ebd726 Michael Hanselmann
  return selected.split(",")
1815 a4ebd726 Michael Hanselmann
1816 a4ebd726 Michael Hanselmann
1817 e0e916fe Iustin Pop
UsesRPC = rpc.RunWithRPC
1818 4331f6cd Michael Hanselmann
1819 4331f6cd Michael Hanselmann
1820 47988778 Iustin Pop
def AskUser(text, choices=None):
1821 47988778 Iustin Pop
  """Ask the user a question.
1822 a8083063 Iustin Pop

1823 c41eea6e Iustin Pop
  @param text: the question to ask
1824 a8083063 Iustin Pop

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

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

1834 a8083063 Iustin Pop
  """
1835 47988778 Iustin Pop
  if choices is None:
1836 d0c8c01d Iustin Pop
    choices = [("y", True, "Perform the operation"),
1837 d0c8c01d Iustin Pop
               ("n", False, "Do not perform the operation")]
1838 47988778 Iustin Pop
  if not choices or not isinstance(choices, list):
1839 5bbd3f7f Michael Hanselmann
    raise errors.ProgrammerError("Invalid choices argument to AskUser")
1840 47988778 Iustin Pop
  for entry in choices:
1841 d0c8c01d Iustin Pop
    if not isinstance(entry, tuple) or len(entry) < 3 or entry[0] == "?":
1842 5bbd3f7f Michael Hanselmann
      raise errors.ProgrammerError("Invalid choices element to AskUser")
1843 47988778 Iustin Pop
1844 47988778 Iustin Pop
  answer = choices[-1][1]
1845 47988778 Iustin Pop
  new_text = []
1846 47988778 Iustin Pop
  for line in text.splitlines():
1847 47988778 Iustin Pop
    new_text.append(textwrap.fill(line, 70, replace_whitespace=False))
1848 47988778 Iustin Pop
  text = "\n".join(new_text)
1849 a8083063 Iustin Pop
  try:
1850 3023170f Iustin Pop
    f = file("/dev/tty", "a+")
1851 a8083063 Iustin Pop
  except IOError:
1852 47988778 Iustin Pop
    return answer
1853 a8083063 Iustin Pop
  try:
1854 47988778 Iustin Pop
    chars = [entry[0] for entry in choices]
1855 47988778 Iustin Pop
    chars[-1] = "[%s]" % chars[-1]
1856 d0c8c01d Iustin Pop
    chars.append("?")
1857 47988778 Iustin Pop
    maps = dict([(entry[0], entry[1]) for entry in choices])
1858 47988778 Iustin Pop
    while True:
1859 47988778 Iustin Pop
      f.write(text)
1860 d0c8c01d Iustin Pop
      f.write("\n")
1861 47988778 Iustin Pop
      f.write("/".join(chars))
1862 47988778 Iustin Pop
      f.write(": ")
1863 47988778 Iustin Pop
      line = f.readline(2).strip().lower()
1864 47988778 Iustin Pop
      if line in maps:
1865 47988778 Iustin Pop
        answer = maps[line]
1866 47988778 Iustin Pop
        break
1867 d0c8c01d Iustin Pop
      elif line == "?":
1868 47988778 Iustin Pop
        for entry in choices:
1869 47988778 Iustin Pop
          f.write(" %s - %s\n" % (entry[0], entry[2]))
1870 47988778 Iustin Pop
        f.write("\n")
1871 47988778 Iustin Pop
        continue
1872 a8083063 Iustin Pop
  finally:
1873 a8083063 Iustin Pop
    f.close()
1874 a8083063 Iustin Pop
  return answer
1875 a8083063 Iustin Pop
1876 a8083063 Iustin Pop
1877 e9d741b6 Iustin Pop
class JobSubmittedException(Exception):
1878 e9d741b6 Iustin Pop
  """Job was submitted, client should exit.
1879 e9d741b6 Iustin Pop

1880 e9d741b6 Iustin Pop
  This exception has one argument, the ID of the job that was
1881 e9d741b6 Iustin Pop
  submitted. The handler should print this ID.
1882 e9d741b6 Iustin Pop

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

1885 e9d741b6 Iustin Pop
  """
1886 e9d741b6 Iustin Pop
1887 e9d741b6 Iustin Pop
1888 0a1e74d9 Iustin Pop
def SendJob(ops, cl=None):
1889 0a1e74d9 Iustin Pop
  """Function to submit an opcode without waiting for the results.
1890 a8083063 Iustin Pop

1891 0a1e74d9 Iustin Pop
  @type ops: list
1892 0a1e74d9 Iustin Pop
  @param ops: list of opcodes
1893 0a1e74d9 Iustin Pop
  @type cl: luxi.Client
1894 0a1e74d9 Iustin Pop
  @param cl: the luxi client to use for communicating with the master;
1895 0a1e74d9 Iustin Pop
             if None, a new client will be created
1896 a8083063 Iustin Pop

1897 a8083063 Iustin Pop
  """
1898 e2212007 Iustin Pop
  if cl is None:
1899 b33e986b Iustin Pop
    cl = GetClient()
1900 685ee993 Iustin Pop
1901 0a1e74d9 Iustin Pop
  job_id = cl.SubmitJob(ops)
1902 0a1e74d9 Iustin Pop
1903 0a1e74d9 Iustin Pop
  return job_id
1904 0a1e74d9 Iustin Pop
1905 0a1e74d9 Iustin Pop
1906 4e338533 Michael Hanselmann
def GenericPollJob(job_id, cbs, report_cbs):
1907 4e338533 Michael Hanselmann
  """Generic job-polling function.
1908 0a1e74d9 Iustin Pop

1909 4e338533 Michael Hanselmann
  @type job_id: number
1910 4e338533 Michael Hanselmann
  @param job_id: Job ID
1911 4e338533 Michael Hanselmann
  @type cbs: Instance of L{JobPollCbBase}
1912 4e338533 Michael Hanselmann
  @param cbs: Data callbacks
1913 4e338533 Michael Hanselmann
  @type report_cbs: Instance of L{JobPollReportCbBase}
1914 4e338533 Michael Hanselmann
  @param report_cbs: Reporting callbacks
1915 0a1e74d9 Iustin Pop

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

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

1991 4e338533 Michael Hanselmann
    """
1992 4e338533 Michael Hanselmann
1993 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
1994 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
1995 4e338533 Michael Hanselmann
    """Waits for changes on a job.
1996 4e338533 Michael Hanselmann

1997 4e338533 Michael Hanselmann
    """
1998 4e338533 Michael Hanselmann
    raise NotImplementedError()
1999 4e338533 Michael Hanselmann
2000 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2001 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2002 4e338533 Michael Hanselmann

2003 4e338533 Michael Hanselmann
    @type job_ids: list of numbers
2004 4e338533 Michael Hanselmann
    @param job_ids: Job IDs
2005 4e338533 Michael Hanselmann
    @type fields: list of strings
2006 4e338533 Michael Hanselmann
    @param fields: Fields
2007 4e338533 Michael Hanselmann

2008 4e338533 Michael Hanselmann
    """
2009 4e338533 Michael Hanselmann
    raise NotImplementedError()
2010 4e338533 Michael Hanselmann
2011 4e338533 Michael Hanselmann
2012 4e338533 Michael Hanselmann
class JobPollReportCbBase:
2013 4e338533 Michael Hanselmann
  """Base class for L{GenericPollJob} reporting callbacks.
2014 4e338533 Michael Hanselmann

2015 4e338533 Michael Hanselmann
  """
2016 4e338533 Michael Hanselmann
  def __init__(self):
2017 4e338533 Michael Hanselmann
    """Initializes this class.
2018 4e338533 Michael Hanselmann

2019 4e338533 Michael Hanselmann
    """
2020 4e338533 Michael Hanselmann
2021 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2022 4e338533 Michael Hanselmann
    """Handles a log message.
2023 4e338533 Michael Hanselmann

2024 4e338533 Michael Hanselmann
    """
2025 4e338533 Michael Hanselmann
    raise NotImplementedError()
2026 4e338533 Michael Hanselmann
2027 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2028 4e338533 Michael Hanselmann
    """Called for if a job hasn't changed in a while.
2029 4e338533 Michael Hanselmann

2030 4e338533 Michael Hanselmann
    @type job_id: number
2031 4e338533 Michael Hanselmann
    @param job_id: Job ID
2032 4e338533 Michael Hanselmann
    @type status: string or None
2033 4e338533 Michael Hanselmann
    @param status: Job status if available
2034 4e338533 Michael Hanselmann

2035 4e338533 Michael Hanselmann
    """
2036 4e338533 Michael Hanselmann
    raise NotImplementedError()
2037 4e338533 Michael Hanselmann
2038 4e338533 Michael Hanselmann
2039 4e338533 Michael Hanselmann
class _LuxiJobPollCb(JobPollCbBase):
2040 4e338533 Michael Hanselmann
  def __init__(self, cl):
2041 4e338533 Michael Hanselmann
    """Initializes this class.
2042 4e338533 Michael Hanselmann

2043 4e338533 Michael Hanselmann
    """
2044 4e338533 Michael Hanselmann
    JobPollCbBase.__init__(self)
2045 4e338533 Michael Hanselmann
    self.cl = cl
2046 4e338533 Michael Hanselmann
2047 4e338533 Michael Hanselmann
  def WaitForJobChangeOnce(self, job_id, fields,
2048 4e338533 Michael Hanselmann
                           prev_job_info, prev_log_serial):
2049 4e338533 Michael Hanselmann
    """Waits for changes on a job.
2050 4e338533 Michael Hanselmann

2051 4e338533 Michael Hanselmann
    """
2052 4e338533 Michael Hanselmann
    return self.cl.WaitForJobChangeOnce(job_id, fields,
2053 4e338533 Michael Hanselmann
                                        prev_job_info, prev_log_serial)
2054 4e338533 Michael Hanselmann
2055 4e338533 Michael Hanselmann
  def QueryJobs(self, job_ids, fields):
2056 4e338533 Michael Hanselmann
    """Returns the selected fields for the selected job IDs.
2057 4e338533 Michael Hanselmann

2058 4e338533 Michael Hanselmann
    """
2059 4e338533 Michael Hanselmann
    return self.cl.QueryJobs(job_ids, fields)
2060 4e338533 Michael Hanselmann
2061 4e338533 Michael Hanselmann
2062 4e338533 Michael Hanselmann
class FeedbackFnJobPollReportCb(JobPollReportCbBase):
2063 4e338533 Michael Hanselmann
  def __init__(self, feedback_fn):
2064 4e338533 Michael Hanselmann
    """Initializes this class.
2065 4e338533 Michael Hanselmann

2066 4e338533 Michael Hanselmann
    """
2067 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2068 4e338533 Michael Hanselmann
2069 4e338533 Michael Hanselmann
    self.feedback_fn = feedback_fn
2070 4e338533 Michael Hanselmann
2071 4e338533 Michael Hanselmann
    assert callable(feedback_fn)
2072 4e338533 Michael Hanselmann
2073 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2074 4e338533 Michael Hanselmann
    """Handles a log message.
2075 4e338533 Michael Hanselmann

2076 4e338533 Michael Hanselmann
    """
2077 4e338533 Michael Hanselmann
    self.feedback_fn((timestamp, log_type, log_msg))
2078 4e338533 Michael Hanselmann
2079 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2080 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2081 4e338533 Michael Hanselmann

2082 4e338533 Michael Hanselmann
    """
2083 4e338533 Michael Hanselmann
    # Ignore
2084 4e338533 Michael Hanselmann
2085 4e338533 Michael Hanselmann
2086 4e338533 Michael Hanselmann
class StdioJobPollReportCb(JobPollReportCbBase):
2087 4e338533 Michael Hanselmann
  def __init__(self):
2088 4e338533 Michael Hanselmann
    """Initializes this class.
2089 4e338533 Michael Hanselmann

2090 4e338533 Michael Hanselmann
    """
2091 4e338533 Michael Hanselmann
    JobPollReportCbBase.__init__(self)
2092 4e338533 Michael Hanselmann
2093 4e338533 Michael Hanselmann
    self.notified_queued = False
2094 4e338533 Michael Hanselmann
    self.notified_waitlock = False
2095 4e338533 Michael Hanselmann
2096 4e338533 Michael Hanselmann
  def ReportLogMessage(self, job_id, serial, timestamp, log_type, log_msg):
2097 4e338533 Michael Hanselmann
    """Handles a log message.
2098 4e338533 Michael Hanselmann

2099 4e338533 Michael Hanselmann
    """
2100 4e338533 Michael Hanselmann
    ToStdout("%s %s", time.ctime(utils.MergeTime(timestamp)),
2101 8a7f1c61 Michael Hanselmann
             FormatLogMessage(log_type, log_msg))
2102 4e338533 Michael Hanselmann
2103 4e338533 Michael Hanselmann
  def ReportNotChanged(self, job_id, status):
2104 4e338533 Michael Hanselmann
    """Called if a job hasn't changed in a while.
2105 4e338533 Michael Hanselmann

2106 4e338533 Michael Hanselmann
    """
2107 4e338533 Michael Hanselmann
    if status is None:
2108 4e338533 Michael Hanselmann
      return
2109 4e338533 Michael Hanselmann
2110 4e338533 Michael Hanselmann
    if status == constants.JOB_STATUS_QUEUED and not self.notified_queued:
2111 4e338533 Michael Hanselmann
      ToStderr("Job %s is waiting in queue", job_id)
2112 4e338533 Michael Hanselmann
      self.notified_queued = True
2113 4e338533 Michael Hanselmann
2114 47099cd1 Michael Hanselmann
    elif status == constants.JOB_STATUS_WAITING and not self.notified_waitlock:
2115 4e338533 Michael Hanselmann
      ToStderr("Job %s is trying to acquire all necessary locks", job_id)
2116 4e338533 Michael Hanselmann
      self.notified_waitlock = True
2117 4e338533 Michael Hanselmann
2118 4e338533 Michael Hanselmann
2119 8a7f1c61 Michael Hanselmann
def FormatLogMessage(log_type, log_msg):
2120 8a7f1c61 Michael Hanselmann
  """Formats a job message according to its type.
2121 8a7f1c61 Michael Hanselmann

2122 8a7f1c61 Michael Hanselmann
  """
2123 8a7f1c61 Michael Hanselmann
  if log_type != constants.ELOG_MESSAGE:
2124 8a7f1c61 Michael Hanselmann
    log_msg = str(log_msg)
2125 8a7f1c61 Michael Hanselmann
2126 8a7f1c61 Michael Hanselmann
  return utils.SafeEncode(log_msg)
2127 8a7f1c61 Michael Hanselmann
2128 8a7f1c61 Michael Hanselmann
2129 583163a6 Michael Hanselmann
def PollJob(job_id, cl=None, feedback_fn=None, reporter=None):
2130 4e338533 Michael Hanselmann
  """Function to poll for the result of a job.
2131 4e338533 Michael Hanselmann

2132 4e338533 Michael Hanselmann
  @type job_id: job identified
2133 4e338533 Michael Hanselmann
  @param job_id: the job to poll for results
2134 4e338533 Michael Hanselmann
  @type cl: luxi.Client
2135 4e338533 Michael Hanselmann
  @param cl: the luxi client to use for communicating with the master;
2136 4e338533 Michael Hanselmann
             if None, a new client will be created
2137 4e338533 Michael Hanselmann

2138 4e338533 Michael Hanselmann
  """
2139 4e338533 Michael Hanselmann
  if cl is None:
2140 4e338533 Michael Hanselmann
    cl = GetClient()
2141 4e338533 Michael Hanselmann
2142 583163a6 Michael Hanselmann
  if reporter is None:
2143 583163a6 Michael Hanselmann
    if feedback_fn:
2144 583163a6 Michael Hanselmann
      reporter = FeedbackFnJobPollReportCb(feedback_fn)
2145 583163a6 Michael Hanselmann
    else:
2146 583163a6 Michael Hanselmann
      reporter = StdioJobPollReportCb()
2147 583163a6 Michael Hanselmann
  elif feedback_fn:
2148 583163a6 Michael Hanselmann
    raise errors.ProgrammerError("Can't specify reporter and feedback function")
2149 4e338533 Michael Hanselmann
2150 4e338533 Michael Hanselmann
  return GenericPollJob(job_id, _LuxiJobPollCb(cl), reporter)
2151 ceab32dd Iustin Pop
2152 ceab32dd Iustin Pop
2153 583163a6 Michael Hanselmann
def SubmitOpCode(op, cl=None, feedback_fn=None, opts=None, reporter=None):
2154 0a1e74d9 Iustin Pop
  """Legacy function to submit an opcode.
2155 0a1e74d9 Iustin Pop

2156 0a1e74d9 Iustin Pop
  This is just a simple wrapper over the construction of the processor
2157 0a1e74d9 Iustin Pop
  instance. It should be extended to better handle feedback and
2158 0a1e74d9 Iustin Pop
  interaction functions.
2159 0a1e74d9 Iustin Pop

2160 0a1e74d9 Iustin Pop
  """
2161 0a1e74d9 Iustin Pop
  if cl is None:
2162 0a1e74d9 Iustin Pop
    cl = GetClient()
2163 0a1e74d9 Iustin Pop
2164 293ba2d8 Iustin Pop
  SetGenericOpcodeOpts([op], opts)
2165 293ba2d8 Iustin Pop
2166 5d297d8a Michael Hanselmann
  job_id = SendJob([op], cl=cl)
2167 0a1e74d9 Iustin Pop
2168 583163a6 Michael Hanselmann
  op_results = PollJob(job_id, cl=cl, feedback_fn=feedback_fn,
2169 583163a6 Michael Hanselmann
                       reporter=reporter)
2170 53c04d04 Iustin Pop
2171 53c04d04 Iustin Pop
  return op_results[0]
2172 0a1e74d9 Iustin Pop
2173 0a1e74d9 Iustin Pop
2174 94428652 Iustin Pop
def SubmitOrSend(op, opts, cl=None, feedback_fn=None):
2175 94428652 Iustin Pop
  """Wrapper around SubmitOpCode or SendJob.
2176 94428652 Iustin Pop

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

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

2185 94428652 Iustin Pop
  """
2186 94428652 Iustin Pop
  if opts and opts.submit_only:
2187 293ba2d8 Iustin Pop
    job = [op]
2188 293ba2d8 Iustin Pop
    SetGenericOpcodeOpts(job, opts)
2189 293ba2d8 Iustin Pop
    job_id = SendJob(job, cl=cl)
2190 e9d741b6 Iustin Pop
    raise JobSubmittedException(job_id)
2191 94428652 Iustin Pop
  else:
2192 293ba2d8 Iustin Pop
    return SubmitOpCode(op, cl=cl, feedback_fn=feedback_fn, opts=opts)
2193 293ba2d8 Iustin Pop
2194 293ba2d8 Iustin Pop
2195 293ba2d8 Iustin Pop
def SetGenericOpcodeOpts(opcode_list, options):
2196 293ba2d8 Iustin Pop
  """Processor for generic options.
2197 293ba2d8 Iustin Pop

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

2201 293ba2d8 Iustin Pop
  @param opcode_list: list of opcodes
2202 293ba2d8 Iustin Pop
  @param options: command line options or None
2203 293ba2d8 Iustin Pop
  @return: None (in-place modification)
2204 293ba2d8 Iustin Pop

2205 293ba2d8 Iustin Pop
  """
2206 293ba2d8 Iustin Pop
  if not options:
2207 293ba2d8 Iustin Pop
    return
2208 293ba2d8 Iustin Pop
  for op in opcode_list:
2209 aa06f8c6 Michael Hanselmann
    op.debug_level = options.debug
2210 a0a6ff34 Iustin Pop
    if hasattr(options, "dry_run"):
2211 a0a6ff34 Iustin Pop
      op.dry_run = options.dry_run
2212 aa06f8c6 Michael Hanselmann
    if getattr(options, "priority", None) is not None:
2213 552328b8 Michael Hanselmann
      op.priority = options.priority
2214 94428652 Iustin Pop
2215 94428652 Iustin Pop
2216 42ab9ac4 Iustin Pop
def GetClient(query=False):
2217 42ab9ac4 Iustin Pop
  """Connects to the a luxi socket and returns a client.
2218 42ab9ac4 Iustin Pop

2219 42ab9ac4 Iustin Pop
  @type query: boolean
2220 42ab9ac4 Iustin Pop
  @param query: this signifies that the client will only be
2221 42ab9ac4 Iustin Pop
      used for queries; if the build-time parameter
2222 42ab9ac4 Iustin Pop
      enable-split-queries is enabled, then the client will be
2223 42ab9ac4 Iustin Pop
      connected to the query socket instead of the masterd socket
2224 42ab9ac4 Iustin Pop

2225 42ab9ac4 Iustin Pop
  """
2226 055d6ac0 Iustin Pop
  override_socket = os.getenv(constants.LUXI_OVERRIDE, "")
2227 055d6ac0 Iustin Pop
  if override_socket:
2228 055d6ac0 Iustin Pop
    if override_socket == constants.LUXI_OVERRIDE_MASTER:
2229 055d6ac0 Iustin Pop
      address = pathutils.MASTER_SOCKET
2230 055d6ac0 Iustin Pop
    elif override_socket == constants.LUXI_OVERRIDE_QUERY:
2231 055d6ac0 Iustin Pop
      address = pathutils.QUERY_SOCKET
2232 055d6ac0 Iustin Pop
    else:
2233 055d6ac0 Iustin Pop
      address = override_socket
2234 055d6ac0 Iustin Pop
  elif query and constants.ENABLE_SPLIT_QUERY:
2235 ee4a14c0 Michael Hanselmann
    address = pathutils.QUERY_SOCKET
2236 42ab9ac4 Iustin Pop
  else:
2237 42ab9ac4 Iustin Pop
    address = None
2238 af30b2fd Michael Hanselmann
  # TODO: Cache object?
2239 b33e986b Iustin Pop
  try:
2240 42ab9ac4 Iustin Pop
    client = luxi.Client(address=address)
2241 b33e986b Iustin Pop
  except luxi.NoMasterError:
2242 d9a51679 Michael Hanselmann
    ss = ssconf.SimpleStore()
2243 d9a51679 Michael Hanselmann
2244 d9a51679 Michael Hanselmann
    # Try to read ssconf file
2245 d9a51679 Michael Hanselmann
    try:
2246 d9a51679 Michael Hanselmann
      ss.GetMasterNode()
2247 d9a51679 Michael Hanselmann
    except errors.ConfigurationError:
2248 d9a51679 Michael Hanselmann
      raise errors.OpPrereqError("Cluster not initialized or this machine is"
2249 2cfbc784 Iustin Pop
                                 " not part of a cluster",
2250 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
2251 d9a51679 Michael Hanselmann
2252 d9a51679 Michael Hanselmann
    master, myself = ssconf.GetMasterAndMyself(ss=ss)
2253 b33e986b Iustin Pop
    if master != myself:
2254 b33e986b Iustin Pop
      raise errors.OpPrereqError("This is not the master node, please connect"
2255 b33e986b Iustin Pop
                                 " to node '%s' and rerun the command" %
2256 2cfbc784 Iustin Pop
                                 master, errors.ECODE_INVAL)
2257 d9a51679 Michael Hanselmann
    raise
2258 b33e986b Iustin Pop
  return client
2259 af30b2fd Michael Hanselmann
2260 af30b2fd Michael Hanselmann
2261 73702ee7 Iustin Pop
def FormatError(err):
2262 73702ee7 Iustin Pop
  """Return a formatted error message for a given error.
2263 73702ee7 Iustin Pop

2264 73702ee7 Iustin Pop
  This function takes an exception instance and returns a tuple
2265 73702ee7 Iustin Pop
  consisting of two values: first, the recommended exit code, and
2266 73702ee7 Iustin Pop
  second, a string describing the error message (not
2267 73702ee7 Iustin Pop
  newline-terminated).
2268 73702ee7 Iustin Pop

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

2359 ef9fa5b9 René Nussbaumer
  @param commands: a dictionary with a special structure, see the design doc
2360 ef9fa5b9 René Nussbaumer
                   for command line handling.
2361 ef9fa5b9 René Nussbaumer
  @param override: if not None, we expect a dictionary with keys that will
2362 ef9fa5b9 René Nussbaumer
                   override command line options; this can be used to pass
2363 ef9fa5b9 René Nussbaumer
                   options from the scripts to generic functions
2364 ef9fa5b9 René Nussbaumer
  @param aliases: dictionary with command aliases {'alias': 'target, ...}
2365 ef9fa5b9 René Nussbaumer
  @param env_override: list of environment names which are allowed to submit
2366 ef9fa5b9 René Nussbaumer
                       default args for commands
2367 a8083063 Iustin Pop

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

2445 845c79d8 Michael Hanselmann
  """
2446 845c79d8 Michael Hanselmann
  try:
2447 845c79d8 Michael Hanselmann
    nic_max = max(int(nidx[0]) + 1 for nidx in optvalue)
2448 845c79d8 Michael Hanselmann
  except (TypeError, ValueError), err:
2449 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err),
2450 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
2451 845c79d8 Michael Hanselmann
2452 845c79d8 Michael Hanselmann
  nics = [{}] * nic_max
2453 845c79d8 Michael Hanselmann
  for nidx, ndict in optvalue:
2454 845c79d8 Michael Hanselmann
    nidx = int(nidx)
2455 845c79d8 Michael Hanselmann
2456 845c79d8 Michael Hanselmann
    if not isinstance(ndict, dict):
2457 845c79d8 Michael Hanselmann
      raise errors.OpPrereqError("Invalid nic/%d value: expected dict,"
2458 2cfbc784 Iustin Pop
                                 " got %s" % (nidx, ndict), errors.ECODE_INVAL)
2459 845c79d8 Michael Hanselmann
2460 845c79d8 Michael Hanselmann
    utils.ForceDictType(ndict, constants.INIC_PARAMS_TYPES)
2461 845c79d8 Michael Hanselmann
2462 845c79d8 Michael Hanselmann
    nics[nidx] = ndict
2463 845c79d8 Michael Hanselmann
2464 845c79d8 Michael Hanselmann
  return nics
2465 845c79d8 Michael Hanselmann
2466 845c79d8 Michael Hanselmann
2467 d77490c5 Iustin Pop
def GenericInstanceCreate(mode, opts, args):
2468 d77490c5 Iustin Pop
  """Add an instance to the cluster via either creation or import.
2469 d77490c5 Iustin Pop

2470 d77490c5 Iustin Pop
  @param mode: constants.INSTANCE_CREATE or constants.INSTANCE_IMPORT
2471 d77490c5 Iustin Pop
  @param opts: the command line options selected by the user
2472 d77490c5 Iustin Pop
  @type args: list
2473 d77490c5 Iustin Pop
  @param args: should contain only one element, the new instance name
2474 d77490c5 Iustin Pop
  @rtype: int
2475 d77490c5 Iustin Pop
  @return: the desired exit code
2476 d77490c5 Iustin Pop

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

2610 7e49b6ce Michael Hanselmann
  """
2611 7e49b6ce Michael Hanselmann
  def __init__(self, feedback_fn, cluster_name, master_node, online_nodes):
2612 7e49b6ce Michael Hanselmann
    """Initializes this class.
2613 7e49b6ce Michael Hanselmann

2614 7e49b6ce Michael Hanselmann
    @type feedback_fn: callable
2615 7e49b6ce Michael Hanselmann
    @param feedback_fn: Feedback function
2616 7e49b6ce Michael Hanselmann
    @type cluster_name: string
2617 7e49b6ce Michael Hanselmann
    @param cluster_name: Cluster name
2618 7e49b6ce Michael Hanselmann
    @type master_node: string
2619 7e49b6ce Michael Hanselmann
    @param master_node Master node name
2620 7e49b6ce Michael Hanselmann
    @type online_nodes: list
2621 7e49b6ce Michael Hanselmann
    @param online_nodes: List of names of online nodes
2622 7e49b6ce Michael Hanselmann

2623 7e49b6ce Michael Hanselmann
    """
2624 7e49b6ce Michael Hanselmann
    self.feedback_fn = feedback_fn
2625 7e49b6ce Michael Hanselmann
    self.cluster_name = cluster_name
2626 7e49b6ce Michael Hanselmann
    self.master_node = master_node
2627 7e49b6ce Michael Hanselmann
    self.online_nodes = online_nodes
2628 7e49b6ce Michael Hanselmann
2629 7e49b6ce Michael Hanselmann
    self.ssh = ssh.SshRunner(self.cluster_name)
2630 7e49b6ce Michael Hanselmann
2631 7e49b6ce Michael Hanselmann
    self.nonmaster_nodes = [name for name in online_nodes
2632 7e49b6ce Michael Hanselmann
                            if name != master_node]
2633 7e49b6ce Michael Hanselmann
2634 7e49b6ce Michael Hanselmann
    assert self.master_node not in self.nonmaster_nodes
2635 7e49b6ce Michael Hanselmann
2636 7e49b6ce Michael Hanselmann
  def _RunCmd(self, node_name, cmd):
2637 7e49b6ce Michael Hanselmann
    """Runs a command on the local or a remote machine.
2638 7e49b6ce Michael Hanselmann

2639 7e49b6ce Michael Hanselmann
    @type node_name: string
2640 7e49b6ce Michael Hanselmann
    @param node_name: Machine name
2641 7e49b6ce Michael Hanselmann
    @type cmd: list
2642 7e49b6ce Michael Hanselmann
    @param cmd: Command
2643 7e49b6ce Michael Hanselmann

2644 7e49b6ce Michael Hanselmann
    """
2645 7e49b6ce Michael Hanselmann
    if node_name is None or node_name == self.master_node:
2646 7e49b6ce Michael Hanselmann
      # No need to use SSH
2647 7e49b6ce Michael Hanselmann
      result = utils.RunCmd(cmd)
2648 7e49b6ce Michael Hanselmann
    else:
2649 052783ff Michael Hanselmann
      result = self.ssh.Run(node_name, constants.SSH_LOGIN_USER,
2650 052783ff Michael Hanselmann
                            utils.ShellQuoteArgs(cmd))
2651 7e49b6ce Michael Hanselmann
2652 7e49b6ce Michael Hanselmann
    if result.failed:
2653 7e49b6ce Michael Hanselmann
      errmsg = ["Failed to run command %s" % result.cmd]
2654 7e49b6ce Michael Hanselmann
      if node_name:
2655 7e49b6ce Michael Hanselmann
        errmsg.append("on node %s" % node_name)
2656 7e49b6ce Michael Hanselmann
      errmsg.append(": exitcode %s and error %s" %
2657 7e49b6ce Michael Hanselmann
                    (result.exit_code, result.output))
2658 7e49b6ce Michael Hanselmann
      raise errors.OpExecError(" ".join(errmsg))
2659 7e49b6ce Michael Hanselmann
2660 7e49b6ce Michael Hanselmann
  def Call(self, fn, *args):
2661 7e49b6ce Michael Hanselmann
    """Call function while all daemons are stopped.
2662 7e49b6ce Michael Hanselmann

2663 7e49b6ce Michael Hanselmann
    @type fn: callable
2664 7e49b6ce Michael Hanselmann
    @param fn: Function to be called
2665 7e49b6ce Michael Hanselmann

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

2706 7e49b6ce Michael Hanselmann
  @type feedback_fn: callable
2707 7e49b6ce Michael Hanselmann
  @param feedback_fn: Feedback function
2708 7e49b6ce Michael Hanselmann
  @type fn: callable
2709 7e49b6ce Michael Hanselmann
  @param fn: Function to be called when daemons are stopped
2710 7e49b6ce Michael Hanselmann

2711 7e49b6ce Michael Hanselmann
  """
2712 7e49b6ce Michael Hanselmann
  feedback_fn("Gathering cluster information")
2713 7e49b6ce Michael Hanselmann
2714 7e49b6ce Michael Hanselmann
  # This ensures we're running on the master daemon
2715 7e49b6ce Michael Hanselmann
  cl = GetClient()
2716 7e49b6ce Michael Hanselmann
2717 7e49b6ce Michael Hanselmann
  (cluster_name, master_node) = \
2718 7e49b6ce Michael Hanselmann
    cl.QueryConfigValues(["cluster_name", "master_node"])
2719 7e49b6ce Michael Hanselmann
2720 7e49b6ce Michael Hanselmann
  online_nodes = GetOnlineNodes([], cl=cl)
2721 7e49b6ce Michael Hanselmann
2722 7e49b6ce Michael Hanselmann
  # Don't keep a reference to the client. The master daemon will go away.
2723 7e49b6ce Michael Hanselmann
  del cl
2724 7e49b6ce Michael Hanselmann
2725 7e49b6ce Michael Hanselmann
  assert master_node in online_nodes
2726 7e49b6ce Michael Hanselmann
2727 7e49b6ce Michael Hanselmann
  return _RunWhileClusterStoppedHelper(feedback_fn, cluster_name, master_node,
2728 7e49b6ce Michael Hanselmann
                                       online_nodes).Call(fn, *args)
2729 7e49b6ce Michael Hanselmann
2730 7e49b6ce Michael Hanselmann
2731 16be8703 Iustin Pop
def GenerateTable(headers, fields, separator, data,
2732 9fbfbb7b Iustin Pop
                  numfields=None, unitfields=None,
2733 9fbfbb7b Iustin Pop
                  units=None):
2734 137161c9 Michael Hanselmann
  """Prints a table with headers and different fields.
2735 137161c9 Michael Hanselmann

2736 9fbfbb7b Iustin Pop
  @type headers: dict
2737 9fbfbb7b Iustin Pop
  @param headers: dictionary mapping field names to headers for
2738 9fbfbb7b Iustin Pop
      the table
2739 9fbfbb7b Iustin Pop
  @type fields: list
2740 9fbfbb7b Iustin Pop
  @param fields: the field names corresponding to each row in
2741 9fbfbb7b Iustin Pop
      the data field
2742 9fbfbb7b Iustin Pop
  @param separator: the separator to be used; if this is None,
2743 9fbfbb7b Iustin Pop
      the default 'smart' algorithm is used which computes optimal
2744 9fbfbb7b Iustin Pop
      field width, otherwise just the separator is used between
2745 9fbfbb7b Iustin Pop
      each field
2746 9fbfbb7b Iustin Pop
  @type data: list
2747 9fbfbb7b Iustin Pop
  @param data: a list of lists, each sublist being one row to be output
2748 9fbfbb7b Iustin Pop
  @type numfields: list
2749 9fbfbb7b Iustin Pop
  @param numfields: a list with the fields that hold numeric
2750 9fbfbb7b Iustin Pop
      values and thus should be right-aligned
2751 9fbfbb7b Iustin Pop
  @type unitfields: list
2752 9fbfbb7b Iustin Pop
  @param unitfields: a list with the fields that hold numeric
2753 9fbfbb7b Iustin Pop
      values that should be formatted with the units field
2754 9fbfbb7b Iustin Pop
  @type units: string or None
2755 9fbfbb7b Iustin Pop
  @param units: the units we should use for formatting, or None for
2756 9fbfbb7b Iustin Pop
      automatic choice (human-readable for non-separator usage, otherwise
2757 9fbfbb7b Iustin Pop
      megabytes); this is a one-letter string
2758 137161c9 Michael Hanselmann

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

2842 ee3aedff Michael Hanselmann
  """
2843 ee3aedff Michael Hanselmann
  if value:
2844 ee3aedff Michael Hanselmann
    return "Y"
2845 ee3aedff Michael Hanselmann
  return "N"
2846 ee3aedff Michael Hanselmann
2847 ee3aedff Michael Hanselmann
2848 ee3aedff Michael Hanselmann
#: Default formatting for query results; (callback, align right)
2849 ee3aedff Michael Hanselmann
_DEFAULT_FORMAT_QUERY = {
2850 ee3aedff Michael Hanselmann
  constants.QFT_TEXT: (str, False),
2851 ee3aedff Michael Hanselmann
  constants.QFT_BOOL: (_FormatBool, False),
2852 ee3aedff Michael Hanselmann
  constants.QFT_NUMBER: (str, True),
2853 ee3aedff Michael Hanselmann
  constants.QFT_TIMESTAMP: (utils.FormatTime, False),
2854 ee3aedff Michael Hanselmann
  constants.QFT_OTHER: (str, False),
2855 ee3aedff Michael Hanselmann
  constants.QFT_UNKNOWN: (str, False),
2856 ee3aedff Michael Hanselmann
  }
2857 ee3aedff Michael Hanselmann
2858 ee3aedff Michael Hanselmann
2859 ee3aedff Michael Hanselmann
def _GetColumnFormatter(fdef, override, unit):
2860 ee3aedff Michael Hanselmann
  """Returns formatting function for a field.
2861 ee3aedff Michael Hanselmann

2862 ee3aedff Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
2863 ee3aedff Michael Hanselmann
  @type override: dict
2864 ee3aedff Michael Hanselmann
  @param override: Dictionary for overriding field formatting functions,
2865 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2866 ee3aedff Michael Hanselmann
  @type unit: string
2867 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT}
2868 ee3aedff Michael Hanselmann
  @rtype: tuple; (callable, bool)
2869 ee3aedff Michael Hanselmann
  @return: Returns the function to format a value (takes one parameter) and a
2870 ee3aedff Michael Hanselmann
    boolean for aligning the value on the right-hand side
2871 ee3aedff Michael Hanselmann

2872 ee3aedff Michael Hanselmann
  """
2873 ee3aedff Michael Hanselmann
  fmt = override.get(fdef.name, None)
2874 ee3aedff Michael Hanselmann
  if fmt is not None:
2875 ee3aedff Michael Hanselmann
    return fmt
2876 ee3aedff Michael Hanselmann
2877 ee3aedff Michael Hanselmann
  assert constants.QFT_UNIT not in _DEFAULT_FORMAT_QUERY
2878 ee3aedff Michael Hanselmann
2879 ee3aedff Michael Hanselmann
  if fdef.kind == constants.QFT_UNIT:
2880 ee3aedff Michael Hanselmann
    # Can't keep this information in the static dictionary
2881 ee3aedff Michael Hanselmann
    return (lambda value: utils.FormatUnit(value, unit), True)
2882 ee3aedff Michael Hanselmann
2883 ee3aedff Michael Hanselmann
  fmt = _DEFAULT_FORMAT_QUERY.get(fdef.kind, None)
2884 ee3aedff Michael Hanselmann
  if fmt is not None:
2885 ee3aedff Michael Hanselmann
    return fmt
2886 ee3aedff Michael Hanselmann
2887 ee3aedff Michael Hanselmann
  raise NotImplementedError("Can't format column type '%s'" % fdef.kind)
2888 ee3aedff Michael Hanselmann
2889 ee3aedff Michael Hanselmann
2890 ee3aedff Michael Hanselmann
class _QueryColumnFormatter:
2891 ee3aedff Michael Hanselmann
  """Callable class for formatting fields of a query.
2892 ee3aedff Michael Hanselmann

2893 ee3aedff Michael Hanselmann
  """
2894 f0b1bafe Iustin Pop
  def __init__(self, fn, status_fn, verbose):
2895 ee3aedff Michael Hanselmann
    """Initializes this class.
2896 ee3aedff Michael Hanselmann

2897 ee3aedff Michael Hanselmann
    @type fn: callable
2898 ee3aedff Michael Hanselmann
    @param fn: Formatting function
2899 ee3aedff Michael Hanselmann
    @type status_fn: callable
2900 ee3aedff Michael Hanselmann
    @param status_fn: Function to report fields' status
2901 f0b1bafe Iustin Pop
    @type verbose: boolean
2902 f0b1bafe Iustin Pop
    @param verbose: whether to use verbose field descriptions or not
2903 ee3aedff Michael Hanselmann

2904 ee3aedff Michael Hanselmann
    """
2905 ee3aedff Michael Hanselmann
    self._fn = fn
2906 ee3aedff Michael Hanselmann
    self._status_fn = status_fn
2907 cbfa4f0f Michael Hanselmann
    self._verbose = verbose
2908 ee3aedff Michael Hanselmann
2909 ee3aedff Michael Hanselmann
  def __call__(self, data):
2910 ee3aedff Michael Hanselmann
    """Returns a field's string representation.
2911 ee3aedff Michael Hanselmann

2912 ee3aedff Michael Hanselmann
    """
2913 ee3aedff Michael Hanselmann
    (status, value) = data
2914 ee3aedff Michael Hanselmann
2915 ee3aedff Michael Hanselmann
    # Report status
2916 ee3aedff Michael Hanselmann
    self._status_fn(status)
2917 ee3aedff Michael Hanselmann
2918 cfb084ae René Nussbaumer
    if status == constants.RS_NORMAL:
2919 ee3aedff Michael Hanselmann
      return self._fn(value)
2920 ee3aedff Michael Hanselmann
2921 ee3aedff Michael Hanselmann
    assert value is None, \
2922 ee3aedff Michael Hanselmann
           "Found value %r for abnormal status %s" % (value, status)
2923 ee3aedff Michael Hanselmann
2924 f2c6673d Michael Hanselmann
    return FormatResultError(status, self._verbose)
2925 ee3aedff Michael Hanselmann
2926 ee3aedff Michael Hanselmann
2927 f2c6673d Michael Hanselmann
def FormatResultError(status, verbose):
2928 ae95e419 René Nussbaumer
  """Formats result status other than L{constants.RS_NORMAL}.
2929 ee3aedff Michael Hanselmann

2930 ae95e419 René Nussbaumer
  @param status: The result status
2931 f2c6673d Michael Hanselmann
  @type verbose: boolean
2932 f2c6673d Michael Hanselmann
  @param verbose: Whether to return the verbose text
2933 ae95e419 René Nussbaumer
  @return: Text of result status
2934 a6070ef7 Michael Hanselmann

2935 ae95e419 René Nussbaumer
  """
2936 ae95e419 René Nussbaumer
  assert status != constants.RS_NORMAL, \
2937 cbfa4f0f Michael Hanselmann
         "FormatResultError called with status equal to constants.RS_NORMAL"
2938 ae95e419 René Nussbaumer
  try:
2939 cbfa4f0f Michael Hanselmann
    (verbose_text, normal_text) = constants.RSS_DESCRIPTION[status]
2940 ae95e419 René Nussbaumer
  except KeyError:
2941 ee3aedff Michael Hanselmann
    raise NotImplementedError("Unknown status %s" % status)
2942 cbfa4f0f Michael Hanselmann
  else:
2943 cbfa4f0f Michael Hanselmann
    if verbose:
2944 cbfa4f0f Michael Hanselmann
      return verbose_text
2945 cbfa4f0f Michael Hanselmann
    return normal_text
2946 ee3aedff Michael Hanselmann
2947 ee3aedff Michael Hanselmann
2948 ee3aedff Michael Hanselmann
def FormatQueryResult(result, unit=None, format_override=None, separator=None,
2949 f0b1bafe Iustin Pop
                      header=False, verbose=False):
2950 ee3aedff Michael Hanselmann
  """Formats data in L{objects.QueryResponse}.
2951 ee3aedff Michael Hanselmann

2952 ee3aedff Michael Hanselmann
  @type result: L{objects.QueryResponse}
2953 ee3aedff Michael Hanselmann
  @param result: result of query operation
2954 ee3aedff Michael Hanselmann
  @type unit: string
2955 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT},
2956 18009c1e Iustin Pop
    see L{utils.text.FormatUnit}
2957 ee3aedff Michael Hanselmann
  @type format_override: dict
2958 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
2959 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
2960 ee3aedff Michael Hanselmann
  @type separator: string or None
2961 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
2962 ee3aedff Michael Hanselmann
  @type header: bool
2963 ee3aedff Michael Hanselmann
  @param header: Whether to output header row
2964 f0b1bafe Iustin Pop
  @type verbose: boolean
2965 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
2966 ee3aedff Michael Hanselmann

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

3015 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3016 ee3aedff Michael Hanselmann

3017 ee3aedff Michael Hanselmann
  """
3018 ee3aedff Michael Hanselmann
  return [fdef for fdef in fdefs
3019 ee3aedff Michael Hanselmann
          if fdef.kind == constants.QFT_UNKNOWN]
3020 ee3aedff Michael Hanselmann
3021 ee3aedff Michael Hanselmann
3022 ee3aedff Michael Hanselmann
def _WarnUnknownFields(fdefs):
3023 ee3aedff Michael Hanselmann
  """Prints a warning to stderr if a query included unknown fields.
3024 ee3aedff Michael Hanselmann

3025 ee3aedff Michael Hanselmann
  @type fdefs: list of L{objects.QueryFieldDefinition}
3026 ee3aedff Michael Hanselmann

3027 ee3aedff Michael Hanselmann
  """
3028 ee3aedff Michael Hanselmann
  unknown = _GetUnknownFields(fdefs)
3029 ee3aedff Michael Hanselmann
  if unknown:
3030 ee3aedff Michael Hanselmann
    ToStderr("Warning: Queried for unknown fields %s",
3031 ee3aedff Michael Hanselmann
             utils.CommaJoin(fdef.name for fdef in unknown))
3032 ee3aedff Michael Hanselmann
    return True
3033 ee3aedff Michael Hanselmann
3034 ee3aedff Michael Hanselmann
  return False
3035 ee3aedff Michael Hanselmann
3036 ee3aedff Michael Hanselmann
3037 ee3aedff Michael Hanselmann
def GenericList(resource, fields, names, unit, separator, header, cl=None,
3038 03ec545a Michael Hanselmann
                format_override=None, verbose=False, force_filter=False,
3039 6f287cf3 Iustin Pop
                namefield=None, qfilter=None, isnumeric=False):
3040 ee3aedff Michael Hanselmann
  """Generic implementation for listing all items of a resource.
3041 ee3aedff Michael Hanselmann

3042 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3043 ee3aedff Michael Hanselmann
  @type fields: list of strings
3044 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3045 ee3aedff Michael Hanselmann
  @type names: list of strings
3046 ee3aedff Michael Hanselmann
  @param names: Names of items to query for
3047 ee3aedff Michael Hanselmann
  @type unit: string or None
3048 ee3aedff Michael Hanselmann
  @param unit: Unit used for formatting fields of type L{constants.QFT_UNIT} or
3049 ee3aedff Michael Hanselmann
    None for automatic choice (human-readable for non-separator usage,
3050 ee3aedff Michael Hanselmann
    otherwise megabytes); this is a one-letter string
3051 ee3aedff Michael Hanselmann
  @type separator: string or None
3052 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3053 ee3aedff Michael Hanselmann
  @type header: bool
3054 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3055 2928de47 Michael Hanselmann
  @type force_filter: bool
3056 2928de47 Michael Hanselmann
  @param force_filter: Whether to always treat names as filter
3057 ee3aedff Michael Hanselmann
  @type format_override: dict
3058 ee3aedff Michael Hanselmann
  @param format_override: Dictionary for overriding field formatting functions,
3059 ee3aedff Michael Hanselmann
    indexed by field name, contents like L{_DEFAULT_FORMAT_QUERY}
3060 f0b1bafe Iustin Pop
  @type verbose: boolean
3061 f0b1bafe Iustin Pop
  @param verbose: whether to use verbose field descriptions or not
3062 03ec545a Michael Hanselmann
  @type namefield: string
3063 03ec545a Michael Hanselmann
  @param namefield: Name of field to use for simple filters (see
3064 03ec545a Michael Hanselmann
    L{qlang.MakeFilter} for details)
3065 f037e9d7 Michael Hanselmann
  @type qfilter: list or None
3066 f037e9d7 Michael Hanselmann
  @param qfilter: Query filter (in addition to names)
3067 6f287cf3 Iustin Pop
  @param isnumeric: bool
3068 6f287cf3 Iustin Pop
  @param isnumeric: Whether the namefield's type is numeric, and therefore
3069 6f287cf3 Iustin Pop
    any simple filters built by namefield should use integer values to
3070 6f287cf3 Iustin Pop
    reflect that
3071 ee3aedff Michael Hanselmann

3072 ee3aedff Michael Hanselmann
  """
3073 ee3aedff Michael Hanselmann
  if not names:
3074 ee3aedff Michael Hanselmann
    names = None
3075 ee3aedff Michael Hanselmann
3076 6f287cf3 Iustin Pop
  namefilter = qlang.MakeFilter(names, force_filter, namefield=namefield,
3077 6f287cf3 Iustin Pop
                                isnumeric=isnumeric)
3078 f037e9d7 Michael Hanselmann
3079 f037e9d7 Michael Hanselmann
  if qfilter is None:
3080 f037e9d7 Michael Hanselmann
    qfilter = namefilter
3081 f037e9d7 Michael Hanselmann
  elif namefilter is not None:
3082 f037e9d7 Michael Hanselmann
    qfilter = [qlang.OP_AND, namefilter, qfilter]
3083 2928de47 Michael Hanselmann
3084 727274dd Iustin Pop
  if cl is None:
3085 727274dd Iustin Pop
    cl = GetClient()
3086 727274dd Iustin Pop
3087 2e5c33db Iustin Pop
  response = cl.Query(resource, fields, qfilter)
3088 ee3aedff Michael Hanselmann
3089 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3090 ee3aedff Michael Hanselmann
3091 ee3aedff Michael Hanselmann
  (status, data) = FormatQueryResult(response, unit=unit, separator=separator,
3092 ee3aedff Michael Hanselmann
                                     header=header,
3093 f0b1bafe Iustin Pop
                                     format_override=format_override,
3094 f0b1bafe Iustin Pop
                                     verbose=verbose)
3095 ee3aedff Michael Hanselmann
3096 ee3aedff Michael Hanselmann
  for line in data:
3097 ee3aedff Michael Hanselmann
    ToStdout(line)
3098 ee3aedff Michael Hanselmann
3099 ee3aedff Michael Hanselmann
  assert ((found_unknown and status == QR_UNKNOWN) or
3100 ee3aedff Michael Hanselmann
          (not found_unknown and status != QR_UNKNOWN))
3101 ee3aedff Michael Hanselmann
3102 ee3aedff Michael Hanselmann
  if status == QR_UNKNOWN:
3103 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3104 ee3aedff Michael Hanselmann
3105 ee3aedff Michael Hanselmann
  # TODO: Should the list command fail if not all data could be collected?
3106 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3107 ee3aedff Michael Hanselmann
3108 ee3aedff Michael Hanselmann
3109 c1912a48 Michael Hanselmann
def _FieldDescValues(fdef):
3110 c1912a48 Michael Hanselmann
  """Helper function for L{GenericListFields} to get query field description.
3111 c1912a48 Michael Hanselmann

3112 c1912a48 Michael Hanselmann
  @type fdef: L{objects.QueryFieldDefinition}
3113 c1912a48 Michael Hanselmann
  @rtype: list
3114 c1912a48 Michael Hanselmann

3115 c1912a48 Michael Hanselmann
  """
3116 c1912a48 Michael Hanselmann
  return [
3117 c1912a48 Michael Hanselmann
    fdef.name,
3118 c1912a48 Michael Hanselmann
    _QFT_NAMES.get(fdef.kind, fdef.kind),
3119 c1912a48 Michael Hanselmann
    fdef.title,
3120 c1912a48 Michael Hanselmann
    fdef.doc,
3121 c1912a48 Michael Hanselmann
    ]
3122 c1912a48 Michael Hanselmann
3123 c1912a48 Michael Hanselmann
3124 ee3aedff Michael Hanselmann
def GenericListFields(resource, fields, separator, header, cl=None):
3125 ee3aedff Michael Hanselmann
  """Generic implementation for listing fields for a resource.
3126 ee3aedff Michael Hanselmann

3127 abd66bf8 Michael Hanselmann
  @param resource: One of L{constants.QR_VIA_LUXI}
3128 ee3aedff Michael Hanselmann
  @type fields: list of strings
3129 ee3aedff Michael Hanselmann
  @param fields: List of fields to query for
3130 ee3aedff Michael Hanselmann
  @type separator: string or None
3131 ee3aedff Michael Hanselmann
  @param separator: String used to separate fields
3132 ee3aedff Michael Hanselmann
  @type header: bool
3133 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3134 ee3aedff Michael Hanselmann

3135 ee3aedff Michael Hanselmann
  """
3136 ee3aedff Michael Hanselmann
  if cl is None:
3137 ee3aedff Michael Hanselmann
    cl = GetClient()
3138 ee3aedff Michael Hanselmann
3139 ee3aedff Michael Hanselmann
  if not fields:
3140 ee3aedff Michael Hanselmann
    fields = None
3141 ee3aedff Michael Hanselmann
3142 ee3aedff Michael Hanselmann
  response = cl.QueryFields(resource, fields)
3143 ee3aedff Michael Hanselmann
3144 ee3aedff Michael Hanselmann
  found_unknown = _WarnUnknownFields(response.fields)
3145 ee3aedff Michael Hanselmann
3146 ee3aedff Michael Hanselmann
  columns = [
3147 ee3aedff Michael Hanselmann
    TableColumn("Name", str, False),
3148 c1912a48 Michael Hanselmann
    TableColumn("Type", str, False),
3149 ee3aedff Michael Hanselmann
    TableColumn("Title", str, False),
3150 ea1440c1 Michael Hanselmann
    TableColumn("Description", str, False),
3151 ee3aedff Michael Hanselmann
    ]
3152 ee3aedff Michael Hanselmann
3153 c1912a48 Michael Hanselmann
  rows = map(_FieldDescValues, response.fields)
3154 ee3aedff Michael Hanselmann
3155 ee3aedff Michael Hanselmann
  for line in FormatTable(rows, columns, header, separator):
3156 ee3aedff Michael Hanselmann
    ToStdout(line)
3157 ee3aedff Michael Hanselmann
3158 ee3aedff Michael Hanselmann
  if found_unknown:
3159 ee3aedff Michael Hanselmann
    return constants.EXIT_UNKNOWN_FIELD
3160 ee3aedff Michael Hanselmann
3161 ee3aedff Michael Hanselmann
  return constants.EXIT_SUCCESS
3162 ee3aedff Michael Hanselmann
3163 ee3aedff Michael Hanselmann
3164 ee3aedff Michael Hanselmann
class TableColumn:
3165 ee3aedff Michael Hanselmann
  """Describes a column for L{FormatTable}.
3166 ee3aedff Michael Hanselmann

3167 ee3aedff Michael Hanselmann
  """
3168 ee3aedff Michael Hanselmann
  def __init__(self, title, fn, align_right):
3169 ee3aedff Michael Hanselmann
    """Initializes this class.
3170 ee3aedff Michael Hanselmann

3171 ee3aedff Michael Hanselmann
    @type title: string
3172 ee3aedff Michael Hanselmann
    @param title: Column title
3173 ee3aedff Michael Hanselmann
    @type fn: callable
3174 ee3aedff Michael Hanselmann
    @param fn: Formatting function
3175 ee3aedff Michael Hanselmann
    @type align_right: bool
3176 ee3aedff Michael Hanselmann
    @param align_right: Whether to align values on the right-hand side
3177 ee3aedff Michael Hanselmann

3178 ee3aedff Michael Hanselmann
    """
3179 ee3aedff Michael Hanselmann
    self.title = title
3180 ee3aedff Michael Hanselmann
    self.format = fn
3181 ee3aedff Michael Hanselmann
    self.align_right = align_right
3182 ee3aedff Michael Hanselmann
3183 ee3aedff Michael Hanselmann
3184 ee3aedff Michael Hanselmann
def _GetColFormatString(width, align_right):
3185 ee3aedff Michael Hanselmann
  """Returns the format string for a field.
3186 ee3aedff Michael Hanselmann

3187 ee3aedff Michael Hanselmann
  """
3188 ee3aedff Michael Hanselmann
  if align_right:
3189 ee3aedff Michael Hanselmann
    sign = ""
3190 ee3aedff Michael Hanselmann
  else:
3191 ee3aedff Michael Hanselmann
    sign = "-"
3192 ee3aedff Michael Hanselmann
3193 ee3aedff Michael Hanselmann
  return "%%%s%ss" % (sign, width)
3194 ee3aedff Michael Hanselmann
3195 ee3aedff Michael Hanselmann
3196 ee3aedff Michael Hanselmann
def FormatTable(rows, columns, header, separator):
3197 ee3aedff Michael Hanselmann
  """Formats data as a table.
3198 ee3aedff Michael Hanselmann

3199 ee3aedff Michael Hanselmann
  @type rows: list of lists
3200 ee3aedff Michael Hanselmann
  @param rows: Row data, one list per row
3201 ee3aedff Michael Hanselmann
  @type columns: list of L{TableColumn}
3202 ee3aedff Michael Hanselmann
  @param columns: Column descriptions
3203 ee3aedff Michael Hanselmann
  @type header: bool
3204 ee3aedff Michael Hanselmann
  @param header: Whether to show header row
3205 ee3aedff Michael Hanselmann
  @type separator: string or None
3206 ee3aedff Michael Hanselmann
  @param separator: String used to separate columns
3207 ee3aedff Michael Hanselmann

3208 ee3aedff Michael Hanselmann
  """
3209 ee3aedff Michael Hanselmann
  if header:
3210 ee3aedff Michael Hanselmann
    data = [[col.title for col in columns]]
3211 ee3aedff Michael Hanselmann
    colwidth = [len(col.title) for col in columns]
3212 ee3aedff Michael Hanselmann
  else:
3213 ee3aedff Michael Hanselmann
    data = []
3214 ee3aedff Michael Hanselmann
    colwidth = [0 for _ in columns]
3215 ee3aedff Michael Hanselmann
3216 ee3aedff Michael Hanselmann
  # Format row data
3217 ee3aedff Michael Hanselmann
  for row in rows:
3218 ee3aedff Michael Hanselmann
    assert len(row) == len(columns)
3219 ee3aedff Michael Hanselmann
3220 ee3aedff Michael Hanselmann
    formatted = [col.format(value) for value, col in zip(row, columns)]
3221 ee3aedff Michael Hanselmann
3222 ee3aedff Michael Hanselmann
    if separator is None:
3223 ee3aedff Michael Hanselmann
      # Update column widths
3224 ee3aedff Michael Hanselmann
      for idx, (oldwidth, value) in enumerate(zip(colwidth, formatted)):
3225 ee3aedff Michael Hanselmann
        # Modifying a list's items while iterating is fine
3226 ee3aedff Michael Hanselmann
        colwidth[idx] = max(oldwidth, len(value))
3227 ee3aedff Michael Hanselmann
3228 ee3aedff Michael Hanselmann
    data.append(formatted)
3229 ee3aedff Michael Hanselmann
3230 ee3aedff Michael Hanselmann
  if separator is not None:
3231 ee3aedff Michael Hanselmann
    # Return early if a separator is used
3232 ee3aedff Michael Hanselmann
    return [separator.join(row) for row in data]
3233 ee3aedff Michael Hanselmann
3234 ee3aedff Michael Hanselmann
  if columns and not columns[-1].align_right:
3235 ee3aedff Michael Hanselmann
    # Avoid unnecessary spaces at end of line
3236 ee3aedff Michael Hanselmann
    colwidth[-1] = 0
3237 ee3aedff Michael Hanselmann
3238 ee3aedff Michael Hanselmann
  # Build format string
3239 ee3aedff Michael Hanselmann
  fmt = " ".join([_GetColFormatString(width, col.align_right)
3240 ee3aedff Michael Hanselmann
                  for col, width in zip(columns, colwidth)])
3241 ee3aedff Michael Hanselmann
3242 ee3aedff Michael Hanselmann
  return [fmt % tuple(row) for row in data]
3243 ee3aedff Michael Hanselmann
3244 ee3aedff Michael Hanselmann
3245 3386e7a9 Iustin Pop
def FormatTimestamp(ts):
3246 3386e7a9 Iustin Pop
  """Formats a given timestamp.
3247 3386e7a9 Iustin Pop

3248 3386e7a9 Iustin Pop
  @type ts: timestamp
3249 3386e7a9 Iustin Pop
  @param ts: a timeval-type timestamp, a tuple of seconds and microseconds
3250 3386e7a9 Iustin Pop

3251 3386e7a9 Iustin Pop
  @rtype: string
3252 5fcc718f Iustin Pop
  @return: a string with the formatted timestamp
3253 3386e7a9 Iustin Pop

3254 3386e7a9 Iustin Pop
  """
3255 e687ec01 Michael Hanselmann
  if not isinstance(ts, (tuple, list)) or len(ts) != 2:
3256 d0c8c01d Iustin Pop
    return "?"
3257 26a72a48 Michael Hanselmann
3258 26a72a48 Michael Hanselmann
  (sec, usecs) = ts
3259 26a72a48 Michael Hanselmann
  return utils.FormatTime(sec, usecs=usecs)
3260 2241e2b9 Iustin Pop
3261 2241e2b9 Iustin Pop
3262 2241e2b9 Iustin Pop
def ParseTimespec(value):
3263 2241e2b9 Iustin Pop
  """Parse a time specification.
3264 2241e2b9 Iustin Pop

3265 2241e2b9 Iustin Pop
  The following suffixed will be recognized:
3266 2241e2b9 Iustin Pop

3267 2241e2b9 Iustin Pop
    - s: seconds
3268 2241e2b9 Iustin Pop
    - m: minutes
3269 2241e2b9 Iustin Pop
    - h: hours
3270 2241e2b9 Iustin Pop
    - d: day
3271 2241e2b9 Iustin Pop
    - w: weeks
3272 2241e2b9 Iustin Pop

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

3275 2241e2b9 Iustin Pop
  """
3276 2241e2b9 Iustin Pop
  value = str(value)
3277 2241e2b9 Iustin Pop
  if not value:
3278 2cfbc784 Iustin Pop
    raise errors.OpPrereqError("Empty time specification passed",
3279 2cfbc784 Iustin Pop
                               errors.ECODE_INVAL)
3280 2241e2b9 Iustin Pop
  suffix_map = {
3281 d0c8c01d Iustin Pop
    "s": 1,
3282 d0c8c01d Iustin Pop
    "m": 60,
3283 d0c8c01d Iustin Pop
    "h": 3600,
3284 d0c8c01d Iustin Pop
    "d": 86400,
3285 d0c8c01d Iustin Pop
    "w": 604800,
3286 2241e2b9 Iustin Pop
    }
3287 2241e2b9 Iustin Pop
  if value[-1] not in suffix_map:
3288 2241e2b9 Iustin Pop
    try:
3289 2241e2b9 Iustin Pop
      value = int(value)
3290 691744c4 Iustin Pop
    except (TypeError, ValueError):
3291 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3292 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3293 2241e2b9 Iustin Pop
  else:
3294 2241e2b9 Iustin Pop
    multiplier = suffix_map[value[-1]]
3295 2241e2b9 Iustin Pop
    value = value[:-1]
3296 2241e2b9 Iustin Pop
    if not value: # no data left after stripping the suffix
3297 2241e2b9 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification (only"
3298 2cfbc784 Iustin Pop
                                 " suffix passed)", errors.ECODE_INVAL)
3299 2241e2b9 Iustin Pop
    try:
3300 2241e2b9 Iustin Pop
      value = int(value) * multiplier
3301 691744c4 Iustin Pop
    except (TypeError, ValueError):
3302 2cfbc784 Iustin Pop
      raise errors.OpPrereqError("Invalid time specification '%s'" % value,
3303 2cfbc784 Iustin Pop
                                 errors.ECODE_INVAL)
3304 2241e2b9 Iustin Pop
  return value
3305 46fbdd04 Iustin Pop
3306 46fbdd04 Iustin Pop
3307 e9e26bb3 Iustin Pop
def GetOnlineNodes(nodes, cl=None, nowarn=False, secondary_ips=False,
3308 05484a24 Michael Hanselmann
                   filter_master=False, nodegroup=None):
3309 4040a784 Iustin Pop
  """Returns the names of online nodes.
3310 4040a784 Iustin Pop

3311 4040a784 Iustin Pop
  This function will also log a warning on stderr with the names of
3312 4040a784 Iustin Pop
  the online nodes.
3313 4040a784 Iustin Pop

3314 4040a784 Iustin Pop
  @param nodes: if not empty, use only this subset of nodes (minus the
3315 4040a784 Iustin Pop
      offline ones)
3316 4040a784 Iustin Pop
  @param cl: if not None, luxi client to use
3317 4040a784 Iustin Pop
  @type nowarn: boolean
3318 4040a784 Iustin Pop
  @param nowarn: by default, this function will output a note with the
3319 4040a784 Iustin Pop
      offline nodes that are skipped; if this parameter is True the
3320 4040a784 Iustin Pop
      note is not displayed
3321 e9e26bb3 Iustin Pop
  @type secondary_ips: boolean
3322 e9e26bb3 Iustin Pop
  @param secondary_ips: if True, return the secondary IPs instead of the
3323 e9e26bb3 Iustin Pop
      names, useful for doing network traffic over the replication interface
3324 e9e26bb3 Iustin Pop
      (if any)
3325 e9e26bb3 Iustin Pop
  @type filter_master: boolean
3326 e9e26bb3 Iustin Pop
  @param filter_master: if True, do not return the master node in the list
3327 e9e26bb3 Iustin Pop
      (useful in coordination with secondary_ips where we cannot check our
3328 e9e26bb3 Iustin Pop
      node name against the list)
3329 05484a24 Michael Hanselmann
  @type nodegroup: string
3330 05484a24 Michael Hanselmann
  @param nodegroup: If set, only return nodes in this node group
3331 4040a784 Iustin Pop

3332 4040a784 Iustin Pop
  """
3333 4040a784 Iustin Pop
  if cl is None:
3334 4040a784 Iustin Pop
    cl = GetClient()
3335 4040a784 Iustin Pop
3336 2e5c33db Iustin Pop
  qfilter = []
3337 05484a24 Michael Hanselmann
3338 05484a24 Michael Hanselmann
  if nodes:
3339 2e5c33db Iustin Pop
    qfilter.append(qlang.MakeSimpleFilter("name", nodes))
3340 05484a24 Michael Hanselmann
3341 05484a24 Michael Hanselmann
  if nodegroup is not None:
3342 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_OR, [qlang.OP_EQUAL, "group", nodegroup],
3343 05484a24 Michael Hanselmann
                                 [qlang.OP_EQUAL, "group.uuid", nodegroup]])
3344 e9e26bb3 Iustin Pop
3345 e9e26bb3 Iustin Pop
  if filter_master:
3346 2e5c33db Iustin Pop
    qfilter.append([qlang.OP_NOT, [qlang.OP_TRUE, "master"]])
3347 05484a24 Michael Hanselmann
3348 2e5c33db Iustin Pop
  if qfilter:
3349 2e5c33db Iustin Pop
    if len(qfilter) > 1:
3350 2e5c33db Iustin Pop
      final_filter = [qlang.OP_AND] + qfilter
3351 05484a24 Michael Hanselmann
    else:
3352 2e5c33db Iustin Pop
      assert len(qfilter) == 1
3353 2e5c33db Iustin Pop
      final_filter = qfilter[0]
3354 e9e26bb3 Iustin Pop
  else:
3355 05484a24 Michael Hanselmann
    final_filter = None
3356 05484a24 Michael Hanselmann
3357 05484a24 Michael Hanselmann
  result = cl.Query(constants.QR_NODE, ["name", "offline", "sip"], final_filter)
3358 05484a24 Michael Hanselmann
3359 05484a24 Michael Hanselmann
  def _IsOffline(row):
3360 05484a24 Michael Hanselmann
    (_, (_, offline), _) = row
3361 05484a24 Michael Hanselmann
    return offline
3362 05484a24 Michael Hanselmann
3363 05484a24 Michael Hanselmann
  def _GetName(row):
3364 05484a24 Michael Hanselmann
    ((_, name), _, _) = row
3365 05484a24 Michael Hanselmann
    return name
3366 05484a24 Michael Hanselmann
3367 05484a24 Michael Hanselmann
  def _GetSip(row):
3368 05484a24 Michael Hanselmann
    (_, _, (_, sip)) = row
3369 05484a24 Michael Hanselmann
    return sip
3370 05484a24 Michael Hanselmann
3371 05484a24 Michael Hanselmann
  (offline, online) = compat.partition(result.data, _IsOffline)
3372 e9e26bb3 Iustin Pop
3373 4040a784 Iustin Pop
  if offline and not nowarn:
3374 05484a24 Michael Hanselmann
    ToStderr("Note: skipping offline node(s): %s" %
3375 05484a24 Michael Hanselmann
             utils.CommaJoin(map(_GetName, offline)))
3376 05484a24 Michael Hanselmann
3377 05484a24 Michael Hanselmann
  if secondary_ips:
3378 05484a24 Michael Hanselmann
    fn = _GetSip
3379 05484a24 Michael Hanselmann
  else:
3380 05484a24 Michael Hanselmann
    fn = _GetName
3381 05484a24 Michael Hanselmann
3382 05484a24 Michael Hanselmann
  return map(fn, online)
3383 4040a784 Iustin Pop
3384 4040a784 Iustin Pop
3385 46fbdd04 Iustin Pop
def _ToStream(stream, txt, *args):
3386 46fbdd04 Iustin Pop
  """Write a message to a stream, bypassing the logging system
3387 46fbdd04 Iustin Pop

3388 46fbdd04 Iustin Pop
  @type stream: file object
3389 46fbdd04 Iustin Pop
  @param stream: the file to which we should write
3390 46fbdd04 Iustin Pop
  @type txt: str
3391 46fbdd04 Iustin Pop
  @param txt: the message
3392 46fbdd04 Iustin Pop

3393 46fbdd04 Iustin Pop
  """
3394 225e2544 Iustin Pop
  try:
3395 225e2544 Iustin Pop
    if args:
3396 225e2544 Iustin Pop
      args = tuple(args)
3397 225e2544 Iustin Pop
      stream.write(txt % args)
3398 225e2544 Iustin Pop
    else:
3399 225e2544 Iustin Pop
      stream.write(txt)
3400 d0c8c01d Iustin Pop
    stream.write("\n")
3401 225e2544 Iustin Pop
    stream.flush()
3402 225e2544 Iustin Pop
  except IOError, err:
3403 225e2544 Iustin Pop
    if err.errno == errno.EPIPE:
3404 225e2544 Iustin Pop
      # our terminal went away, we'll exit
3405 225e2544 Iustin Pop
      sys.exit(constants.EXIT_FAILURE)
3406 225e2544 Iustin Pop
    else:
3407 225e2544 Iustin Pop
      raise
3408 46fbdd04 Iustin Pop
3409 46fbdd04 Iustin Pop
3410 46fbdd04 Iustin Pop
def ToStdout(txt, *args):
3411 46fbdd04 Iustin Pop
  """Write a message to stdout only, bypassing the logging system
3412 46fbdd04 Iustin Pop

3413 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3414 46fbdd04 Iustin Pop

3415 46fbdd04 Iustin Pop
  @type txt: str
3416 46fbdd04 Iustin Pop
  @param txt: the message
3417 46fbdd04 Iustin Pop

3418 46fbdd04 Iustin Pop
  """
3419 46fbdd04 Iustin Pop
  _ToStream(sys.stdout, txt, *args)
3420 46fbdd04 Iustin Pop
3421 46fbdd04 Iustin Pop
3422 46fbdd04 Iustin Pop
def ToStderr(txt, *args):
3423 46fbdd04 Iustin Pop
  """Write a message to stderr only, bypassing the logging system
3424 46fbdd04 Iustin Pop

3425 46fbdd04 Iustin Pop
  This is just a wrapper over _ToStream.
3426 46fbdd04 Iustin Pop

3427 46fbdd04 Iustin Pop
  @type txt: str
3428 46fbdd04 Iustin Pop
  @param txt: the message
3429 46fbdd04 Iustin Pop

3430 46fbdd04 Iustin Pop
  """
3431 46fbdd04 Iustin Pop
  _ToStream(sys.stderr, txt, *args)
3432 479636a3 Iustin Pop
3433 479636a3 Iustin Pop
3434 479636a3 Iustin Pop
class JobExecutor(object):
3435 479636a3 Iustin Pop
  """Class which manages the submission and execution of multiple jobs.
3436 479636a3 Iustin Pop

3437 479636a3 Iustin Pop
  Note that instances of this class should not be reused between
3438 479636a3 Iustin Pop
  GetResults() calls.
3439 479636a3 Iustin Pop

3440 479636a3 Iustin Pop
  """
3441 919ca415 Iustin Pop
  def __init__(self, cl=None, verbose=True, opts=None, feedback_fn=None):
3442 479636a3 Iustin Pop
    self.queue = []
3443 479636a3 Iustin Pop
    if cl is None:
3444 479636a3 Iustin Pop
      cl = GetClient()
3445 479636a3 Iustin Pop
    self.cl = cl
3446 479636a3 Iustin Pop
    self.verbose = verbose
3447 23b4b983 Iustin Pop
    self.jobs = []
3448 cff5fa7f Iustin Pop
    self.opts = opts
3449 919ca415 Iustin Pop
    self.feedback_fn = feedback_fn
3450 60452edf Michael Hanselmann
    self._counter = itertools.count()
3451 479636a3 Iustin Pop
3452 8d99a8bf Michael Hanselmann
  @staticmethod
3453 8d99a8bf Michael Hanselmann
  def _IfName(name, fmt):
3454 8d99a8bf Michael Hanselmann
    """Helper function for formatting name.
3455 8d99a8bf Michael Hanselmann

3456 8d99a8bf Michael Hanselmann
    """
3457 8d99a8bf Michael Hanselmann
    if name:
3458 8d99a8bf Michael Hanselmann
      return fmt % name
3459 8d99a8bf Michael Hanselmann
3460 8d99a8bf Michael Hanselmann
    return ""
3461 8d99a8bf Michael Hanselmann
3462 479636a3 Iustin Pop
  def QueueJob(self, name, *ops):
3463 23b4b983 Iustin Pop
    """Record a job for later submit.
3464 479636a3 Iustin Pop

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

3468 479636a3 Iustin Pop
    """
3469 cff5fa7f Iustin Pop
    SetGenericOpcodeOpts(ops, self.opts)
3470 60452edf Michael Hanselmann
    self.queue.append((self._counter.next(), name, ops))
3471 23b4b983 Iustin Pop
3472 8d99a8bf Michael Hanselmann
  def AddJobId(self, name, status, job_id):
3473 8d99a8bf Michael Hanselmann
    """Adds a job ID to the internal queue.
3474 8d99a8bf Michael Hanselmann

3475 8d99a8bf Michael Hanselmann
    """
3476 8d99a8bf Michael Hanselmann
    self.jobs.append((self._counter.next(), status, job_id, name))
3477 8d99a8bf Michael Hanselmann
3478 66ecc479 Guido Trotter
  def SubmitPending(self, each=False):
3479 23b4b983 Iustin Pop
    """Submit all pending jobs.
3480 23b4b983 Iustin Pop

3481 23b4b983 Iustin Pop
    """
3482 66ecc479 Guido Trotter
    if each:
3483 66ecc479 Guido Trotter
      results = []
3484 60452edf Michael Hanselmann
      for (_, _, ops) in self.queue:
3485 66ecc479 Guido Trotter
        # SubmitJob will remove the success status, but raise an exception if
3486 66ecc479 Guido Trotter
        # the submission fails, so we'll notice that anyway.
3487 519fafa1 Andrea Spadaccini
        results.append([True, self.cl.SubmitJob(ops)[0]])
3488 66ecc479 Guido Trotter
    else:
3489 60452edf Michael Hanselmann
      results = self.cl.SubmitManyJobs([ops for (_, _, ops) in self.queue])
3490 60452edf Michael Hanselmann
    for ((status, data), (idx, name, _)) in zip(results, self.queue):
3491 5299e61f Iustin Pop
      self.jobs.append((idx, status, data, name))
3492 5299e61f Iustin Pop
3493 5299e61f Iustin Pop
  def _ChooseJob(self):
3494 5299e61f Iustin Pop
    """Choose a non-waiting/queued job to poll next.
3495 5299e61f Iustin Pop

3496 5299e61f Iustin Pop
    """
3497 5299e61f Iustin Pop
    assert self.jobs, "_ChooseJob called with empty job list"
3498 5299e61f Iustin Pop
3499 11705e3d Iustin Pop
    result = self.cl.QueryJobs([i[2] for i in self.jobs[:_CHOOSE_BATCH]],
3500 11705e3d Iustin Pop
                               ["status"])
3501 5299e61f Iustin Pop
    assert result
3502 5299e61f Iustin Pop
3503 5299e61f Iustin Pop
    for job_data, status in zip(self.jobs, result):
3504 91c622a8 Iustin Pop
      if (isinstance(status, list) and status and
3505 91c622a8 Iustin Pop
          status[0] in (constants.JOB_STATUS_QUEUED,
3506 47099cd1 Michael Hanselmann
                        constants.JOB_STATUS_WAITING,
3507 91c622a8 Iustin Pop
                        constants.JOB_STATUS_CANCELING)):
3508 91c622a8 Iustin Pop
        # job is still present and waiting
3509 5299e61f Iustin Pop
        continue
3510 91c622a8 Iustin Pop
      # good candidate found (either running job or lost job)
3511 5299e61f Iustin Pop
      self.jobs.remove(job_data)
3512 5299e61f Iustin Pop
      return job_data
3513 5299e61f Iustin Pop
3514 5299e61f Iustin Pop
    # no job found
3515 5299e61f Iustin Pop
    return self.jobs.pop(0)
3516 479636a3 Iustin Pop
3517 479636a3 Iustin Pop
  def GetResults(self):
3518 479636a3 Iustin Pop
    """Wait for and return the results of all jobs.
3519 479636a3 Iustin Pop

3520 479636a3 Iustin Pop
    @rtype: list
3521 479636a3 Iustin Pop
    @return: list of tuples (success, job results), in the same order
3522 479636a3 Iustin Pop
        as the submitted jobs; if a job has failed, instead of the result
3523 479636a3 Iustin Pop
        there will be the error message
3524 479636a3 Iustin Pop

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

3569 479636a3 Iustin Pop
    @type wait: boolean
3570 479636a3 Iustin Pop
    @param wait: whether to wait or not
3571 479636a3 Iustin Pop

3572 479636a3 Iustin Pop
    """
3573 479636a3 Iustin Pop
    if wait:
3574 479636a3 Iustin Pop
      return self.GetResults()
3575 479636a3 Iustin Pop
    else:
3576 23b4b983 Iustin Pop
      if not self.jobs:
3577 23b4b983 Iustin Pop
        self.SubmitPending()
3578 71834b2a Guido Trotter
      for _, status, result, name in self.jobs:
3579 23b4b983 Iustin Pop
        if status:
3580 4474f112 Iustin Pop
          ToStdout("%s: %s", result, name)
3581 23b4b983 Iustin Pop
        else:
3582 4474f112 Iustin Pop
          ToStderr("Failure for %s: %s", name, result)
3583 53a8a54d Iustin Pop
      return [row[1:3] for row in self.jobs]
3584 acd19189 René Nussbaumer
3585 acd19189 René Nussbaumer
3586 acd19189 René Nussbaumer
def FormatParameterDict(buf, param_dict, actual, level=1):
3587 acd19189 René Nussbaumer
  """Formats a parameter dictionary.
3588 acd19189 René Nussbaumer

3589 acd19189 René Nussbaumer
  @type buf: L{StringIO}
3590 acd19189 René Nussbaumer
  @param buf: the buffer into which to write
3591 acd19189 René Nussbaumer
  @type param_dict: dict
3592 acd19189 René Nussbaumer
  @param param_dict: the own parameters
3593 acd19189 René Nussbaumer
  @type actual: dict
3594 acd19189 René Nussbaumer
  @param actual: the current parameter set (including defaults)
3595 acd19189 René Nussbaumer
  @param level: Level of indent
3596 acd19189 René Nussbaumer

3597 acd19189 René Nussbaumer
  """
3598 acd19189 René Nussbaumer
  indent = "  " * level
3599 64da5a53 René Nussbaumer
3600 acd19189 René Nussbaumer
  for key in sorted(actual):
3601 64da5a53 René Nussbaumer
    data = actual[key]
3602 64da5a53 René Nussbaumer
    buf.write("%s- %s:" % (indent, key))
3603 64da5a53 René Nussbaumer
3604 64da5a53 René Nussbaumer
    if isinstance(data, dict) and data:
3605 64da5a53 René Nussbaumer
      buf.write("\n")
3606 64da5a53 René Nussbaumer
      FormatParameterDict(buf, param_dict.get(key, {}), data,
3607 64da5a53 René Nussbaumer
                          level=level + 1)
3608 64da5a53 René Nussbaumer
    else:
3609 64da5a53 René Nussbaumer
      val = param_dict.get(key, "default (%s)" % data)
3610 64da5a53 René Nussbaumer
      buf.write(" %s\n" % val)
3611 25bd815c René Nussbaumer
3612 25bd815c René Nussbaumer
3613 25bd815c René Nussbaumer
def ConfirmOperation(names, list_type, text, extra=""):
3614 25bd815c René Nussbaumer
  """Ask the user to confirm an operation on a list of list_type.
3615 25bd815c René Nussbaumer

3616 25bd815c René Nussbaumer
  This function is used to request confirmation for doing an operation
3617 25bd815c René Nussbaumer
  on a given list of list_type.
3618 25bd815c René Nussbaumer

3619 25bd815c René Nussbaumer
  @type names: list
3620 25bd815c René Nussbaumer
  @param names: the list of names that we display when
3621 25bd815c René Nussbaumer
      we ask for confirmation
3622 25bd815c René Nussbaumer
  @type list_type: str
3623 25bd815c René Nussbaumer
  @param list_type: Human readable name for elements in the list (e.g. nodes)
3624 25bd815c René Nussbaumer
  @type text: str
3625 25bd815c René Nussbaumer
  @param text: the operation that the user should confirm
3626 25bd815c René Nussbaumer
  @rtype: boolean
3627 25bd815c René Nussbaumer
  @return: True or False depending on user's confirmation.
3628 25bd815c René Nussbaumer

3629 25bd815c René Nussbaumer
  """
3630 25bd815c René Nussbaumer
  count = len(names)
3631 25bd815c René Nussbaumer
  msg = ("The %s will operate on %d %s.\n%s"
3632 25bd815c René Nussbaumer
         "Do you want to continue?" % (text, count, list_type, extra))
3633 25bd815c René Nussbaumer
  affected = (("\nAffected %s:\n" % list_type) +
3634 25bd815c René Nussbaumer
              "\n".join(["  %s" % name for name in names]))
3635 25bd815c René Nussbaumer
3636 25bd815c René Nussbaumer
  choices = [("y", True, "Yes, execute the %s" % text),
3637 25bd815c René Nussbaumer
             ("n", False, "No, abort the %s" % text)]
3638 25bd815c René Nussbaumer
3639 25bd815c René Nussbaumer
  if count > 20:
3640 25bd815c René Nussbaumer
    choices.insert(1, ("v", "v", "View the list of affected %s" % list_type))
3641 25bd815c René Nussbaumer
    question = msg
3642 25bd815c René Nussbaumer
  else:
3643 25bd815c René Nussbaumer
    question = msg + affected
3644 25bd815c René Nussbaumer
3645 25bd815c René Nussbaumer
  choice = AskUser(question, choices)
3646 25bd815c René Nussbaumer
  if choice == "v":
3647 25bd815c René Nussbaumer
    choices.pop(1)
3648 25bd815c René Nussbaumer
    choice = AskUser(msg + affected, choices)
3649 25bd815c René Nussbaumer
  return choice
3650 703fa9ab Iustin Pop
3651 703fa9ab Iustin Pop
3652 cd415612 René Nussbaumer
def _MaybeParseUnit(elements):
3653 cd415612 René Nussbaumer
  """Parses and returns an array of potential values with units.
3654 cd415612 René Nussbaumer

3655 cd415612 René Nussbaumer
  """
3656 ef40c537 René Nussbaumer
  parsed = {}
3657 ef40c537 René Nussbaumer
  for k, v in elements.items():
3658 ef40c537 René Nussbaumer
    if v == constants.VALUE_DEFAULT:
3659 ef40c537 René Nussbaumer
      parsed[k] = v
3660 cd415612 René Nussbaumer
    else:
3661 ef40c537 René Nussbaumer
      parsed[k] = utils.ParseUnit(v)
3662 cd415612 René Nussbaumer
  return parsed
3663 cd415612 René Nussbaumer
3664 cd415612 René Nussbaumer
3665 703fa9ab Iustin Pop
def CreateIPolicyFromOpts(ispecs_mem_size=None,
3666 703fa9ab Iustin Pop
                          ispecs_cpu_count=None,
3667 703fa9ab Iustin Pop
                          ispecs_disk_count=None,
3668 703fa9ab Iustin Pop
                          ispecs_disk_size=None,
3669 703fa9ab Iustin Pop
                          ispecs_nic_count=None,
3670 703fa9ab Iustin Pop
                          ipolicy_disk_templates=None,
3671 703fa9ab Iustin Pop
                          ipolicy_vcpu_ratio=None,
3672 ad5cc6bd René Nussbaumer
                          ipolicy_spindle_ratio=None,
3673 703fa9ab Iustin Pop
                          group_ipolicy=False,
3674 703fa9ab Iustin Pop
                          allowed_values=None,
3675 703fa9ab Iustin Pop
                          fill_all=False):
3676 703fa9ab Iustin Pop
  """Creation of instance policy based on command line options.
3677 703fa9ab Iustin Pop

3678 703fa9ab Iustin Pop
  @param fill_all: whether for cluster policies we should ensure that
3679 703fa9ab Iustin Pop
    all values are filled
3680 703fa9ab Iustin Pop

3681 703fa9ab Iustin Pop

3682 703fa9ab Iustin Pop
  """
3683 d67e0a94 Iustin Pop
  try:
3684 d67e0a94 Iustin Pop
    if ispecs_mem_size:
3685 cd415612 René Nussbaumer
      ispecs_mem_size = _MaybeParseUnit(ispecs_mem_size)
3686 d67e0a94 Iustin Pop
    if ispecs_disk_size:
3687 cd415612 René Nussbaumer
      ispecs_disk_size = _MaybeParseUnit(ispecs_disk_size)
3688 d67e0a94 Iustin Pop
  except (TypeError, ValueError, errors.UnitParseError), err:
3689 d67e0a94 Iustin Pop
    raise errors.OpPrereqError("Invalid disk (%s) or memory (%s) size"
3690 d67e0a94 Iustin Pop
                               " in policy: %s" %
3691 d67e0a94 Iustin Pop
                               (ispecs_disk_size, ispecs_mem_size, err),
3692 d67e0a94 Iustin Pop
                               errors.ECODE_INVAL)
3693 d67e0a94 Iustin Pop
3694 703fa9ab Iustin Pop
  # prepare ipolicy dict
3695 703fa9ab Iustin Pop
  ipolicy_transposed = {
3696 703fa9ab Iustin Pop
    constants.ISPEC_MEM_SIZE: ispecs_mem_size,
3697 703fa9ab Iustin Pop
    constants.ISPEC_CPU_COUNT: ispecs_cpu_count,
3698 703fa9ab Iustin Pop
    constants.ISPEC_DISK_COUNT: ispecs_disk_count,
3699 703fa9ab Iustin Pop
    constants.ISPEC_DISK_SIZE: ispecs_disk_size,
3700 703fa9ab Iustin Pop
    constants.ISPEC_NIC_COUNT: ispecs_nic_count,
3701 703fa9ab Iustin Pop
    }
3702 703fa9ab Iustin Pop
3703 703fa9ab Iustin Pop
  # first, check that the values given are correct
3704 703fa9ab Iustin Pop
  if group_ipolicy:
3705 703fa9ab Iustin Pop
    forced_type = TISPECS_GROUP_TYPES
3706 703fa9ab Iustin Pop
  else:
3707 703fa9ab Iustin Pop
    forced_type = TISPECS_CLUSTER_TYPES
3708 703fa9ab Iustin Pop
3709 703fa9ab Iustin Pop
  for specs in ipolicy_transposed.values():
3710 703fa9ab Iustin Pop
    utils.ForceDictType(specs, forced_type, allowed_values=allowed_values)
3711 703fa9ab Iustin Pop
3712 703fa9ab Iustin Pop
  # then transpose
3713 703fa9ab Iustin Pop
  ipolicy_out = objects.MakeEmptyIPolicy()
3714 703fa9ab Iustin Pop
  for name, specs in ipolicy_transposed.iteritems():
3715 703fa9ab Iustin Pop
    assert name in constants.ISPECS_PARAMETERS
3716 703fa9ab Iustin Pop
    for key, val in specs.items(): # {min: .. ,max: .., std: ..}
3717 703fa9ab Iustin Pop
      ipolicy_out[key][name] = val
3718 703fa9ab Iustin Pop
3719 703fa9ab Iustin Pop
  # no filldict for non-dicts
3720 703fa9ab Iustin Pop
  if not group_ipolicy and fill_all:
3721 703fa9ab Iustin Pop
    if ipolicy_disk_templates is None:
3722 703fa9ab Iustin Pop
      ipolicy_disk_templates = constants.DISK_TEMPLATES
3723 703fa9ab Iustin Pop
    if ipolicy_vcpu_ratio is None:
3724 703fa9ab Iustin Pop
      ipolicy_vcpu_ratio = \
3725 703fa9ab Iustin Pop
        constants.IPOLICY_DEFAULTS[constants.IPOLICY_VCPU_RATIO]
3726 ad5cc6bd René Nussbaumer
    if ipolicy_spindle_ratio is None:
3727 ad5cc6bd René Nussbaumer
      ipolicy_spindle_ratio = \
3728 ad5cc6bd René Nussbaumer
        constants.IPOLICY_DEFAULTS[constants.IPOLICY_SPINDLE_RATIO]
3729 703fa9ab Iustin Pop
  if ipolicy_disk_templates is not None:
3730 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_DTS] = list(ipolicy_disk_templates)
3731 703fa9ab Iustin Pop
  if ipolicy_vcpu_ratio is not None:
3732 703fa9ab Iustin Pop
    ipolicy_out[constants.IPOLICY_VCPU_RATIO] = ipolicy_vcpu_ratio
3733 ad5cc6bd René Nussbaumer
  if ipolicy_spindle_ratio is not None:
3734 ad5cc6bd René Nussbaumer
    ipolicy_out[constants.IPOLICY_SPINDLE_RATIO] = ipolicy_spindle_ratio
3735 703fa9ab Iustin Pop
3736 703fa9ab Iustin Pop
  assert not (frozenset(ipolicy_out.keys()) - constants.IPOLICY_ALL_KEYS)
3737 703fa9ab Iustin Pop
3738 703fa9ab Iustin Pop
  return ipolicy_out