Example #1
0
def st2kv_(context, key):

    # Get StackStorm auth token from the action context.
    token = None
    env = context['__env']
    actions_env = env.get('__actions', {})
    st2_ctx = actions_env.get('st2.action', {}).get('st2_context', {})
    st2_ctx_log_safe = copy.deepcopy(st2_ctx)
    st2_ctx_log_safe.pop('auth_token', None)

    if 'auth_token' in st2_ctx:
        token = st2_ctx.get('auth_token')
    elif 'st2' in cfg.CONF and 'auth_token' in cfg.CONF.st2:
        token = cfg.CONF.st2.auth_token

    if key.startswith('system.'):
        scope = 'system'
        key_id = key[key.index('.') + 1:]
    else:
        scope = 'user'
        key_id = key

    endpoint = st2_ctx['api_url'] + '/keys/' + key_id
    params = {'decrypt': True, 'scope': scope}

    LOG.info(
        'Sending HTTP request for custom YAQL function st2kv '
        '[url=%s, st2_context=%s]' % (
            endpoint, st2_ctx_log_safe
        )
    )

    try:
        resp = http.get(endpoint, params=params, token=token)
    except Exception as e:
        raise exc.CustomYaqlException(
            'Failed to send HTTP request for custom YAQL function st2kv '
            '[url=%s, st2_context=%s]: %s' % (
                endpoint, st2_ctx_log_safe, e
            )
        )

    if resp.status_code == http_client.NOT_FOUND:
        raise exc.YaqlEvaluationException(
            'Key %s does not exist in StackStorm datastore.' % key
        )
    elif resp.status_code != http_client.OK:
        raise exc.YaqlEvaluationException(
            'Failed to send HTTP request for custom YAQL function st2kv '
            '[url=%s, st2_context=%s]: %s' % (
                endpoint, st2_ctx_log_safe, resp.text
            )
        )

    return resp.json().get('value', None)
Example #2
0
def st2kv_(context, key, decrypt=False):
    """Retrieve value for provided key in StackStorm datastore

    :param key: User to whom key belongs.
    :type key: ``str``
    :param decrypt: Request decrypted version of the value (defaults to False)
    :type decrypt: ``bool``

    :rtype: ``dict``
    """

    # Get StackStorm auth token from the action context.
    token = None
    env = context['__env']
    actions_env = env.get('__actions', {})
    st2_ctx = actions_env.get('st2.action', {}).get('st2_context', {})
    st2_ctx_log_safe = copy.deepcopy(st2_ctx)
    st2_ctx_log_safe.pop('auth_token', None)

    if 'auth_token' in st2_ctx:
        token = st2_ctx.get('auth_token')
    elif 'st2' in cfg.CONF and 'auth_token' in cfg.CONF.st2:
        token = cfg.CONF.st2.auth_token

    if key.startswith('system.'):
        scope = 'system'
        key_id = key[key.index('.') + 1:]
    else:
        scope = 'user'
        key_id = key

    endpoint = st2_ctx['api_url'] + '/keys/' + key_id
    params = {'decrypt': decrypt, 'scope': scope}

    LOG.info('Sending HTTP request for custom YAQL function st2kv '
             '[url=%s, st2_context=%s]' % (endpoint, st2_ctx_log_safe))

    try:
        resp = http.get(endpoint, params=params, token=token)
    except Exception as e:
        raise exc.CustomYaqlException(
            'Failed to send HTTP request for custom YAQL function st2kv '
            '[url=%s, st2_context=%s]: %s' % (endpoint, st2_ctx_log_safe, e))

    if resp.status_code == http_client.NOT_FOUND:
        raise exc.YaqlEvaluationException(
            'Key %s does not exist in StackStorm datastore.' % key)
    elif resp.status_code != http_client.OK:
        raise exc.YaqlEvaluationException(
            'Failed to send HTTP request for custom YAQL function st2kv '
            '[url=%s, st2_context=%s]: %s' %
            (endpoint, st2_ctx_log_safe, resp.text))

    return resp.json().get('value', None)
    def evaluate(cls, expression, data_context):
        expression = expression.strip() if expression else expression

        try:
            result = YAQL_ENGINE(expression).evaluate(
                context=expression_utils.get_yaql_context(data_context))
        except Exception as e:
            # NOTE(rakhmerov): if we hit a database error then we need to
            # re-raise the initial exception so that upper layers had a
            # chance to handle it properly (e.g. in case of DB deadlock
            # the operations needs to retry. Essentially, such situation
            # indicates a problem with DB rather than with the expression
            # syntax or values.
            if isinstance(e, db_exc.DBError):
                LOG.error(
                    "Failed to evaluate YAQL expression due to a database"
                    " error, re-raising initial exception [expression=%s,"
                    " error=%s, data=%s]", expression, str(e), data_context)

                raise e

            raise exc.YaqlEvaluationException(
                "Can not evaluate YAQL expression [expression=%s, error=%s"
                ", data=%s]" % (expression, str(e), data_context))

        return result if not inspect.isgenerator(result) else list(result)
