Example #1
0
    def _get_value_as_type(self, forced_type=None):
        """Convert metadata value to the specified data type.

        This method is called during metadata query to help convert the
        querying metadata to the data type specified by user. If there is no
        data type given, the metadata will be parsed by ast.literal_eval to
        try to do a smart converting.

        NOTE (flwang) Using "_" as prefix to avoid an InvocationError raised
        from wsmeext/sphinxext.py. It's OK to call it outside the Query class.
        Because the "public" side of that class is actually the outside of the
        API, and the "private" side is the API implementation. The method is
        only used in the API implementation, so it's OK.

        :returns: metadata value converted with the specified data type.
        """
        type = forced_type or self.type
        try:
            converted_value = self.value
            if not type:
                try:
                    converted_value = ast.literal_eval(self.value)
                except (ValueError, SyntaxError):
                    msg = _('Failed to convert the metadata value %s'
                            ' automatically') % (self.value)
                    LOG.debug(msg)
            else:
                if type not in self._supported_types:
                    # Types must be explicitly declared so the
                    # correct type converter may be used. Subclasses
                    # of Query may define _supported_types and
                    # _type_converters to define their own types.
                    raise TypeError()
                converted_value = self._type_converters[type](self.value)
        except ValueError:
            msg = _('Failed to convert the value %(value)s'
                    ' to the expected data type %(type)s.') % \
                {'value': self.value, 'type': type}
            raise wsme.exc.ClientSideError(msg)
        except TypeError:
            msg = _('The data type %(type)s is not supported. The supported'
                    ' data type list is: %(supported)s') % \
                {'type': type, 'supported': self._supported_types}
            raise wsme.exc.ClientSideError(msg)
        except Exception:
            msg = _('Unexpected exception converting %(value)s to'
                    ' the expected data type %(type)s.') % \
                {'value': self.value, 'type': type}
            raise wsme.exc.ClientSideError(msg)
        return converted_value
Example #2
0
    def before(self, state):
        headers = state.request.headers
        environ = state.request.environ
        user_name = headers.get('X-User-Name')
        user_id = headers.get('X-User-Id')
        project = headers.get('X-Project-Name')
        project_id = headers.get('X-Project-Id')
        domain_id = headers.get('X-User-Domain-Id')
        domain_name = headers.get('X-User-Domain-Name')
        auth_token = headers.get('X-Auth-Token')
        roles = headers.get('X-Roles', '').split(',')
        catalog_header = headers.get('X-Service-Catalog')
        service_catalog = None
        if catalog_header:
            try:
                service_catalog = jsonutils.loads(catalog_header)
            except ValueError:
                raise webob.exc.HTTPInternalServerError(
                    _('Invalid service catalog json.'))

        auth_token_info = environ.get('keystone.token_info')
        auth_url = CONF.keystone_authtoken.auth_uri

        state.request.context = context.make_context(
            auth_token=auth_token,
            auth_url=auth_url,
            auth_token_info=auth_token_info,
            user_name=user_name,
            user_id=user_id,
            project_name=project,
            project_id=project_id,
            domain_id=domain_id,
            domain_name=domain_name,
            roles=roles,
            service_catalog=service_catalog)
Example #3
0
def uuid_or_none(val):
    """Attempt to dictify a value, or None."""
    if val is None:
        return None
    elif isinstance(val, str):
        return str(uuid.UUID(val.strip()))
    raise ValueError(_('Invalid UUID value %s') % val)
Example #4
0
def validate_sort_dir(sort_dir):
    if sort_dir not in ['asc', 'desc']:
        raise wsme.exc.ClientSideError(
            _("Invalid sort direction: %s. "
              "Acceptable values are "
              "'asc' or 'desc'") % sort_dir)
    return sort_dir
Example #5
0
 def validate(value):
     try:
         json.dumps(value)
     except TypeError:
         raise exceptions.Invalid(_('%s is not JSON serializable') % value)
     else:
         return value
Example #6
0
    def validate(patch):
        _path = '/' + patch.path.split('/')[1]
        if _path in patch.internal_attrs():
            msg = _("'%s' is an internal attribute and can not be updated")
            raise wsme.exc.ClientSideError(msg % patch.path)

        if patch.path in patch.non_removable_attrs() and patch.op == 'remove':
            msg = _("'%s' is a mandatory attribute and can not be removed")
            raise wsme.exc.ClientSideError(msg % patch.path)

        if patch.op != 'remove':
            if patch.value is wsme.Unset:
                msg = _("'add' and 'replace' operations need a value")
                raise wsme.exc.ClientSideError(msg)

        ret = {'path': patch.path, 'op': patch.op}
        if patch.value is not wsme.Unset:
            ret['value'] = patch.value
        return ret
Example #7
0
    def _check_event_suppression_updates(updates):
        """Check attributes to be updated"""

        for parameter in updates:
            if parameter == 'suppression_status':
                if not ((updates.get(parameter) == constants.FM_SUPPRESSED) or
                        (updates.get(parameter) == constants.FM_UNSUPPRESSED)):
                    msg = _("Invalid event_suppression parameter "
                            "suppression_status values. Valid values are: "
                            "suppressed, unsuppressed")
                    raise wsme.exc.ClientSideError(msg)
            elif parameter == 'alarm_id':
                msg = _("event_suppression parameter alarm_id is not allowed "
                        "to be updated.")
                raise wsme.exc.ClientSideError(msg)
            elif parameter == 'description':
                msg = _("event_suppression parameter description is not "
                        "allowed to be updated.")
                raise wsme.exc.ClientSideError(msg)
            else:
                msg = _("event_suppression invalid parameter.")
                raise wsme.exc.ClientSideError(msg)
