Exemple #1
0
    def validate(self, value):
        if self.minlen is not None and len(value) < self.minlen:
            error = _('Value %(value)s is invalid (length should be greater or equal '
                      'to %(min)s)') % dict(value=value, min=self.minlen)
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))

        if self.maxlen is not None and len(value) > self.maxlen:
            error = _('Value %(value)s is invalid (length should be lower or equal '
                      'to %(max)s)') % dict(value=value, max=self.maxlen)
            response.translatable_error = error
            raise wsme.exc.ClientSideError(unicode(error))
        return value
Exemple #2
0
 def __str__(self):
     # NOTE(luisg): Logging in python 2.6 tries to str() log records,
     # and it expects specifically a UnicodeError in order to proceed.
     from oslo_i18n._i18n import _
     msg = _('Message objects do not support str() because they may '
             'contain non-ascii characters. '
             'Please use unicode() or translate() instead.')
     raise UnicodeError(msg)
Exemple #3
0
 def __str__(self):
     # NOTE(luisg): Logging in python 2.6 tries to str() log records,
     # and it expects specifically a UnicodeError in order to proceed.
     from oslo_i18n._i18n import _
     msg = _('Message objects do not support str() because they may '
             'contain non-ascii characters. '
             'Please use unicode() or translate() instead.')
     raise UnicodeError(msg)
Exemple #4
0
def validate_ip(value):
    try:
        if value:
            IPAddress(value)
    except AddrFormatError:
        error = _('Value %(value)s is not a valid IP Address') % dict(value=value)
        response.translatable_error = error
        raise wsme.exc.ClientSideError(unicode(error))
Exemple #5
0
def setup_logging(conf):
    """Sets up the logging options for a log with supplied name.

    :param conf: a cfg.ConfOpts object
    """
    product_name = "nscsas"
    logging.setup(product_name)
    LOG.info(_("Logging enabled!"))
Exemple #6
0
 def _set(self, parent, value):
     try:
         if value and IPNetwork(value):
             setattr(parent, self._name, value)
     except AddrFormatError:
         error = _('Value %(value)s is not a valid IP Address') % dict(value=value)
         response.translatable_error = error
         raise wsme.exc.ClientSideError(unicode(error))
Exemple #7
0
    def post(self, service_locator):
        """
        This function implements create record functionality of the
        Service Locator attributes of Service Locator.

        :return: Dictionary of the added record.
        """
        
        LOG.debug(_("Service Locator create: %s"), str(service_locator))
        return ServiceLocatorResp(**({'service_locator': service_locator}))
Exemple #8
0
    def post(self, service_group):
        """
        This function implements create record functionality of the
        Service Group attributes of Service Group.

        :return: Dictionary of the added record.
        """
        
        LOG.debug(_("Service Group create: %s"), str(service_group))
        return ServiceGroupResp(**({'service_group': service_group}))
Exemple #9
0
    def test_default(self):

        # Turn lazy off to check that fixture turns it on
        self.useFixture(fixture.ToggleLazy(False))
        self.useFixture(fixture.PrefixLazyTranslation())
        self.assertTrue(_lazy.USE_LAZY)
        default_lang = fixture.PrefixLazyTranslation._DEFAULT_LANG
        raw_id1 = 'fake msg1'
        expected_msg = 'oslo_i18n/' + default_lang + ': ' + raw_id1
        msg1 = _(raw_id1)  # noqa
        self.assertEqual([default_lang],
                         _gettextutils.get_available_languages('oslo_i18n'))
        self.assertEqual([default_lang],
                         oslo_i18n.get_available_languages('oslo_i18n'))
        self.assertEqual(expected_msg, _translate.translate(msg1))
