示例#1
0
文件: versions.py 项目: knowx/digital
    def parse_headers(headers, default_version, latest_version):
        """Determine the API version requested based on the headers supplied.

        :param headers: webob headers
        :param default_version: version to use if not specified in headers
        :param latest_version: version to use if latest is requested
        :returns: a tuple of (major, minor) version numbers
        :raises: webob.HTTPNotAcceptable
        """

        version_hdr = headers.get(Version.string, default_version)

        try:
            version_service, version_str = version_hdr.split()
        except ValueError:
            raise exc.HTTPNotAcceptable(
                _("Invalid service type for %s header") % Version.string)

        if version_str.lower() == 'latest':
            version_service, version_str = latest_version.split()

        if version_service != Version.service_string:
            raise exc.HTTPNotAcceptable(
                _("Invalid service type for %s header") % Version.string)
        try:
            version = tuple(int(i) for i in version_str.split('.'))
        except ValueError:
            version = ()

        if len(version) != 2:
            raise exc.HTTPNotAcceptable(
                _("Invalid value for %s header") % Version.string)
        return version
示例#2
0
 def get_validate_region_name(self, region_name):
     if region_name is None:
         message = _("region_name needs to be configured in digital.conf")
         raise exception.InvalidParameterValue(message)
     """matches the region of a public endpoint for the Keystone
     service."""
     regions = None
     try:
         regions = self.client.regions.list()
     except kc_exception.NotFound:
         pass
     except Exception:
         LOG.exception('Failed to list regions')
         raise exception.RegionsListFailed()
     region_list = []
     for region in regions:
         region_list.append(region.id)
     if region_name not in region_list:
         raise exception.InvalidParameterValue(_(
             'region_name %(region_name)s is invalid, '
             'expecting a region_name in %(region_name_list)s.') % {
                 'region_name': region_name,
                 'region_name_list': '/'.join(
                     region_list + ['unspecified'])})
     return region_name
示例#3
0
 def _check_version(self, version, headers=None):
     if headers is None:
         headers = {}
     # ensure that major version in the URL matches the header
     if version.major != BASE_VERSION:
         raise http_error.HTTPNotAcceptableAPIVersion(
             _("Mutually exclusive versions requested. Version %(ver)s "
               "requested but not supported by this service."
               "The supported version range is: "
               "[%(min)s, %(max)s].") % {
                   'ver': version,
                   'min': MIN_VER_STR,
                   'max': MAX_VER_STR
               },
             headers=headers,
             max_version=str(MAX_VER),
             min_version=str(MIN_VER))
     # ensure the minor version is within the supported range
     if version < MIN_VER or version > MAX_VER:
         raise http_error.HTTPNotAcceptableAPIVersion(
             _("Version %(ver)s was requested but the minor version is not "
               "supported by this service. The supported version range is: "
               "[%(min)s, %(max)s].") % {
                   'ver': version,
                   'min': MIN_VER_STR,
                   'max': MAX_VER_STR
               },
             headers=headers,
             max_version=str(MAX_VER),
             min_version=str(MIN_VER))
示例#4
0
    def get_cert(cert_ref, **kwargs):
        """Retrieves the specified cert.

        :param cert_ref: the UUID of the cert to retrieve

        :return: digital.common.cert_manager.cert_manager.Cert
                 representation of the certificate data
        :raises CertificateStorageException: if certificate retrieval fails
        """
        LOG.warning(
            "Loading certificate {0} from the local filesystem. "
            "CertManager type 'local' should be used for testing purpose.".
            format(cert_ref))

        filename_base = os.path.join(CONF.certificates.storage_path, cert_ref)

        filename_certificate = "{0}.crt".format(filename_base)
        filename_private_key = "{0}.key".format(filename_base)
        filename_intermediates = "{0}.int".format(filename_base)
        filename_pkp = "{0}.pass".format(filename_base)

        cert_data = dict()

        try:
            with open(filename_certificate, 'r') as cert_file:
                cert_data['certificate'] = cert_file.read()
        except IOError:
            LOG.error("Failed to read certificate for {0}.".format(cert_ref))
            raise exception.CertificateStorageException(
                msg=_("Certificate could not be read."))
        try:
            with open(filename_private_key, 'r') as key_file:
                cert_data['private_key'] = key_file.read()
        except IOError:
            LOG.error("Failed to read private key for {0}.".format(cert_ref))
            raise exception.CertificateStorageException(
                msg=_("Private Key could not be read."))

        try:
            if path.isfile(filename_intermediates):
                with open(filename_intermediates, 'r') as int_file:
                    cert_data['intermediates'] = int_file.read()
        except IOError as ioe:
            LOG.error("Failed to read certificate.")
            raise exception.CertificateStorageException(msg=str(ioe))

        try:
            if path.isfile(filename_pkp):
                with open(filename_pkp, 'r') as pass_file:
                    cert_data['private_key_passphrase'] = pass_file.read()
        except IOError as ioe:
            LOG.error("Failed to read certificate.")
            raise exception.CertificateStorageException(msg=str(ioe))

        return Cert(**cert_data)
