def wrap(): try: exe = basename(argv[0]) parser = ArgumentParseManager(exe) if parser.arguments['version'].value: exit(0) _cnf = parser.arguments['config'] log_file = _cnf.get('global', 'log_file') if log_file: logger.set_log_filename(log_file) global filelog filelog = logger.add_file_logger(__name__.split('.')[0]) filelog.info('* Initial Call *\n%s\n- - -' % ' '.join(argv)) from kamaki.cli.utils import suggest_missing global _colors exclude = ['ansicolors'] if not _colors == 'on' else [] suggest_missing(exclude=exclude) func(exe, parser) except CLIError as err: print_error_message(err) if _debug: raise err exit(1) except KeyboardInterrupt: print('Canceled by user') exit(1) except Exception as er: print('Unknown Error: %s' % er) if _debug: raise exit(1)
def test_add_file_logger(self, GL, GLF): from kamaki.cli.logger import add_file_logger with patch('kamaki.cli.logger._add_logger', return_value='AL') as AL: GLFcount = GLF.call_count for name, level, filename in product( ('my name'), ('my level', None), ('my filename', None)): self.assertEqual(add_file_logger(name, level, filename), 'AL') self.assertEqual(AL.mock_calls[-1], call( name, level, filename or 'my log fname', fmt='%(name)s(%(levelname)s) %(asctime)s\n\t%(message)s')) if filename: self.assertEqual(GLFcount, GLF.call_count) else: GLFcount = GLF.call_count self.assertEqual(GLF.mock_calls[-1], call()) with patch('kamaki.cli.logger._add_logger', side_effect=Exception): self.assertEqual(add_file_logger('X'), 'my get logger ret') GL.assert_called_once_with('X')
def test_add_file_logger(self, GL, GLF): from kamaki.cli.logger import add_file_logger with patch('kamaki.cli.logger._add_logger', return_value='AL') as AL: GLFcount = GLF.call_count for name, level, filename in product( ('my name'), ('my level', None), ('my filename', None)): self.assertEqual(add_file_logger(name, level, filename), 'AL') from logging import DEBUG as dbg fmt = '%(name)s(%(levelname)s) %(asctime)s\n\t%(message)s' if ( level == dbg) else '%(name)s: %(message)s' self.assertEqual( AL.mock_calls[-1], call(name, level, filename or 'my log fname', fmt=fmt)) if filename: self.assertEqual(GLFcount, GLF.call_count) else: GLFcount = GLF.call_count self.assertEqual(GLF.mock_calls[-1], call()) with patch('kamaki.cli.logger._add_logger', side_effect=Exception): self.assertEqual(add_file_logger('X'), 'my get logger ret') GL.assert_called_once_with('X')
def make_log_file(): f = NamedTemporaryFile() add_file_logger('kamaki.cli.config', filename=f.name) return f
# interpreted as representing official policies, either expressed # or implied, of GRNET S.A. from cmd import Cmd from os import popen from sys import stdout from kamaki.cli import exec_cmd, print_error_message, print_subcommands_help from kamaki.cli.argument import ArgumentParseManager from kamaki.cli.utils import print_dict, split_input, pref_enc from kamaki.cli.history import History from kamaki.cli.errors import CLIError from kamaki.clients import ClientError from kamaki.cli.logger import add_file_logger log = add_file_logger(__name__) def init_shell(exe_string, parser, username='', userid=''): parser.arguments.pop('version', None) shell = Shell() shell.set_prompt(exe_string) from kamaki import __version__ as version shell.greet(version, username, userid) shell.do_EOF = shell.do_exit from kamaki.cli.cmdtree import CommandTree shell.cmd_tree = CommandTree( 'kamaki', 'A command line tool for poking clouds') return shell
def wrap(): try: exe = basename(argv[0]) internal_argv = [] for i, a in enumerate(argv): try: internal_argv.append(a.decode(pref_enc)) except UnicodeDecodeError as ude: raise CLIError( 'Invalid encoding in command', importance=3, details=[ 'The invalid term is #%s (with "%s" being 0)' % (i, exe), 'Encoding is invalid with current locale settings ' '(%s)' % pref_enc, '( %s )' % ude ]) for i, a in enumerate(internal_argv): argv[i] = a logger.add_stream_logger( __name__, logging.WARNING, fmt='%(levelname)s (%(name)s): %(message)s') _config_arg = ConfigArgument('Path to a custom config file') parser = ArgumentParseManager( exe, arguments=dict( config=_config_arg, cloud=ValueArgument('Chose a cloud to connect to', ('--cloud')), help=Argument(0, 'Show help message', ('-h', '--help')), debug=FlagArgument('Include debug output', ('-d', '--debug')), verbose=FlagArgument( 'Show HTTP requests and responses, without HTTP body', ('-v', '--verbose')), verbose_with_data=FlagArgument( 'Show HTTP requests and responses, including HTTP body', ('-vv', '--verbose-with-data')), version=VersionArgument('Print current version', ('-V', '--version')), options=RuntimeConfigArgument( _config_arg, 'Override a config option (not persistent)', ('-o', '--options')), ignore_ssl=FlagArgument( 'Allow connections to SSL sites without certs', ('-k', '--ignore-ssl', '--insecure')), ca_file=ValueArgument( 'CA certificates for SSL authentication', '--ca-certs'), )) if parser.arguments['version'].value: exit(0) _cnf = parser.arguments['config'] log_file = _cnf.get('global', 'log_file') if log_file: logger.set_log_filename(log_file) filelog = logger.add_file_logger(__name__.split('.')[0]) filelog.info('%s\n- - -' % ' '.join(argv)) _colors = _cnf.value.get('global', 'colors') exclude = ['ansicolors'] if not _colors == 'on' else [] suggest_missing(exclude=exclude) func(exe, parser) except CLIError as err: print_error_message(err) if _debug: raise err exit(1) except KamakiSSLError as err: ca_arg = parser.arguments.get('ca_file') ca = ca_arg.value if ca_arg and ca_arg.value else _cnf.get( 'global', 'ca_certs') stderr.write(red('SSL Authentication failed\n')) if ca: stderr.write('Path used for CA certifications file: %s\n' % (escape_ctrl_chars(ca))) stderr.write('Please make sure the path is correct\n') if not (ca_arg and ca_arg.value): stderr.write('| To set the correct path:\n') stderr.write('| kamaki config set ca_certs CA_FILE\n') else: stderr.write('| To use a CA certifications file:\n') stderr.write('| kamaki config set ca_certs CA_FILE\n') stderr.write('| OR run with --ca-certs=FILE_LOCATION\n') stderr.write('| To ignore SSL errors and move on (%s):\n' % (red('insecure'))) stderr.write('| kamaki config set ignore_ssl on\n') stderr.write('| OR run with --ignore-ssl\n') stderr.flush() if _debug: raise stderr.write('| %s: %s\n' % (type(err), escape_ctrl_chars('%s' % err))) stderr.flush() exit(1) except KeyboardInterrupt: print('Canceled by user') exit(1) except Exception as er: print('Unknown Error: %s' % er) if _debug: raise exit(1)
def wrap(): try: exe = basename(argv[0]) internal_argv = [] for i, a in enumerate(argv): try: internal_argv.append(a.decode(pref_enc)) except UnicodeDecodeError as ude: raise CLIError( 'Invalid encoding in command', importance=3, details=[ 'The invalid term is #%s (with "%s" being 0)' % ( i, exe), 'Encoding is invalid with current locale settings ' '(%s)' % pref_enc, '( %s )' % ude]) for i, a in enumerate(internal_argv): argv[i] = a logger.add_stream_logger( __name__, logging.WARNING, fmt='%(levelname)s (%(name)s): %(message)s') _config_arg = ConfigArgument('Path to config file') parser = ArgumentParseManager(exe, arguments=dict( config=_config_arg, cloud=ValueArgument( 'Chose a cloud to connect to', ('--cloud')), help=Argument(0, 'Show help message', ('-h', '--help')), debug=FlagArgument('Include debug output', ('-d', '--debug')), verbose=FlagArgument( 'More info at response', ('-v', '--verbose')), version=VersionArgument( 'Print current version', ('-V', '--version')), options=RuntimeConfigArgument( _config_arg, 'Override a config value', ('-o', '--options')), ignore_ssl=FlagArgument( 'Allow connections to SSL sites without certs', ('-k', '--ignore-ssl', '--insecure')), ca_file=ValueArgument( 'CA certificates for SSL authentication', '--ca-certs'),) ) if parser.arguments['version'].value: exit(0) _cnf = parser.arguments['config'] log_file = _cnf.get('global', 'log_file') if log_file: logger.set_log_filename(log_file) filelog = logger.add_file_logger(__name__.split('.')[0]) filelog.info('%s\n- - -' % ' '.join(argv)) _colors = _cnf.value.get('global', 'colors') exclude = ['ansicolors'] if not _colors == 'on' else [] suggest_missing(exclude=exclude) func(exe, parser) except CLIError as err: print_error_message(err) if _debug: raise err exit(1) except KamakiSSLError as err: ca_arg = parser.arguments.get('ca_file') ca = ca_arg.value if ca_arg and ca_arg.value else _cnf.get( 'global', 'ca_certs') stderr.write(red('SSL Authentication failed\n')) if ca: stderr.write('Path used for CA certifications file: %s\n' % ( escape_ctrl_chars(ca))) stderr.write('Please make sure the path is correct\n') if not (ca_arg and ca_arg.value): stderr.write('| To set the correct path:\n') stderr.write('| kamaki config set ca_certs CA_FILE\n') else: stderr.write('| To use a CA certifications file:\n') stderr.write('| kamaki config set ca_certs CA_FILE\n') stderr.write('| OR run with --ca-certs=FILE_LOCATION\n') stderr.write('| To ignore SSL errors and move on (%s):\n' % ( red('insecure'))) stderr.write('| kamaki config set ignore_ssl on\n') stderr.write('| OR run with --ignore-ssl\n') stderr.flush() if _debug: raise stderr.write('| %s: %s\n' % ( type(err), escape_ctrl_chars('%s' % err))) stderr.flush() exit(1) except KeyboardInterrupt: print('Canceled by user') exit(1) except Exception as er: print('Unknown Error: %s' % er) if _debug: raise exit(1)
# interpreted as representing official policies, either expressed # or implied, of GRNET S.A. from cmd import Cmd from os import popen from sys import stdout from kamaki.cli import exec_cmd, print_error_message, print_subcommands_help from kamaki.cli.argument import ArgumentParseManager from kamaki.cli.utils import print_dict, split_input, pref_enc from kamaki.cli.history import History from kamaki.cli.errors import CLIError from kamaki.clients import ClientError from kamaki.cli.logger import add_file_logger log = add_file_logger(__name__) def init_shell(exe_string, parser, username='', userid=''): parser.arguments.pop('version', None) shell = Shell() shell.set_prompt(exe_string) from kamaki import __version__ as version shell.greet(version, username, userid) shell.do_EOF = shell.do_exit from kamaki.cli.cmdtree import CommandTree shell.cmd_tree = CommandTree('kamaki', 'A command line tool for poking clouds') return shell