Exemple #1
0
 def inner(self, context, *args, **kwargs):
     # FIXME(kevinbenton): get rid of all uses of this flag
     if (context.session.is_active and
             getattr(context, 'GUARD_TRANSACTION', True)):
         raise RuntimeError(_("Method %s cannot be called within a "
                              "transaction.") % f)
     return f(self, context, *args, **kwargs)
class SecurityGroupInUse(nexception.InUse):
    message = _("Security Group %(id)s %(reason)s.")

    def __init__(self, **kwargs):
        if 'reason' not in kwargs:
            kwargs['reason'] = _("in use")
        super(SecurityGroupInUse, self).__init__(**kwargs)
Exemple #3
0
    def __call__(self, target, creds, enforcer):
        if self.target_field not in target:
            # policy needs a plugin check
            # target field is in the form resource:field
            # however if they're not separated by a colon, use an underscore
            # as a separator for backward compatibility

            def do_split(separator):
                parent_res, parent_field = self.target_field.split(
                    separator, 1)
                return parent_res, parent_field

            for separator in (':', '_'):
                try:
                    parent_res, parent_field = do_split(separator)
                    break
                except ValueError:
                    LOG.debug("Unable to find ':' as separator in %s.",
                              self.target_field)
            else:
                # If we are here split failed with both separators
                err_reason = (_("Unable to find resource name in %s") %
                              self.target_field)
                LOG.error(err_reason)
                raise exceptions.PolicyCheckError(policy="%s:%s" %
                                                  (self.kind, self.match),
                                                  reason=err_reason)
            parent_foreign_key = attributes.RESOURCE_FOREIGN_KEYS.get(
                "%ss" % parent_res, None)
            if not parent_foreign_key:
                err_reason = (_("Unable to verify match:%(match)s as the "
                                "parent resource: %(res)s was not found") % {
                                    'match': self.match,
                                    'res': parent_res
                                })
                LOG.error(err_reason)
                raise exceptions.PolicyCheckError(policy="%s:%s" %
                                                  (self.kind, self.match),
                                                  reason=err_reason)

            target[self.target_field] = self._extract(
                parent_res, target[parent_foreign_key], parent_field)

        match = self.match % target
        if self.kind in creds:
            return match == six.text_type(creds[self.kind])
        return False
def convert_to_uuid_list_or_none(value_list):
    if value_list is None:
        return
    for sg_id in value_list:
        if not uuidutils.is_uuid_like(sg_id):
            msg = _("'%s' is not an integer or uuid") % sg_id
            raise nexception.InvalidInput(error_message=msg)
    return value_list
Exemple #5
0
class NetworkVlanRangeError(e.NeutronException):
    message = _("Invalid network VLAN range: '%(vlan_range)s' - '%(error)s'.")

    def __init__(self, **kwargs):
        # Convert vlan_range tuple to 'start:end' format for display
        if isinstance(kwargs['vlan_range'], tuple):
            kwargs['vlan_range'] = "%d:%d" % kwargs['vlan_range']
        super(NetworkVlanRangeError, self).__init__(**kwargs)
Exemple #6
0
class NeutronPrimaryKeyMissing(exceptions.BadRequest):
    message = _("For class %(object_type)s missing primary keys: "
                "%(missing_keys)s")

    def __init__(self, object_class, missing_keys):
        super(NeutronPrimaryKeyMissing, self).__init__(
            object_type=reflection.get_class_name(object_class,
                                                  fully_qualified=False),
            missing_keys=missing_keys)
