def print_error_message(cli_err, out=stderr): errmsg = '%s' % cli_err if cli_err.importance == 1: errmsg = magenta(errmsg) elif cli_err.importance == 2: errmsg = yellow(errmsg) elif cli_err.importance > 2: errmsg = red(errmsg) out.write(errmsg) for errmsg in cli_err.details: out.write('| %s\n' % errmsg) out.flush()
def print_error_message(cli_err, out=stderr): errmsg = escape_ctrl_chars(('%s' % cli_err).strip('\n')).encode( pref_enc, 'replace') if cli_err.importance == 1: errmsg = magenta(errmsg) elif cli_err.importance == 2: errmsg = yellow(errmsg) elif cli_err.importance > 2: errmsg = red(errmsg) out.write(errmsg) out.write('\n') for errmsg in cli_err.details: out.write('| %s\n' % escape_ctrl_chars(u'%s' % errmsg).encode( pref_enc, 'replace')) out.flush()
def print_error_message(cli_err, out=stderr): errmsg = escape_ctrl_chars( ('%s' % cli_err).strip('\n')).encode(pref_enc, 'replace') if cli_err.importance == 1: errmsg = magenta(errmsg) elif cli_err.importance == 2: errmsg = yellow(errmsg) elif cli_err.importance > 2: errmsg = red(errmsg) out.write(errmsg) out.write('\n') for errmsg in cli_err.details: out.write( '| %s\n' % escape_ctrl_chars(u'%s' % errmsg).encode(pref_enc, 'replace')) out.flush()
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 _init_session(arguments, is_non_api=False): """ :returns: cloud name """ _help = arguments['help'].value global _debug _debug = arguments['debug'].value _verbose_with_data = arguments['verbose_with_data'].value _verbose = arguments['verbose'].value or _verbose_with_data _cnf = arguments['config'] _setup_logging(_debug, _verbose, _verbose_with_data) if _help or is_non_api: return None # Patch https for SSL Authentication ca_file = arguments['ca_file'].value or _cnf.get('global', 'ca_certs') ignore_ssl = arguments['ignore_ssl'].value or (_cnf.get( 'global', 'ignore_ssl').lower() == 'on') if ca_file: try: https.patch_with_certs(ca_file) except https.SSLUnicodeError as sslu: raise CLIError( 'Failed to set CA certificates file %s' % ca_file, importance=2, details=[ 'SSL module cannot handle non-ascii file names', 'Check the file path and consider moving and renaming', 'To set the new CA certificates path', ' kamaki config set ca_certs CA_FILE', sslu, ]) else: warn = red('CA certifications path not set (insecure) ') kloger.warning(warn) https.patch_ignore_ssl(ignore_ssl) _check_config_version(_cnf.value) _colors = _cnf.value.get('global', 'colors') if not (stdout.isatty() and _colors == 'on'): remove_colors() cloud = arguments['cloud'].value or _cnf.value.get( 'global', 'default_cloud') or os.environ.get(DEF_CLOUD_ENV) if not cloud: num_of_clouds = len(_cnf.value.keys('cloud')) if num_of_clouds == 1: cloud = _cnf.value.keys('cloud')[0] elif num_of_clouds > 1: raise CLIError( 'Found %s clouds but none of them is set as default' % (num_of_clouds), importance=2, details=[ 'Please, choose one of the following cloud names:', ', '.join(_cnf.value.keys('cloud')), 'To see all cloud settings:', ' kamaki config get cloud.<cloud name>', 'To set a default cloud:', ' kamaki config set default_cloud <cloud name>', ' or set the %s enviroment variable' % DEF_CLOUD_ENV, 'To pick a cloud for the current session, use --cloud:', ' kamaki --cloud=<cloud name> ...' ]) if cloud not in _cnf.value.keys('cloud'): raise CLIError('No cloud%s is configured' % ((' "%s"' % cloud) if cloud else ''), importance=3, details=[ 'To configure a new cloud "%s", find and set the' % (cloud or '<cloud name>'), 'single authentication URL and token:', ' kamaki config set cloud.%s.url <URL>' % (cloud or '<cloud name>'), ' kamaki config set cloud.%s.token <t0k3n>' % (cloud or '<cloud name>') ]) auth_args = dict() for term in ('url', 'token'): try: auth_args[term] = _cnf.get_cloud(cloud, term) except KeyError or IndexError: auth_args[term] = '' if not auth_args[term]: raise CLIError('No authentication %s provided for cloud "%s"' % (term.upper(), cloud), importance=3, details=[ 'Set a %s for cloud %s:' % (term.upper(), cloud), ' kamaki config set cloud.%s.%s <%s>' % (cloud, term, term.upper()) ]) return cloud
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)
def _init_session(arguments, is_non_api=False): """ :returns: cloud name """ _help = arguments['help'].value global _debug _debug = arguments['debug'].value _verbose = arguments['verbose'].value _cnf = arguments['config'] _setup_logging(_debug, _verbose) if _help or is_non_api: return None # Patch https for SSL Authentication ca_file = arguments['ca_file'].value or _cnf.get('global', 'ca_certs') ignore_ssl = arguments['ignore_ssl'].value or ( _cnf.get('global', 'ignore_ssl').lower() == 'on') if ca_file: try: https.patch_with_certs(ca_file) except https.SSLUnicodeError as sslu: raise CLIError( 'Failed to set CA certificates file %s' % ca_file, importance=2, details=[ 'SSL module cannot handle non-ascii file names', 'Check the file path and consider moving and renaming', 'To set the new CA certificates path', ' kamaki config set ca_certs CA_FILE', sslu, ]) else: warn = red('CA certifications path not set (insecure) ') kloger.warning(warn) https.patch_ignore_ssl(ignore_ssl) _check_config_version(_cnf.value) _colors = _cnf.value.get('global', 'colors') if not (stdout.isatty() and _colors == 'on'): remove_colors() cloud = arguments['cloud'].value or _cnf.value.get( 'global', 'default_cloud') if not cloud: num_of_clouds = len(_cnf.value.keys('cloud')) if num_of_clouds == 1: cloud = _cnf.value.keys('cloud')[0] elif num_of_clouds > 1: raise CLIError( 'Found %s clouds but none of them is set as default' % ( num_of_clouds), importance=2, details=[ 'Please, choose one of the following cloud names:', ', '.join(_cnf.value.keys('cloud')), 'To see all cloud settings:', ' kamaki config get cloud.<cloud name>', 'To set a default cloud:', ' kamaki config set default_cloud <cloud name>', 'To pick a cloud for the current session, use --cloud:', ' kamaki --cloud=<cloud name> ...']) if cloud not in _cnf.value.keys('cloud'): raise CLIError( 'No cloud%s is configured' % ((' "%s"' % cloud) if cloud else ''), importance=3, details=[ 'To configure a new cloud "%s", find and set the' % ( cloud or '<cloud name>'), 'single authentication URL and token:', ' kamaki config set cloud.%s.url <URL>' % ( cloud or '<cloud name>'), ' kamaki config set cloud.%s.token <t0k3n>' % ( cloud or '<cloud name>')]) auth_args = dict() for term in ('url', 'token'): try: auth_args[term] = _cnf.get_cloud(cloud, term) except KeyError or IndexError: auth_args[term] = '' if not auth_args[term]: raise CLIError( 'No authentication %s provided for cloud "%s"' % ( term.upper(), cloud), importance=3, details=[ 'Set a %s for cloud %s:' % (term.upper(), cloud), ' kamaki config set cloud.%s.%s <%s>' % ( cloud, term, term.upper())]) return cloud