Example #1
0
class BlazarException(Exception):
    """Base Blazar Exception.

    To correctly use this class, inherit from it and define
    a 'msg_fmt' and 'code' properties.
    """
    msg_fmt = _("An unknown exception occurred")
    code = 500

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

        if 'code' not in self.kwargs:
            self.kwargs['code'] = self.code

        if not message:
            try:
                message = self.msg_fmt % kwargs
            except KeyError:
                # kwargs doesn't match a variable in the message
                # log the issue and the kwargs
                LOG.exception('Exception in string format operation')
                for name, value in kwargs.items():
                    LOG.error("%(name)s: %(value)s", {
                        'name': name,
                        'value': value
                    })

                message = self.msg_fmt

        super(BlazarException, self).__init__(message)
Example #2
0
def request_data():
    """Method called to process POST and PUT REST methods."""
    if hasattr(flask.request, 'parsed_data'):
        return flask.request.parsed_data

    if not flask.request.content_length > 0:
        LOG.debug("Empty body provided in request")
        return dict()

    if flask.request.file_upload:
        return flask.request.data

    deserializer = None
    content_type = flask.request.mimetype
    if not content_type or content_type in RT_JSON:
        deserializer = jsonutils
    else:
        abort_and_log(400,
                      _("Content type '%s' isn't supported") % content_type)
        return

    # parsed request data to avoid unwanted re-parsings
    parsed_data = deserializer.loads(flask.request.data)
    flask.request.parsed_data = parsed_data

    return flask.request.parsed_data
Example #3
0
def main():
    config = alembic_config.Config(
        os.path.join(os.path.dirname(__file__), 'alembic.ini'))
    config.blazar_config = CONF

    CONF()
    db_options.set_defaults(CONF)
    if not CONF.database.connection:
        raise SystemExit(
            _("Provide a configuration file with DB connection information"))

    CONF.command.func(config, CONF.command.name)
Example #4
0
    def post(self, lease):
        """Creates a new lease.

        :param lease: a lease within the request body.
        """
        # FIXME(sbauza): DB exceptions are currently catched and return a lease
        #                equal to None instead of being sent to the API
        lease_dct = lease.as_dict()
        lease = pecan.request.rpcapi.create_lease(lease_dct)
        if lease is not None:
            return Lease.convert(lease)
        else:
            raise exceptions.BlazarException(_("Lease can't be created"))
Example #5
0
def do_upgrade_downgrade(config, cmd):
    if not CONF.command.revision and not CONF.command.delta:
        raise SystemExit(_('You must provide a revision or relative delta'))

    revision = CONF.command.revision

    if CONF.command.delta:
        sign = '+' if CONF.command.name == 'upgrade' else '-'
        revision = sign + str(CONF.command.delta)
    else:
        revision = CONF.command.revision

    do_alembic_command(config, cmd, revision, sql=CONF.command.sql)
Example #6
0
    def post(self, host):
        """Creates a new host.

        :param host: a host within the request body.
        """
        # here API should go to Keystone API v3 and create trust
        host_dct = host.as_dict()
        # FIXME(sbauza): DB exceptions are currently catched and return a lease
        #                equal to None instead of being sent to the API
        host = pecan.request.hosts_rpcapi.create_computehost(host_dct)
        if host is not None:
            return Host.convert(host)
        else:
            raise exceptions.BlazarException(_("Host can't be created"))
Example #7
0
def render(result=None, response_type=None, status=None, **kwargs):
    """Render response to return."""
    if not result:
        result = {}
    if type(result) is dict:
        result.update(kwargs)
    elif kwargs:
        # can't merge kwargs into the non-dict res
        abort_and_log(500,
                      _("Non-dict and non-empty kwargs passed to render."))
        return

    status_code = getattr(flask.request, 'status_code', None)
    if status:
        status_code = status
    if not status_code:
        status_code = 200

    if not response_type:
        response_type = getattr(flask.request, 'resp_type', RT_JSON)

    serializer = None
    if "application/json" in response_type:
        response_type = RT_JSON
        serializer = jsonutils
    else:
        abort_and_log(400,
                      _("Content type '%s' isn't supported") % response_type)
        return

    body = serializer.dump_as_bytes(result)

    response_type = str(response_type)

    return flask.Response(response=body,
                          status=status_code,
                          mimetype=response_type)
Example #8
0
class Checks(upgradecheck.UpgradeCommands):
    """Various upgrade checks should be added as separate methods in this class

    and added to _upgrade_checks tuple.
    """

    # The format of the check functions is to return an
    # oslo_upgradecheck.upgradecheck.Result
    # object with the appropriate
    # oslo_upgradecheck.upgradecheck.Code and details set.
    # If the check hits warnings or failures then those should be stored
    # in the returned Result's "details" attribute. The
    # summary will be rolled up at the end of the check() method.
    _upgrade_checks = ((_("Policy File JSON to YAML Migration"),
                        (common_checks.check_policy_json, {
                            'conf': cfg.CONF
                        })), )
