Debian Codegraph @

ipapython/admintool.py

raw
1 # Authors:
2 # Petr Viktorin <[email protected]>
3 #
4 # Copyright (C) 2012 Red Hat
5 # see file 'COPYING' for use and warranty information
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20 """A common framework for command-line admin tools, e.g. install scripts
21
22 Handles common operations like option parsing and logging
23 """
24
25 import logging
26 import sys
27 import os
28 import traceback
29
30 from ipaplatform.osinfo import osinfo
31 from ipapython import version
32 from ipapython import config
33 from ipapython.ipa_log_manager import standard_logging_setup
34
35 SUCCESS = 0
36 SERVER_INSTALL_ERROR = 1
37 SERVER_NOT_CONFIGURED = 2
38
39 logger = logging.getLogger(__name__)
40
41
42 def admin_cleanup_global_argv(option_parser, options, argv):
43 """Takes option parser and generated options and scrubs sensitive arguments
44 from the global program arguments. Note that this only works for GNU GLIBC
45 as Python has no generic way to get access to the original argv values to
46 modify them in place.
47
48 The code assumes Python behavior, e.g. there are two additional args in the
49 list (/path/to/python -I ...) than what's passed as 'argv' here.
50 """
51 import ctypes
52 import ctypes.util
53 try:
54 _c = ctypes.CDLL(ctypes.util.find_library("c"))
55 if _c._name is None:
56 return
57 _argv = ctypes.POINTER(ctypes.c_voidp).in_dll(_c, "_dl_argv")
58 # since we run as 'python -I <executable> ...', add two args
59 _argc = len(argv) + 2
60 all_options = []
61 if '_get_all_options' in dir(option_parser):
62 # OptParse parser
63 all_options = option_parser._get_all_options()
64 elif '_actions' in dir(option_parser):
65 # ArgParse parser
66 all_options = option_parser._actions
67
68 for opt in all_options:
69 if getattr(opt, 'sensitive', False):
70 v = getattr(options, opt.dest)
71 for i in range(0, _argc):
72 vi = ctypes.cast(_argv[i],
73 ctypes.c_char_p
74 ).value.decode('utf-8')
75 if vi == v:
76 ctypes.memset(_argv[i], ord('X'), len(v))
77 except Exception:
78 pass
79
80
81 class ScriptError(Exception):
82 """An exception that records an error message and a return value
83 """
84 def __init__(self, msg='', rval=1):
85 if msg is None:
86 msg = ''
87 super(ScriptError, self).__init__(msg)
88 self.rval = rval
89
90 @property
91 def msg(self):
92 return str(self)
93
94
95 class AdminTool:
96 """Base class for command-line admin tools
97
98 To run the tool, call the main() classmethod with a list of command-line
99 arguments.
100 Alternatively, call run_cli() to run with command-line arguments in
101 sys.argv, and call sys.exit() with the return value.
102
103 Some commands actually represent multiple related tools, e.g.
104 ``ipa-server-install`` and ``ipa-server-install --uninstall`` would be
105 represented by separate classes. Only their options are the same.
106
107 To handle this, AdminTool provides classmethods for option parsing
108 and selecting the appropriate command class.
109
110 A class-wide option parser is made by calling add_options.
111 The options are then parsed into options and arguments, and
112 get_command_class is called with those to retrieve the class.
113 That class is then instantiated and run.
114
115 Running consists of a few steps:
116 - validating options or the environment (validate_options)
117 - setting up logging (setup_logging)
118 - running the actual command (run)
119
120 Any unhandled exceptions are handled in handle_error.
121 And at the end, either log_success or log_failure is called.
122
123 Class attributes to define in subclasses:
124 command_name - shown in logs
125 log_file_name - if None, logging is to stderr only
126 usage - text shown in help
127 description - text shown in help
128
129 See the setup_logging method for more info on logging.
130 """
131 command_name = None
132 log_file_name = None
133 usage = None
134 description = None
135
136 _option_parsers = dict()
137
138 @classmethod
139 def make_parser(cls):
140 """Create an option parser shared across all instances of this class"""
141 parser = config.IPAOptionParser(version=version.VERSION,
142 usage=cls.usage, formatter=config.IPAFormatter(),
143 description=cls.description)
144 cls.option_parser = parser
145 cls.add_options(parser)
146
147 @classmethod
148 def add_options(cls, parser, debug_option=False):
149 """Add command-specific options to the option parser
150
151 :param parser: The parser to add options to
152 :param debug_option: Add a --debug option as an alias to --verbose
153 """
154 group = config.OptionGroup(parser, "Logging and output options")
155 group.add_option("-v", "--verbose", dest="verbose", default=False,
156 action="store_true", help="print debugging information")
157 if debug_option:
158 group.add_option("-d", "--debug", dest="verbose", default=False,
159 action="store_true", help="alias for --verbose (deprecated)")
160 group.add_option("-q", "--quiet", dest="quiet", default=False,
161 action="store_true", help="output only errors")
162 group.add_option("--log-file", dest="log_file", default=None,
163 metavar="FILE", help="log to the given file")
164 parser.add_option_group(group)
165
166 @classmethod
167 def run_cli(cls):
168 """Run this command with sys.argv, exit process with the return value
169 """
170 sys.exit(cls.main(sys.argv))
171
172 @classmethod
173 def main(cls, argv):
174 """The main entry point
175
176 Parses command-line arguments, selects the actual command class to use
177 based on them, and runs that command.
178
179 :param argv: Command-line arguments.
180 :return: Command exit code
181 """
182 if cls not in cls._option_parsers:
183 # We use cls._option_parsers, a dictionary keyed on class, to check
184 # if we need to create a parser. This is because cls.option_parser
185 # can refer to the parser of a superclass.
186 cls.make_parser()
187 cls._option_parsers[cls] = cls.option_parser
188
189 options, args = cls.option_parser.parse_args(argv[1:])
190 admin_cleanup_global_argv(cls.option_parser, options, argv)
191
192 command_class = cls.get_command_class(options, args)
193 command = command_class(options, args)
194
195 return command.execute()
196
197 @classmethod
198 def get_command_class(cls, options, args):
199 return cls
200
201 def __init__(self, options, args):
202 self.options = options
203 self.args = args
204 self.log_file_initialized = False
205 self.safe_options = self.option_parser.get_safe_opts(options)
206
207 def execute(self):
208 """Do everything needed after options are parsed
209
210 This includes validating options, setting up logging, doing the
211 actual work, and handling the result.
212 """
213 self._setup_logging(no_file=True)
214 return_value = 1
215 try:
216 self.validate_options()
217 self.ask_for_options()
218 self.setup_logging()
219 return_value = self.run()
220 except BaseException as exception:
221 if isinstance(exception, ScriptError):
222 if exception.rval and exception.rval > return_value:
223 return_value = exception.rval
224 traceback = sys.exc_info()[2]
225 error_message, return_value = self.handle_error(exception)
226 if return_value:
227 self.log_failure(error_message, return_value, exception,
228 traceback)
229 return return_value
230 self.log_success()
231 return return_value
232
233 def validate_options(self, needs_root=False):
234 """Validate self.options
235
236 It's also possible to compute and store information that will be
237 useful later, but no changes to the system should be made here.
238 """
239 if needs_root and os.getegid() != 0:
240 raise ScriptError('Must be root to run %s' % self.command_name, 1)
241 if self.options.verbose and self.options.quiet:
242 raise ScriptError(
243 'The --quiet and --verbose options are mutually exclusive')
244
245 def ask_for_options(self):
246 """Ask for missing options interactively
247
248 Similar to validate_options. This is separate method because we want
249 any validation errors to abort the script before bothering the user
250 with prompts.
251
252 Any options that might be asked for should also be validated here.
253 """
254
255 def setup_logging(self, log_file_mode='w'):
256 """Set up logging
257
258 :param _to_file: Setting this to false will disable logging to file.
259 For internal use.
260
261 If the --log-file option was given or if a filename is in
262 self.log_file_name, the tool will log to that file. In this case,
263 all messages are logged.
264
265 What is logged to the console depends on command-line options:
266 the default is INFO; --quiet sets ERROR; --verbose sets DEBUG.
267
268 Rules of thumb for logging levels:
269 - CRITICAL for fatal errors
270 - ERROR for critical things that the admin must see, even with --quiet
271 - WARNING for things that need to stand out in the log
272 - INFO to display normal messages
273 - DEBUG to spam about everything the program does
274 - a plain print for things that should not be log (for example,
275 interactive prompting)
276
277 To log, use a module-level logger.
278
279 Logging to file is only set up after option validation and prompting;
280 before that, all output will go to the console only.
281 """
282 root_logger = logging.getLogger()
283 for handler in root_logger.handlers:
284 if (isinstance(handler, logging.StreamHandler) and
285 handler.stream is sys.stderr):
286 root_logger.removeHandler(handler)
287 break
288
289 self._setup_logging(log_file_mode=log_file_mode)
290 if self.log_file_name:
291 self.log_file_initialized = True
292
293 def _setup_logging(self, log_file_mode='w', no_file=False):
294 if no_file:
295 log_file_name = None
296 elif self.options.log_file:
297 log_file_name = self.options.log_file
298 self.log_file_name = log_file_name
299 else:
300 log_file_name = self.log_file_name
301 if self.options.verbose:
302 console_format = '%(name)s: %(levelname)s: %(message)s'
303 verbose = True
304 debug = True
305 else:
306 console_format = '%(message)s'
307 debug = False
308 if self.options.quiet:
309 verbose = False
310 else:
311 verbose = True
312 standard_logging_setup(
313 log_file_name, console_format=console_format,
314 filemode=log_file_mode, debug=debug, verbose=verbose)
315 if log_file_name:
316 logger.debug('Logging to %s', log_file_name)
317 elif not no_file:
318 logger.debug('Not logging to a file')
319
320
321 def handle_error(self, exception):
322 """Given an exception, return a message (or None) and process exit code
323 """
324 if isinstance(exception, ScriptError):
325 return exception.msg, exception.rval
326 elif isinstance(exception, SystemExit):
327 if isinstance(exception.code, int):
328 return None, exception.code
329 return str(exception.code), 1
330
331 return str(exception), 1
332
333 def run(self):
334 """Actual running of the command
335
336 This is where the hard work is done. The base implementation logs
337 the invocation of the command.
338
339 If this method returns (i.e. doesn't raise an exception), the tool is
340 assumed to have run successfully, and the return value is used as the
341 SystemExit code.
342 """
343 logger.debug('%s was invoked with arguments %s and options: %s',
344 self.command_name, self.args, self.safe_options)
345 logger.debug('IPA version %s', version.VENDOR_VERSION)
346 logger.debug('IPA platform %s', osinfo.platform)
347 logger.debug('IPA os-release %s %s', osinfo.name, osinfo.version)
348
349 def log_failure(self, error_message, return_value, exception, backtrace):
350 logger.debug('%s', ''.join(traceback.format_tb(backtrace)))
351 logger.debug('The %s command failed, exception: %s: %s',
352 self.command_name, type(exception).__name__, exception)
353 if error_message:
354 logger.error('%s', error_message)
355 if return_value == 0:
356 # A script may raise an exception but still want quit gracefully,
357 # like the case of ipa-client-install called from
358 # ipa-server-install.
359 return
360 message = "The %s command failed." % self.command_name
361 if self.log_file_initialized and return_value != SERVER_NOT_CONFIGURED:
362 message += " See %s for more information" % self.log_file_name
363 logger.error('%s', message)
364
365 def log_success(self):
366 logger.info('The %s command was successful', self.command_name)