def format_isodate_for_user_timezone(value): """ Format the provided ISO date time string for human friendly display taking into user timezone specific in the config. """ config = get_config() timezone = config.get("cli", {}).get("timezone", "UTC") result = format_isodate(value=value, timezone=timezone) return result
def format_isodate_for_user_timezone(value): """ Format the provided ISO date time string for human friendly display taking into user timezone specific in the config. """ config = get_config() timezone = config.get('cli', {}).get('timezone', 'UTC') result = format_isodate(value=value, timezone=timezone) return result
def format(cls, entry, *args, **kwargs): attrs = kwargs.get('attributes', []) attribute_transform_functions = kwargs.get('attribute_transform_functions', {}) key = kwargs.get('key', None) if key: output = jsutil.get_value(entry.result, key) else: # drop entry to the dict so that jsutil can operate entry = vars(entry) output = '' for attr in attrs: value = jsutil.get_value(entry, attr) value = strutil.strip_carriage_returns(strutil.unescape(value)) # TODO: This check is inherently flawed since it will crash st2client # if the leading character is objectish start and last character is objectish # end but the string isn't supposed to be a object. Try/Except will catch # this for now, but this should be improved. if (isinstance(value, six.string_types) and len(value) > 0 and value[0] in ['{', '['] and value[len(value) - 1] in ['}', ']']): try: new_value = ast.literal_eval(value) except: new_value = value if type(new_value) in [dict, list]: value = new_value if type(value) in [dict, list]: # 1. To get a nice overhang indent get safe_dump to generate output with # the attribute key and then remove the attribute key from the string. # 2. Drop the trailing newline # 3. Set width to maxint so pyyaml does not split text. Anything longer # and likely we will see other issues like storage :P. formatted_value = yaml.safe_dump({attr: value}, default_flow_style=False, width=PLATFORM_MAXINT, indent=2)[len(attr) + 2:-1] value = ('\n' if isinstance(value, dict) else '') + formatted_value value = strutil.dedupe_newlines(value) # transform the value of our attribute so things like 'status' # and 'timestamp' are formatted nicely transform_function = attribute_transform_functions.get(attr, lambda value: value) value = transform_function(value=value) output += ('\n' if output else '') + '%s: %s' % \ (DisplayColors.colorize(attr, DisplayColors.BLUE), value) output_schema = entry.get('action', {}).get('output_schema') schema_check = get_config()['general']['silence_schema_output'] if not output_schema and kwargs.get('with_schema'): rendered_schema = { 'output_schema': schema.render_output_schema_from_output(entry['result']) } rendered_schema = yaml.safe_dump(rendered_schema, default_flow_style=False) output += '\n' output += _print_bordered( "Based on the action output the following inferred schema was built:" "\n\n" "%s" % rendered_schema ) elif not output_schema and not schema_check: output += ( "\n\n** This action does not have an output_schema. " "Run again with --with-schema to see a suggested schema." ) if six.PY3: return strutil.unescape(str(output)) else: # Assume Python 2 try: result = strutil.unescape(str(output)).decode('unicode_escape').encode('utf-8') except UnicodeDecodeError: # String contains a value which is not an unicode escape sequence, ignore the error result = strutil.unescape(str(output)) return result
def get_client(self, args, debug=False): ST2_CLI_SKIP_CONFIG = os.environ.get('ST2_CLI_SKIP_CONFIG', 0) ST2_CLI_SKIP_CONFIG = int(ST2_CLI_SKIP_CONFIG) skip_config = args.skip_config skip_config = skip_config or ST2_CLI_SKIP_CONFIG # Note: Options provided as the CLI argument have the highest precedence # Precedence order: cli arguments > environment variables > rc file variables cli_options = [ 'base_url', 'auth_url', 'api_url', 'api_version', 'cacert' ] cli_options = {opt: getattr(args, opt, None) for opt in cli_options} config_file_options = self._get_config_file_options(args=args) kwargs = {} if not skip_config: # Config parsing is not skipped kwargs = merge_dicts(kwargs, config_file_options) kwargs = merge_dicts(kwargs, cli_options) kwargs['debug'] = debug client = Client(**kwargs) if skip_config: # Config parsing is skipped self.LOG.info('Skipping parsing CLI config') return client # Ok to use config at this point rc_config = get_config() # Silence SSL warnings silence_ssl_warnings = rc_config.get('general', {}).get('silence_ssl_warnings', False) if silence_ssl_warnings: requests.packages.urllib3.disable_warnings() # We skip automatic authentication for some commands such as auth try: command_class_name = args.func.im_class.__name__ except Exception: command_class_name = None if command_class_name in self.SKIP_AUTH_CLASSES: return client # We also skip automatic authentication if token is provided via the environment variable # or as a command line argument env_var_token = os.environ.get('ST2_AUTH_TOKEN', None) cli_argument_token = getattr(args, 'token', None) env_var_api_key = os.environ.get('ST2_API_KEY', None) cli_argument_api_key = getattr(args, 'api_key', None) if env_var_token or cli_argument_token or env_var_api_key or cli_argument_api_key: return client # If credentials are provided in the CLI config use them and try to authenticate credentials = rc_config.get('credentials', {}) username = credentials.get('username', None) password = credentials.get('password', None) cache_token = rc_config.get('cli', {}).get('cache_token', False) if credentials: # Credentials are provided, try to authenticate agaist the API try: token = self._get_auth_token(client=client, username=username, password=password, cache_token=cache_token) except requests.exceptions.ConnectionError as e: self.LOG.warn( 'Auth API server is not available, skipping authentication.' ) self.LOG.exception(e) return client except Exception as e: print( 'Failed to authenticate with credentials provided in the config.' ) raise e client.token = token # TODO: Hack, refactor when splitting out the client os.environ['ST2_AUTH_TOKEN'] = token return client
def format(cls, entry, *args, **kwargs): attrs = kwargs.get('attributes', []) attribute_transform_functions = kwargs.get( 'attribute_transform_functions', {}) key = kwargs.get('key', None) if key: output = jsutil.get_value(entry.result, key) else: # drop entry to the dict so that jsutil can operate entry = vars(entry) output = '' for attr in attrs: value = jsutil.get_value(entry, attr) value = strutil.strip_carriage_returns(strutil.unescape(value)) # TODO: This check is inherently flawed since it will crash st2client # if the leading character is objectish start and last character is objectish # end but the string isn't supposed to be a object. Try/Except will catch # this for now, but this should be improved. if (isinstance(value, six.string_types) and len(value) > 0 and value[0] in ['{', '['] and value[len(value) - 1] in ['}', ']']): try: new_value = ast.literal_eval(value) except: new_value = value if type(new_value) in [dict, list]: value = new_value if type(value) in [dict, list]: # 1. To get a nice overhang indent get safe_dump to generate output with # the attribute key and then remove the attribute key from the string. # 2. Drop the trailing newline # 3. Set width to maxint so pyyaml does not split text. Anything longer # and likely we will see other issues like storage :P. formatted_value = yaml.safe_dump({attr: value}, default_flow_style=False, width=PLATFORM_MAXINT, indent=2)[len(attr) + 2:-1] value = ('\n' if isinstance(value, dict) else '') + formatted_value value = strutil.dedupe_newlines(value) # transform the value of our attribute so things like 'status' # and 'timestamp' are formatted nicely transform_function = attribute_transform_functions.get( attr, lambda value: value) value = transform_function(value=value) output += ('\n' if output else '') + '%s: %s' % \ (DisplayColors.colorize(attr, DisplayColors.BLUE), value) output_schema = entry.get('action', {}).get('output_schema') schema_check = get_config()['general']['silence_schema_output'] if not output_schema and kwargs.get('with_schema'): rendered_schema = { 'output_schema': schema.render_output_schema_from_output(entry['result']) } rendered_schema = yaml.safe_dump(rendered_schema, default_flow_style=False) output += '\n' output += _print_bordered( "Based on the action output the following inferred schema was built:" "\n\n" "%s" % rendered_schema) elif not output_schema and not schema_check: output += ( "\n\n** This action does not have an output_schema. " "Run again with --with-schema to see a suggested schema.") if six.PY3: return strutil.unescape(str(output)) else: # Assume Python 2 try: result = strutil.unescape( str(output)).decode('unicode_escape').encode('utf-8') except UnicodeDecodeError: # String contains a value which is not an unicode escape sequence, ignore the error result = strutil.unescape(str(output)) return result
def get_client(self, args, debug=False): ST2_CLI_SKIP_CONFIG = os.environ.get('ST2_CLI_SKIP_CONFIG', 0) ST2_CLI_SKIP_CONFIG = int(ST2_CLI_SKIP_CONFIG) skip_config = args.skip_config skip_config = skip_config or ST2_CLI_SKIP_CONFIG # Note: Options provided as the CLI argument have the highest precedence # Precedence order: cli arguments > environment variables > rc file variables cli_options = ['base_url', 'auth_url', 'api_url', 'api_version', 'cacert'] cli_options = {opt: getattr(args, opt) for opt in cli_options} config_file_options = self._get_config_file_options(args=args) kwargs = {} if not skip_config: # Config parsing is not skipped kwargs = merge_dicts(kwargs, config_file_options) kwargs = merge_dicts(kwargs, cli_options) kwargs['debug'] = debug client = Client(**kwargs) if skip_config: # Config parsing is skipped LOG.info('Skipping parsing CLI config') return client # Ok to use config at this point rc_config = get_config() # Silence SSL warnings silence_ssl_warnings = rc_config.get('general', {}).get('silence_ssl_warnings', False) if silence_ssl_warnings: requests.packages.urllib3.disable_warnings() # We skip automatic authentication for some commands such as auth try: command_class_name = args.func.im_class.__name__ except Exception: command_class_name = None if command_class_name in SKIP_AUTH_CLASSES: return client # We also skip automatic authentication if token is provided via the environment variable # or as a command line argument env_var_token = os.environ.get('ST2_AUTH_TOKEN', None) cli_argument_token = getattr(args, 'token', None) env_var_api_key = os.environ.get('ST2_API_KEY', None) cli_argument_api_key = getattr(args, 'api_key', None) if env_var_token or cli_argument_token or env_var_api_key or cli_argument_api_key: return client # If credentials are provided in the CLI config use them and try to authenticate credentials = rc_config.get('credentials', {}) username = credentials.get('username', None) password = credentials.get('password', None) cache_token = rc_config.get('cli', {}).get('cache_token', False) if username and password: # Credentials are provided, try to authenticate agaist the API try: token = self._get_auth_token(client=client, username=username, password=password, cache_token=cache_token) except requests.exceptions.ConnectionError as e: LOG.warn('Auth API server is not available, skipping authentication.') LOG.exception(e) return client except Exception as e: print('Failed to authenticate with credentials provided in the config.') raise e client.token = token # TODO: Hack, refactor when splitting out the client os.environ['ST2_AUTH_TOKEN'] = token return client
def get_client(self, args, debug=False): ST2_CLI_SKIP_CONFIG = os.environ.get("ST2_CLI_SKIP_CONFIG", 0) ST2_CLI_SKIP_CONFIG = int(ST2_CLI_SKIP_CONFIG) skip_config = args.skip_config skip_config = skip_config or ST2_CLI_SKIP_CONFIG # Note: Options provided as the CLI argument have the highest precedence # Precedence order: cli arguments > environment variables > rc file variables cli_options = [ "base_url", "auth_url", "api_url", "stream_url", "api_version", "cacert", "basic_auth", ] cli_options = {opt: getattr(args, opt, None) for opt in cli_options} if cli_options.get("cacert", None) is not None: if cli_options["cacert"].lower() in ["true", "1", "t", "y", "yes"]: cli_options["cacert"] = True elif cli_options["cacert"].lower() in ["false", "0", "f", "no"]: cli_options["cacert"] = False config_file_options = self._get_config_file_options(args=args) kwargs = {} if not skip_config: # Config parsing is not skipped kwargs = merge_dicts(kwargs, config_file_options) kwargs = merge_dicts(kwargs, cli_options) kwargs["debug"] = debug client = Client(**kwargs) if skip_config: # Config parsing is skipped self.LOG.info("Skipping parsing CLI config") return client # Ok to use config at this point rc_config = get_config() # Silence SSL warnings silence_ssl_warnings = rc_config.get("general", {}).get("silence_ssl_warnings", False) if silence_ssl_warnings: # pylint: disable=no-member requests.packages.urllib3.disable_warnings(InsecureRequestWarning) # We skip automatic authentication for some commands such as auth try: command_class_name = args.func.__self__.__class__.__name__ except Exception: command_class_name = None if command_class_name in self.SKIP_AUTH_CLASSES: return client # We also skip automatic authentication if token is provided via the environment variable # or as a command line argument env_var_token = os.environ.get("ST2_AUTH_TOKEN", None) cli_argument_token = getattr(args, "token", None) env_var_api_key = os.environ.get("ST2_API_KEY", None) cli_argument_api_key = getattr(args, "api_key", None) if (env_var_token or cli_argument_token or env_var_api_key or cli_argument_api_key): return client # If credentials are provided in the CLI config use them and try to authenticate credentials = rc_config.get("credentials", {}) username = credentials.get("username", None) password = credentials.get("password", None) cache_token = rc_config.get("cli", {}).get("cache_token", False) if username: # Credentials are provided, try to authenticate agaist the API try: token = self._get_auth_token( client=client, username=username, password=password, cache_token=cache_token, ) except requests.exceptions.ConnectionError as e: self.LOG.warn( "Auth API server is not available, skipping authentication." ) self.LOG.exception(e) return client except Exception as e: print( "Failed to authenticate with credentials provided in the config." ) raise e client.token = token # TODO: Hack, refactor when splitting out the client os.environ["ST2_AUTH_TOKEN"] = token return client
def format(cls, entry, *args, **kwargs): attrs = kwargs.get("attributes", []) attribute_transform_functions = kwargs.get( "attribute_transform_functions", {}) key = kwargs.get("key", None) if key: output = jsutil.get_value(entry.result, key) else: # drop entry to the dict so that jsutil can operate entry = vars(entry) output = "" for attr in attrs: value = jsutil.get_value(entry, attr) value = strutil.strip_carriage_returns(strutil.unescape(value)) # transform the value of our attribute so things like 'status' # and 'timestamp' are formatted nicely transform_function = attribute_transform_functions.get( attr, lambda value: value) value = transform_function(value=value) # TODO: This check is inherently flawed since it will crash st2client # if the leading character is objectish start and last character is objectish # end but the string isn't supposed to be a object. Try/Except will catch # this for now, but this should be improved. if (isinstance(value, six.string_types) and len(value) > 0 and value[0] in ["{", "["] and value[len(value) - 1] in ["}", "]"]): try: new_value = ast.literal_eval(value) except: new_value = value if type(new_value) in [dict, list]: value = new_value if isinstance(value, (dict, list)): # 1. To get a nice overhang indent get safe_dump to generate output with # the attribute key and then remove the attribute key from the string. # 2. Drop the trailing newline # 3. Set width to maxint so pyyaml does not split text. Anything longer # and likely we will see other issues like storage :P. # NOTE: We use C version of the safe dumper which is faster. # Keep in mind that using YamlSafeDumper is the same as using yaml.safe_dumps # (same class is used underneath when using yaml.safe_dump) so the code is safe. formatted_value = yaml.dump( {attr: value}, default_flow_style=False, width=PLATFORM_MAXINT, indent=2, Dumper=YamlSafeDumper, )[len(attr) + 2:-1] if isinstance(value, list): # Indent list values with 2 spaces for a nicer display. lines = formatted_value.split("\n") formatted_value = [] for line in lines: formatted_value.append(" %s" % (line)) formatted_value = "\n".join(formatted_value) value = ("\n" if isinstance(value, (dict, list)) else "") + formatted_value value = strutil.dedupe_newlines(value) # transform the value of our attribute so things like 'status' # and 'timestamp' are formatted nicely transform_function = attribute_transform_functions.get( attr, lambda value: value) value = transform_function(value=value) output += ("\n" if output else "") + "%s: %s" % ( DisplayColors.colorize(attr, DisplayColors.BLUE), value, ) output_schema = entry.get("action", {}).get("output_schema") schema_check = get_config()["general"]["silence_schema_output"] if not output_schema and kwargs.get("with_schema"): rendered_schema = { "output_schema": schema.render_output_schema_from_output(entry["result"]) } rendered_schema = yaml.safe_dump(rendered_schema, default_flow_style=False) output += "\n" output += _print_bordered( "Based on the action output the following inferred schema was built:" "\n\n" "%s" % rendered_schema) elif not output_schema and not schema_check: output += ( "\n\n** This action does not have an output_schema. " "Run again with --with-schema to see a suggested schema.") if six.PY3: return strutil.unescape(str(output)) else: # Assume Python 2 try: result = (strutil.unescape( str(output)).decode("unicode_escape").encode("utf-8")) except UnicodeDecodeError: # String contains a value which is not an unicode escape sequence, ignore the error result = strutil.unescape(str(output)) return result