Exemple #10
0
    def test_default(self):

        # Turn lazy off to check that fixture turns it on
        self.useFixture(fixture.ToggleLazy(False))
        self.useFixture(fixture.PrefixLazyTranslation())
        self.assertTrue(_lazy.USE_LAZY)
        default_lang = fixture.PrefixLazyTranslation._DEFAULT_LANG
        raw_id1 = 'fake msg1'
        expected_msg = 'oslo_i18n/' + default_lang + ': ' + raw_id1
        msg1 = _(raw_id1)    # noqa
        self.assertEqual([default_lang],
                         _gettextutils.get_available_languages('oslo_i18n'))
        self.assertEqual([default_lang],
                         oslo_i18n.get_available_languages('oslo_i18n'))
        self.assertEqual(expected_msg, _translate.translate(msg1))
Exemple #11
0
 def test_extra_lang(self):
     languages = _gettextutils.get_available_languages('oslo')
     languages.append(_FAKE_LANG)
     self.useFixture(fixture.PrefixLazyTranslation(languages=languages))
     raw_id1 = 'fake msg1'
     expected_msg_en_US = ('oslo_i18n/' +
                           fixture.PrefixLazyTranslation._DEFAULT_LANG +
                           ': ' + raw_id1)
     expected_msg_en_ZZ = 'oslo_i18n/' + _FAKE_LANG + ': ' + raw_id1
     msg1 = _(raw_id1)  # noqa
     self.assertEqual(languages,
                      _gettextutils.get_available_languages('oslo_i18n'))
     self.assertEqual(languages,
                      oslo_i18n.get_available_languages('oslo_i18n'))
     self.assertEqual(expected_msg_en_US, _translate.translate(msg1))
     self.assertEqual(expected_msg_en_ZZ,
                      _translate.translate(msg1, desired_locale=_FAKE_LANG))
Exemple #12
0
 def test_extra_lang(self):
     languages = _gettextutils.get_available_languages('oslo')
     languages.append(_FAKE_LANG)
     self.useFixture(fixture.PrefixLazyTranslation(languages=languages))
     raw_id1 = 'fake msg1'
     expected_msg_en_US = ('oslo_i18n/' +
                           fixture.PrefixLazyTranslation._DEFAULT_LANG +
                           ': ' + raw_id1)
     expected_msg_en_ZZ = 'oslo_i18n/' + _FAKE_LANG + ': ' + raw_id1
     msg1 = _(raw_id1)     # noqa
     self.assertEqual(languages,
                      _gettextutils.get_available_languages('oslo_i18n'))
     self.assertEqual(languages,
                      oslo_i18n.get_available_languages('oslo_i18n'))
     self.assertEqual(expected_msg_en_US, _translate.translate(msg1))
     self.assertEqual(expected_msg_en_ZZ,
                      _translate.translate(msg1,
                                           desired_locale=_FAKE_LANG))
Exemple #13
0
import copy
import os
import re

from oslo_config import cfg

from oslo_log import log as logging
from oslo_i18n._i18n import _

from nscs.nscsas.version import version as nscsas_version

LOG = logging.getLogger(__name__)

core_opts = [
    cfg.StrOpt('bind_host', default='0.0.0.0',
               help=_("The host IP to bind to")),
    cfg.IntOpt('bind_port', default=20202,
               help=_("The port to bind to")),
]

# Register the configuration options
cfg.CONF.register_opts(core_opts)


def get_all_configs(conf_path):
    confs = []
    for cf in os.listdir(conf_path):
        if re.search(r'/.conf$/', cf):
            confs.append(cf)
    return confs
