Exemple #1
0
    def post(self):
        """
        ceilometer don't send content-type, so need to parse it manually
        just in case.
        There should be a way for this, but it can be dynamic based
        on source. Still need to look for, since we miss the mime type
        handled by wsme
        """
        source = pecan.request.GET.get('source')
        status = pecan.request.GET.get('status')
        contract_id = pecan.request.GET.get('contract_id')
        resource_id = pecan.request.GET.get('resource_id')
        body = six.moves.urllib_parse.unquote_plus(pecan.request.body)
        if body and body[-1] == '=':
            body = body[:-1]

        #validate body
        ctx = utils.get_context_req(pecan.request)
        if not status or not source:
            abort(400, 'Status and Source are required')
        alarm = jsonutils.loads(body)
        if status == 'alarm':
            self.action_api.alarm(ctx,
                                  alarm.get('alarm_id'),
                                  source=source,
                                  contract_id=contract_id,
                                  resource_id=resource_id)
        return ""
Exemple #2
0
    def post(self):
        """
        ceilometer don't send content-type, so need to parse it manually
        just in case.
        There should be a way for this, but it can be dynamic based
        on source. Still need to look for, since we miss the mime type
        handled by wsme
        """
        source = pecan.request.GET.get('source')
        status = pecan.request.GET.get('status')
        contract_id = pecan.request.GET.get('contract_id')
        resource_id = pecan.request.GET.get('resource_id')
        body = six.moves.urllib_parse.unquote_plus(pecan.request.body)
        if body and body[-1] == '=':
            body = body[:-1]

        #validate body
        ctx = utils.get_context_req(pecan.request)
        if not status or not source:
            abort(400, 'Status and Source are required')
        alarm = jsonutils.loads(body)
        if status == 'alarm':
            self.action_api.alarm(ctx, alarm.get('alarm_id'), source=source,
                              contract_id=contract_id,
                              resource_id=resource_id)
        return ""
Exemple #3
0
    def load_json(cls, data, default_rule=None):
        """Allow loading of JSON rule data."""

        # Suck in the JSON data and parse the rules
        rules = dict(
            (k, parse_rule(v)) for k, v in jsonutils.loads(data).items())

        return cls(rules, default_rule)
Exemple #4
0
    def load_json(cls, data, default_rule=None):
        """Allow loading of JSON rule data."""

        # Suck in the JSON data and parse the rules
        rules = dict((k, parse_rule(v)) for k, v in
                     jsonutils.loads(data).items())

        return cls(rules, default_rule)
Exemple #5
0
def context_from_headers(headers):
    token = headers.get('X-Auth-Token')
    catalog = jsonutils.loads(headers.get('X-Service-Catalog', {}))
    ctx = context.Context(user_id=headers.get('X-User-Id'),
                          project=headers.get('X-Project-Name'),
                          token=token,
                          service_catalog=catalog,
                          user=headers.get('X-User-Name'),
                          roles=headers.get('X-Roles', "").split(","))
    return ctx
Exemple #6
0
def context_from_headers(headers):
    token = headers.get('X-Auth-Token')
    catalog = jsonutils.loads(headers.get('X-Service-Catalog', {}))
    ctx = context.Context(user_id=headers.get('X-User-Id'),
                           project=headers.get('X-Project-Name'),
                           token=token,
                           service_catalog=catalog,
                           user=headers.get('X-User-Name'),
                           roles=headers.get('X-Roles', "").split(","))
    return ctx
Exemple #7
0
 def _convert_json(self, data, to_object=True):
     if not data:
         return None #should be '' also.. if to_object==false
     try:
         if to_object:
             return jsonutils.loads(data)
         else:
             return jsonutils.dumps(data)
     except Exception:
         return None
Exemple #8
0
 def _parse_alarm_opts(self, ctx, alarm_type, alarm_data, update=False):
     al_type = SLA_TYPES.get(alarm_type)
     additional_info = {}
     if alarm_data:
         try:
             additional_info = jsonutils.loads(alarm_data)
         except Exception as e:
             LOG.error(e)
             pass
     if not update:
         # to avoid writing the same values
         if not al_type.get('override', False):
             additional_info.update(al_type.get('options'))
     additional_info.pop('id', None)
     return (al_type.get('alarm'), additional_info)
Exemple #9
0
    def _unpack_json_msg(self, msg):
        """Load the JSON data in msg if msg.content_type indicates that it
           is necessary.  Put the loaded data back into msg.content and
           update msg.content_type appropriately.

        A Qpid Message containing a dict will have a content_type of
        'amqp/map', whereas one containing a string that needs to be converted
        back from JSON will have a content_type of JSON_CONTENT_TYPE.

        :param msg: a Qpid Message object
        :returns: None
        """
        if msg.content_type == JSON_CONTENT_TYPE:
            msg.content = jsonutils.loads(msg.content)
            msg.content_type = 'amqp/map'