Exemple #7
0
def port_rule_masking(port_min, port_max):
    """Translate a range [port_min, port_max] into a set of bitwise matches.

    Each match has the form 'port/mask'. The port and mask are 16-bit numbers
    written in hexadecimal prefixed by 0x. Each 1-bit in mask requires that
    the corresponding bit in port must match. Each 0-bit in mask causes the
    corresponding bit to be ignored.
    """

    # Let binary representation of port_min and port_max be n bits long and
    # have first m bits in common, 0 <= m <= n.

    # If remaining (n - m) bits of given ports define 2^(n-m) values, then
    # [port_min, port_max] range is covered by a single rule.
    # For example:
    # n = 6
    # port_min = 16 (binary 010000)
    # port_max = 23 (binary 010111)
    # Ports have m=3 bits in common with the remaining (n-m)=3 bits
    # covering range [0, 2^3), which equals to a single 010xxx rule. The algo
    # will return [0x0010/fff8].

    # Else [port_min, port_max] range will be split into 2: range [port_min, T)
    # and [T, port_max]. Let p_m be the common part of port_min and port_max
    # with other (n-m) bits set to 0. Then T = p_m | 1 << (n-m-1).
    # For example:
    # n = 7
    # port_min = 40  (binary 0101000)
    # port_max = 105 (binary 1101001)
    # Ports have m=0 bits in common, p_m=000000. Then T=1000000 and the
    # initial range [40, 105] is divided into [40, 64) and [64, 105].
    # Each of the ranges will be processed separately, then the generated rules
    # will be merged.

    # Check port_max >= port_min.
    if port_max < port_min:
        raise ValueError(_("'port_max' is smaller than 'port_min'"))

    bitdiff = port_min ^ port_max
    if bitdiff == 0:
        # port_min == port_max
        return [_hex_format(port_min)]
    # for python3.x, bit_length could be used here
    top_bit = 1
    while top_bit <= bitdiff:
        top_bit <<= 1
    if (port_min & (top_bit - 1) == 0 and
            port_max & (top_bit - 1) == top_bit - 1):
        # special case, range of 2^k ports is covered
        return [_hex_format(port_min, top_bit - 1)]

    top_bit >>= 1
    rules = []
    rules.extend(_gen_rules_port_min(port_min, top_bit))
    rules.extend(_gen_rules_port_max(port_max, top_bit))
    return rules
Exemple #8
0
class NeutronDbObjectDuplicateEntry(exceptions.Conflict):
    message = _("Failed to create a duplicate %(object_type)s: "
                "for attribute(s) %(attributes)s with value(s) %(values)s")

    def __init__(self, object_class, db_exception):
        super(NeutronDbObjectDuplicateEntry, self).__init__(
            object_type=reflection.get_class_name(object_class,
                                                  fully_qualified=False),
            attributes=db_exception.columns,
            values=db_exception.value)
Exemple #9
0
def main():
    config.init(sys.argv[1:])
    config.setup_logging()
    n_utils.log_opt_values(LOG)
    if not CONF.config_file:
        sys.exit(
            _("ERROR: Unable to find configuration file via the default"
              " search paths (~/.neutron/, ~/, /etc/neutron/, /etc/) and"
              " the '--config-file' option!"))
    run()
Exemple #10
0
 def __init__(self, kind, match):
     # Process the match
     try:
         self.target_field = re.findall(r'^\%\((.*)\)s$', match)[0]
     except IndexError:
         err_reason = (_("Unable to identify a target field from:%s. "
                         "Match should be in the form %%(<field_name>)s") %
                       match)
         LOG.exception(err_reason)
         raise exceptions.PolicyInitError(policy="%s:%s" % (kind, match),
                                          reason=err_reason)
     self._cache = cache._get_memory_cache_region(expiration_time=5)
     super(OwnerCheck, self).__init__(kind, match)
Exemple #11
0
def is_cidr_host(cidr):
    """Determines if the cidr passed in represents a single host network

    :param cidr: Either an ipv4 or ipv6 cidr.
    :returns: True if the cidr is /32 for ipv4 or /128 for ipv6.
    :raises ValueError: raises if cidr does not contain a '/'.  This disallows
        plain IP addresses specifically to avoid ambiguity.
    """
    if '/' not in str(cidr):
        raise ValueError(_("cidr doesn't contain a '/'"))
    net = netaddr.IPNetwork(cidr)
    if net.version == 4:
        return net.prefixlen == n_const.IPv4_BITS
    return net.prefixlen == n_const.IPv6_BITS
Exemple #12
0
def init(args, **kwargs):
    cfg.CONF(args=args,
             project='neutron',
             version='%%(prog)s %s' % version.version_info.release_string(),
             **kwargs)

    # FIXME(ihrachys): if import is put in global, circular import
    # failure occurs
    from neutron.common import rpc as n_rpc
    n_rpc.init(cfg.CONF)

    # Validate that the base_mac is of the correct format
    msg = validators.validate_regex(cfg.CONF.base_mac, validators.MAC_PATTERN)
    if msg:
        msg = _("Base MAC: %s") % msg
        raise Exception(msg)
Exemple #13
0
def get_related_rand_names(prefixes, max_length=None):
    """Returns a list of the prefixes with the same random characters appended

    :param prefixes: A list of prefix strings
    :param max_length: The maximum length of each returned string
    :returns: A list with each prefix appended with the same random characters
    """

    if max_length:
        length = max_length - max(len(p) for p in prefixes)
        if length <= 0:
            raise ValueError(
                _("'max_length' must be longer than all prefixes"))
    else:
        length = 8
    rndchrs = helpers.get_random_string(length)
    return [p + rndchrs for p in prefixes]