示例#5
0
文件: api.py 项目: knowx/digital
def _get_ssl_configs(use_ssl):
    if use_ssl:
        cert_file = CONF.api.ssl_cert_file
        key_file = CONF.api.ssl_key_file

        if cert_file and not os.path.exists(cert_file):
            raise RuntimeError(_("Unable to find cert_file : %s") % cert_file)

        if key_file and not os.path.exists(key_file):
            raise RuntimeError(_("Unable to find key_file : %s") % key_file)

        return cert_file, key_file
    else:
        return None
示例#6
0
 def __init__(self, cert_container):
     if not isinstance(cert_container,
                       barbican_client.containers.CertificateContainer):
         raise TypeError(_(
             "Retrieved Barbican Container is not of the correct type "
             "(certificate)."))
     self._cert_container = cert_container
示例#7
0
    def validate(patch):
        if patch.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 not patch.value:
                msg = _("'add' and 'replace' operations needs value")
                raise wsme.exc.ClientSideError(msg)

        ret = {'path': patch.path, 'op': patch.op}
        if patch.value:
            ret['value'] = patch.value
        return ret
示例#8
0
 def validate(self, value):
     for t in self.types:
         try:
             return wtypes.validate_value(t, value)
         except (exception.InvalidUUID, ValueError):
             pass
     else:
         raise ValueError(
             _("Wrong type. Expected '%(type)s', got '%(value)s'") % {
                 'type': self.types,
                 'value': type(value)
             })
