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)
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)
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)
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)
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()
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()
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)
class InvalidDiscoveryURL(Invalid): message = _("Received invalid discovery URL '%(discovery_url)s' for " "discovery endpoint '%(discovery_endpoint)s'.")
class PatchError(Invalid): message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")
class ConfigInvalid(HigginsException): message = _("Invalid configuration file. %(error_msg)s")
class Conflict(HigginsException): message = _('Conflict.') code = 409
class InvalidParameterValue(Invalid): message = _("%(err)s")
class AuthorizationFailure(HigginsException): message = _("%(client)s connection failed. %(message)s")
class InvalidIdentity(Invalid): message = _("Expected an uuid or int but received %(identity)s.")
class ResourceNotFound(ObjectNotFound): message = _("The %(name)s resource %(id)s could not be found.") code = 404
class ResourceExists(ObjectNotUnique): message = _("The %(name)s resource already exists.") code = 409
class ObjectNotUnique(HigginsException): message = _("The %(name)s already exists.")
class ObjectNotFound(HigginsException): message = _("The %(name)s %(id)s could not be found.")
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
class GetDiscoveryUrlFailed(HigginsException): message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")
class UnsupportedObjectError(HigginsException): message = _('Unsupported object type %(objtype)s')
class InvalidUuidOrName(Invalid): message = _("Expected a name or uuid but received %(uuid)s.")
class IncompatibleObjectVersion(HigginsException): message = _('Version %(objver)s of %(objname)s is not supported')
class InvalidCsr(Invalid): message = _("Received invalid csr %(csr)s.")
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)
class InvalidState(Conflict): message = _("Invalid resource state.")
class Invalid(HigginsException): message = _("Unacceptable parameters.") code = 400
class InstanceNotFound(ResourceNotFound): message = _("Instance %(instance)s could not be found.")
class InvalidUUID(Invalid): message = _("Expected a uuid but received %(uuid)s.")
class NotAuthorized(HigginsException): message = _("Not authorized.") code = 403
class InvalidName(Invalid): message = _("Expected a name but received %(uuid)s.")
class OrphanedObjectError(HigginsException): message = _('Cannot call %(method)s on orphaned %(objtype)s object')