Esempio n. 1
0
    def validate(cls, value, minimum=None, maximum=None):
        if value is None:
            return None

        if not isinstance(value, six.integer_types):
            try:
                value = int(value)
            except Exception:
                LOG.exception(_LE('Failed to convert value to int'))
                raise exception.InvalidValue(value=value, type=cls.type_name)

        if minimum is not None and value < minimum:
            message = _("Integer '%(value)s' is smaller than "
                        "'%(min)d'.") % {
                            'value': value,
                            'min': minimum
                        }
            raise exception.InvalidValue(message=message)

        if maximum is not None and value > maximum:
            message = _("Integer '%(value)s' is large than "
                        "'%(max)d'.") % {
                            'value': value,
                            'max': maximum
                        }
            raise exception.InvalidValue(message=message)

        return value
Esempio n. 2
0
def apply_jsonpatch(doc, patch):
    for p in patch:
        if p['op'] == 'add' and p['path'].count('/') == 1:
            attr = p['path'].lstrip('/')
            if attr not in doc:
                msg = _("Adding a new attribute %s to the root of "
                        "the resource is not allowed.") % p['path']
                raise wsme.exc.ClientSideError(msg)
            if doc[attr] is not None:
                msg = _("The attribute %s has existed, please use "
                        "'replace' operation instead.") % p['path']
                raise wsme.exc.ClientSideError(msg)
    return jsonpatch.apply_patch(doc, patch)
Esempio n. 3
0
def validate_docker_memory(mem_str):
    """Docker require that Minimum memory limit >= 4M."""
    try:
        mem = utils.get_docker_quanity(mem_str)
    except exception.UnsupportedDockerQuantityFormat:
        raise wsme.exc.ClientSideError(
            _("Invalid docker memory specified. "
              "Acceptable values are format: "
              "<number>[<unit>],"
              "where unit = b, k, m or g"))
    if mem < DOCKER_MINIMUM_MEMORY:
        raise wsme.exc.ClientSideError(
            _("Docker Minimum memory limit"
              "allowed is %d B.") % DOCKER_MINIMUM_MEMORY)
Esempio n. 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
Esempio n. 5
0
def validate_limit(limit):
    if limit is not None and int(limit) <= 0:
        raise wsme.exc.ClientSideError(_("Limit must be positive"))

    if limit is not None:
        return min(CONF.api.max_limit, int(limit))
    else:
        return CONF.api.max_limit
Esempio n. 6
0
 def validate(cls, value):
     if value is None:
         return value
     super(NameType, cls).validate(value, min_length=2, max_length=255)
     match = name_pattern.match(value)
     if match:
         return value
     else:
         message = _('%s does not match [a-zA-Z0-9][a-zA-Z0-9_.-].') % value
         raise exception.InvalidValue(message)
class Commissaire_OpenstackException(Exception):
    """Base Commissaire_Openstack 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 KeyError:
            # 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:
                ferr = CONF.fatal_exception_format_errors
            except cfg.NoSuchOptError:
                ferr = CONF.oslo_versionedobjects.fatal_exception_format_errors
            if ferr:
                raise

        super(Commissaire_OpenstackException, 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, 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.load_app()
        self.workers = (CONF.api.workers or 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)
Esempio n. 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])
         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()
class InvalidCsr(Invalid):
    message = _("Received invalid csr %(csr)s.")
class Conflict(Commissaire_OpenstackException):
    message = _('Conflict.')
    code = 409
class InvalidState(Conflict):
    message = _("Invalid resource state.")
class InvalidParameterValue(Invalid):
    message = _("%(err)s")
Esempio n. 15
0
from commissaire_openstack.common.i18n import _LI


# Register options for the service
API_SERVICE_OPTS = [
    cfg.PortOpt('port',
                default=9512,
                help='The port for the commissaire-openstack API server.'),
    cfg.IPOpt('host',
              default='127.0.0.1',
              help='The listen IP for the commissaire-openstack 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.")),
    cfg.IntOpt('workers',
               help=_("Number of workers for commissaire-openstack-api service. "
                      "The default will be the number of CPUs available.")),
    cfg.IntOpt('max_limit',
               default=1000,
               help='The maximum number of items returned in a single '
                    'response from a collection resource.'),
    cfg.StrOpt('api_paste_config',
               default="api-paste.ini",
               help="Configuration file for WSGI definition of API.")
]

CONF = cfg.CONF
class ConfigInvalid(Commissaire_OpenstackException):
    message = _("Invalid configuration file. %(error_msg)s")
Esempio n. 17
0
from oslo_config import cfg
from oslo_log import log
from oslo_service import service
from oslo_service import wsgi

from commissaire_openstack.api import app
from commissaire_openstack.common import config
from commissaire_openstack.common import exception
from commissaire_openstack.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 DockerError(Commissaire_OpenstackException):
    message = _("Docker internal error: %(error_msg)s.")
class InvalidIdentity(Invalid):
    message = _("Expected an uuid or int but received %(identity)s.")
class ContainerAlreadyExists(ResourceExists):
    message = _("A container with UUID %(uuid)s already exists.")
class ImageNotFound(HTTPNotFound):
    message = _("Image %(image)s could not be found.")
class ContainerNotFound(HTTPNotFound):
    message = _("Container %(container)s could not be found.")
class PolicyNotAuthorized(NotAuthorized):
    message = _("Policy doesn't allow %(action)s to be performed.")
Esempio n. 24
0
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from glanceclient import client as glanceclient
from oslo_config import cfg
from oslo_log import log as logging

from commissaire_openstack.common import exception
from commissaire_openstack.common.i18n import _
from commissaire_openstack.common import keystone

common_security_opts = [
    cfg.StrOpt('ca_file',
               help=_('Optional CA cert file to use in SSL connections.')),
    cfg.StrOpt('cert_file',
               help=_('Optional PEM-formatted certificate chain file.')),
    cfg.StrOpt('key_file',
               help=_('Optional PEM-formatted file that contains the '
                      'private key.')),
    cfg.BoolOpt('insecure',
                default=False,
                help=_("If set, then the server's certificate will not "
                       "be verified."))
]

commissaire_openstack_client_opts = [
    cfg.StrOpt('region_name',
               help=_('Region in Identity service catalog to use for '
                      'communication with the OpenStack service.')),
class PatchError(Invalid):
    message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")
class InstanceNotFound(ResourceNotFound):
    message = _("Instance %(instance)s could not be found.")
class ImageAlreadyExists(ResourceExists):
    message = _("An image with this tag and repo already exists.")
class NotAuthorized(Commissaire_OpenstackException):
    message = _("Not authorized.")
    code = 403
Esempio n. 29
0
 def decorated_function(*args, **kwargs):
     container = args[1]
     if getattr(container, 'container_id', None) is None:
         msg = _("Cannot operate an uncreated container.")
         raise exception.Invalid(message=msg)
     return function(*args, **kwargs)
class InvalidStateException(Commissaire_OpenstackException):
    message = _("Cannot %(action)s container %(id)s in %(actual_state)s state")
    code = 409