示例#9
0
class DigitalException(Exception):
    """Base Digital 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:
            # kwargs doesn't match a variable in the message
            # log the issue and the kwargs
            LOG.exception('Exception in string format operation, '
                          'kwargs: %s', kwargs)
            try:
                if CONF.fatal_exception_format_errors:
                    raise
            except cfg.NoSuchOptError:
                # Note: work around for Bug: #1447873
                if CONF.oslo_versionedobjects.fatal_exception_format_errors:
                    raise

        super(DigitalException, 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)
示例#10
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()
示例#11
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)
示例#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)
示例#13
0
文件: base.py 项目: knowx/digital
        def version_select():
            """Select the correct method based on version

            @return: Returns the correct versioned method
            @raises: HTTPNotAcceptable if there is no method which
                 matches the name and version constraints
            """

            from pecan import request
            ver = request.version

            func_list = self.versioned_methods[key]
            for func in func_list:
                if ver.matches(func.start_version, func.end_version):
                    return func.func

            raise exc.HTTPNotAcceptable(
                _("Version %(ver)s was requested but the requested API %(api)s "
                  "is not supported for this version.") % {
                      'ver': ver,
                      'api': key
                  })
示例#14
0
class TrustDeleteFailed(DigitalException):
    message = _("Failed to delete trust %(trust_id)s.")
示例#15
0
文件: barbican.py 项目: knowx/digital
from oslo_config import cfg

from digital.i18n import _

barbican_group = cfg.OptGroup(name='barbican_client',
                              title='Options for the Barbican client')

barbican_client_opts = [
    cfg.StrOpt('region_name',
               help=_('Region in Identity service catalog to use for '
                      'communication with the OpenStack service.')),
    cfg.StrOpt('endpoint_type',
               default='publicURL',
               help=_('Type of endpoint in Identity service catalog to use '
                      'for communication with the OpenStack service.'))
]


def register_opts(conf):
    conf.register_group(barbican_group)
    conf.register_opts(barbican_client_opts, group=barbican_group)


def list_opts():
    return {barbican_group: barbican_client_opts}
示例#16
0
class TrusteeCreateFailed(DigitalException):
    message = _("Failed to create trustee %(username)s "
                "in domain %(domain_id)s")
示例#17
0
class TrusteeOrTrustToClusterFailed(DigitalException):
    message = _("Failed to create trustee or trust for Cluster: "
                "%(cluster_uuid)s")
示例#18
0
from oslo_config import cfg

from digital.i18n import _

trust_group = cfg.OptGroup(name='trust',
                           title='Trustee options for the digital services')

trust_opts = [
    cfg.BoolOpt('cluster_user_trust',
                default=False,
                help=_('This setting controls whether to assign a trust to'
                       ' the cluster user or not. You will need to set it to'
                       ' True for clusters with volume_driver=cinder or'
                       ' registry_enabled=true in the underlying cluster'
                       ' template to work. This is a potential security risk'
                       ' since the trust gives instances OpenStack API access'
                       " to the cluster's project. Note that this setting"
                       ' does not affect per-cluster trusts assigned to the'
                       'Digital service user.')),
    cfg.StrOpt('trustee_domain_id',
               help=_('Id of the domain to create trustee for clusters')),
    cfg.StrOpt('trustee_domain_name',
               help=_('Name of the domain to create trustee for s')),
    cfg.StrOpt('trustee_domain_admin_id',
               help=_('Id of the admin with roles sufficient to manage users'
                      ' in the trustee_domain')),
    cfg.StrOpt('trustee_domain_admin_name',
               help=_('Name of the admin with roles sufficient to manage users'
                      ' in the trustee_domain')),
    cfg.StrOpt('trustee_domain_admin_domain_id',
示例#19
0
class KeyPairNotFound(ResourceNotFound):
    message = _("Unable to find keypair %(keypair)s.")
示例#20
0
class MemberAlreadyExists(Conflict):
    message = _("A cluster with UUID %(uuid)s is already a member of the"
                "federation %(federation_name)s.")
示例#21
0
class FederationAlreadyExists(Conflict):
    message = _("A federation with UUID %(uuid)s already exists.")
示例#22
0
class FederationNotFound(ResourceNotFound):
    message = _("Federation %(federation)s could not be found.")
示例#23
0
class CertificatesToClusterFailed(DigitalException):
    message = _("Failed to create certificates for Cluster: %(cluster_uuid)s")
示例#24
0
class TrustCreateFailed(DigitalException):
    message = _("Failed to create trust for trustee %(trustee_user_id)s.")
示例#25
0
class DigitalServiceAlreadyExists(Conflict):
    message = _("A digital service with ID %(id)s already exists.")
示例#26
0
文件: utils.py 项目: knowx/digital
               'running commands as root.'),
    cfg.StrOpt('tempdir',
               help='Explicitly specify the temporary working directory.'),
    cfg.ListOpt('password_symbols',
                default=DEFAULT_PASSWORD_SYMBOLS,
                help='Symbols to use for passwords')
]

periodic_opts = [
    cfg.IntOpt('service_down_time',
               default=180,
               help='Max interval size between periodic tasks execution in '
               'seconds.'),
]

urlfetch_opts = [
    cfg.IntOpt('max_manifest_size',
               default=524288,
               help=_('Maximum raw byte size of any manifest.'))
]

ALL_OPTS = list(itertools.chain(utils_opts, periodic_opts, urlfetch_opts))


def register_opts(conf):
    conf.register_opts(ALL_OPTS)


def list_opts():
    return {"DEFAULT": ALL_OPTS}
示例#27
0
class DigitalServiceNotFound(ResourceNotFound):
    message = _("A digital service %(digital_service_id)s could not be found.")
示例#28
0
class RegionsListFailed(DigitalException):
    message = _("Failed to list regions.")
示例#29
0
class TrusteeDeleteFailed(DigitalException):
    message = _("Failed to delete trustee %(trustee_id)s")
示例#30
0
class ServicesListFailed(DigitalException):
    message = _("Failed to list services.")