Example #9
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])
     except (ValueError, TypeError):  # pragma: nocover
         raise exceptions.BlazarException(
             _('Status {0} was unexpected').format(status))
     else:
         if status_code >= 400:
             # 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.lower() != 'content-length']
             # Save the headers as we need to modify them.
             state['status_code'] = status_code
             state['headers'] = headers
             state['exc_info'] = exc_info
         return start_response(status, headers, exc_info)
Example #10
0
    def __init__(self):
        extensions = []

        self.extension_manager = enabled.EnabledExtensionManager(
            check_func=lambda ext: ext.name in CONF.api.api_v2_controllers,
            namespace='blazar.api.v2.controllers.extensions',
            invoke_on_load=True)
        self._log_missing_plugins(CONF.api.api_v2_controllers)

        for ext in self.extension_manager.extensions:
            try:
                setattr(self, ext.obj.name, ext.obj)
            except TypeError:
                raise exceptions.BlazarException(
                    _("API name must be specified for "
                      "extension {0}").format(ext.name))
            self._routes.update(ext.obj.extra_routes)
            extensions.append(ext.obj.name)

        LOG.debug("Loaded extensions: {0}".format(extensions))
Example #11
0
class Checks(upgradecheck.UpgradeCommands):
    """Various upgrade checks should be added as separate methods in this class

    and added to _upgrade_checks tuple.
    """
    def _check_placeholder(self):
        # This is just a placeholder for upgrade checks, it should be
        # removed when the actual checks are added
        return upgradecheck.Result(upgradecheck.Code.SUCCESS)

    # The format of the check functions is to return an
    # oslo_upgradecheck.upgradecheck.Result
    # object with the appropriate
    # oslo_upgradecheck.upgradecheck.Code and details set.
    # If the check hits warnings or failures then those should be stored
    # in the returned Result's "details" attribute. The
    # summary will be rolled up at the end of the check() method.
    _upgrade_checks = (
        # In the future there should be some real checks added here
        (_('Placeholder'), _check_placeholder), )
Example #12
0
class PluginConfigurationError(exceptions.BlazarException):
    msg_fmt = _("Plugin Configuration error : %(error)s")
Example #13
0
class InvalidDate(exceptions.BlazarException):
    code = 400
    msg_fmt = _(
        '%(date)s is an invalid date. Required format: %(date_format)s')
Example #14
0
class MultipleHostsFound(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Multiple Hosts found for pattern '%(host)s'")
Example #15
0
class HostHavingServers(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Servers [%(servers)s] found for host %(host)s")
Example #16
0
class NoFreePool(exceptions.NotFound):
    msg_fmt = _("No Freepool found")
Example #17
0
class InvalidHost(exceptions.NotAuthorized):
    msg_fmt = _("Invalid values for host %(host)s")
Example #18
0
class AggregateAlreadyHasHost(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Conflict while adding host %(host)s to aggregate %(pool)s: "
                "%(nova_exception)s")
Example #19
0
class MissingTrustId(exceptions.BlazarException):
    msg_fmt = _("A trust id is required")
Example #20
0
class CantAddHost(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Can't add host(s) %(host)s to Aggregate %(pool)s")
Example #21
0
class AggregateHaveHost(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Can't delete Aggregate '%(name)s', "
                "host(s) attached to it : %(hosts)s")
Example #22
0
class CantUpdateParameter(exceptions.BlazarException):
    code = 409
    msg_fmt = _("%(param)s cannot be updated")
Example #23
0
class CantRemoveHost(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Can't remove host(s) %(host)s from Aggregate %(pool)s")
Example #24
0
class HostNotInFreePool(exceptions.NotFound):
    msg_fmt = _("Host %(host)s not in freepool '%(freepool_name)s'")
Example #25
0
class UnsupportedResourceType(exceptions.BlazarException):
    msg_fmt = _("The %(resource_type)s resource type is not supported")
Example #26
0
class AggregateNotFound(exceptions.NotFound):
    msg_fmt = _("Aggregate '%(pool)s' not found!")
Example #27
0
class LeaseNameAlreadyExists(exceptions.BlazarException):
    code = 409
    msg_fmt = _("The lease with name: %(name)s already exists")
Example #28
0
class HostNotFound(exceptions.NotFound):
    msg_fmt = _("Host '%(host)s' not found!")
Example #29
0
class CantDeleteHost(exceptions.BlazarException):
    code = 409
    msg_fmt = _("Can't delete host %(host)s. %(msg)s")
Example #30
0
class InvalidPeriod(exceptions.BlazarException):
    code = 400
    msg_fmt = _('The end_date must be later than the start_date.')