Exemple #10
0
    def _unpack_json_msg(self, msg):
        """Load the JSON data in msg if msg.content_type indicates that it
           is necessary.  Put the loaded data back into msg.content and
           update msg.content_type appropriately.

        A Qpid Message containing a dict will have a content_type of
        'amqp/map', whereas one containing a string that needs to be converted
        back from JSON will have a content_type of JSON_CONTENT_TYPE.

        :param msg: a Qpid Message object
        :returns: None
        """
        if msg.content_type == JSON_CONTENT_TYPE:
            msg.content = jsonutils.loads(msg.content)
            msg.content_type = 'amqp/map'
Exemple #11
0
 def _parse_alarm_opts(self, ctx, alarm_type, alarm_data, update=False):
     al_type = SLA_TYPES.get(alarm_type)
     additional_info = {}
     if alarm_data:
         try:
             additional_info = jsonutils.loads(alarm_data)
         except Exception as e:
             LOG.error(e)
             pass
     if not update:
         # to avoid writing the same values
         if not al_type.get('override', False):
             additional_info.update(al_type.get('options'))
     additional_info.pop('id', None)
     return (al_type.get('alarm'), additional_info)
Exemple #12
0
def deserialize_msg(msg):
    # NOTE(russellb): Hang on to your hats, this road is about to
    # get a little bumpy.
    #
    # Robustness Principle:
    #    "Be strict in what you send, liberal in what you accept."
    #
    # At this point we have to do a bit of guessing about what it
    # is we just received.  Here is the set of possibilities:
    #
    # 1) We received a dict.  This could be 2 things:
    #
    #   a) Inspect it to see if it looks like a standard message envelope.
    #      If so, great!
    #
    #   b) If it doesn't look like a standard message envelope, it could either
    #      be a notification, or a message from before we added a message
    #      envelope (referred to as version 1.0).
    #      Just return the message as-is.
    #
    # 2) It's any other non-dict type.  Just return it and hope for the best.
    #    This case covers return values from rpc.call() from before message
    #    envelopes were used.  (messages to call a method were always a dict)

    if not isinstance(msg, dict):
        # See #2 above.
        return msg

    base_envelope_keys = (_VERSION_KEY, _MESSAGE_KEY)
    if not all(map(lambda key: key in msg, base_envelope_keys)):
        #  See #1.b above.
        return msg

    # At this point we think we have the message envelope
    # format we were expecting. (#1.a above)

    if not version_is_compatible(_RPC_ENVELOPE_VERSION, msg[_VERSION_KEY]):
        raise UnsupportedRpcEnvelopeVersion(version=msg[_VERSION_KEY])

    raw_msg = jsonutils.loads(msg[_MESSAGE_KEY])

    return raw_msg
Exemple #13
0
def deserialize_remote_exception(conf, data):
    failure = jsonutils.loads(str(data))

    trace = failure.get('tb', [])
    message = failure.get('message', "") + "\n" + "\n".join(trace)
    name = failure.get('class')
    module = failure.get('module')

    # NOTE(ameade): We DO NOT want to allow just any module to be imported, in
    # order to prevent arbitrary code execution.
    if module not in conf.allowed_rpc_exception_modules:
        return RemoteError(name, failure.get('message'), trace)

    try:
        mod = importutils.import_module(module)
        klass = getattr(mod, name)
        if not issubclass(klass, Exception):
            raise TypeError("Can only deserialize Exceptions")

        failure = klass(*failure.get('args', []), **failure.get('kwargs', {}))
    except (AttributeError, TypeError, ImportError):
        return RemoteError(name, failure.get('message'), trace)

    ex_type = type(failure)
    str_override = lambda self: message
    new_ex_type = type(ex_type.__name__ + _REMOTE_POSTFIX, (ex_type, ), {
        '__str__': str_override,
        '__unicode__': str_override
    })
    new_ex_type.__module__ = '%s%s' % (module, _REMOTE_POSTFIX)
    try:
        # NOTE(ameade): Dynamically create a new exception type and swap it in
        # as the new type for the exception. This only works on user defined
        # Exceptions and not core python exceptions. This is important because
        # we cannot necessarily change an exception message so we must override
        # the __str__ method.
        failure.__class__ = new_ex_type
    except TypeError:
        # NOTE(ameade): If a core exception then just add the traceback to the
        # first exception argument.
        failure.args = (message, ) + failure.args[1:]
    return failure
Exemple #14
0
 def from_data(name=None, target_resource=None,
              data=None, headers=None, internal_data=None,
              request_id=None, project_id=None,
              status=ACTION_PENDING):
     action = Action()
     action.name = name
     action.target_id = target_resource
     
     if data and isinstance(data, six.string_types):
         try:
             data = jsonutils.loads(data)
         except:
             raise
             LOG.error("Invalid data for action. must be dict"
                       "for json string")
             data = None
     action.action_meta_obj = {'headers': headers, 'data': data}
     action.internal_data_obj = internal_data
     action.request_id = request_id
     action.output = None
     action.project_id = project_id
     action.status = status
     return action
Exemple #15
0
 def query(self):
     # TODO MUST: Add a json field that do this into fields.py
     try:
         return jsonutils.loads(self.alarm_track.query)
     except:
         return []
Exemple #16
0
def _deserialize(data):
    """Deserialization wrapper."""
    LOG.debug("Deserializing: %s", data)
    return jsonutils.loads(data)