Debian Codegraph @

ipapython/install/cli.py

raw
1 #
2 # Copyright (C) 2015 FreeIPA Contributors see COPYING for license
3 #
4
5 """
6 Command line support.
7 """
8
9 import collections
10 import enum
11 import logging
12 import signal
13
14 import six
15
16 from ipapython import admintool, config
17 from ipapython.ipa_log_manager import standard_logging_setup
18 from ipapython.ipautil import (CheckedIPAddress, CheckedIPAddressLoopback,
19 private_ccache)
20
21 from . import core, common
22
23 __all__ = ['install_tool', 'uninstall_tool']
24
25 if six.PY3:
26 long = int
27
28 NoneType = type(None)
29
30 logger = logging.getLogger(__name__)
31
32
33 def _get_usage(configurable_class):
34 usage = '%prog [options]'
35
36 for owner_cls, name in configurable_class.knobs():
37 knob_cls = getattr(owner_cls, name)
38 if knob_cls.is_cli_positional():
39 if knob_cls.cli_metavar is not None:
40 metavar = knob_cls.cli_metavar
41 elif knob_cls.cli_names:
42 metavar = knob_cls.cli_names[0].upper()
43 else:
44 metavar = name.replace('_', '-').upper()
45
46 try:
47 knob_cls.default
48 except AttributeError:
49 fmt = ' {}'
50 else:
51 fmt = ' [{}]'
52
53 usage += fmt.format(metavar)
54
55 return usage
56
57
58 def install_tool(configurable_class, command_name, log_file_name,
59 debug_option=False, verbose=False, console_format=None,
60 use_private_ccache=True, uninstall_log_file_name=None):
61 """
62 Some commands represent multiple related tools, e.g.
63 ``ipa-server-install`` and ``ipa-server-install --uninstall`` would be
64 represented by separate classes. Only their options are the same.
65
66 :param configurable_class: the command class for options
67 :param command_name: the command name shown in logs/output
68 :param log_file_name: if None, logging is to stderr only
69 :param debug_option: log level is DEBUG
70 :param verbose: log level is INFO
71 :param console_format: logging format for stderr
72 :param use_private_ccache: a temporary ccache is created and used
73 :param uninstall_log_file_name: if not None the log for uninstall
74 """
75 if uninstall_log_file_name is not None:
76 uninstall_kwargs = dict(
77 configurable_class=configurable_class,
78 command_name=command_name,
79 log_file_name=uninstall_log_file_name,
80 debug_option=debug_option,
81 verbose=verbose,
82 console_format=console_format,
83 )
84 else:
85 uninstall_kwargs = None
86
87 return type(
88 'install_tool({0})'.format(configurable_class.__name__),
89 (InstallTool,),
90 dict(
91 configurable_class=configurable_class,
92 command_name=command_name,
93 log_file_name=log_file_name,
94 usage=_get_usage(configurable_class),
95 debug_option=debug_option,
96 verbose=verbose,
97 console_format=console_format,
98 uninstall_kwargs=uninstall_kwargs,
99 use_private_ccache=use_private_ccache,
100 )
101 )
102
103
104 def uninstall_tool(configurable_class, command_name, log_file_name,
105 debug_option=False, verbose=False, console_format=None):
106 return type(
107 'uninstall_tool({0})'.format(configurable_class.__name__),
108 (UninstallTool,),
109 dict(
110 configurable_class=configurable_class,
111 command_name=command_name,
112 log_file_name=log_file_name,
113 usage=_get_usage(configurable_class),
114 debug_option=debug_option,
115 verbose=verbose,
116 console_format=console_format,
117 )
118 )
119
120
121 class ConfigureTool(admintool.AdminTool):
122 configurable_class = None
123 debug_option = False
124 verbose = False
125 console_format = None
126 use_private_ccache = True
127
128 @staticmethod
129 def _transform(configurable_class):
130 raise NotImplementedError
131
132 @classmethod
133 def add_options( # pylint: disable=arguments-renamed
134 cls, parser, positional=False
135 ):
136 transformed_cls = cls._transform(cls.configurable_class)
137
138 if issubclass(transformed_cls, common.Interactive):
139 parser.add_option(
140 '-U', '--unattended',
141 dest='unattended',
142 default=False,
143 action='store_true',
144 help="unattended (un)installation never prompts the user",
145 )
146
147 groups = collections.OrderedDict()
148 # if no group is defined, add the option to the parser top level
149 groups[None] = parser
150
151 for owner_cls, name in transformed_cls.knobs():
152 knob_cls = getattr(owner_cls, name)
153 if knob_cls.is_cli_positional() is not positional:
154 continue
155
156 group_cls = knob_cls.group()
157 try:
158 opt_group = groups[group_cls]
159 except KeyError:
160 opt_group = groups[group_cls] = config.OptionGroup(
161 parser, "{0} options".format(group_cls.description))
162 parser.add_option_group(opt_group)
163
164 knob_type = knob_cls.type
165 if issubclass(knob_type, list):
166 try:
167 # typing.List[X].__parameters__ == (X,)
168 knob_scalar_type = knob_type.__parameters__[0]
169 except AttributeError:
170 knob_scalar_type = str
171 else:
172 knob_scalar_type = knob_type
173
174 kwargs = dict()
175 if knob_scalar_type is NoneType:
176 kwargs['type'] = None
177 kwargs['const'] = True
178 kwargs['default'] = False
179 elif knob_scalar_type is str:
180 kwargs['type'] = 'string'
181 elif knob_scalar_type is int:
182 kwargs['type'] = 'int'
183 elif knob_scalar_type is long:
184 kwargs['type'] = 'long'
185 elif knob_scalar_type is CheckedIPAddressLoopback:
186 kwargs['type'] = 'ip_with_loopback'
187 elif knob_scalar_type is CheckedIPAddress:
188 kwargs['type'] = 'ip'
189 elif issubclass(knob_scalar_type, enum.Enum):
190 kwargs['type'] = 'choice'
191 kwargs['choices'] = [i.value for i in knob_scalar_type]
192 kwargs['metavar'] = "{{{0}}}".format(
193 ",".join(kwargs['choices']))
194 else:
195 kwargs['type'] = 'constructor'
196 kwargs['constructor'] = knob_scalar_type
197 kwargs['dest'] = name
198 if issubclass(knob_type, list):
199 if kwargs['type'] is None:
200 kwargs['action'] = 'append_const'
201 else:
202 kwargs['action'] = 'append'
203 else:
204 if kwargs['type'] is None:
205 kwargs['action'] = 'store_const'
206 else:
207 kwargs['action'] = 'store'
208 if knob_cls.sensitive:
209 kwargs['sensitive'] = True
210 if knob_cls.cli_metavar:
211 kwargs['metavar'] = knob_cls.cli_metavar
212
213 if not positional:
214 cli_info = (
215 (knob_cls.deprecated, knob_cls.cli_names),
216 (True, knob_cls.cli_deprecated_names),
217 )
218 else:
219 cli_info = (
220 (knob_cls.deprecated, (None,)),
221 )
222 for hidden, cli_names in cli_info:
223 opt_strs = []
224 for cli_name in cli_names:
225 if cli_name is None:
226 cli_name = '--{}'.format(name.replace('_', '-'))
227 opt_strs.append(cli_name)
228 if not opt_strs:
229 continue
230
231 if not hidden:
232 help = knob_cls.description
233 else:
234 help = config.SUPPRESS_HELP
235
236 opt_group.add_option(
237 *opt_strs,
238 help=help,
239 **kwargs
240 )
241
242 super(ConfigureTool, cls).add_options(parser,
243 debug_option=cls.debug_option)
244
245 def __init__(self, options, args):
246 super(ConfigureTool, self).__init__(options, args)
247
248 self.transformed_cls = self._transform(self.configurable_class)
249 self.positional_arguments = []
250
251 for owner_cls, name in self.transformed_cls.knobs():
252 knob_cls = getattr(owner_cls, name)
253 if knob_cls.is_cli_positional():
254 self.positional_arguments.append(name)
255
256 # fake option parser to parse positional arguments
257 # (because optparse does not support positional argument parsing)
258 fake_option_parser = config.IPAOptionParser()
259 self.add_options(fake_option_parser, True)
260
261 fake_option_map = {option.dest: option
262 for group in fake_option_parser.option_groups
263 for option in group.option_list}
264
265 for index, name in enumerate(self.positional_arguments):
266 try:
267 value = self.args.pop(0)
268 except IndexError:
269 break
270
271 fake_option = fake_option_map[name]
272 fake_option.process('argument {}'.format(index + 1),
273 value,
274 self.options,
275 self.option_parser)
276
277 def validate_options(self, needs_root=True):
278 super(ConfigureTool, self).validate_options(needs_root=needs_root)
279
280 if self.args:
281 self.option_parser.error("Too many arguments provided")
282
283 def _setup_logging(self, log_file_mode='w', no_file=False):
284 if no_file:
285 log_file_name = None
286 elif self.options.log_file:
287 log_file_name = self.options.log_file
288 else:
289 log_file_name = self.log_file_name
290 standard_logging_setup(
291 log_file_name,
292 verbose=self.verbose,
293 debug=self.options.verbose,
294 console_format=self.console_format)
295 if log_file_name:
296 logger.debug('Logging to %s', log_file_name)
297 elif not no_file:
298 logger.debug('Not logging to a file')
299
300 def init_configurator(self):
301 """Executes transformation, getting a flattened Installer object
302
303 :returns: common.installer.Installer object
304 """
305 kwargs = {}
306
307 transformed_cls = self._transform(self.configurable_class)
308 knob_classes = {n: getattr(c, n) for c, n in transformed_cls.knobs()}
309 for name in knob_classes:
310 value = getattr(self.options, name, None)
311 if value is not None:
312 kwargs[name] = value
313
314 if (issubclass(self.configurable_class, common.Interactive) and
315 not self.options.unattended):
316 kwargs['interactive'] = True
317
318 try:
319 return transformed_cls(**kwargs)
320 except core.KnobValueError as e:
321 knob_cls = knob_classes[e.name]
322 try:
323 index = self.positional_arguments.index(e.name)
324 except ValueError:
325 cli_name = knob_cls.cli_names[0] or e.name.replace('_', '-')
326 desc = "option {0}".format(cli_name)
327 else:
328 desc = "argument {0}".format(index + 1)
329 self.option_parser.error("{0}: {1}".format(desc, e))
330 except RuntimeError as e:
331 self.option_parser.error(str(e))
332
333 return None
334
335 def run(self):
336 cfgr = self.init_configurator()
337
338 signal.signal(signal.SIGTERM, self.__signal_handler)
339
340 if self.use_private_ccache:
341 with private_ccache():
342 super(ConfigureTool, self).run()
343 return cfgr.run()
344 else:
345 super(ConfigureTool, self).run()
346 return cfgr.run()
347
348 @staticmethod
349 def __signal_handler(signum, frame):
350 raise KeyboardInterrupt
351
352
353 class InstallTool(ConfigureTool):
354 uninstall_kwargs = None
355
356 _transform = staticmethod(common.installer)
357
358 @classmethod
359 def add_options(cls, parser, positional=False):
360 super(InstallTool, cls).add_options(parser, positional)
361
362 if cls.uninstall_kwargs is not None:
363 parser.add_option(
364 '--uninstall',
365 dest='uninstall',
366 default=False,
367 action='store_true',
368 help=("uninstall an existing installation. The uninstall can "
369 "be run with --unattended option"),
370 )
371
372 @classmethod
373 def get_command_class(cls, options, args):
374 if cls.uninstall_kwargs is not None and options.uninstall:
375 uninstall_cls = uninstall_tool(**cls.uninstall_kwargs)
376 uninstall_cls.option_parser = cls.option_parser
377 return uninstall_cls
378 else:
379 return super(InstallTool, cls).get_command_class(options, args)
380
381
382 class UninstallTool(ConfigureTool):
383 _transform = staticmethod(common.uninstaller)