diff --git a/neutron_dynamic_routing/db/bgp_db.py b/neutron_dynamic_routing/db/bgp_db.py index c136f499..0a22e407 100644 --- a/neutron_dynamic_routing/db/bgp_db.py +++ b/neutron_dynamic_routing/db/bgp_db.py @@ -27,6 +27,7 @@ from neutron.objects import subnetpool as subnetpool_obj from neutron.plugins.ml2 import models as ml2_models from neutron_lib.api import validators +from neutron_lib.api.definitions import bgp_associations from neutron_lib import constants as lib_consts from neutron_lib.db import api as db_api from neutron_lib.db import model_base @@ -44,6 +45,8 @@ from sqlalchemy.orm import exc as sa_exc from neutron_dynamic_routing._i18n import _ from neutron_dynamic_routing.extensions import bgp as bgp_ext +from neutron_dynamic_routing.extensions import bgp_associations as bgp_asso_ext +from neutron_dynamic_routing.services.bgp.common import constants as bgp_consts DEVICE_OWNER_ROUTER_GW = lib_consts.DEVICE_OWNER_ROUTER_GW @@ -69,6 +72,24 @@ class BgpSpeakerPeerBinding(model_base.BASEV2): primary_key=True) +class BgpSpeakerRouterAssociation(model_base.BASEV2, + model_base.HasId, + model_base.HasProject): + + """Represents a mapping between a router and BGP speaker""" + + __tablename__ = 'bgp_speaker_router_associations' + + bgp_speaker_id = sa.Column(sa.String(length=36), + sa.ForeignKey('bgp_speakers.id'), + nullable=False) + router_id = sa.Column(sa.String(length=36), + sa.ForeignKey('routers.id'), + nullable=False) + advertise_extra_routes = sa.Column(sa.Boolean, nullable=False) + status = sa.Column(sa.String(16)) + + class BgpSpeakerNetworkBinding(model_base.BASEV2): """Represents a mapping between a network and BGP speaker""" @@ -109,6 +130,10 @@ class BgpSpeaker(model_base.BASEV2, backref='bgp_speaker_network_bindings', cascade='all, delete, delete-orphan', lazy='joined') + router_associations = orm.relationship( + BgpSpeakerRouterAssociation, + backref='bgp_speaker_router_associations', + lazy='joined') ip_version = sa.Column(sa.Integer, nullable=False, autoincrement=False) @@ -221,6 +246,56 @@ class BgpDbMixin(object): network_id) return {'network_id': network_id} + def create_bgp_speaker_router_association(self, context, bgp_speaker_id, + router_association): + assoc_info = router_association[bgp_associations.ROUTER_ASSOCIATION] + router_id = self._get_id_for(assoc_info, 'router_id') + assoc_info['bgp_speaker_id'] = bgp_speaker_id + assoc_info['status'] = bgp_consts.STATUS_DOWN + assoc_info['tenant_id'] = context.tenant_id + with db_api.CONTEXT_WRITER.using(context): + try: + model_query.get_by_id(context, BgpSpeaker, bgp_speaker_id) + except sa_exc.NoResultFound: + raise bgp_ext.BgpSpeakerNotFound(id=bgp_speaker_id) + + try: + model_query.get_by_id(context, l3_db.Router, router_id) + except sa_exc.NoResultFound: + raise l3_exc.RouterNotFound(router_id=router_id) + + res_keys = ['bgp_speaker_id', 'tenant_id', 'router_id', + 'advertise_extra_routes', 'status'] + res = dict((k, assoc_info[k]) for k in res_keys) + res['id'] = uuidutils.generate_uuid() + speaker_router_assoc_db = BgpSpeakerRouterAssociation(**res) + context.session.add(speaker_router_assoc_db) + return self._make_bgp_speaker_router_association_dict( + speaker_router_assoc_db) + + def delete_bgp_speaker_router_association(self, context, id): + with db_api.CONTEXT_WRITER.using(context): + binding = self._get_bgp_speaker_router_association(context, id) + context.session.delete(binding) + + def get_bgp_speaker_router_associations(self, context, bgp_speaker_id, + fields=None, filters=None, + sorts=None, limit=None, + marker=None, page_reverse=False): + if not filters: + filters = {} + filters['bgp_speaker_id'] = [bgp_speaker_id] + return model_query.get_collection( + context, BgpSpeakerRouterAssociation, + self._make_bgp_speaker_router_association_dict, + filters=filters, fields=fields, sorts=sorts, + limit=limit, page_reverse=page_reverse) + + def get_bgp_speaker_router_association(self, context, id, fields=None): + router_assoc = self._get_bgp_speaker_router_association(context, id) + return self._make_bgp_speaker_router_association_dict(router_assoc, + fields=fields) + def delete_bgp_speaker(self, context, bgp_speaker_id): with db_api.CONTEXT_WRITER.using(context): bgp_speaker_db = self._get_bgp_speaker(context, bgp_speaker_id) @@ -314,6 +389,10 @@ class BgpDbMixin(object): routes = self.get_routes_by_bgp_speaker_id(context, bgp_speaker_id) return self._make_advertised_routes_dict(routes) + def get_routes(self, context, bgp_speaker_id): + """TODO: Add implementation to list advertised and learnt routes""" + pass + def _get_id_for(self, resource, id_name): try: uuid = resource[id_name] @@ -421,9 +500,11 @@ class BgpDbMixin(object): 'advertise_tenant_networks'} peer_bindings = bgp_speaker['peers'] network_bindings = bgp_speaker['networks'] + router_associations = bgp_speaker['router_associations'] res = dict((k, bgp_speaker[k]) for k in attrs) res['peers'] = [x.bgp_peer_id for x in peer_bindings] res['networks'] = [x.network_id for x in network_bindings] + res['router_associations'] = [x.id for x in router_associations] return db_utils.resource_fields(res, fields) def _make_advertised_routes_dict(self, routes): @@ -449,6 +530,20 @@ class BgpDbMixin(object): BgpSpeakerNetworkBinding.bgp_speaker_id == bgp_speaker_id, BgpSpeakerNetworkBinding.network_id == network_id).one() + def _get_bgp_speaker_router_association(self, context, id): + try: + return model_query.get_by_id(context, BgpSpeakerRouterAssociation, + id) + except sa_exc.NoResultFound: + raise bgp_asso_ext.BgpSpeakerRouterAssociationNotFound(id=id) + + def _make_bgp_speaker_router_association_dict(self, router_association, + fields=None): + attrs = ['id', 'tenant_id', 'router_id', 'bgp_speaker_id', + 'advertise_extra_routes', 'status'] + res = dict((k, router_association[k]) for k in attrs) + return db_utils.resource_fields(res, fields) + def _make_bgp_peer_dict(self, bgp_peer, fields=None): attrs = ['tenant_id', 'id', 'name', 'peer_ip', 'remote_as', 'auth_type', 'password'] diff --git a/neutron_dynamic_routing/db/migration/alembic_migrations/versions/EXPAND_HEAD b/neutron_dynamic_routing/db/migration/alembic_migrations/versions/EXPAND_HEAD index 6177b331..ce4634aa 100644 --- a/neutron_dynamic_routing/db/migration/alembic_migrations/versions/EXPAND_HEAD +++ b/neutron_dynamic_routing/db/migration/alembic_migrations/versions/EXPAND_HEAD @@ -1 +1 @@ -f399fa0f5f25 +738d0ae1984e diff --git a/neutron_dynamic_routing/db/migration/alembic_migrations/versions/xena/expand/738d0ae1984e_bgpaas_enh.py b/neutron_dynamic_routing/db/migration/alembic_migrations/versions/xena/expand/738d0ae1984e_bgpaas_enh.py new file mode 100644 index 00000000..b842ed79 --- /dev/null +++ b/neutron_dynamic_routing/db/migration/alembic_migrations/versions/xena/expand/738d0ae1984e_bgpaas_enh.py @@ -0,0 +1,42 @@ +# Copyright 2016 Huawei Technologies India Pvt Limited. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# 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. +# + +"""bgpaas enh + +Revision ID: 738d0ae1984e +Revises: f399fa0f5f25 +Create Date: 2021-05-21 10:25:57.492514 + +""" + +from alembic import op +import sqlalchemy as sa + +from neutron_lib.db import constants + + +def upgrade(): + op.create_table( + 'bgp_speaker_router_associations', + sa.Column('id', sa.String(length=constants.UUID_FIELD_SIZE), + nullable=False), + sa.Column('project_id', sa.String(length=255)), + sa.Column('bgp_speaker_id', sa.String(length=36), + sa.ForeignKey('bgp_speakers.id'), nullable=False), + sa.Column('router_id', sa.String(length=36), + sa.ForeignKey('routers.id'), nullable=False), + sa.Column('advertise_extra_routes', sa.Boolean, nullable=False), + sa.Column('status', sa.String(16)), + ) diff --git a/neutron_dynamic_routing/extensions/bgp.py b/neutron_dynamic_routing/extensions/bgp.py index 416b7b46..0beeca42 100644 --- a/neutron_dynamic_routing/extensions/bgp.py +++ b/neutron_dynamic_routing/extensions/bgp.py @@ -145,6 +145,16 @@ class BgpSpeakerNetworkBindingError(n_exc.Conflict): "%(bgp_speaker_id)s.") +class BgpSpeakerRouterNotAssociated(n_exc.NotFound): + message = _("Router %(router_id)s is not associated with " + "BGP speaker %(bgp_speaker_id)s.") + + +class BgpSpeakerRouterBindingError(n_exc.Conflict): + message = _("Router %(router_id)s is already bound to BgpSpeaker " + "%(bgp_speaker_id)s.") + + class NetworkNotBound(n_exc.NotFound): message = _("Network %(network_id)s is not bound to a BgpSpeaker.") diff --git a/neutron_dynamic_routing/extensions/bgp_associations.py b/neutron_dynamic_routing/extensions/bgp_associations.py new file mode 100644 index 00000000..d266a008 --- /dev/null +++ b/neutron_dynamic_routing/extensions/bgp_associations.py @@ -0,0 +1,70 @@ +# Copyright 2016 Hewlett Packard Development Coompany LP +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# 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. +# +import itertools + +from neutron_lib import exceptions as n_exc +from neutron_lib.api import extensions as api_extensions +from neutron_lib.api.definitions import bgp +from neutron_lib.api.definitions import bgp_associations as bgp_ext +from neutron_lib.plugins import directory + +from neutron.api import extensions +from neutron.api.v2 import resource_helper as rh +from neutron.api.v2 import base + +from neutron_dynamic_routing._i18n import _ + + +class Bgp_associations(api_extensions.APIExtensionDescriptor): + + api_definition = bgp_ext + + @classmethod + def get_resources(cls): + special_mappings = {'bgp-speakers': 'bgp-speaker'} + plural_mappings = rh.build_plural_mappings( + special_mappings, itertools.chain( + bgp_ext.RESOURCE_ATTRIBUTE_MAP, + bgp_ext.SUB_RESOURCE_ATTRIBUTE_MAP)) + + resources = rh.build_resource_info( + plural_mappings, + bgp_ext.RESOURCE_ATTRIBUTE_MAP, + bgp.ALIAS) + plugin = directory.get_plugin(bgp.ALIAS) + + for sub_resource in bgp_ext.SUB_RESOURCE_ATTRIBUTE_MAP: + parent = bgp_ext.SUB_RESOURCE_ATTRIBUTE_MAP[ + sub_resource].get('parent') + params = bgp_ext.SUB_RESOURCE_ATTRIBUTE_MAP[ + sub_resource].get('parameters') + controller = base.create_resource(sub_resource, sub_resource[:-1], + plugin, params, allow_bulk=True, + parent=parent, + allow_pagination=True, + allow_sorting=True) + resource = extensions.ResourceExtension( + sub_resource, + controller, parent, + attr_map=params) + resources.append(resource) + + return resources + + +#Bgp Association Exceptions +class BgpSpeakerRouterAssociationNotFound(n_exc.NotFound): + message = _("BGP speaker Router Association %(id)s could not be found.") diff --git a/neutron_dynamic_routing/policies/bgp_router_association.py b/neutron_dynamic_routing/policies/bgp_router_association.py new file mode 100644 index 00000000..6a85fd9d --- /dev/null +++ b/neutron_dynamic_routing/policies/bgp_router_association.py @@ -0,0 +1,74 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# 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_policy import policy + +from neutron_dynamic_routing.policies import base + + +rules = [ + policy.DocumentedRuleDefault( + 'create_bgp_speaker_router_association', + base.RULE_ADMIN_ONLY, + 'Create a BGP speaker router association', + [ + { + 'method': 'POST', + 'path': '/bgp-speakers/{bgp_speaker_id}/router_associations', + }, + ] + ), + policy.DocumentedRuleDefault( + 'update_bgp_speaker_router_association', + base.RULE_ADMIN_ONLY, + 'Update a BGP speaker router association', + [ + { + 'method': 'PUT', + 'path': '/bgp-speakers/{bgp_speaker_id}/router_associations/' + '{router_association_id}', + }, + ] + ), + policy.DocumentedRuleDefault( + 'delete_bgp_speaker_router_association', + base.RULE_ADMIN_ONLY, + 'Delete a BGP speaker router association', + [ + { + 'method': 'DELETE', + 'path': '/bgp-speakers/{bgp_speaker_id}/router_associations/' + '{router_association_id}', + }, + ] + ), + policy.DocumentedRuleDefault( + 'get_bgp_speaker_router_association', + base.RULE_ADMIN_ONLY, + 'Get BGP speaker Router Associations', + [ + { + 'method': 'GET', + 'path': '/bgp-speakers/{bgp_speaker_id}/router_associations', + }, + { + 'method': 'GET', + 'path': '/bgp-speakers/{bgp_speaker_id}/router_associations/' + '{router_association_id}', + }, + ] + ), +] + + +def list_rules(): + return rules diff --git a/neutron_dynamic_routing/policies/bgp_speaker.py b/neutron_dynamic_routing/policies/bgp_speaker.py index cc72468e..3297a341 100644 --- a/neutron_dynamic_routing/policies/bgp_speaker.py +++ b/neutron_dynamic_routing/policies/bgp_speaker.py @@ -109,6 +109,39 @@ rules = [ }, ] ), + policy.DocumentedRuleDefault( + 'add_gateway_router', + base.RULE_ADMIN_ONLY, + 'Add a gateway router to a BGP speaker', + [ + { + 'method': 'PUT', + 'path': '/bgp-speakers/{id}/add_gateway_router', + }, + ] + ), + policy.DocumentedRuleDefault( + 'remove_gateway_router', + base.RULE_ADMIN_ONLY, + 'Remove a gateway router from a BGP speaker', + [ + { + 'method': 'PUT', + 'path': '/bgp-speakers/{id}/remove_gateway_router', + }, + ] + ), + policy.DocumentedRuleDefault( + 'get_routes', + base.RULE_ADMIN_ONLY, + 'Get advertised and learned routes of a BGP speaker', + [ + { + 'method': 'GET', + 'path': '/bgp-speakers/{id}/get_routes', + }, + ] + ), policy.DocumentedRuleDefault( 'get_advertised_routes', base.RULE_ADMIN_ONLY, diff --git a/neutron_dynamic_routing/services/bgp/bgp_plugin.py b/neutron_dynamic_routing/services/bgp/bgp_plugin.py index 20e56321..2037f9cc 100644 --- a/neutron_dynamic_routing/services/bgp/bgp_plugin.py +++ b/neutron_dynamic_routing/services/bgp/bgp_plugin.py @@ -15,6 +15,7 @@ from netaddr import IPAddress from neutron_lib.api.definitions import portbindings +from neutron_lib.api.definitions import bgp_associations from neutron_lib.callbacks import events from neutron_lib.callbacks import registry from neutron_lib.callbacks import resources @@ -46,7 +47,8 @@ class BgpPlugin(service_base.ServicePluginBase, supported_extension_aliases = [bgp_ext.BGP_EXT_ALIAS, dras_ext.BGP_DRAGENT_SCHEDULER_EXT_ALIAS, - bgp_4byte_asn.BGP_4BYTE_ASN_EXT_ALIAS] + bgp_4byte_asn.BGP_4BYTE_ASN_EXT_ALIAS, + bgp_associations.ALIAS] def __init__(self): super(BgpPlugin, self).__init__() @@ -220,6 +222,38 @@ class BgpPlugin(service_base.ServicePluginBase, bgp_speaker_id, network_info) + def create_bgp_speaker_router_association(self, context, bgp_speaker_id, + router_association): + return super(BgpPlugin, self).create_bgp_speaker_router_association( + context, bgp_speaker_id, + router_association) + + def delete_bgp_speaker_router_association(self, context, id, + bgp_speaker_id): + super(BgpPlugin, self).delete_bgp_speaker_router_association(context, + id) + + def get_bgp_speaker_router_association(self, context, id, bgp_speaker_id, + fields=None): + return super(BgpPlugin, self).get_bgp_speaker_router_association( + context, id, fields=fields) + + def get_bgp_speaker_router_associations( + self, context, bgp_speaker_id, + filters=None, fields=None, sorts=None, + limit=None, marker=None, + page_reverse=False): + return super(BgpPlugin, self).get_bgp_speaker_router_associations( + context, bgp_speaker_id, + fields=fields, + filters=filters, sorts=sorts, + limit=limit, marker=marker, + page_reverse=page_reverse) + + def get_routes(self, context, bgp_speaker_id): + return super(BgpPlugin, self).get_routes(context, + bgp_speaker_id) + def get_advertised_routes(self, context, bgp_speaker_id): return super(BgpPlugin, self).get_advertised_routes(context, bgp_speaker_id) diff --git a/neutron_dynamic_routing/services/bgp/common/constants.py b/neutron_dynamic_routing/services/bgp/common/constants.py index 0ca122d4..4dd91215 100644 --- a/neutron_dynamic_routing/services/bgp/common/constants.py +++ b/neutron_dynamic_routing/services/bgp/common/constants.py @@ -26,3 +26,7 @@ SUPPORTED_AUTH_TYPES = ['none', 'md5'] MIN_ASNUM = 1 MAX_ASNUM = 65535 MAX_4BYTE_ASNUM = 4294967295 + +#Supported association status +STATUS_DOWN = 'DOWN' +STATUS_ACTIVE = 'ACTIVE' diff --git a/neutron_dynamic_routing/tests/unit/db/test_bgp_db.py b/neutron_dynamic_routing/tests/unit/db/test_bgp_db.py index 71c7579c..f8586c4f 100644 --- a/neutron_dynamic_routing/tests/unit/db/test_bgp_db.py +++ b/neutron_dynamic_routing/tests/unit/db/test_bgp_db.py @@ -19,6 +19,7 @@ import netaddr from neutron.db import l3_dvr_ha_scheduler_db from neutron.tests.unit.extensions import test_l3 from neutron.tests.unit.plugins.ml2 import test_plugin +from neutron_lib.api.definitions import bgp_associations as bgp_assocs from neutron_lib.api.definitions import external_net from neutron_lib.api.definitions import portbindings from neutron_lib import constants as n_const @@ -29,6 +30,7 @@ from oslo_config import cfg from oslo_utils import uuidutils from neutron_dynamic_routing.extensions import bgp +from neutron_dynamic_routing.extensions import bgp_associations as bgp_asso_ext from neutron_dynamic_routing.services.bgp import bgp_plugin _uuid = uuidutils.generate_uuid @@ -48,7 +50,7 @@ class BgpEntityCreationMixin(object): def bgp_speaker(self, ip_version, local_as, name='my-speaker', advertise_fip_host_routes=True, advertise_tenant_networks=True, - networks=None, peers=None): + networks=None, peers=None, router_id=None): data = {'ip_version': ip_version, ADVERTISE_FIPS_KEY: advertise_fip_host_routes, 'advertise_tenant_networks': advertise_tenant_networks, @@ -67,6 +69,12 @@ class BgpEntityCreationMixin(object): for peer_id in peers: self.bgp_plugin.add_bgp_peer(self.context, bgp_speaker_id, {'bgp_peer_id': peer_id}) + if router_id: + self.bgp_plugin.create_bgp_speaker_router_association( + self.context, bgp_speaker_id, + {'router_association': + {'router_id': router_id, + 'advertise_extra_routes': True}}) yield self.bgp_plugin.get_bgp_speaker(self.context, bgp_speaker_id) @@ -487,6 +495,64 @@ class BgpTests(BgpEntityCreationMixin): self.assertEqual(network_id, speaker['networks'][0]) + def test_create_bgp_speaker_router_association(self): + tenant_id = _uuid() + scope_data = {'tenant_id': tenant_id, 'ip_version': 4, + 'shared': True, 'name': 'bgp-scope'} + scope = self.plugin.create_address_scope( + self.context, + {'address_scope': scope_data}) + with self.router_with_external_and_tenant_networks( + tenant_id=tenant_id, + address_scope=scope) as res,\ + self.bgp_speaker(scope_data['ip_version'], 1234) as speaker: + router, *_ = res + router_id = router['id'] + router_assoc = self.bgp_plugin\ + .create_bgp_speaker_router_association( + self.context, speaker['id'], + {bgp_assocs.ROUTER_ASSOCIATION: + {'router_id': router_id, + 'advertise_extra_routes': True}}) + new_speaker = self.bgp_plugin.get_bgp_speaker(self.context, + speaker['id']) + router_binding = self.bgp_plugin\ + .get_bgp_speaker_router_association( + self.context, router_assoc['id'], + speaker['id']) + self.assertEqual(1, len(new_speaker['router_associations'])) + self.assertIsNotNone(router_binding['id']) + self.assertTrue( + router_binding['id'] in new_speaker['router_associations']) + self.assertEqual(router_binding['bgp_speaker_id'], speaker['id']) + + def test_delete_bgp_speaker_router_association(self): + tenant_id = _uuid() + scope_data = {'tenant_id': tenant_id, 'ip_version': 4, + 'shared': True, 'name': 'bgp-scope'} + scope = self.plugin.create_address_scope( + self.context, + {'address_scope': scope_data}) + with self.router_with_external_and_tenant_networks( + tenant_id=tenant_id, + address_scope=scope) as res: + router, *_ = res + router_id = router['id'] + with self.bgp_speaker(scope_data['ip_version'], 1234, + router_id=router_id) as speaker: + self.bgp_plugin.delete_bgp_speaker_router_association( + self.context, + speaker['router_associations'][0], + speaker['id']) + new_speaker = self.bgp_plugin.get_bgp_speaker(self.context, + speaker['id']) + self.assertEqual(0, len(new_speaker['router_associations'])) + self.assertRaises( + bgp_asso_ext.BgpSpeakerRouterAssociationNotFound, + self.bgp_plugin.get_bgp_speaker_router_association, + self.context, speaker['router_associations'][0], + speaker['id']) + def test_create_bgp_peer_md5_auth_no_password(self): bgp_peer = {'bgp_peer': {'auth_type': 'md5', 'password': None}} self.assertRaises(bgp.InvalidBgpPeerMd5Authentication,