Example #4
0
    def validate(cls, expression):
        LOG.debug("Validating YAQL expression [expression='%s']", expression)

        try:
            YAQL_ENGINE(expression)
        except (yaql_exc.YaqlException, KeyError, ValueError, TypeError) as e:
            raise exc.YaqlEvaluationException(getattr(e, 'message', e))
Example #5
0
    def validate(cls, expression):
        LOG.debug("Validating YAQL expression [expression='%s']", expression)

        try:
            yaql.parse(expression)
        except (yaql_exc.YaqlException, KeyError, ValueError, TypeError) as e:
            raise exc.YaqlEvaluationException(e.message)
Example #6
0
    def validate(cls, expression):
        if not isinstance(expression, six.string_types):
            raise exc.YaqlEvaluationException(
                "Unsupported type '%s'." % type(expression)
            )

        found_expressions = cls.find_inline_expressions(expression)

        if found_expressions:
            [super(InlineYAQLEvaluator, cls).validate(expr.strip("<%>"))
             for expr in found_expressions]
Example #7
0
    def evaluate(cls, expression, data_context):
        expression = expression.strip() if expression else expression

        try:
            result = YAQL_ENGINE(expression).evaluate(
                context=expression_utils.get_yaql_context(data_context))
        except Exception as e:
            raise exc.YaqlEvaluationException(
                "Can not evaluate YAQL expression [expression=%s, error=%s"
                ", data=%s]" % (expression, str(e), data_context))

        return result if not inspect.isgenerator(result) else list(result)
Example #8
0
def to_json(context, obj=None):
    tmp = None
    try:
        tmp = json.dumps(obj)
        LOG.info("JSON to string produced : {} {}.".format(tmp, type(tmp)))
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        LOG.error("{}\n{}\n{}\n".format(exc_type, exc_value, exc_traceback))
        raise mistral_exceptions.YaqlEvaluationException(
            'Error converting object to JSON: {} {} {}'.format(
                exc_type, exc_value, exc_traceback))
    return tmp
Example #9
0
    def evaluate(cls, expression, data_context):
        LOG.debug("Evaluating YAQL expression [expression='%s', context=%s]" %
                  (expression, data_context))

        try:
            result = YAQL_ENGINE(expression).evaluate(
                context=expression_utils.get_yaql_context(data_context))
        except (yaql_exc.YaqlException, KeyError, ValueError, TypeError) as e:
            raise exc.YaqlEvaluationException(
                "Can not evaluate YAQL expression: %s, error=%s, data = %s" %
                (expression, str(e), data_context))

        LOG.debug("YAQL expression result: %s" % result)

        return result if not inspect.isgenerator(result) else list(result)
Example #10
0
    def evaluate(cls, expression, data_context):
        LOG.debug("Evaluating YAQL expression [expression='%s', context=%s]" %
                  (expression, data_context))

        try:
            result = yaql.parse(expression).evaluate(
                data=data_context, context=yaql_utils.create_yaql_context())
        except (yaql_exc.YaqlException, KeyError, ValueError, TypeError) as e:
            raise exc.YaqlEvaluationException(
                "Can not evaluate YAQL expression: %s, data = %s; error:"
                " %s" % (expression, data_context, str(e)))

        LOG.debug("YAQL expression result: %s" % result)

        return result if not inspect.isgenerator(result) else list(result)