Beispiel #1
0
class HigginsException(Exception):
    """Base Higgins Exception

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.

    """
    message = _("An unknown exception occurred.")
    code = 500

    def __init__(self, message=None, **kwargs):
        self.kwargs = kwargs

        if 'code' not in self.kwargs and hasattr(self, 'code'):
            self.kwargs['code'] = self.code

        if message:
            self.message = message

        try:
            self.message = self.message % kwargs
        except Exception as e:
            # kwargs doesn't match a variable in the message
            # log the issue and the kwargs
            LOG.exception(
                _LE('Exception in string format operation, '
                    'kwargs: %s') % kwargs)
            try:
                if CONF.fatal_exception_format_errors:
                    raise e
            except cfg.NoSuchOptError:
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise e

        super(HigginsException, self).__init__(self.message)

    def __str__(self):
        if six.PY3:
            return self.message
        return self.message.encode('utf-8')

    def __unicode__(self):
        return self.message

    def format_message(self):
        if self.__class__.__name__.endswith('_Remote'):
            return self.args[0]
        else:
            return six.text_type(self)
Beispiel #2
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 exception.ConfigInvalid(error_msg=msg)

        super(AuthTokenMiddleware, self).__init__(app, conf)
Beispiel #3
0
    def __init__(self, name, use_ssl=False):
        """Initialize, but do not start the WSGI server.

        :param name: The name of the WSGI server given to the loader.
        :param use_ssl: Wraps the socket in an SSL context if True.
        :returns: None
        """
        self.name = name
        self.app = app.setup_app()
        self.workers = (processutils.get_worker_count())
        if self.workers and self.workers < 1:
            raise exception.ConfigInvalid(
                _("api_workers value of %d is invalid, "
                  "must be greater than 0.") % self.workers)

        self.server = wsgi.Server(CONF, name, self.app,
                                  host=CONF.api.host,
                                  port=CONF.api.port,
                                  use_ssl=use_ssl)
Beispiel #4
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)
Beispiel #5
0
def get_id(source_uuid):
    """Derive a short (12 character) id from a random UUID.

    The supplied UUID must be a version 4 UUID object.
    """

    if isinstance(source_uuid, six.string_types):
        source_uuid = uuid.UUID(source_uuid)
    if source_uuid.version != 4:
        raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)

    # The "time" field of a v4 UUID contains 60 random bits
    # (see RFC4122, Section 4.4)
    random_bytes = _to_byte_string(source_uuid.time, 60)
    # The first 12 bytes (= 60 bits) of base32-encoded output is our data
    encoded = base64.b32encode(six.b(random_bytes))[:12]

    if six.PY3:
        return encoded.lower().decode('utf-8')
    else:
        return encoded.lower()
Beispiel #6
0
def _paginate_query(model,
                    limit=None,
                    marker=None,
                    sort_key=None,
                    sort_dir=None,
                    query=None):
    if not query:
        query = model_query(model)
    sort_keys = ['id']
    if sort_key and sort_key not in sort_keys:
        sort_keys.insert(0, sort_key)
    try:
        query = db_utils.paginate_query(query,
                                        model,
                                        limit,
                                        sort_keys,
                                        marker=marker,
                                        sort_dir=sort_dir)
    except db_exc.InvalidSortKey:
        raise exception.InvalidParameterValue(
            _('The sort_key value "%(key)s" is an invalid field for sorting') %
            {'key': sort_key})
    return query.all()
Beispiel #7
0
                        temp_type = event_type
                        if not temp_type:
                            # If f has multiple decorators, they must use
                            # functools.wraps to ensure the name is
                            # propagated.
                            temp_type = f.__name__

                        notifier.error(context, temp_type, payload)

        return functools.wraps(f)(wrapped)

    return inner


OBFUSCATED_MSG = _('Your request could not be handled '
                   'because of a problem in the server. '
                   'Error Correlation id is: %s')


def wrap_controller_exception(func, func_server_error, func_client_error):
    """This decorator wraps controllers methods to handle exceptions:

    - if an unhandled Exception or a HigginsException with an error code >=500
    is catched, raise a http 5xx ClientSideError and correlates it with a log
    message

    - if a HigginsException is catched and its error code is <500, raise a http
    4xx and logs the excp in debug mode

    """
    @functools.wraps(func)
Beispiel #8
0
class InvalidDiscoveryURL(Invalid):
    message = _("Received invalid discovery URL '%(discovery_url)s' for "
                "discovery endpoint '%(discovery_endpoint)s'.")
Beispiel #9
0
class PatchError(Invalid):
    message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")
Beispiel #10
0
class ConfigInvalid(HigginsException):
    message = _("Invalid configuration file. %(error_msg)s")
Beispiel #11
0
class Conflict(HigginsException):
    message = _('Conflict.')
    code = 409
Beispiel #12
0
class InvalidParameterValue(Invalid):
    message = _("%(err)s")