Exemple #14
0
def _get_cache_region_for_legacy(url):
    parsed = parse.urlparse(url)
    backend = parsed.scheme

    if backend == 'memory':
        query = parsed.query
        # NOTE(flaper87): We need the following hack
        # for python versions < 2.7.5. Previous versions
        # of python parsed query params just for 'known'
        # schemes. This was changed in this patch:
        # http://hg.python.org/cpython/rev/79e6ff3d9afd
        if not query and '?' in parsed.path:
            query = parsed.path.split('?', 1)[-1]
        parameters = parse.parse_qs(query)
        return _get_memory_cache_region(
            expiration_time=int(parameters.get('default_ttl', [0])[0]))
    else:
        raise RuntimeError(_('Old style configuration can use only memory '
                             '(dict) backend'))
Exemple #15
0
 def __call__(self, target_self, *args, **kwargs):
     target_self_cls_name = reflection.get_class_name(target_self,
                                                      fully_qualified=False)
     if not hasattr(target_self, '_cache'):
         raise NotImplementedError(
             _("Instance of class %(module)s.%(class)s must contain _cache "
               "attribute") % {
                 'module': target_self.__module__,
                 'class': target_self_cls_name})
     if not target_self._cache:
         if self._first_call:
             LOG.debug("Instance of class %(module)s.%(class)s doesn't "
                       "contain attribute _cache therefore results "
                       "cannot be cached for %(func_name)s.",
                       {'module': target_self.__module__,
                        'class': target_self_cls_name,
                        'func_name': self.func.__name__})
             self._first_call = False
         return self.func(target_self, *args, **kwargs)
     return self._get_from_cache(target_self, *args, **kwargs)
Exemple #16
0
class SegmentIdUnsupported(n_exc.NeutronException):
    message = _("Segmentation ID is unsupported for network type %(net_type)s")
Exemple #17
0
class InvalidSegmentAllocationRange(n_exc.NeutronException):
    message = _("Invalid segment allocation range: %(msg)s.")
Exemple #18
0
class DuplicateRouteConflict(n_exc.NeutronException):
    message = _("More than one default route found for subnet %(subnet_id)s")
Exemple #19
0
class InvalidPhysicalNetworkType(n_exc.NeutronException):
    message = _("Providernet type %(net_type)s is invalid")
Exemple #20
0
class PortRequiresDisassociation(n_exc.BadRequest):
    message = _("Port requires disassociation before IP can be deleted")
Exemple #21
0
class RouteConflict(n_exc.NeutronException):
    message = _("Route overlaps existing route %(route_id)s with %(cidr)s")
Exemple #22
0
class AmbigiousLswitchCount(n_exc.NeutronException):
    message = _("Too many lswitches for network %(net_id)s.")
Exemple #23
0
class IpAddressNotFound(n_exc.NotFound):
    message = _("IP Address %(addr_id)s not found.")
Exemple #24
0
class AmbiguousNetworkId(n_exc.InvalidInput):
    msg = _("Segment ID required for network %(net_id)s.")
Exemple #25
0
class RouteNotFound(n_exc.NotFound):
    message = _("Route %(route_id)s not found.")
Exemple #26
0
class SegmentAllocationFailure(n_exc.Conflict):
    message = _("No more segment ids available for segment "
                "type:%(segment_type)s id:%(segment_id)s.")
Exemple #27
0
class SegmentAllocationRangeInUse(n_exc.InUse):
    message = _(
        "Segment allocation range %(segment_allocation_range_id)s in use.")
Exemple #28
0
class MacAddressNotFound(n_exc.NotFound):
    message = _("MAC address %(mac_address_id)s (%(readable_mac)s) not found.")
Exemple #29
0
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    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 oslo_config import cfg
from oslo_service import wsgi

from neutrondeps._i18n import _

socket_opts = [
    cfg.IntOpt('backlog',
               default=4096,
               help=_("Number of backlog requests to configure "
                      "the socket with")),
    cfg.IntOpt('retry_until_window',
               default=30,
               help=_("Number of seconds to keep retrying to listen")),
    cfg.BoolOpt('use_ssl',
                default=False,
                help=_('Enable SSL on the API server')),
]


def register_socket_opts(cfg=cfg.CONF):
    cfg.register_opts(socket_opts)
    wsgi.register_opts(cfg)
Exemple #30
0
class SegmentAllocationRangeNotFound(n_exc.NotFound):
    message = _(
        "Segment allocation range %(segment_allocation_range_id)s not found.")