Exemple #14
0
    def post(self, service_function):
        """
        This function implements create record functionality of the
        Service Function Instance.

        :return: Dictionary of the added record.
        """
        LOG.debug(_("####################################################"))
        LOG.debug(_("Service Function create: %s"), str(service_function.as_dict()))
        LOG.debug(_("####################################################"))
        tenant_id = self._format_uuid_string(service_function.tenant_id)
        flavor_attr = self._parse_flavor(service_function.flavor)
        instance_id = flavor_attr.get("instance_id", None)
        if not instance_id:
            raise sfcexc.InstanceNotFound(instance_id=instance_id)
        instance = self._fetch_instance_details(instance_id, tenant_id)

        print instance.to_dict()

        app_details = self._fetch_image_details(instance.image["id"])

        print app_details.to_dict()

        # Create Network Function with type if the same does not exist in
        # CRD.
        nf = request.crdclient.list_networkfunctions(name=service_function.type.lower(), tenant_id=tenant_id)[
            "networkfunctions"
        ]
        if not nf:
            nf = {
                "networkfunction": {
                    "name": service_function.type.lower(),
                    "description": service_function.type.lower(),
                    "tenant_id": tenant_id,
                }
            }
            nf = request.crdclient.create_networkfunction(body=nf)
            nf = nf["networkfunction"]["id"]
        else:
            nf = nf[0]["id"]

        # Create a default Category
        ctg = request.crdclient.list_categories(name=app_details.metadata["category"], tenant_id=tenant_id)[
            "categories"
        ]
        if not ctg:
            ctg = {
                "category": {
                    "name": app_details.metadata["category"],
                    "description": app_details.metadata["category"],
                    "tenant_id": tenant_id,
                    "category_networkfunctions": [nf],
                }
            }
            ctg = request.crdclient.create_category(body=ctg)
            ctg = ctg["category"]["id"]
        else:
            ctg = ctg[0]["id"]

        # Create Configuration
        cfg = request.crdclient.list_config_handles(networkfunction_id=nf, tenant_id=tenant_id)["config_handles"]

        if not cfg:
            cfg_name = flavor_attr["config"] + uuidutils.generate_uuid()[:13]
            if not cfg_name:
                raise sfcexc.InvalidName(name="config")
            cfg = {
                "config_handle": {
                    "name": cfg_name,
                    "tenant_id": tenant_id,
                    "status": True,
                    "slug": self.SF_SLUG_MAP[service_function.type.lower()],
                    "config_mode": "NFV",
                }
            }
            cfg = request.crdclient.create_config_handle(body=cfg)
            cfg = cfg["config_handle"]["id"]
        else:
            cfg = cfg[0]["id"]

        # Map Firewall
        if service_function.type.lower() == "fw":
            fwc = fwclient.Client(
                username=ocfg.CONF.crd.username,
                password=ocfg.CONF.crd.password,
                tenant_name=ocfg.CONF.crd.tenant_name,
                auth_url=ocfg.CONF.crd.auth_url,
            )
            fws = fwc.list_firewalls(name=flavor_attr.get("config", ""), tenant_id=tenant_id)
            if fws:
                fw_id = fws["firewalls"][0]["id"]
                fwc.update_firewall(fw_id, body={"firewall": {"config_handle_id": cfg}})

        # Map Loadbalancer
        if service_function.type.lower() == "lb":
            lbc = lbclient.Client(
                username=ocfg.CONF.crd.username,
                password=ocfg.CONF.crd.password,
                tenant_name=ocfg.CONF.crd.tenant_name,
                auth_url=ocfg.CONF.crd.auth_url,
            )
            pools = lbc.list_pools(name=flavor_attr.get("config", ""), tenant_id=tenant_id)
            if pools:
                pool_id = pools["pools"][0]["id"]
                lbc.update_pool(pool_id, body={"loadbalancer": {"config_handle_id": cfg}})

        # Create Vendor
        vendor = request.crdclient.list_vendors(name=app_details.metadata["vendor"], tenant_id=tenant_id)["vendors"]

        if not vendor:
            vendor = {
                "vendor": {
                    "name": app_details.metadata["vendor"],
                    "description": app_details.metadata["vendor"],
                    "tenant_id": tenant_id,
                }
            }
            vendor = request.crdclient.create_vendor(body=vendor)["vendor"]
        else:
            vendor = vendor[0]
        print vendor

        sf_group = self._fetch_sf_group(service_function.sf_group, tenant_id)["service_group"]
        print sf_group
        sec_group = self._fetch_security_group(instance.security_groups[0]["name"], tenant_id)[0]["id"]

        load_share_algorithm = ""
        if sf_group["algorithm"] == "round-robin":
            load_share_algorithm = "Round Robin"
        appliance = dict(
            {
                "name": app_details.name[:6] + sf_group["id"][:10],
                "tenant_id": tenant_id,
                "category_id": ctg,
                "vendor_id": vendor["id"],
                "image_id": app_details.id,
                "flavor_id": instance.flavor["id"],
                "security_group_id": sec_group,
                "form_factor_type": "virtual",
                "type": "L2",
                "load_share_algorithm": load_share_algorithm,
                "high_threshold": 100,
                "low_threshold": 1,
                "pkt_field_to_hash": sf_group["hash_field"],
                "load_indication_type": "connection_based",
                "config_handle_id": cfg,
            }
        )
        appliances = request.crdclient.list_appliances(name=appliance["name"], config_handle_id=cfg)

        if not appliances["appliances"]:
            app = request.crdclient.create_appliance(body={"appliance": appliance})

        # print app
        return ServiceFunctionResp(**({"service_function": service_function}))