Beispiel #13
0
class AuthorizationFailure(HigginsException):
    message = _("%(client)s connection failed. %(message)s")
Beispiel #14
0
class InvalidIdentity(Invalid):
    message = _("Expected an uuid or int but received %(identity)s.")
Beispiel #15
0
class ResourceNotFound(ObjectNotFound):
    message = _("The %(name)s resource %(id)s could not be found.")
    code = 404
Beispiel #16
0
class ResourceExists(ObjectNotUnique):
    message = _("The %(name)s resource already exists.")
    code = 409
Beispiel #17
0
class ObjectNotUnique(HigginsException):
    message = _("The %(name)s already exists.")
Beispiel #18
0
class ObjectNotFound(HigginsException):
    message = _("The %(name)s %(id)s could not be found.")
Beispiel #19
0
from higgins.common.i18n import _


# Register options for the service
API_SERVICE_OPTS = [
    cfg.PortOpt('port',
                default=9512,
                help='The port for the higgins API server.'),
    cfg.IPOpt('host',
              default='127.0.0.1',
              help='The listen IP for the higgins API server.'),
    cfg.BoolOpt('enable_ssl_api',
                default=False,
                help=_("Enable the integrated stand-alone API to service "
                       "requests via HTTPS instead of HTTP. If there is a "
                       "front-end service performing HTTPS offloading from "
                       "the service, this option should be False; note, you "
                       "will want to change public API endpoint to represent "
                       "SSL termination URL with 'public_endpoint' option.")),
]

CONF = cfg.CONF
opt_group = cfg.OptGroup(name='api',
                         title='Options for the higgins-api service')
CONF.register_group(opt_group)
CONF.register_opts(API_SERVICE_OPTS, opt_group)

LOG = log.getLogger(__name__)


def get_pecan_config():
    # Set up the pecan configuration
Beispiel #20
0
class GetDiscoveryUrlFailed(HigginsException):
    message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")
Beispiel #21
0
class UnsupportedObjectError(HigginsException):
    message = _('Unsupported object type %(objtype)s')
Beispiel #22
0
class InvalidUuidOrName(Invalid):
    message = _("Expected a name or uuid but received %(uuid)s.")
Beispiel #23
0
class IncompatibleObjectVersion(HigginsException):
    message = _('Version %(objver)s of %(objname)s is not supported')
Beispiel #24
0
class InvalidCsr(Invalid):
    message = _("Received invalid csr %(csr)s.")
Beispiel #25
0
from oslo_log import log
from oslo_service import service
from oslo_service import wsgi

from higgins.api import app
from higgins.common import config
from higgins.common import exception
from higgins.common.i18n import _


service_opts = [
    cfg.StrOpt('host',
               default=socket.getfqdn(),
               help=_('Name of this node. This can be an opaque identifier. '
                      'It is not necessarily a hostname, FQDN, or IP address. '
                      'However, the node name must be valid within '
                      'an AMQP key, and if using ZeroMQ, a valid '
                      'hostname, FQDN, or IP address.')),
]

CONF = cfg.CONF
LOG = log.getLogger(__name__)

CONF.register_opts(service_opts)


def prepare_service(argv=None):
    if argv is None:
        argv = []
    log.register_options(CONF)
    config.parse_args(argv)
Beispiel #26
0
class InvalidState(Conflict):
    message = _("Invalid resource state.")
Beispiel #27
0
class Invalid(HigginsException):
    message = _("Unacceptable parameters.")
    code = 400
Beispiel #28
0
class InstanceNotFound(ResourceNotFound):
    message = _("Instance %(instance)s could not be found.")
Beispiel #29
0
class InvalidUUID(Invalid):
    message = _("Expected a uuid but received %(uuid)s.")
Beispiel #30
0
class NotAuthorized(HigginsException):
    message = _("Not authorized.")
    code = 403
Beispiel #31
0
class InvalidName(Invalid):
    message = _("Expected a name but received %(uuid)s.")
Beispiel #32
0
class OrphanedObjectError(HigginsException):
    message = _('Cannot call %(method)s on orphaned %(objtype)s object')
Beispiel #33
0
                        temp_type = event_type
                        if not temp_type:
                            # If f has multiple decorators, they must use
                            # functools.wraps to ensure the name is
                            # propagated.
                            temp_type = f.__name__

                        notifier.error(context, temp_type, payload)

        return functools.wraps(f)(wrapped)
    return inner


OBFUSCATED_MSG = _('Your request could not be handled '
                   'because of a problem in the server. '
                   'Error Correlation id is: %s')


def wrap_controller_exception(func, func_server_error, func_client_error):
    """This decorator wraps controllers methods to handle exceptions:

    - if an unhandled Exception or a HigginsException with an error code >=500
    is catched, raise a http 5xx ClientSideError and correlates it with a log
    message

    - if a HigginsException is catched and its error code is <500, raise a http
    4xx and logs the excp in debug mode

    """
    @functools.wraps(func)