Example #8
0
    def _get_eventlog_collection(self,
                                 marker,
                                 limit,
                                 sort_key,
                                 sort_dir,
                                 expand=False,
                                 resource_url=None,
                                 q=None,
                                 alarms=False,
                                 logs=False,
                                 include_suppress=False):

        if limit and limit < 0:
            raise wsme.exc.ClientSideError(_("Limit must be positive"))
        sort_dir = utils.validate_sort_dir(sort_dir)
        kwargs = {}
        if q is not None:
            for i in q:
                if i.op == 'eq':
                    if i.field == 'start' or i.field == 'end':
                        val = timeutils.normalize_time(
                            timeutils.parse_isotime(
                                i.value).replace(tzinfo=None))
                        i.value = val.isoformat()
                    kwargs[i.field] = i.value

        evtType = _getEventType(alarms, logs)
        kwargs["evtType"] = evtType
        kwargs["include_suppress"] = include_suppress

        if marker:
            marker_obj = objects.event_log.get_by_uuid(pecan.request.context,
                                                       marker)

            ilog = pecan.request.dbapi.event_log_get_list(
                limit,
                marker_obj,
                sort_key=sort_key,
                sort_dir=sort_dir,
                evtType=evtType,
                include_suppress=include_suppress)
        else:
            kwargs['limit'] = limit
            ilog = pecan.request.dbapi.event_log_get_all(**kwargs)

        return EventLogCollection.convert_with_links(ilog,
                                                     limit,
                                                     url=resource_url,
                                                     expand=expand,
                                                     sort_key=sort_key,
                                                     sort_dir=sort_dir)
Example #9
0
    def __init__(self, app, conf, public_api_routes=None):
        if public_api_routes is None:
            public_api_routes = []
        route_pattern_tpl = '%s(\.json)?$'

        try:
            self.public_api_routes = [re.compile(route_pattern_tpl % route_tpl)
                                      for route_tpl in public_api_routes]
        except re.error as e:
            msg = _('Cannot compile public API routes: %s') % e

            LOG.error(msg)
            raise exceptions.ConfigInvalid(error_msg=msg)

        super(AuthTokenMiddleware, self).__init__(app, conf)
Example #10
0
 def date_handler_wrapper(*args, **kwargs):
     try:
         return f(*args, **kwargs)
     except Exception as e:
         import re
         e_str = "{}".format(e)
         for r in [".*date/time field value out of range: \"(.*)\".*LINE",
                   ".*invalid input syntax for type timestamp: \"(.*)\".*",
                   ".*timestamp out of range: \"(.*)\".*"]:
             p = re.compile(r, re.DOTALL)
             m = p.match(e_str)
             if m and len(m.groups()) > 0:
                 bad_date = m.group(1)
                 raise wsme.exc.ClientSideError(_(
                     "Invalid date '{}' specified".format(bad_date)))
         raise
Example #11
0
def save_and_reraise_exception():
    """Save current exception, run some code and then re-raise.

    In some cases the exception context can be cleared, resulting in None
    being attempted to be re-raised after an exception handler is run. This
    can happen when eventlet switches greenthreads or when running an
    exception handler, code raises and catches an exception. In both
    cases the exception context will be cleared.

    To work around this, we save the exception state, run handler code, and
    then re-raise the original exception. If another exception occurs, the
    saved exception is logged and the new exception is re-raised.
    """
    type_, value, tb = sys.exc_info()
    try:
        yield
    except Exception:
        LOG.error(_('Original exception being dropped: %s'),
                  traceback.format_exception(type_, value, tb))
        raise
    raise (type_, value, tb)
Example #12
0
 def replacement_start_response(status, headers, exc_info=None):
     """Overrides the default response to make errors parsable."""
     try:
         status_code = int(status.split(' ')[0])
         state['status_code'] = status_code
     except (ValueError, TypeError):  # pragma: nocover
         raise Exception(_(
             'ErrorDocumentMiddleware received an invalid '
             'status %s') % status)
     else:
         if (state['status_code'] // 100) not in (2, 3):
             # Remove some headers so we can replace them later
             # when we have the full error message and can
             # compute the length.
             headers = [(h, v)
                        for (h, v) in headers
                        if h not in ('Content-Length', 'Content-Type')
                        ]
         # Save the headers in case we need to modify them.
         state['headers'] = headers
         return start_response(status, headers, exc_info)
Example #13
0
def serve(api_service, conf, workers=1):
    global _launcher
    if _launcher:
        raise RuntimeError(_('serve() can only be called once'))

    _launcher = service.launch(conf, api_service, workers=workers)
Example #14
0
def validate_limit(limit):
    if limit and limit < 0:
        raise wsme.exc.ClientSideError(_("Limit must be positive"))

    return min(CONF.api.limit_max, limit) or CONF.api.limit_max
Example #15
0
import eventlet
from oslo_config import cfg
from oslo_log import log as logging
from oslo_service import systemd
from oslo_service import wsgi

import logging as std_logging

from fm.common.i18n import _
from fm.api import app
from fm.api import config

api_opts = [
    cfg.StrOpt('bind_host',
               default="0.0.0.0",
               help=_('IP address for fm api to listen')),
    cfg.IntOpt('bind_port', default=18002, help=_('listen port for fm api')),
    cfg.IntOpt('api_workers', default=2, help=_("number of api workers")),
    cfg.IntOpt('limit_max',
               default=2000,
               help='the maximum number of items returned in a single '
               'response from a collection resource')
]

CONF = cfg.CONF

LOG = logging.getLogger(__name__)
eventlet.monkey_patch(os=False)


def main():