Exemple #15
0
 def __init__(self, entity, id):
     super(EntityNotFound, self).__init__(
         _("%(entity)s '%(id)s' Not Found") % {'entity': entity,
                                               'id': id})
Exemple #16
0
    def post(self, chain_function):
        """
        This function implements create record functionality of the RESTful
        request.
        It converts the requested body in JSON format to dictionary in string
        representation and verifies whether
        required ATTRIBUTES are present in the POST request body.

        :return: Dictionary of the added record.
        """
        LOG.debug(_("ChainFunction create: %s"), str(chain_function.as_dict()))
        print chain_function.as_dict()
        tenant_id = self._format_uuid_string(chain_function.tenant_id)

        ### Check if the Chain Exists in CRD Service...
        chain_details = request.crdclient.show_chain(chain_function.service_chain_id)
        if chain_details:
            ### If Chain Exists...Add Chain - Appliances association
            ### Get Appliance ID from the combination of Service Function
            ### Instance Image Name and Service Function Group UUID
            ### (first 11 chars)
            sf_details = self._fetch_sf_details(
                chain_function.service_instance_id,
                tenant_id)

            print sf_details
            sf_details = sf_details['reg_service_function']
            sf_group_details = self._fetch_sf_group(sf_details['sf_group_id'])

            print sf_group_details
            
            ### Fetch Service Function Instance Details from Nova
            flavor = self._parse_flavor(sf_details['flavor'])
            instance_id = flavor.get('instance_id', None)
            if not instance_id:
                raise sfcexc.InstanceNotFound(instance_id=instance_id)
            instance_details = self._fetch_instance_details(instance_id,
                                                            tenant_id)
            intf = instance_details.interface_list()[0]
            instance_details = instance_details.to_dict()
            
            image_details = self._fetch_image_details(instance_details[
                'image']['id']
            ).to_dict()

            image_name = image_details.get('name')
            appliance_name = image_name[:6] + sf_group_details['id'][:10]
            LOG.debug(_("Appliance Name: %s"), str(appliance_name))
            
            appliances = request.crdclient.list_appliances(
                name=appliance_name, tenant_id=tenant_id)
            appliances = appliances['appliances']
            if appliances:
                appliance_details = appliances[0]
                appliance_id = appliance_details['id']
            else:
                raise sfcexc.AppliancesNotFound(name=appliance_name)
            
            seq_number = chain_function.order + 1
            if chain_function.service_chain_id and appliance_id:
                chain_function_data = {
                    'appliance': {
                        'name': chain_function.name,
                        'tenant_id': sf_details['tenant_id'],
                        'appliance_id': appliance_id,
                        #'sequence_number': chain_function.order,
                        'sequence_number': seq_number,
                    }
                }
                
                if chain_function.id:
                    chain_function_data['appliance'].update(
                        {'id': chain_function.id})
                    
                ### Create CRD Chain Appliance Association....
                chain_function_resp = self._map_chain_service_function(
                    chain_function.service_chain_id,
                    chain_function.id, chain_function_data)
                LOG.debug(_("Chain Appliance Association Response: %s"),
                          str(chain_function_resp))
                
                ### Get Locators information from Service Function Instances
                ### to get VLAN IN and VLAN OUT
                locators = self._fetch_locators(sf_details['id'])
                LOG.debug(_("Locators List: %s"), str(locators))
                print locators[0]
                print locators[1]
                print "****************************************"
                ### TODO:: Get locator information from Huawei Neutron
                ### extension
                
                ### Sample vlan_in and vlan_out locators for
                ### the time being
                vlan_in = None
                vlan_out = None

                for lc in locators:
                    if lc['direction'] == 'ingress' and not vlan_in:
                        vlan_in = int(lc['vlan_id'])
                    elif lc['direction'] == 'egress' and not vlan_out:
                        vlan_out = int(lc['vlan_id'])
                
                LOG.debug(_("VLAN IN: %s"), str(vlan_in))
                LOG.debug(_("##################"))
                LOG.debug(_("VLAN OUT: %s"), str(vlan_out))
                
                if vlan_in and vlan_out and chain_function_resp and intf.net_id:
                    ### Insert SFC Appliance-Instances mapping ...
                    appliance_instance_data = {
                        'instance': {
                            'tenant_id': sf_details['tenant_id'],
                            'instance_uuid': instance_id,
                            'vlan_in': str(vlan_in),
                            'vlan_out': str(vlan_out),
                            'network_id': intf.net_id
                        }
                    }
                    
                    LOG.debug(_("Appliance - Instance Association Body: %s"), str(appliance_instance_data))
                    appliance_instance_resp = request.crdclient.create_appliance_map_instance(
                        chain_function.service_chain_id,
                        appliance_id,
                        body=appliance_instance_data)
                    LOG.debug(_("Appliance - Instance Association Response: %s"), str(appliance_instance_resp))
                
                ### Insert Chainset Network Map, only when chainset exists
                classifier_str = chain_details['chain']['extras']
                if classifier_str:
                    chainsets = classifier_str.split(',')
                    for chainset in chainsets:
                        if chainset:
                            name = 'chainmap_' + chainset[:11]
                            chainmaps = request.crdclient.list_chainmaps(
                                inbound_network_id=intf.net_id,
                                chainset_id=chainset)['chainmaps']
                            LOG.debug(_("##################################"))
                            LOG.debug(_("ChainMaps: %s"), str(chainmaps))
                            LOG.debug(_("##################################"))
                            if not chainmaps:
                                chainset_network_data = {
                                    'chainmap': {
                                        'name': name,
                                        'chainset_id': chainset,
                                        'inbound_network_id': intf.net_id,
                                        #'outbound_network_id': intf.net_id
                                        }
                                }
                                
                                LOG.debug(_("Chainset - Network Map body: %s"), str(chainset_network_data))
                                chainset_network_resp = request.crdclient.create_chainmap(
                                    body=chainset_network_data)
                                LOG.debug(_("Chainset - Network Map Association Response: %s"), str(chainset_network_resp))
                
            else:
                LOG.error(_("Either Chain ID %s or Appliance ID %s is INVALID"), str(chain_function.service_chain_id), str(appliance_id))
                raise sfcexc.NotAcceptable()
        else:
            raise sfcexc.ChainNotFound()

        return ChainFunctionResp(**({'chain_function': chain_function}))
Exemple #17
0
 def __add__(self, other):
     from oslo_i18n._i18n import _
     msg = _('Message objects do not support addition.')
     raise TypeError(msg)
Exemple #18
0
 def __add__(self, other):
     from oslo_i18n._i18n import _
     msg = _('Message objects do not support addition.')
     raise TypeError(msg)