<configfile finalname="${config.configfile.directory}/15-groupbasedpolicy-netconf.xml">mvn:org.opendaylight.groupbasedpolicy/netconf-renderer/{{VERSION}}/xml/config</configfile>
</feature>
-
<!--
The Neutron provider
-->
<feature name='odl-groupbasedpolicy-neutronmapper' version='${project.version}' description='OpenDaylight :: groupbasedpolicy :: Neutron Mapper mapps neutron APIs to GBP APIs '>
<feature version="${neutron.version}">odl-neutron-service</feature>
<feature version="${project.version}">odl-groupbasedpolicy-base</feature>
- <feature version="${project.version}">odl-groupbasedpolicy-ofoverlay</feature>
<bundle>mvn:org.opendaylight.neutron/dummyprovider/{{VERSION}}</bundle>
<bundle>mvn:org.opendaylight.groupbasedpolicy/neutron-mapper/{{VERSION}}</bundle>
- <bundle>mvn:org.opendaylight.groupbasedpolicy/neutron-ovsdb/{{VERSION}}</bundle>
<configfile finalname="${config.configfile.directory}/15-neutron-mapper.xml">mvn:org.opendaylight.groupbasedpolicy/neutron-mapper/{{VERSION}}/xml/config</configfile>
+ </feature>
+
+ <!--
+ The Neutron provider and OFOVERLAY renderer
+ -->
+ <feature name='odl-groupbasedpolicy-neutron-and-ofoverlay' version='${project.version}' description='OpenDaylight :: groupbasedpolicy :: Neutron Mapper mapps neutron APIs to GBP APIs '>
+ <feature version="${project.version}">odl-groupbasedpolicy-ofoverlay</feature>
+ <feature version="${project.version}">odl-groupbasedpolicy-neutronmapper</feature>
+ <bundle>mvn:org.opendaylight.groupbasedpolicy/neutron-ovsdb/{{VERSION}}</bundle>
<configfile finalname="${config.configfile.directory}/15-neutron-ovsdb.xml">mvn:org.opendaylight.groupbasedpolicy/neutron-ovsdb/{{VERSION}}/xml/config</configfile>
</feature>
<value>src/app/gbp/common/gbp.css</value>
<value>src/app/gbp/vendor/angular-material/angular-material.css</value>
<value>src/app/gbp/vendor/angular-material-data-table/dist/md-data-table.min.css</value>
+ <value>src/app/gbp/vendor/roboto-fontface/css/roboto-fontface.css</value>
</list>
</property>
</bean>
.gbpUiWrapper.flt-r {
float: right;
}
+
+/* LAYOUT */
+.layout-padding-lr15 {
+ padding: 0 15px;
+}
+
+/* TABLES */
+.gbpUiWrapper .md-table span {
+ color: rgba(0,0,0,.87);
+}
+
+/* BUTTONS */
+.gbpUiWrapper button.md-primary span {
+ color: rgb(33,150,243);
+}
'angular-animate',
'angular-aria',
'angular-material',
- 'angular-material-data-table'], function () {
+ 'angular-material-data-table',
+ 'angular-messages'], function () {
var gbp = angular.module('app.gbp',
[
- 'app.core', 'ui.router.state', 'restangular', 'ngAnimate', 'ngAria', 'ngMaterial', 'md.data.table',
+ 'app.core', 'ui.router.state', 'restangular', 'ngAnimate', 'ngAria', 'ngMaterial', 'md.data.table', 'ngMessages'
]);
gbp.register = gbp; // for adding services, controllers, directives etc. to angular module before bootstrap
NavHelperProvider.addControllerUrl('app/gbp/contract/contract.controller');
NavHelperProvider.addControllerUrl('app/gbp/epg/epg.controller');
NavHelperProvider.addControllerUrl('app/gbp/policy/policy.controller');
+ NavHelperProvider.addControllerUrl('app/gbp/tenant/add-tenant.controller');
NavHelperProvider.addControllerUrl('app/gbp/tenant/tenant.controller');
NavHelperProvider.addToMenu('gbp', {
'icon': 'icon-level-down',
'page': {
'title': 'GBP',
- 'description': 'GBP ui',
- },
+ 'description': 'GBP ui'
+ }
});
var access = routingConfig.accessLevels;
// access: access.public,
views: {
'content': {
- templateUrl: 'src/app/gbp/common/views/root.tpl.html',
+ templateUrl: 'src/app/gbp/common/views/root.tpl.html'
},
},
views: {
'': {
controller: 'RootGbpCtrl',
- templateUrl: 'src/app/gbp/common/views/index.tpl.html',
+ templateUrl: 'src/app/gbp/common/views/index.tpl.html'
},
},
});
'angular-aria': 'app/gbp/vendor/angular-aria/angular-aria.min',
'lodash': 'app/gbp/vendor/lodash/dist/lodash.min',
'angular-material-data-table': 'app/gbp/vendor/angular-material-data-table/dist/md-data-table.min',
+ 'angular-messages' : 'app/gbp/vendor/angular-messages/angular-messages.min'
},
shim: {
'angular-material': ['angular'],
'angular-animate': ['angular'],
'angular-aria': ['angular'],
'angular-material-data-table': ['angular', 'angular-material'],
+ 'angular-messages' : ['angular'],
},
});
--- /dev/null
+define([
+ 'app/gbp/tenant/tenant.service'
+], function () {
+ 'use strict';
+
+ angular.module('app.gbp').controller('AddTenantController', AddTenantController);
+
+ AddTenantController.$inject = ['$mdDialog', '$scope', 'TenantService'];
+ /* @ngInject */
+ function AddTenantController($mdDialog, $scope, TenantService) {
+ /* properties */
+ $scope.tenant = TenantService.createObject();
+
+ /* methods */
+ $scope.closeDialog = closeDialog;
+ $scope.save = save;
+
+ /* Implementations */
+
+ function closeDialog(){
+ $mdDialog.cancel();
+ }
+
+ function save() {
+ $scope.tenant.put(function(data) {
+ $scope.closeDialog();
+ }, function(err) {
+ } );
+ }
+ }
+});
--- /dev/null
+<md-dialog ng-cloak>
+ <form name="tenantForm">
+ <md-toolbar>
+ <div class="md-toolbar-tools">
+ <h2>Tenant</h2>
+ <span flex></span>
+ <md-button ng-click="closeDialog()" class="md-button">Close dialog</md-button>
+ </div>
+ </md-toolbar>
+ <md-dialog-content style="width:350px;">
+ <div layout="column" class="layout-padding-lr15">
+ <div layout="row">
+ <md-input-container flex>
+ <label>Id</label>
+ <input name="id" ng-model="tenant.data.id" ng-required="true">
+ <div ng-messages="tenantForm.id.$error" md-auto-hide="false">
+ <div ng-message="required">Required field</div>
+ </div>
+ </md-input-container>
+ <md-input-container flex>
+ <label>Name</label>
+ <input name="name" ng-model="tenant.data.name" ng-required="true">
+ <div ng-messages="tenantForm.name.$error" md-auto-hide="false">
+ <div ng-message="required">Required field</div>
+ </div>
+ </md-input-container>
+ </div>
+ <div layout="row">
+ <md-input-container flex>
+ <label>Description</label>
+ <input name="description" ng-model="tenant.data.description">
+ </md-input-container>
+ </div>
+ </div>
+ </md-dialog-content>
+ <md-dialog-actions layout="row">
+ <span flex></span>
+ <md-button ng-click="closeDialog()" class="md-primary">
+ Close
+ </md-button>
+ <md-button ng-click="save()" style="margin-right:20px;" ng-disabled="tenantForm.$invalid" class="md-primary">
+ Save
+ </md-button>
+ </md-dialog-actions>
+ </form>
+</md-dialog>
angular.module('app.gbp').controller('TenantController', TenantController);
- TenantController.$inject = ['$scope', 'TenantService', 'TenantListService'];
+ TenantController.$inject = ['$mdDialog', '$scope', 'TenantListService'];
/* @ngInject */
- function TenantController($scope, TenantService, TenantListService) {
- $scope.tenantsTableQuery = {
- order: "data.id",
- limit: 25,
- page: 1,
- options: [25, 50, 100],
- filter: ''
- };
-
+ function TenantController($mdDialog, $scope, TenantListService) {
+ /* properties */
$scope.tenants = TenantListService.createList();
- $scope.tenants.get('config');
+ $scope.tenantsTableQuery = {};
+
+ /* methods */
+ $scope.getTenantList = getTenantList;
+ $scope.openTenantDialog = openTenantDialog;
+
+ init();
+
+ /* Implementations */
+
+ /**
+ * fills $scope.tenants array with data from data store
+ */
+ function getTenantList() {
+ $scope.tenants.get('config');
+ }
+
+ /**
+ * Initializing function
+ */
+ function init() {
+ $scope.tenantsTableQuery = {
+ order: "data.id",
+ limit: 25,
+ page: 1,
+ options: [25, 50, 100],
+ filter: ''
+ };
+
+ getTenantList();
+ }
+
+ function openTenantDialog() {
+ $mdDialog.show({
+ clickOutsideToClose: true,
+ controller: 'AddTenantController',
+ preserveScope: true,
+ templateUrl: 'src/app/gbp/tenant/dialog-add-tenant.tpl.html',
+ parent: angular.element(document.body),
+ scope: $scope,
+ locals: {
+ //policy: $scope.selectedObjects.policy
+ }
+ });
+ }
+
+
}
});
/* methods */
this.setData = setData;
this.get = get;
+ this.put = put;
/* Implementation */
/**
self.setData(data.tenant[0]);
});
}
+
+ function put(successCallback) {
+ var self = this;
+
+ var restObj = Restangular.one('restconf').one('config').one('policy:tenants').one('tenant')
+ .one(self.data.id),
+ dataObj = {tenant: [self.data]};
+
+ return restObj.customPUT(dataObj).then(function(data) {
+ successCallback(data);
+ }, function(res) {
+
+ });
+ }
}
/**
<section flex layout="column">
- <md-table-container ng-if="tenants.data.length">
+ <div flex layout="row">
+ <md-button ng-click="openTenantDialog()" class="md-primary">Add</md-button>
+ <md-button ng-click="getTenantList()" class="md-primary">Reload</md-button>
+ </div>
+ <md-table-container>
<table md-table>
<thead md-head md-order="tenantsTableQuery.order">
<tr md-row>
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.NetworkDomain;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
+import com.google.common.collect.HashBasedTable;
+import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.SetMultimap;
+import com.google.common.collect.Table;
/**
* Wrap some convenient indexes around a {@link Tenant} object
new HashMap<>();
private final Map<ContractId, Contract> contracts =
new HashMap<>();
- private final Map<String, NetworkDomain> networkDomains =
- new HashMap<>();
+ private final Table<String, Class<? extends NetworkDomainId>, NetworkDomain> networkDomains = HashBasedTable.<String, Class<? extends NetworkDomainId>, NetworkDomain>create();
private final Map<ClassifierName, ClassifierInstance> classifiers =
new HashMap<>();
private final Map<ActionName, ActionInstance> actions =
private void processForwardingContext(ForwardingContext fwCtx) {
if (fwCtx.getL3Context() != null) {
for (L3Context c : fwCtx.getL3Context()) {
- networkDomains.put(c.getId().getValue(), c);
+ networkDomains.put(c.getId().getValue(), L3ContextId.class, c);
}
}
if (fwCtx.getL2BridgeDomain() != null) {
for (L2BridgeDomain c : fwCtx.getL2BridgeDomain()) {
- networkDomains.put(c.getId().getValue(), c);
+ networkDomains.put(c.getId().getValue(), L2BridgeDomainId.class, c);
}
}
if (fwCtx.getL2FloodDomain() != null) {
for (L2FloodDomain c : fwCtx.getL2FloodDomain()) {
- networkDomains.put(c.getId().getValue(), c);
+ networkDomains.put(c.getId().getValue(), L2FloodDomainId.class, c);
}
}
if (fwCtx.getSubnet() != null) {
for (Subnet s : fwCtx.getSubnet()) {
- networkDomains.put(s.getId().getValue(), s);
+ networkDomains.put(s.getId().getValue(), SubnetId.class, s);
Set<SubnetId> sset = subnetMap.get(s.getParent().getValue());
if (sset == null) {
subnetMap.put(s.getParent().getValue(), sset = new HashSet<SubnetId>());
public Set<ExternalImplicitGroup> getExternalImplicitGroups() {
return externalImplicitGroups;
}
-
- /**
- * Look up the network domain specified
- * @param id the {@link NetworkDomainId}
- * @return the {@link NetworkDomain} if it exists, or <code>null</code>
- * otherwise
- */
- public NetworkDomain getNetworkDomain(NetworkDomainId id) {
- return networkDomains.get(id.getValue());
- }
/**
* Look up the endpoint group specified
* @param id the {@link EndpointGroupId}
- * @return the {@link EndpointGroup} if it exists, or <code>null</code>
+ * @return the {@link EndpointGroup} if it exists, or <code>null</code>
* otherwise
*/
public EndpointGroup getEndpointGroup(EndpointGroupId id) {
return endpointGroups.get(id);
}
-
+
/**
* Look up the contract specified
* @param id the {@link ContractId}
- * @return the {@link Contract} if it exists, or <code>null</code>
+ * @return the {@link Contract} if it exists, or <code>null</code>
* otherwise
*/
public Contract getContract(ContractId id) {
return contracts.get(id);
}
-
+
/**
* Look up the classifier instance specified
* @param name the {@link ClassifierName}
- * @return the {@link ClassifierInstance} if it exists, or <code>null</code>
+ * @return the {@link ClassifierInstance} if it exists, or <code>null</code>
* otherwise
*/
public ClassifierInstance getClassifier(ClassifierName name) {
/**
* Look up the classifier instance specified
* @param name the {@link ActionName}
- * @return the {@link ActionInstance} if it exists, or <code>null</code>
+ * @return the {@link ActionInstance} if it exists, or <code>null</code>
* otherwise
*/
public ActionInstance getAction(ActionName name) {
}
/**
- * Get the layer 3 context for the specified network domain by walking
+ * Get the layer 3 context
+ * @param id the {@link L3ContextId}
+ * @return the {@link L3Context} or <code>null</code> if it does not exist
+ */
+ public L3Context resolveL3Context(L3ContextId id) {
+ return resolveDomain(L3Context.class, id);
+ }
+
+ /**
+ * Get the layer 3 context for the specified l2 bridge domain by walking
* up the hierarchy
- * @param id the {@link NetworkDomainId} for the network domain
+ * @param id the {@link L2BridgeDomainId}
* @return the {@link L3Context} or <code>null</code> if it does not exist
*/
- public L3Context resolveL3Context(NetworkDomainId id) {
+ public L3Context resolveL3Context(L2BridgeDomainId id) {
return resolveDomain(L3Context.class, id);
}
/**
- * Get the layer 2 bridge domain for the specified network domain by walking
+ * Get the layer 3 context for the specified l2 flood domain by walking
* up the hierarchy
- * @param id the {@link NetworkDomainId} for the network domain
- * @return the {@link L2BridgeDomain} or <code>null</code> if it does
- * not exist
+ * @param id the {@link L2FloodDomainId}
+ * @return the {@link L3Context} or <code>null</code> if it does not exist
+ */
+ public L3Context resolveL3Context(L2FloodDomainId id) {
+ return resolveDomain(L3Context.class, id);
+ }
+
+ /**
+ * Get the layer 2 bridge domain
+ * @param id the {@link L2BridgeDomainId}
+ * @return the {@link L2BridgeDomain} or <code>null</code> if it does not exist
*/
- public L2BridgeDomain resolveL2BridgeDomain(NetworkDomainId id) {
+ public L2BridgeDomain resolveL2BridgeDomain(L2BridgeDomainId id) {
return resolveDomain(L2BridgeDomain.class, id);
}
/**
- * Get the layer 2 flood domain for the specified network domain by walking
+ * Get the layer 2 bridge domain for the specified l2 flood domain by walking
* up the hierarchy
- * @param id the {@link NetworkDomainId} for the network domain
- * @return the {@link L2FloodDomain} or <code>null</code> if it does
- * not exist
+ * @param id the {@link L2FloodDomainId}
+ * @return the {@link L2BridgeDomain} or <code>null</code> if it does not exist
+ */
+ public L2BridgeDomain resolveL2BridgeDomain(L2FloodDomainId id) {
+ return resolveDomain(L2BridgeDomain.class, id);
+ }
+
+ /**
+ * Get the layer 2 flood domain
+ * @param id the {@link L2FloodDomainId}
+ * @return the {@link L2FloodDomain} or <code>null</code> if it does not exist
*/
- public L2FloodDomain resolveL2FloodDomain(NetworkDomainId id) {
+ public L2FloodDomain resolveL2FloodDomain(L2FloodDomainId id) {
return resolveDomain(L2FloodDomain.class, id);
}
/**
* Get the subnet based on it's ID. Since subnet is on the bottom
- * of the forwarding hierarchy, there is no other underlying domain
- * from which {@link Subnet} could be resolved. That is why the
- * argument refers directly to {@link SubnetId} and not
- * {@link NetworkDomainId}
+ * of the forwarding hierarchy, there is no other upstream domain
+ * to resolved.
*
- * @param id of the {@link Subnet}
+ * @param id of the {@link SubnetId}
* @return the {@link Subnet} or <code>null</code> if it does
* not exist
*/
Set<SubnetId> cursset = subnetMap.get(id.getValue());
if (cursset != null)
sset.addAll(cursset);
- NetworkDomain d = networkDomains.get(id.getValue());
+ NetworkDomain d = networkDomains.get(id.getValue(), id.getClass());
if (d == null) break;
if (d instanceof Subnet) {
id = ((Subnet)d).getParent();
sset.add(((Subnet) d).getId());
- }
+ }
else if (d instanceof L2BridgeDomain)
id = ((L2BridgeDomain)d).getParent();
else if (d instanceof L2FloodDomain)
return Collections2.transform(sset, new Function<SubnetId, Subnet>() {
@Override
public Subnet apply(SubnetId input) {
- return (Subnet)networkDomains.get(input.getValue());
+ return (Subnet)networkDomains.get(input.getValue(), SubnetId.class);
}
});
}
// ******
// Object
// ******
-
+
@Override
public int hashCode() {
return hashCode;
// Implementation
// **************
- private <C extends NetworkDomain> C resolveDomain(Class<C> domainClass,
- NetworkDomainId id) {
- HashSet<NetworkDomainId> visited = new HashSet<>();
+ @SuppressWarnings("unchecked")
+ private <C extends NetworkDomain, I extends NetworkDomainId> C resolveDomain(Class<C> domainClass, I id) {
+ SetMultimap<I, Class<? extends NetworkDomainId>> visited = HashMultimap.create();
while (id != null) {
- if (visited.contains(id)) return null;
- visited.add(id);
- NetworkDomain d = networkDomains.get(id.getValue());
- if (d == null) return null;
- if (domainClass.isInstance(d)) return domainClass.cast(d);
- if (d instanceof Subnet)
- id = ((Subnet)d).getParent();
- else if (d instanceof L2BridgeDomain)
- id = ((L2BridgeDomain)d).getParent();
- else if (d instanceof L2FloodDomain)
- id = ((L2FloodDomain)d).getParent();
- else
+ // TODO condition
+ if (visited.get(id) != null && visited.containsEntry(id, id.getClass())) {
+ return null;
+ }
+ visited.put(id, id.getClass());
+ NetworkDomain d = networkDomains.get(id.getValue(), id.getClass());
+ if (d == null)
+ return null;
+ if (domainClass.isInstance(d))
+ return domainClass.cast(d);
+ if (d instanceof L2BridgeDomain) {
+ id = (I) ((L2BridgeDomain) d).getParent();
+ } else if (d instanceof L2FloodDomain) {
+ id = (I) ((L2FloodDomain) d).getParent();
+ } else {
id = null;
+ }
}
return null;
}
// UUID type from ietf-yang-types@2013-07-15
typedef uuid {
+
+ status deprecated;
+
type string {
pattern '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-'
+ '[0-9a-fA-F]{4}-[0-9a-fA-F]{12}';
type policy-name;
}
- container resolved-policy {
- list rule-group-with-renderer-endpoint-participation {
+ container provided-resolved-policy {
+ list provided-rule-group {
description "A specific policy rule group that apply to pair of endpoints.
+ Renderer Endpoint is a provider of the rule group.
Entire rule-group is located on /renderers/renderer/renderer-policy/configuration/rule-groups/rule-group";
- key "tenant-id contract-id subject-name renderer-endpoint-participation";
+ key "tenant-id contract-id subject-name";
+ uses resolved-policy:has-subject-key;
+ }
+ }
+
+ container consumed-resolved-policy {
+ list consumed-rule-group {
+ description "A specific policy rule group that apply to pair of endpoints.
+ Renderer Endpoint is a consumer of the rule group.
+ Entire rule-group is located on /renderers/renderer/renderer-policy/configuration/rule-groups/rule-group";
+ key "tenant-id contract-id subject-name";
uses resolved-policy:has-subject-key;
- leaf renderer-endpoint-participation {
- type endpoint-policy-participation;
- }
}
}
.build();
IndexedTenant it = new IndexedTenant(t);
- assertNotNull(it.getNetworkDomain(sid));
+ assertNotNull(it.resolveSubnet(sid));
Collection<Subnet> sns = it.resolveSubnets(sid);
assertTrue(sns.contains(s));
assertTrue(sns.contains(s2));
- assertEquals(l3id, it.resolveL3Context(sid).getId());
- assertEquals(bdid, it.resolveL2BridgeDomain(sid).getId());
- assertEquals(fdid, it.resolveL2FloodDomain(sid).getId());
+ assertEquals(l3id, it.resolveL3Context(fdid).getId());
+ assertEquals(bdid, it.resolveL2BridgeDomain(fdid).getId());
+ assertEquals(fdid, it.resolveL2FloodDomain(fdid).getId());
}
@Test
when(policy.getContract()).thenReturn(contractList);
ContractId contractId = mock(ContractId.class);
when(contract.getId()).thenReturn(contractId);
-
- L3Context l3Context = mock(L3Context.class);
- List<L3Context> l3ContextList = Arrays.asList(l3Context);
- when(fwCtx.getL3Context()).thenReturn(l3ContextList);
- L3ContextId l3ContextId = mock(L3ContextId.class);
- when(l3Context.getId()).thenReturn(l3ContextId);
- String l3ContextValue = "contextID";
- when(l3ContextId.getValue()).thenReturn(l3ContextValue);
-
- L2BridgeDomain l2BridgeDomain = mock(L2BridgeDomain.class);
- List<L2BridgeDomain> l2BridgeDomainList = Arrays.asList(l2BridgeDomain);
- when(fwCtx.getL2BridgeDomain()).thenReturn(l2BridgeDomainList);
- L2BridgeDomainId l2BridgeDomainId = mock(L2BridgeDomainId.class);
- when(l2BridgeDomain.getId()).thenReturn(l2BridgeDomainId);
- String l2BridgeDomainIdValue = "bridgeDomainID";
- when(l2BridgeDomainId.getValue()).thenReturn(l2BridgeDomainIdValue);
-
- L2FloodDomain l2FloodDomain = mock(L2FloodDomain.class);
- List<L2FloodDomain> l2FloodDomainList = Arrays.asList(l2FloodDomain);
- when(fwCtx.getL2FloodDomain()).thenReturn(l2FloodDomainList);
- L2FloodDomainId l2FloodDomainId = mock(L2FloodDomainId.class);
- when(l2FloodDomain.getId()).thenReturn(l2FloodDomainId);
- String cValue = "floodDomainID";
- when(l2FloodDomainId.getValue()).thenReturn(cValue);
-
Subnet subnet = mock(Subnet.class);
List<Subnet> subnetList = Arrays.asList(subnet);
when(fwCtx.getSubnet()).thenReturn(subnetList);
when(subnet.getParent()).thenReturn(sParent);
String sParentValue = "sParentValue";
when(sParent.getValue()).thenReturn(sParentValue);
-
SubjectFeatureInstances sfi = mock(SubjectFeatureInstances.class);
when(policy.getSubjectFeatureInstances()).thenReturn(sfi);
-
ClassifierInstance ci = mock(ClassifierInstance.class);
List<ClassifierInstance> ciList = Arrays.asList(ci);
when(sfi.getClassifierInstance()).thenReturn(ciList);
ClassifierName ciName = mock(ClassifierName.class);
when(ci.getName()).thenReturn(ciName);
-
ActionInstance ai = mock(ActionInstance.class);
List<ActionInstance> actionList = Arrays.asList(ai);
when(sfi.getActionInstance()).thenReturn(actionList);
assertEquals(tenant, it.getTenant());
assertEquals(eg, it.getEndpointGroup(egId));
assertEquals(contract, it.getContract(contractId));
- assertEquals(l3Context, it.getNetworkDomain(l3ContextId));
- assertEquals(l2BridgeDomain, it.getNetworkDomain(l2BridgeDomainId));
- assertEquals(l2FloodDomain, it.getNetworkDomain(l2FloodDomainId));
assertEquals(ci, it.getClassifier(ciName));
assertEquals(ai, it.getAction(actionName));
}
</dependency>
<dependency>
<groupId>org.opendaylight.neutron</groupId>
- <artifactId>neutron-spi</artifactId>
+ <artifactId>model</artifactId>
<version>${neutron.version}</version>
</dependency>
<!-- testing dependencies -->
public java.lang.AutoCloseable createInstance() {
final NeutronMapper neutronMapper = new NeutronMapper(getDataBrokerDependency(), getRpcRegistryDependency());
LOG.info("Neutron mapper started.");
- return new AutoCloseable() {
+ return neutronMapper;
+ }
- @Override
- public void close() throws Exception {
- neutronMapper.close();
- }
- };
+ public static boolean isDebugEnabled() {
+ return true; // TODO add to config-subsystem
}
}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3AddressBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3GatewaysBuilder;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+public class EndpointRegistrator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(EndpointRegistrator.class);
+ private final EndpointService epService;
+
+ public EndpointRegistrator(EndpointService epService) {
+ this.epService = Preconditions.checkNotNull(epService);
+ }
+
+ public boolean registerEndpoint(RegisterEndpointInput regEndpointInput) {
+ try {
+ RpcResult<Void> rpcResult = epService.registerEndpoint(regEndpointInput).get();
+ if (!rpcResult.isSuccessful()) {
+ LOG.warn("Illegal state - registerEndpoint was not successful. Input of RPC: {}", regEndpointInput);
+ return false;
+ }
+ return true;
+ } catch (InterruptedException | ExecutionException e) {
+ LOG.error("registerEndpoint failed. {}", regEndpointInput, e);
+ return false;
+ }
+ }
+
+ public boolean unregisterEndpoint(UnregisterEndpointInput unregEndpointInput) {
+ try {
+ RpcResult<Void> rpcResult = epService.unregisterEndpoint(unregEndpointInput).get();
+ if (!rpcResult.isSuccessful()) {
+ LOG.warn("Illegal state - unregisterEndpoint was not successful. Input of RPC: {}", unregEndpointInput);
+ return false;
+ }
+ return true;
+ } catch (InterruptedException | ExecutionException e) {
+ LOG.error("unregisterEndpoint failed. {}", unregEndpointInput, e);
+ return false;
+ }
+ }
+
+ public boolean registerExternalL3PrefixEndpoint(IpPrefix ipPrefix, L3ContextId l3Context,
+ @Nullable IpAddress gatewayIp, TenantId tenantId) {
+ List<EndpointL3Gateways> l3Gateways = new ArrayList<EndpointL3Gateways>();
+ if (gatewayIp != null) {
+ EndpointL3Gateways l3Gateway =
+ new EndpointL3GatewaysBuilder().setIpAddress(gatewayIp).setL3Context(l3Context).build();
+ l3Gateways.add(l3Gateway);
+ }
+ RegisterL3PrefixEndpointInput registerL3PrefixEpRpcInput = new RegisterL3PrefixEndpointInputBuilder()
+ .setL3Context(l3Context)
+ .setIpPrefix(ipPrefix)
+ .setEndpointGroup(MappingUtils.EPG_EXTERNAL_ID)
+ .setTenant(tenantId)
+ .setEndpointL3Gateways(l3Gateways)
+ .setTimestamp(System.currentTimeMillis())
+ .build();
+ try {
+ RpcResult<Void> rpcResult = epService.registerL3PrefixEndpoint(registerL3PrefixEpRpcInput).get();
+ if (!rpcResult.isSuccessful()) {
+ LOG.warn("Illegal state - registerExternalL3PrefixEndpoint was not successful. Input of RPC: {}",
+ registerL3PrefixEpRpcInput);
+ return false;
+ }
+ return true;
+ } catch (InterruptedException | ExecutionException e) {
+ LOG.error("registerExternalL3PrefixEndpoint failed. {}", registerL3PrefixEpRpcInput, e);
+ return false;
+ }
+ }
+
+ public boolean registerL3EndpointAsExternalGateway(TenantId tenantId, IpAddress ipAddress, L3ContextId l3Context,
+ NetworkDomainId networkContainment) {
+ RegisterEndpointInput registerEndpointInput =
+ new RegisterEndpointInputBuilder()
+ .setL3Address(ImmutableList
+ .of(new L3AddressBuilder().setL3Context(l3Context).setIpAddress(ipAddress).build()))
+ .setTenant(tenantId)
+ .setNetworkContainment(networkContainment)
+ .setEndpointGroups(ImmutableList.of(MappingUtils.EPG_EXTERNAL_ID))
+ .setTimestamp(System.currentTimeMillis())
+ .build();
+ try {
+ RpcResult<Void> rpcResult = epService.registerEndpoint(registerEndpointInput).get();
+ if (!rpcResult.isSuccessful()) {
+ LOG.warn("Illegal state - registerL3EndpointAsExternalGateway was not successful. Input of RPC: {}",
+ registerEndpointInput);
+ return false;
+ }
+ } catch (InterruptedException | ExecutionException e) {
+ LOG.error("registerL3EndpointAsExternalGateway failed. {}", registerEndpointInput, e);
+ return false;
+ }
+ return true;
+ }
+
+}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.groupbasedpolicy.neutron.mapper;
-import static com.google.common.base.Preconditions.checkNotNull;
-
+import java.io.IOException;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.List;
+import java.util.Set;
+
+import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
+import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
+import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronAware;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronFloatingIpAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronListener;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronNetworkAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronNetworkDao;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronPortAware;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronRouterAware;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronSecurityGroupAware;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronSubnetAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.NeutronSecurityGroupAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronGbpMapperServiceImpl;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleDao;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NetworkUtils;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.NeutronGbpMapperService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.Floatingips;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.NeutronBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroupsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroupBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRulesBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.osgi.framework.ServiceRegistration;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
+
+import com.google.common.base.Function;
+import com.google.common.base.Predicate;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.Iterators;
+import com.google.common.collect.PeekingIterator;
+
+public class NeutronMapper implements DataTreeChangeListener<Neutron>, AutoCloseable {
-public class NeutronMapper implements AutoCloseable {
+ private final static SecurityRuleBuilder EIG_INGRESS_IPV4_SEC_RULE_BUILDER = new SecurityRuleBuilder()
+ .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18"))
+ .setDirection(DirectionIngress.class)
+ .setEthertype(EthertypeV4.class)
+ .setSecurityGroupId(MappingUtils.EIG_UUID);
+ private final static SecurityRuleBuilder EIG_EGRESS_IPV4_SEC_RULE_BUILDER = new SecurityRuleBuilder()
+ .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18"))
+ .setDirection(DirectionEgress.class)
+ .setEthertype(EthertypeV4.class)
+ .setSecurityGroupId(MappingUtils.EIG_UUID);
+ private final static SecurityRuleBuilder EIG_INGRESS_IPV6_SEC_RULE_BUILDER = new SecurityRuleBuilder()
+ .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18"))
+ .setDirection(DirectionIngress.class)
+ .setEthertype(EthertypeV6.class)
+ .setSecurityGroupId(MappingUtils.EIG_UUID);
+ private final static SecurityRuleBuilder EIG_EGRESS_IPV6_SEC_RULE_BUILDER = new SecurityRuleBuilder()
+ .setId(new Uuid("19b85ad2-bdfc-11e5-9912-ba0be0483c18"))
+ .setDirection(DirectionEgress.class)
+ .setEthertype(EthertypeV6.class)
+ .setSecurityGroupId(MappingUtils.EIG_UUID);
+ private final static SecurityGroupBuilder EIG_SEC_GROUP_BUILDER =
+ new SecurityGroupBuilder().setUuid(MappingUtils.EIG_UUID).setDescription("EXTERNAL_group");
- private final List<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>();
- private final DataBroker dataProvider;
- private final RpcProviderRegistry providerRegistry;
- private final EndpointService epService;
- private RpcRegistration<NeutronGbpMapperService> rpcRegistration;
- private NeutronListener neutronListener;
+ private final NeutronNetworkAware networkAware;
+ private final NeutronSecurityGroupAware securityGroupAware;
+ private final NeutronSecurityRuleAware securityRuleAware;
+ private final NeutronSubnetAware subnetAware;
+ private final NeutronPortAware portAware;
+ private final NeutronRouterAware routerAware;
+ private final NeutronFloatingIpAware floatingIpAware;
+
+ private final ListenerRegistration<NeutronMapper> registerDataTreeChangeListener;
+ private Neutron neutronBefore;
+ private Neutron neutronAfter;
public NeutronMapper(DataBroker dataProvider, RpcProviderRegistry rpcProvider) {
- this.dataProvider = checkNotNull(dataProvider);
- this.providerRegistry = checkNotNull(rpcProvider);
- this.epService = rpcProvider.getRpcService(EndpointService.class);
- neutronListener = new NeutronListener(dataProvider);
- registerAwareProviders();
+ EndpointService epService = rpcProvider.getRpcService(EndpointService.class);
+ EndpointRegistrator epRegistrator = new EndpointRegistrator(epService);
+ networkAware = new NeutronNetworkAware(dataProvider);
+ securityGroupAware = new NeutronSecurityGroupAware(dataProvider);
+ securityRuleAware = new NeutronSecurityRuleAware(dataProvider);
+ subnetAware = new NeutronSubnetAware(dataProvider, epRegistrator);
+ portAware = new NeutronPortAware(dataProvider, epRegistrator);
+ routerAware = new NeutronRouterAware(dataProvider, epRegistrator);
+ floatingIpAware = new NeutronFloatingIpAware(dataProvider);
+ registerDataTreeChangeListener =
+ dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
+ InstanceIdentifier.builder(Neutron.class).build()), this);
+ }
+
+ @Override
+ public void onDataTreeChanged(Collection<DataTreeModification<Neutron>> changes) {
+ for (DataTreeModification<Neutron> change : changes) {
+ DataObjectModification<Neutron> neutronModif = change.getRootNode();
+ resolveAndSetNeutron(neutronModif);
+ // network
+ List<DataObjectModification<Network>> networkModifs =
+ findModifiedData(NeutronNetworkAware.NETWORK_WILDCARD_IID, neutronModif);
+ for (Uuid tenantFromCreatedRouterExternalNetwork : filterCreatedRouterExternalNetworksAndTransformToTenants(
+ networkModifs)) {
+ SecurityGroup eigSecGroup =
+ EIG_SEC_GROUP_BUILDER.setTenantId(tenantFromCreatedRouterExternalNetwork).build();
+ securityGroupAware.onCreated(eigSecGroup, neutronAfter);
+ List<SecurityRule> eigSecRules = createEigSecurityRules(tenantFromCreatedRouterExternalNetwork);
+ for (SecurityRule eigSecRule : eigSecRules) {
+ securityRuleAware.onCreated(eigSecRule, neutronAfter);
+ }
+ }
+ onDataObjectModification(networkModifs, networkAware);
+ // security group
+ List<DataObjectModification<SecurityGroup>> secGroupModifs =
+ findModifiedData(NeutronSecurityGroupAware.SECURITY_GROUP_WILDCARD_IID, neutronModif);
+ onDataObjectModification(secGroupModifs, securityGroupAware);
+ // security rules
+ List<DataObjectModification<SecurityRule>> secRuleModifs =
+ findModifiedData(NeutronSecurityRuleAware.SECURITY_RULE_WILDCARD_IID, neutronModif);
+ onDataObjectModification(secRuleModifs, securityRuleAware);
+ // subnet
+ List<DataObjectModification<Subnet>> subnetModifs = findModifiedData(NeutronSubnetAware.SUBNET_WILDCARD_IID, neutronModif);
+ onDataObjectModification(subnetModifs, subnetAware);
+ // port
+ List<DataObjectModification<Port>> portModifs = findModifiedData(NeutronPortAware.PORT_WILDCARD_IID, neutronModif);
+ onDataObjectModification(portModifs, portAware);
+ // router
+ List<DataObjectModification<Router>> routerModifs = findModifiedData(NeutronRouterAware.ROUTER_WILDCARD_IID, neutronModif);
+ onDataObjectModification(routerModifs, routerAware);
+ // floating IP
+ List<DataObjectModification<Floatingip>> floatingIpModifs = findModifiedData(NeutronFloatingIpAware.FLOATING_IP_WILDCARD_IID, neutronModif);
+ onDataObjectModification(floatingIpModifs, floatingIpAware);
+ }
}
- private void registerAwareProviders() {
- SecGroupDao secGroupDao = new SecGroupDao();
- SecRuleDao secRuleDao = new SecRuleDao();
- NeutronNetworkDao networkDao = new NeutronNetworkDao();
- NeutronSecurityRuleAware securityRuleAware = new NeutronSecurityRuleAware(dataProvider, secRuleDao, secGroupDao);
- NeutronSecurityGroupAware securityGroupAware = new NeutronSecurityGroupAware(dataProvider, securityRuleAware, secGroupDao);
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(Floatingips.class).child(Floatingip.class).build(),
- new NeutronFloatingIpAware(dataProvider));
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(Ports.class).child(Port.class).build(),
- new NeutronPortAware(dataProvider, epService, securityRuleAware, securityGroupAware));
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(Routers.class).child(Router.class).build(),
- new NeutronRouterAware(dataProvider, epService));
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(SecurityRules.class).child(SecurityRule.class).build(),
- securityRuleAware);
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(SecurityGroups.class).child(SecurityGroup.class).build(),
- securityGroupAware);
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(Subnets.class).child(Subnet.class).build(),
- new NeutronSubnetAware(dataProvider, networkDao));
- neutronListener.registerMappingProviders(
- InstanceIdentifier.builder(Neutron.class).child(Networks.class).child(Network.class).build(),
- new NeutronNetworkAware(dataProvider, securityGroupAware, networkDao));
- NeutronGbpMapperService neutronGbpMapperService = new NeutronGbpMapperServiceImpl(dataProvider, securityRuleAware);
- rpcRegistration = providerRegistry.addRpcImplementation(NeutronGbpMapperService.class, neutronGbpMapperService);
+ private <T extends DataObject> void onDataObjectModification(List<DataObjectModification<T>> dataModifs,
+ NeutronAware<T> neutronAware) {
+ for (DataObjectModification<T> dataModif : dataModifs) {
+ switch (dataModif.getModificationType()) {
+ case DELETE:
+ neutronAware.onDeleted(dataModif.getDataBefore(), neutronBefore, neutronAfter);
+ break;
+ case SUBTREE_MODIFIED:
+ neutronAware.onUpdated(dataModif.getDataBefore(), dataModif.getDataAfter(), neutronBefore,
+ neutronAfter);
+ break;
+ case WRITE:
+ if (dataModif.getDataBefore() == null) {
+ neutronAware.onCreated(dataModif.getDataAfter(), neutronAfter);
+ } else {
+ neutronAware.onUpdated(dataModif.getDataBefore(), dataModif.getDataAfter(), neutronBefore,
+ neutronAfter);
+ }
+ break;
+ default:
+ throw new IllegalStateException("Unknown modification type within data " + dataModif);
+ }
+ }
+ }
+
+ private Set<Uuid> filterCreatedRouterExternalNetworksAndTransformToTenants(
+ List<DataObjectModification<Network>> modifiedNetworks) {
+ return FluentIterable.from(modifiedNetworks).filter(new Predicate<DataObjectModification<Network>>() {
+
+ @Override
+ public boolean apply(DataObjectModification<Network> modifiedNetwork) {
+ return (ModificationType.WRITE == modifiedNetwork.getModificationType()
+ && NetworkUtils.isRouterExternal(modifiedNetwork.getDataAfter()));
+ }
+ }).transform(new Function<DataObjectModification<Network>, Uuid>() {
+
+ @Override
+ public Uuid apply(DataObjectModification<Network> modifiedNetwork) {
+ return modifiedNetwork.getDataAfter().getTenantId();
+ }
+ }).toSet();
+ }
+
+ private void resolveAndSetNeutron(DataObjectModification<Neutron> originalNeutron) {
+ Neutron oldNeutronBefore = originalNeutron.getDataBefore();
+ neutronBefore = resolveAndCreateNewNeutron(oldNeutronBefore);
+ Neutron oldNeutronAfter = originalNeutron.getDataAfter();
+ neutronAfter = resolveAndCreateNewNeutron(oldNeutronAfter);
+ }
+
+ private @Nullable Neutron resolveAndCreateNewNeutron(@Nullable Neutron originalNeutron) {
+ if (originalNeutron == null) {
+ return null;
+ }
+ NeutronBuilder newNeutronBuilder = new NeutronBuilder(originalNeutron);
+ resolveAndAddSecurityRulesAndGroups(originalNeutron, newNeutronBuilder);
+ return newNeutronBuilder.build();
+ }
+
+ private void resolveAndAddSecurityRulesAndGroups(Neutron originalNeutron, NeutronBuilder newNeutronBuilder) {
+ List<SecurityRule> eigSecRulesAndOriginalSecRules = new ArrayList<>();
+ List<SecurityGroup> eigSecGroupAndOriginalSecGroup = new ArrayList<>();
+ // resolve EIG sec rules and groups
+ List<Network> routerExternalNetworks = NetworkUtils.findRouterExternalNetworks(originalNeutron.getNetworks());
+ Set<Uuid> tenantsFromRouterExternalNetwork = resolveTenantsFromNetworks(routerExternalNetworks);
+ for (Uuid tenantFromRouterExternalNetwork : tenantsFromRouterExternalNetwork) {
+ eigSecRulesAndOriginalSecRules.addAll(createEigSecurityRules(tenantFromRouterExternalNetwork));
+ eigSecGroupAndOriginalSecGroup
+ .add(EIG_SEC_GROUP_BUILDER.setTenantId(tenantFromRouterExternalNetwork).build());
+ }
+ // set new sec rules
+ SecurityRules newSecRules = null;
+ if (originalNeutron.getSecurityRules() != null) {
+ List<SecurityRule> originalSecRules = originalNeutron.getSecurityRules().getSecurityRule();
+ if (originalSecRules != null) {
+ eigSecRulesAndOriginalSecRules.addAll(originalSecRules);
+ }
+ newSecRules = new SecurityRulesBuilder(originalNeutron.getSecurityRules())
+ .setSecurityRule(eigSecRulesAndOriginalSecRules).build();
+ } else {
+ newSecRules = new SecurityRulesBuilder().setSecurityRule(eigSecRulesAndOriginalSecRules).build();
+ }
+ newNeutronBuilder.setSecurityRules(newSecRules);
+ // set new sec groups
+ SecurityGroups newSecGroups = null;
+ if (originalNeutron.getSecurityGroups() != null) {
+ List<SecurityGroup> originalSecGroups = originalNeutron.getSecurityGroups().getSecurityGroup();
+ if (originalSecGroups != null) {
+ eigSecGroupAndOriginalSecGroup.addAll(originalSecGroups);
+ }
+ newSecGroups = new SecurityGroupsBuilder(originalNeutron.getSecurityGroups())
+ .setSecurityGroup(eigSecGroupAndOriginalSecGroup).build();
+ } else {
+ newSecGroups = new SecurityGroupsBuilder().setSecurityGroup(eigSecGroupAndOriginalSecGroup).build();
+ }
+ newNeutronBuilder.setSecurityGroups(newSecGroups);
+ }
+
+ private Set<Uuid> resolveTenantsFromNetworks(List<Network> networks) {
+ return FluentIterable.from(networks).transform(new Function<Network, Uuid>() {
+
+ @Override
+ public Uuid apply(Network network) {
+ return network.getTenantId();
+ }
+ }).toSet();
+ }
+
+ private List<SecurityRule> createEigSecurityRules(Uuid tenant) {
+ List<SecurityRule> eigSecRules = new ArrayList<>();
+ eigSecRules.add(EIG_INGRESS_IPV4_SEC_RULE_BUILDER.setTenantId(tenant).build());
+ eigSecRules.add(EIG_EGRESS_IPV4_SEC_RULE_BUILDER.setTenantId(tenant).build());
+ eigSecRules.add(EIG_INGRESS_IPV6_SEC_RULE_BUILDER.setTenantId(tenant).build());
+ eigSecRules.add(EIG_EGRESS_IPV6_SEC_RULE_BUILDER.setTenantId(tenant).build());
+ return eigSecRules;
}
/**
- * @see java.lang.AutoCloseable#close()
+ * Finds all modified subnodes of given type in {@link Neutron} node.
+ *
+ * @param <T>
+ * @param iid path to data in root node
+ * @param rootNode modified data of {@link Neutron} node
+ * @return {@link List} of modified subnodes
*/
- @Override
- public void close() throws Exception {
- for (ServiceRegistration<?> registration : registrations) {
- registration.unregister();
+ private <T extends DataObject> List<DataObjectModification<T>> findModifiedData(InstanceIdentifier<T> iid,
+ DataObjectModification<Neutron> rootNode) {
+ List<DataObjectModification<T>> modDtos = new ArrayList<>();
+ PeekingIterator<PathArgument> pathArgs = Iterators.peekingIterator(iid.getPathArguments().iterator());
+ DataObjectModification<? extends DataObject> modifDto = rootNode;
+ while (pathArgs.hasNext()) {
+ pathArgs.next();
+ for (DataObjectModification<? extends DataObject> childDto : modifDto.getModifiedChildren()) {
+ if (pathArgs.hasNext() && childDto.getDataType().equals(pathArgs.peek().getType())) {
+ if (childDto.getDataType().equals(iid.getTargetType())) {
+ modDtos.add((DataObjectModification<T>) childDto);
+ } else {
+ modifDto = childDto;
+ break;
+ }
+ }
+ }
}
- if (neutronListener != null) {
- neutronListener.close();
- neutronListener = null;
- }
- rpcRegistration.close();
+ return modDtos;
+ }
+
+ @Override
+ public void close() throws IOException {
+ registerDataTreeChangeListener.close();
}
}
+++ /dev/null
-/*\r
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;\r
-\r
-import org.opendaylight.neutron.spi.NeutronObject;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-\r
-public interface MappingProcessor <D extends DataObject, T extends NeutronObject> {\r
-\r
- int canCreate(T t);\r
- int canUpdate(T original, T delta);\r
- int canDelete(T t);\r
-\r
- void updated(T t);\r
- void created(T t);\r
- void deleted(T t);\r
-\r
- T convertToNeutron(D d);\r
-}\r
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;
+
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+
+public interface NeutronAware<T extends DataObject> {
+
+ void onCreated(T createdItem, Neutron neutron);
+ void onUpdated(T oldItem, T newItem, Neutron oldNeutron, Neutron newNeutron);
+ void onDeleted(T deletedItem, Neutron oldNeutron, Neutron newNeutron);
+
+}
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronFloatingIP;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddressBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.Floatingips;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.floatingips.attributes.floatingips.Floatingip;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Strings;
+import com.google.common.base.Objects;
-public class NeutronFloatingIpAware implements MappingProcessor<Floatingip, NeutronFloatingIP> {
+public class NeutronFloatingIpAware implements NeutronAware<Floatingip> {
- public static final Logger LOG = LoggerFactory.getLogger(NeutronFloatingIpAware.class);
+ private static final Logger LOG = LoggerFactory.getLogger(NeutronFloatingIpAware.class);
+ public static final InstanceIdentifier<Floatingip> FLOATING_IP_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class).child(Floatingips.class).child(Floatingip.class).build();
private final DataBroker dataProvider;
public NeutronFloatingIpAware(DataBroker dataProvider) {
}
@Override
- public NeutronFloatingIP convertToNeutron(Floatingip fip) {
- NeutronFloatingIP result = new NeutronFloatingIP();
- result.setID(fip.getUuid().getValue());
- if (fip.getFloatingNetworkId() != null) {
- result.setFloatingNetworkUUID(fip.getFloatingNetworkId().getValue());
- }
- if (fip.getPortId() != null) {
- result.setPortUUID(fip.getPortId().getValue());
- }
- if (fip.getFixedIpAddress() != null ) {
- result.setFixedIPAddress(String.valueOf(fip.getFixedIpAddress().getValue()));
- }
- if (fip.getFloatingIpAddress() != null) {
- result.setFloatingIPAddress(String.valueOf(fip.getFloatingIpAddress().getValue()));
- }
- if (fip.getTenantId() != null) {
- result.setTenantID(fip.getTenantId());
- }
- if (fip.getRouterId() != null) {
- result.setRouterUUID(fip.getRouterId().getValue());
- }
- result.setStatus(fip.getStatus());
- return result;
- }
-
- @Override
- public int canCreate(NeutronFloatingIP floatingIP) {
- LOG.trace("canCreate floatingIP - {}", floatingIP);
- return StatusCode.OK;
- }
-
- @Override
- public void created(NeutronFloatingIP floatingIP) {
+ public void onCreated(Floatingip floatingIP, Neutron neutron) {
LOG.trace("created floatinIp - {}", floatingIP);
}
@Override
- public int canUpdate(NeutronFloatingIP delta, NeutronFloatingIP original) {
- LOG.trace("canUpdate floatingIP - delta: {} original: {}", delta, original);
- String oldFixedIPAddress = Strings.nullToEmpty(original.getFixedIPAddress());
- String newFixedIPAddress = Strings.nullToEmpty(delta.getFixedIPAddress());
- if (oldFixedIPAddress.equals(newFixedIPAddress)) {
- // interesting fields were not changed
- return StatusCode.OK;
+ public void onUpdated(Floatingip oldFloatingIp, Floatingip newFloatingIp, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("updated floatingIP - OLD: {}\nNEW: {}", oldFloatingIp, newFloatingIp);
+ IpAddress oldEpIp = oldFloatingIp.getFixedIpAddress();
+ IpAddress newEpIp = newFloatingIp.getFixedIpAddress();
+ if (Objects.equal(oldEpIp, newEpIp)) {
+ // floating IP was not moved from one port to the other
+ return;
}
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- L3ContextId routerL3Context = new L3ContextId(delta.getRouterUUID());
- String newFloatingIp = Strings.nullToEmpty(delta.getFloatingIPAddress());
- if (!newFixedIPAddress.isEmpty() && !newFloatingIp.isEmpty()) {
- IpAddress epIp = Utils.createIpAddress(newFixedIPAddress);
- IpAddress epNatIp = Utils.createIpAddress(newFloatingIp);
+ IpAddress epNatIp = newFloatingIp.getFloatingIpAddress();
+ L3ContextId routerL3ContextId = new L3ContextId(newFloatingIp.getRouterId().getValue());
+ if (epNatIp != null && newEpIp != null) {
NatAddress nat = new NatAddressBuilder().setNatAddress(epNatIp).build();
rwTx.put(LogicalDatastoreType.OPERATIONAL,
- IidFactory.l3EndpointIid(routerL3Context, epIp).augmentation(NatAddress.class), nat, true);
+ IidFactory.l3EndpointIid(routerL3ContextId, newEpIp).augmentation(NatAddress.class),
+ nat, true);
}
- if (!oldFixedIPAddress.isEmpty()) {
+ if (oldEpIp != null) {
DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
- IidFactory.l3EndpointIid(routerL3Context, Utils.createIpAddress(oldFixedIPAddress))
- .augmentation(NatAddress.class),
+ IidFactory.l3EndpointIid(routerL3ContextId, oldEpIp).augmentation(NatAddress.class),
rwTx);
}
boolean isSubmitToDsSuccessful = DataStoreHelper.submitToDs(rwTx);
if (!isSubmitToDsSuccessful) {
- return StatusCode.INTERNAL_SERVER_ERROR;
+ LOG.warn("Nat address {} was not added to endpoint {}", epNatIp, newEpIp);
}
-
- return StatusCode.OK;
- }
-
- @Override
- public void updated(NeutronFloatingIP floatingIP) {
- LOG.trace("updated floatingIP - {}", floatingIP);
- }
-
- @Override
- public int canDelete(NeutronFloatingIP floatingIP) {
- LOG.trace("canDelete floatingIP - {}", floatingIP);
- return StatusCode.OK;
}
@Override
- public void deleted(NeutronFloatingIP floatingIP) {
+ public void onDeleted(Floatingip floatingIP, Neutron oldNeutron, Neutron newNeutron) {
LOG.trace("deleted floatingIP - {}", floatingIP);
}
}
+++ /dev/null
-/*\r
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;\r
-\r
-import java.io.Closeable;\r
-import java.io.IOException;\r
-import java.util.ArrayList;\r
-import java.util.Collection;\r
-import java.util.LinkedHashMap;\r
-import java.util.List;\r
-import java.util.Map;\r
-\r
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;\r
-import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;\r
-import org.opendaylight.controller.md.sal.binding.api.DataObjectModification.ModificationType;\r
-import org.opendaylight.controller.md.sal.binding.api.DataTreeChangeListener;\r
-import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;\r
-import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;\r
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;\r
-import org.opendaylight.neutron.spi.NeutronObject;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;\r
-import org.opendaylight.yangtools.concepts.ListenerRegistration;\r
-import org.opendaylight.yangtools.yang.binding.DataObject;\r
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;\r
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;\r
-\r
-import com.google.common.collect.Iterators;\r
-import com.google.common.collect.PeekingIterator;\r
-\r
-public class NeutronListener implements DataTreeChangeListener<Neutron>, Closeable {\r
-\r
- private final ListenerRegistration<NeutronListener> registerDataTreeChangeListener;\r
- private final Map<InstanceIdentifier<? extends DataObject>, MappingProcessor<? extends DataObject, ? extends NeutronObject>> dataChangeProviders = new LinkedHashMap<>();\r
- private static DataObjectModification<Neutron> neutron;\r
-\r
- public NeutronListener(DataBroker dataProvider) {\r
- registerDataTreeChangeListener = dataProvider.registerDataTreeChangeListener(new DataTreeIdentifier<>(\r
- LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(Neutron.class).build()), this);\r
- }\r
-\r
- @Override\r
- public void onDataTreeChanged(Collection<DataTreeModification<Neutron>> changes) {\r
- for (DataTreeModification<Neutron> change : changes) {\r
- neutron = change.getRootNode();\r
- for (InstanceIdentifier<? extends DataObject> iid : dataChangeProviders.keySet()) {\r
- for (DataObjectModification<? extends DataObject> modifDto : findModifiedData(iid, change.getRootNode())) {\r
- processChangedData(modifDto, modifDto.getModificationType(), getMappingProvider(iid));\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Finds all modified subnodes of given type in {@link Neutron} node.\r
- *\r
- * @param iid path to data in root node\r
- * @param rootNode modified data of {@link Neutron} node\r
- * @return {@link List} of modified subnodes\r
- */\r
- private List<DataObjectModification<? extends DataObject>> findModifiedData(\r
- InstanceIdentifier<? extends DataObject> iid, DataObjectModification<Neutron> rootNode) {\r
- List<DataObjectModification<? extends DataObject>> modDtos = new ArrayList<>();\r
- PeekingIterator<PathArgument> pathArgs = Iterators.peekingIterator(iid.getPathArguments().iterator());\r
- DataObjectModification<? extends DataObject> modifDto = rootNode;\r
- while (pathArgs.hasNext()) {\r
- pathArgs.next();\r
- for (DataObjectModification<? extends DataObject> childDto : modifDto.getModifiedChildren()) {\r
- if (pathArgs.hasNext() && childDto.getDataType().equals(pathArgs.peek().getType())) {\r
- if (childDto.getDataType().equals(iid.getTargetType())) {\r
- modDtos.add(childDto);\r
- } else {\r
- modifDto = childDto;\r
- break;\r
- }\r
- }\r
- }\r
- }\r
- return modDtos;\r
- }\r
-\r
- static Neutron getNeutronDataBefore() {\r
- return neutron.getDataBefore();\r
- }\r
-\r
- static Neutron getNeutronDataAfter() {\r
- return neutron.getDataAfter();\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- <T extends DataObject, X extends NeutronObject> void processChangedData(DataObjectModification<?> dto,\r
- ModificationType m, MappingProcessor<T, X> d) {\r
- switch (m) {\r
- case WRITE: {\r
- T dataAfter = (T) dto.getDataAfter();\r
- X neutronObject = d.convertToNeutron(dataAfter);\r
- if (StatusCode.OK == d.canCreate(neutronObject)) {\r
- d.created(neutronObject);\r
- }\r
- break;\r
- }\r
- case SUBTREE_MODIFIED: {\r
- X neutronObjectBefore = d.convertToNeutron((T) dto.getDataBefore());\r
- X neutronObjectAfter = d.convertToNeutron((T) dto.getDataAfter());\r
- if (StatusCode.OK == d.canUpdate(neutronObjectAfter, neutronObjectBefore)) {\r
- d.updated(neutronObjectAfter);\r
- }\r
- break;\r
- }\r
- case DELETE: {\r
- X neutronObjectBefore = d.convertToNeutron((T) dto.getDataBefore());\r
- if (StatusCode.OK == d.canDelete(neutronObjectBefore)) {\r
- d.deleted(neutronObjectBefore);\r
- }\r
- break;\r
- }\r
- }\r
- }\r
-\r
- public <D extends DataObject, N extends NeutronObject> void registerMappingProviders(\r
- InstanceIdentifier<D> iid, MappingProcessor<D, N> np) {\r
- dataChangeProviders.put(iid, np);\r
- }\r
-\r
- @SuppressWarnings("unchecked")\r
- <D extends DataObject, N extends NeutronObject> MappingProcessor<D, N> getMappingProvider(\r
- InstanceIdentifier<D> iid) {\r
- return (MappingProcessor<D, N>) dataChangeProviders.get(iid);\r
- }\r
-\r
- @Override\r
- public void close() throws IOException {\r
- registerDataTreeChangeListener.close();\r
- }\r
-\r
-}\r
-\r
import static com.google.common.base.Preconditions.checkNotNull;
-import java.util.ArrayList;
import java.util.HashSet;
-import java.util.List;
import java.util.Set;
-import java.util.UUID;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory;
import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkClient;
import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkService;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.NeutronSecurityGroupAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronMapperIidFactory;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NetworkUtils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronNetwork;
-import org.opendaylight.neutron.spi.NeutronNetwork_Segment;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.provider.physical.networks.as.l2.flood.domains.ProviderPhysicalNetworkAsL2FloodDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.provider.physical.networks.as.l2.flood.domains.ProviderPhysicalNetworkAsL2FloodDomainBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMappingBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroupBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeFlat;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeGre;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVlan;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.NetworkTypeVxlan;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.neutron.networks.network.Segments;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableBiMap;
-import com.google.common.collect.ImmutableList;
-public class NeutronNetworkAware implements MappingProcessor<Network, NeutronNetwork> {
+public class NeutronNetworkAware implements NeutronAware<Network> {
private static final Logger LOG = LoggerFactory.getLogger(NeutronNetworkAware.class);
+ public static final InstanceIdentifier<Network> NETWORK_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class).child(Networks.class).child(Network.class).build();
private final DataBroker dataProvider;
private final Set<TenantId> tenantsWithRouterAndNetworkSeviceEntities = new HashSet<>();
- private final NeutronSecurityGroupAware secGrpAware;
- private final NeutronNetworkDao networkDao;
- public NeutronNetworkAware(DataBroker dataProvider, NeutronSecurityGroupAware secGrpAware, NeutronNetworkDao networkDao) {
+ public NeutronNetworkAware(DataBroker dataProvider) {
this.dataProvider = checkNotNull(dataProvider);
- this.secGrpAware = checkNotNull(secGrpAware);
- this.networkDao = checkNotNull(networkDao);
}
- private static final ImmutableBiMap<Class<? extends NetworkTypeBase>,String> NETWORK_MAP
- = new ImmutableBiMap.Builder<Class<? extends NetworkTypeBase>,String>()
- .put(NetworkTypeFlat.class,"flat")
- .put(NetworkTypeGre.class,"gre")
- .put(NetworkTypeVlan.class,"vlan")
- .put(NetworkTypeVxlan.class,"vxlan")
- .build();
-
@Override
- public NeutronNetwork convertToNeutron(Network network) {
- NeutronNetwork result = new NeutronNetwork();
- result.initDefaults();
- result.setAdminStateUp(network.isAdminStateUp());
- result.setNetworkName(network.getName());
- result.setShared(network.isShared());
- result.setStatus(network.getStatus());
- result.setTenantID(network.getTenantId());
- result.setID(network.getUuid().getValue());
-
- NetworkL3Extension l3Extension = network.getAugmentation(NetworkL3Extension.class);
- result.setRouterExternal(l3Extension.isExternal());
-
- NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class);
- result.setProviderPhysicalNetwork(providerExtension.getPhysicalNetwork());
- result.setProviderSegmentationID(providerExtension.getSegmentationId());
- result.setProviderNetworkType(NETWORK_MAP.get(providerExtension.getNetworkType()));
- List<NeutronNetwork_Segment> segments = new ArrayList<NeutronNetwork_Segment>();
- if (providerExtension.getSegments() != null) {
- for (Segments segment: providerExtension.getSegments()) {
- NeutronNetwork_Segment neutronSegment = new NeutronNetwork_Segment();
- neutronSegment.setProviderPhysicalNetwork(segment.getPhysicalNetwork());
- neutronSegment.setProviderSegmentationID(segment.getSegmentationId());
- neutronSegment.setProviderNetworkType(NETWORK_MAP.get(segment.getNetworkType()));
- segments.add(neutronSegment);
- }
- }
- result.setSegments(segments);
- return result;
- }
-
- @Override
- public int canCreate(NeutronNetwork network) {
- LOG.trace("canCreate network - {}", network);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void created(NeutronNetwork network) {
+ public void onCreated(Network network, Neutron neutron) {
LOG.trace("created network - {}", network);
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- L2FloodDomainId l2FdId = new L2FloodDomainId(network.getID());
- TenantId tenantId = new TenantId(Utils.normalizeUuid(network.getTenantID()));
+ L2FloodDomainId l2FdId = new L2FloodDomainId(network.getUuid().getValue());
+ TenantId tenantId = new TenantId(network.getTenantId().getValue());
Name name = null;
- if (network.getNetworkName() != null) {
+ if (!Strings.isNullOrEmpty(network.getName())) {
try {
- name = new Name(network.getNetworkName());
+ name = new Name(network.getName());
} catch (Exception e) {
name = null;
- LOG.info("Name of Neutron Network '{}' is ignored.", network.getNetworkName());
+ LOG.info("Name of Neutron Network '{}' is ignored.", network.getName());
LOG.debug("Name exception", e);
}
}
- L3ContextId l3ContextId = new L3ContextId(UUID.randomUUID().toString());
+ L3ContextId l3ContextId = new L3ContextId(l2FdId);
L3Context l3Context = new L3ContextBuilder().setId(l3ContextId).setName(name).build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l3ContextIid(tenantId, l3ContextId), l3Context, true);
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l3ContextIid(tenantId, l3Context.getId()), l3Context, true);
- L2BridgeDomainId l2BdId = new L2BridgeDomainId(UUID.randomUUID().toString());
- L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(l3ContextId).setName(name).build();
+ L2BridgeDomainId l2BdId = new L2BridgeDomainId(l2FdId);
+ L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(l3Context.getId()).setName(name).build();
rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd, true);
L2FloodDomain l2Fd = new L2FloodDomainBuilder().setId(l2FdId).setParent(l2BdId).setName(name).build();
rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2FloodDomainIid(tenantId, l2FdId), l2Fd, true);
- NetworkMapping networkMapping = new NetworkMappingBuilder().setNetworkId(l2FdId)
- .setL2BridgeDomainId(l2BdId)
- .setL3ContextId(l3ContextId)
- .build();
- rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronMapperIidFactory.networkMappingIid(l2FdId), networkMapping,
- true);
-
if (!tenantsWithRouterAndNetworkSeviceEntities.contains(tenantId)) {
tenantsWithRouterAndNetworkSeviceEntities.add(tenantId);
NetworkService.writeNetworkServiceEntitiesToTenant(tenantId, rwTx);
NetworkClient.writeConsumerNamedSelector(tenantId, NetworkService.DNS_CONTRACT_CONSUMER_SELECTOR, rwTx);
NetworkClient.writeConsumerNamedSelector(tenantId, NetworkService.MGMT_CONTRACT_CONSUMER_SELECTOR, rwTx);
}
- networkDao.addNetwork(network);
- if (network.getRouterExternal() != null && network.getRouterExternal() == true) {
- addEigEpgExternalWithContracts(tenantId, rwTx);
- }
- if (!Strings.isNullOrEmpty(network.getProviderPhysicalNetwork())) {
- String segmentationId = network.getProviderSegmentationID();
- addProviderPhysicalNetworkMapping(tenantId, l2FdId, segmentationId, rwTx);
+ if (!NetworkUtils.getPhysicalNetwork(network).isEmpty() && !NetworkUtils.getSegmentationId(network).isEmpty()) {
+ addProviderPhysicalNetworkMapping(tenantId, l2FdId, NetworkUtils.getSegmentationId(network), rwTx);
}
DataStoreHelper.submitToDs(rwTx);
}
- private void addEigEpgExternalWithContracts(TenantId tenantId, ReadWriteTransaction rwTx) {
- Uuid tenantUuid = new Uuid(tenantId.getValue());
- NeutronSecurityRule inIpv4 = new NeutronSecurityRule();
- inIpv4.setID("19b85ad2-bdfc-11e5-9912-ba0be0483c18");
- inIpv4.setSecurityRuleDirection(NeutronUtils.INGRESS);
- inIpv4.setSecurityRuleEthertype(NeutronUtils.IPv4);
- inIpv4.setSecurityRuleGroupID(MappingUtils.EPG_EXTERNAL_ID.getValue());
- inIpv4.setTenantID(tenantUuid);
- NeutronSecurityRule outIpv4 = new NeutronSecurityRule();
- outIpv4.setID("19b85eba-bdfc-11e5-9912-ba0be0483c18");
- outIpv4.setSecurityRuleDirection(NeutronUtils.EGRESS);
- outIpv4.setSecurityRuleEthertype(NeutronUtils.IPv4);
- outIpv4.setSecurityRuleGroupID(MappingUtils.EPG_EXTERNAL_ID.getValue());
- outIpv4.setTenantID(tenantUuid);
- NeutronSecurityRule inIpv6 = new NeutronSecurityRule();
- inIpv6.setID("19b86180-bdfc-11e5-9912-ba0be0483c18");
- inIpv6.setSecurityRuleDirection(NeutronUtils.INGRESS);
- inIpv6.setSecurityRuleEthertype(NeutronUtils.IPv6);
- inIpv6.setSecurityRuleGroupID(MappingUtils.EPG_EXTERNAL_ID.getValue());
- inIpv6.setTenantID(tenantUuid);
- NeutronSecurityRule outIpv6 = new NeutronSecurityRule();
- outIpv6.setID("19b86270-bdfc-11e5-9912-ba0be0483c18");
- outIpv6.setSecurityRuleDirection(NeutronUtils.EGRESS);
- outIpv6.setSecurityRuleEthertype(NeutronUtils.IPv6);
- outIpv6.setSecurityRuleGroupID(MappingUtils.EPG_EXTERNAL_ID.getValue());
- outIpv6.setTenantID(tenantUuid);
- NeutronSecurityGroup externalSecGrp = new NeutronSecurityGroup();
- externalSecGrp.setID(MappingUtils.EPG_EXTERNAL_ID.getValue());
- externalSecGrp.setSecurityGroupName("EXTERNAL_group");
- externalSecGrp.setTenantID(tenantUuid);
- externalSecGrp.setSecurityRules(ImmutableList.of(inIpv4, outIpv4, inIpv6, outIpv6));
- boolean isAddedNeutronSecurityGroup = secGrpAware.addNeutronSecurityGroup(externalSecGrp, rwTx);
- if (!isAddedNeutronSecurityGroup) {
- LOG.error("Problem with adding External Neutron Security Group representing External Implicit Group. {}", externalSecGrp);
- return;
- }
- ExternalImplicitGroup eig = new ExternalImplicitGroupBuilder().setId(MappingUtils.EPG_EXTERNAL_ID).build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION,
- IidFactory.externalImplicitGroupIid(tenantId, eig.getId()), eig, true);
- }
-
private void addProviderPhysicalNetworkMapping(TenantId tenantId, L2FloodDomainId l2FdId, String segmentationId,
WriteTransaction wTx) {
ProviderPhysicalNetworkAsL2FloodDomain provNetAsL2Fd = new ProviderPhysicalNetworkAsL2FloodDomainBuilder()
}
@Override
- public int canUpdate(NeutronNetwork delta, NeutronNetwork original) {
- LOG.trace("canUpdate network - delta: {} original: {}", delta, original);
- // nothing to consider
- return StatusCode.OK;
+ public void onUpdated(Network oldItem, Network newItem, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("updated network - OLD: {} \nNEW: {}", oldItem, newItem);
+ // TODO only name can be updated
}
@Override
- public void updated(NeutronNetwork network) {
- LOG.trace("updated network - {}", network);
- // TODO we could update just name
- }
-
- @Override
- public int canDelete(NeutronNetwork network) {
- LOG.trace("canDelete network - {}", network);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void deleted(NeutronNetwork network) {
+ public void onDeleted(Network network, Neutron oldNeutron, Neutron newNeutron) {
LOG.trace("deleted network - {}", network);
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(network.getTenantID()));
- L2FloodDomainId l2FdId = new L2FloodDomainId(network.getID());
- InstanceIdentifier<NetworkMapping> networkMappingIid = NeutronMapperIidFactory.networkMappingIid(l2FdId);
- Optional<NetworkMapping> potentionalNetworkMapping =
- DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL, networkMappingIid, rwTx);
- if (!potentionalNetworkMapping.isPresent()) {
- LOG.warn("Illegal state - network-mapping {} does not exist.", l2FdId.getValue());
- rwTx.cancel();
- return;
- }
-
- NetworkMapping networkMapping = potentionalNetworkMapping.get();
- L2BridgeDomainId l2BdId = networkMapping.getL2BridgeDomainId();
- L3ContextId l3ContextId = networkMapping.getL3ContextId();
- if (l2BdId == null || l3ContextId == null) {
- LOG.warn("Illegal state - network-mapping {} is not valid.", networkMapping);
- rwTx.cancel();
- return;
- }
-
+ TenantId tenantId = new TenantId(network.getTenantId().getValue());
+ L2FloodDomainId l2FdId = new L2FloodDomainId(network.getUuid().getValue());
Optional<L2FloodDomain> potentialL2Fd = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
IidFactory.l2FloodDomainIid(tenantId, l2FdId), rwTx);
if (!potentialL2Fd.isPresent()) {
LOG.warn("Illegal state - l2-flood-domain {} does not exist.", l2FdId.getValue());
- rwTx.cancel();
return;
}
+ L2BridgeDomainId l2BdId = new L2BridgeDomainId(l2FdId);
Optional<L2BridgeDomain> potentialL2Bd = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
IidFactory.l2BridgeDomainIid(tenantId, l2BdId), rwTx);
if (!potentialL2Bd.isPresent()) {
LOG.warn("Illegal state - l2-bridge-domain {} does not exist.", l2BdId.getValue());
- rwTx.cancel();
- return;
- }
-
- Optional<L3Context> potentialL3Context = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
- IidFactory.l3ContextIid(tenantId, l3ContextId), rwTx);
- if (!potentialL3Context.isPresent()) {
- LOG.warn("Illegal state - l3-context {} does not exist.", l3ContextId.getValue());
- rwTx.cancel();
return;
}
- rwTx.delete(LogicalDatastoreType.OPERATIONAL, networkMappingIid);
-
DataStoreHelper.submitToDs(rwTx);
}
+
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.opendaylight.neutron.spi.NeutronNetwork;
-
-import com.google.common.base.Preconditions;
-
-public class NeutronNetworkDao {
-
- private final Set<String> externalNetworks = new HashSet<>();
-
- public void addNetwork(NeutronNetwork network) {
- Preconditions.checkNotNull(network);
- if (network.getRouterExternal() != null && network.getRouterExternal() == true) {
- externalNetworks.add(network.getID());
- }
- }
-
- /**
- * Checks if neutron network is external
- * @param networkId UUID of the network
- * @return {@code true} if {@link NeutronNetwork#getRouterExternal()} is {@code true}; {@code false} otherwise
- */
- public boolean isExternalNetwork(String networkId) {
- return externalNetworks.contains(networkId);
- }
-
-}
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
+import java.util.Collections;
import java.util.List;
import java.util.Set;
-import java.util.concurrent.ExecutionException;
+
+import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.EndpointRegistrator;
import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkClient;
import org.opendaylight.groupbasedpolicy.neutron.mapper.infrastructure.NetworkService;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.NeutronSecurityGroupAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.PortUtils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SubnetUtils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronPort;
-import org.opendaylight.neutron.spi.NeutronPort_AllowedAddressPairs;
-import org.opendaylight.neutron.spi.NeutronPort_ExtraDHCPOption;
-import org.opendaylight.neutron.spi.NeutronPort_VIFDetail;
-import org.opendaylight.neutron.spi.NeutronRouter;
-import org.opendaylight.neutron.spi.NeutronRouter_Interface;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
-import org.opendaylight.neutron.spi.Neutron_IPs;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterEndpointInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.RegisterL3PrefixEndpointInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3AddressBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3GatewaysBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Builder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3PrefixKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L2Builder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3Builder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.gbp.by.neutron.mappings.endpoints.by.ports.EndpointByPort;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.external.gateways.as.l3.endpoints.ExternalGatewayAsL3Endpoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.ports.by.endpoints.PortByEndpoint;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.PortBindingExtension;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.binding.rev150712.binding.attributes.VifDetails;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.AllowedAddressPairs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.ExtraDhcpOpts;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.base.Function;
import com.google.common.base.Optional;
-import com.google.common.base.Strings;
-import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-public class NeutronPortAware implements MappingProcessor<Port, NeutronPort> {
+public class NeutronPortAware implements NeutronAware<Port> {
- public static final Logger LOG = LoggerFactory.getLogger(NeutronPortAware.class);
- private static final String DEVICE_OWNER_DHCP = "network:dhcp";
- private static final String DEVICE_OWNER_ROUTER_IFACE = "network:router_interface";
- private static final String DEVICE_OWNER_ROUTER_GATEWAY = "network:router_gateway";
- private static final String DEVICE_OWNER_FLOATING_IP = "network:floatingip";
+ private static final Logger LOG = LoggerFactory.getLogger(NeutronPortAware.class);
+ public static final InstanceIdentifier<Port> PORT_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class).child(Ports.class).child(Port.class).build();
private final DataBroker dataProvider;
- private final EndpointService epService;
- private final NeutronSecurityRuleAware secRuleAware;
- private final NeutronSecurityGroupAware secGrpAware;
+ private final EndpointRegistrator epRegistrator;
- public NeutronPortAware(DataBroker dataProvider, EndpointService epService, NeutronSecurityRuleAware secRuleAware, NeutronSecurityGroupAware secGrpAware) {
+ public NeutronPortAware(DataBroker dataProvider, EndpointRegistrator epRegistrator) {
this.dataProvider = checkNotNull(dataProvider);
- this.epService = checkNotNull(epService);
- this.secRuleAware = checkNotNull(secRuleAware);
- this.secGrpAware = secGrpAware;
+ this.epRegistrator = checkNotNull(epRegistrator);
}
@Override
- public NeutronPort convertToNeutron(Port port) {
- return toNeutron(port);
- }
-
- static NeutronPort toNeutron(Port port) {
- NeutronPort result = new NeutronPort();
- result.setAdminStateUp(port.isAdminStateUp());
- if (port.getAllowedAddressPairs() != null) {
- List<NeutronPort_AllowedAddressPairs> pairs = new ArrayList<NeutronPort_AllowedAddressPairs>();
- for (AllowedAddressPairs mdPair : port.getAllowedAddressPairs()) {
- NeutronPort_AllowedAddressPairs pair = new NeutronPort_AllowedAddressPairs();
- pair.setIpAddress(mdPair.getIpAddress());
- pair.setMacAddress(mdPair.getMacAddress());
- pairs.add(pair);
+ public void onCreated(Port port, Neutron neutron) {
+ LOG.trace("created port - {}", port);
+ if (PortUtils.isRouterInterfacePort(port)) {
+ LOG.trace("Port is router interface port: {}", port.getUuid().getValue());
+ // router interface port can have only one IP
+ Optional<FixedIps> potentialPortIpWithSubnet = PortUtils.resolveFirstFixedIps(port);
+ if (!potentialPortIpWithSubnet.isPresent()) {
+ LOG.warn("Illegal state - router interface port does not contain fixed IPs {}",
+ port);
+ return;
}
- result.setAllowedAddressPairs(pairs);
- }
- result.setDeviceID(port.getDeviceId());
- result.setDeviceOwner(port.getDeviceOwner());
- if (port.getExtraDhcpOpts() != null) {
- List<NeutronPort_ExtraDHCPOption> options = new ArrayList<NeutronPort_ExtraDHCPOption>();
- for (ExtraDhcpOpts opt : port.getExtraDhcpOpts()) {
- NeutronPort_ExtraDHCPOption arg = new NeutronPort_ExtraDHCPOption();
- arg.setName(opt.getOptName());
- arg.setValue(opt.getOptValue());
- arg.setIpVersion(NeutronSubnetAware.IPV_MAP.get(opt.getIpVersion()));
- options.add(arg);
+ FixedIps portIpWithSubnet = potentialPortIpWithSubnet.get();
+ L3ContextId routerL3Context = new L3ContextId(port.getDeviceId());
+ // change L3Context for all EPs with same subnet as router port
+ changeL3ContextForEpsInSubnet(portIpWithSubnet.getSubnetId(), neutron.getPorts(), routerL3Context);
+ // set L3Context as parent for bridge domain which is parent of subnet
+ TenantId tenantId = new TenantId(port.getTenantId().getValue());
+ Optional<Subnet> potentialRouterPortSubnet = SubnetUtils.findSubnet(portIpWithSubnet.getSubnetId(), neutron.getSubnets());
+ if (!potentialRouterPortSubnet.isPresent()) {
+ LOG.warn("Illegal state - router interface port is in subnet which does not exist. {}",
+ port);
+ return;
}
- result.setExtraDHCPOptions(options);
- }
- if (port.getFixedIps() != null) {
- List<Neutron_IPs> ips = new ArrayList<Neutron_IPs>();
- for (FixedIps mdIP : port.getFixedIps()) {
- Neutron_IPs ip = new Neutron_IPs();
- ip.setIpAddress(String.valueOf(mdIP.getIpAddress().getValue()));
- ip.setSubnetUUID(mdIP.getSubnetId().getValue());
- ips.add(ip);
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ Subnet routerPortSubnet = potentialRouterPortSubnet.get();
+ L2BridgeDomainId l2BdId = new L2BridgeDomainId(routerPortSubnet.getNetworkId().getValue());
+ L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(routerL3Context).build();
+ rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd);
+ // set virtual router IP for subnet
+ org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet subnet =
+ NeutronSubnetAware.createSubnet(routerPortSubnet, portIpWithSubnet.getIpAddress());
+ rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet);
+ DataStoreHelper.submitToDs(rwTx);
+ } else if (PortUtils.isDhcpPort(port)) {
+ // process as normal port but put it to DHCP group
+ LOG.trace("Port is DHCP port: {}", port.getUuid().getValue());
+ Optional<FixedIps> firstFixedIps = PortUtils.resolveFirstFixedIps(port);
+ if (!firstFixedIps.isPresent()) {
+ LOG.warn("DHCP port does not have an IP address. {}", port);
+ return;
}
- result.setFixedIPs(ips);
- }
- result.setMacAddress(port.getMacAddress());
- result.setName(port.getName());
- result.setNetworkUUID(port.getNetworkId().getValue());
- if(port.getSecurityGroups() != null) {
- result.setSecurityGroups(Lists.transform(port.getSecurityGroups(),
- new Function<Uuid, NeutronSecurityGroup>() {
-
- @Override
- public NeutronSecurityGroup apply(Uuid uuid) {
- NeutronSecurityGroup sg = new NeutronSecurityGroup();
- sg.setID(uuid.getValue());
- return sg;
- }
- }));
- }
- result.setStatus(port.getStatus());
- if (port.getTenantId() != null) {
- result.setTenantID(port.getTenantId());
- }
- result.setID(port.getUuid().getValue());
- addExtensions(port, result);
- return result;
- }
-
- protected static void addExtensions(Port port, NeutronPort result) {
- PortBindingExtension binding = port.getAugmentation(PortBindingExtension.class);
- result.setBindinghostID(binding.getHostId());
- if (binding.getVifDetails() != null) {
- List<NeutronPort_VIFDetail> details = new ArrayList<NeutronPort_VIFDetail>();
- for (VifDetails vifDetail : binding.getVifDetails()) {
- NeutronPort_VIFDetail detail = new NeutronPort_VIFDetail();
- detail.setPortFilter(vifDetail.isPortFilter());
- detail.setOvsHybridPlug(vifDetail.isOvsHybridPlug());
- details.add(detail);
+ RegisterEndpointInputBuilder epInBuilder = createBasicEndpointInputBuilder(port);
+ // endpoint has only one network containment therefore only first IP is used
+ FixedIps ipWithSubnet = firstFixedIps.get();
+ epInBuilder.setNetworkContainment(new SubnetId(ipWithSubnet.getSubnetId().getValue()));
+ L3Address l3Address = new L3AddressBuilder().setL3Context(new L3ContextId(port.getNetworkId().getValue()))
+ .setIpAddress(ipWithSubnet.getIpAddress())
+ .build();
+ epInBuilder.setL3Address(ImmutableList.of(l3Address));
+ List<EndpointGroupId> epgsFromSecGroups = resolveEpgIdsFromSecGroups(port.getSecurityGroups());
+ epgsFromSecGroups.add(NetworkService.EPG_ID);
+ epInBuilder.setEndpointGroups(epgsFromSecGroups);
+ registerEndpointAndStoreMapping(epInBuilder.build(), port);
+ } else if (PortUtils.isNormalPort(port)) {
+ LOG.trace("Port is normal port: {}", port.getUuid().getValue());
+ RegisterEndpointInputBuilder epInBuilder = createBasicEndpointInputBuilder(port);
+ Optional<FixedIps> firstFixedIps = PortUtils.resolveFirstFixedIps(port);
+ if (firstFixedIps.isPresent()) {
+ // endpoint has only one network containment therefore only first IP is used
+ FixedIps ipWithSubnet = firstFixedIps.get();
+ epInBuilder.setNetworkContainment(new SubnetId(ipWithSubnet.getSubnetId().getValue()));
+ L3Address l3Address = resolveL3AddressFromPort(port, ipWithSubnet, neutron);
+ epInBuilder.setL3Address(ImmutableList.of(l3Address));
+ } else {
+ epInBuilder.setNetworkContainment(new L2FloodDomainId(port.getNetworkId().getValue()));
}
- result.setVIFDetail(details);
- }
- result.setBindingvifType(binding.getVifType());
- result.setBindingvnicType(binding.getVnicType());
- }
-
- @Override
- public int canCreate(NeutronPort port) {
- LOG.trace("canCreate port - {}", port);
- // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
- List<Neutron_IPs> fixedIPs = port.getFixedIPs();
- if (fixedIPs != null && fixedIPs.size() > 1) {
- LOG.warn("Neutron mapper does not support multiple IPs on the same port.");
- return StatusCode.BAD_REQUEST;
- }
- NeutronRouter router = (isRouterGatewayPort(port) || isRouterInterfacePort(port)) ? NeutronRouterAware.getRouterForPort(port.getDeviceID()) : null;
- if (router != null) {
- return NeutronRouterAware.canAttachInterface(router, createNeutronRouter_InterfaceFrom(port), dataProvider);
- }
- return StatusCode.OK;
- }
-
- private static NeutronRouter_Interface createNeutronRouter_InterfaceFrom(NeutronPort port) {
- NeutronRouter_Interface nri = new NeutronRouter_Interface();
- if (port.getID() != null) {
- nri.setID(port.getID());
- nri.setPortUUID(port.getID());
- }
- if (port.getTenantID() != null) {
- nri.setTenantID(port.getTenantID());
- }
- if (port.getFixedIPs() != null && port.getFixedIPs().size() == 1) {
- // supported case
- nri.setSubnetUUID(port.getFixedIPs().get(0).getSubnetUUID());
+ List<EndpointGroupId> epgsFromSecGroups = resolveEpgIdsFromSecGroups(port.getSecurityGroups());
+ epgsFromSecGroups.add(NetworkClient.EPG_ID);
+ epInBuilder.setEndpointGroups(epgsFromSecGroups);
+ registerEndpointAndStoreMapping(epInBuilder.build(), port);
+ } else if (PortUtils.isRouterGatewayPort(port)) {
+ // do nothing because actual trigger is attaching of port to router
+ LOG.trace("Port is router gateway port: {}", port.getUuid().getValue());
+ } else if (PortUtils.isFloatingIpPort(port)) {
+ // do nothing because trigger is floating IP
+ LOG.trace("Port is floating ip: {}", port.getUuid().getValue());
+ } else {
+ LOG.warn("Unknown port: {}", port);
}
- return nri;
}
- @Override
- public void created(NeutronPort port) {
- LOG.trace("created port - {}", port);
- if (isRouterInterfacePort(port) || isRouterGatewayPort(port)) {
- NeutronRouter router = NeutronRouterAware.getRouterForPort(port.getDeviceID());
- if (router != null) {
- NeutronRouterAware.neutronRouterInterfaceAttached(router, createNeutronRouter_InterfaceFrom(port),
- dataProvider, epService);
- return;
- }
- }
- if (isFloatingIpPort(port)) {
- LOG.trace("Port is floating ip - {} device id - {}", port.getID(), port.getDeviceID());
- return;
- }
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
- if (isDhcpPort(port)) {
- LOG.trace("Port is DHCP port. - {}", port.getID());
- Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs());
- if (firstIp == null) {
- LOG.warn("Illegal state - DHCP port does not have an IP address.");
- rwTx.cancel();
- return;
- }
- } else {
- // this is here b/c stable/kilo sends sec-groups only with port
- List<NeutronSecurityGroup> secGroups = port.getSecurityGroups();
- if (secGroups != null) {
- for (NeutronSecurityGroup secGroup : secGroups) {
- EndpointGroupId epgId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- Optional<EndpointGroup> potentialEpg = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.endpointGroupIid(tenantId, epgId), rwTx);
- if (!potentialEpg.isPresent()) {
- boolean isSecGroupCreated = secGrpAware.addNeutronSecurityGroup(secGroup, rwTx);
- if (!isSecGroupCreated) {
- rwTx.cancel();
- return;
- }
- } else {
- List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
- if (secRules != null) {
- for (NeutronSecurityRule secRule : secRules) {
- secRuleAware.addNeutronSecurityRule(secRule, rwTx);
- }
- }
- }
+ private void changeL3ContextForEpsInSubnet(Uuid subnetUuid, Ports ports, L3ContextId newl3Context) {
+ Set<Port> portsInSameSubnet = PortUtils.findPortsBySubnet(subnetUuid, ports);
+ for (Port portInSameSubnet : portsInSameSubnet) {
+ if (PortUtils.isNormalPort(portInSameSubnet) || PortUtils.isDhcpPort(portInSameSubnet)) {
+ // endpoints are created only from neutron normal port or DHCP port
+ Optional<FixedIps> firstFixedIps = PortUtils.resolveFirstFixedIps(portInSameSubnet);
+ if (firstFixedIps.isPresent()) {
+ // endpoint has only one network containment therefore only first IP is used
+ FixedIps ipWithSubnet = firstFixedIps.get();
+ RegisterEndpointInputBuilder epInBuilder = createBasicEndpointInputBuilder(portInSameSubnet);
+ epInBuilder.setNetworkContainment(new SubnetId(ipWithSubnet.getSubnetId().getValue()));
+ L3Address l3Address = new L3AddressBuilder().setL3Context(newl3Context)
+ .setIpAddress(ipWithSubnet.getIpAddress())
+ .build();
+ epInBuilder.setL3Address(ImmutableList.of(l3Address));
+ List<EndpointGroupId> epgsFromSecGroups =
+ resolveEpgIdsFromSecGroups(portInSameSubnet.getSecurityGroups());
+ epgsFromSecGroups.add(NetworkClient.EPG_ID);
+ epRegistrator.registerEndpoint(epInBuilder.build());
+ // unregister L3EP
+ L3ContextId oldL3Context = new L3ContextId(portInSameSubnet.getNetworkId().getValue());
+ L3 l3 = new L3Builder().setL3Context(oldL3Context).setIpAddress(ipWithSubnet.getIpAddress())
+ .build();
+ UnregisterEndpointInput epUnreg = new UnregisterEndpointInputBuilder().setL3(ImmutableList.of(l3)).build();
+ epRegistrator.unregisterEndpoint(epUnreg);
}
}
}
- boolean isNeutronPortCreated = addNeutronPort(port, rwTx, epService);
- if (!isNeutronPortCreated) {
- rwTx.cancel();
- return;
- }
+ }
- DataStoreHelper.submitToDs(rwTx);
+ private static RegisterEndpointInputBuilder createBasicEndpointInputBuilder(Port port) {
+ return new RegisterEndpointInputBuilder().setL2Context(new L2BridgeDomainId(port.getNetworkId().getValue()))
+ .setMacAddress(new MacAddress(port.getMacAddress()))
+ .setTenant(new TenantId(port.getTenantId().getValue()))
+ .setTimestamp(System.currentTimeMillis());
}
- public static boolean addNeutronPort(NeutronPort port, ReadWriteTransaction rwTx, EndpointService epService) {
- TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
- L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
- boolean isFwCtxValid = validateForwardingCtx(fwCtx);
- if (!isFwCtxValid) {
- return false;
+ private static List<EndpointGroupId> resolveEpgIdsFromSecGroups(@Nullable List<Uuid> securityGroups) {
+ List<EndpointGroupId> epgIds = new ArrayList<>();
+ if ((securityGroups == null || securityGroups.isEmpty())) {
+ return epgIds;
}
- EndpointKey epKey = new EndpointKey(fwCtx.getL2BridgeDomain().getId(), new MacAddress(port.getMacAddress()));
- addNeutronGbpMapping(port, epKey, rwTx);
- try {
- RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx);
- RpcResult<Void> rpcResult = epService.registerEndpoint(registerEpRpcInput).get();
- if (!rpcResult.isSuccessful()) {
- LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput);
- return false;
- }
- } catch (InterruptedException | ExecutionException e) {
- LOG.error("addNeutronPort failed. {}", port, e);
- return false;
+ for (Uuid secGrp : securityGroups) {
+ epgIds.add(new EndpointGroupId(secGrp.getValue()));
}
- return true;
+ return epgIds;
}
- private static void addNeutronGbpMapping(NeutronPort port, EndpointKey epKey, ReadWriteTransaction rwTx) {
- UniqueId portId = new UniqueId(port.getID());
- if (!isRouterInterfacePort(port) && !isRouterGatewayPort(port) && !isFloatingIpPort(port)) {
- LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", port.getID(),
- port.getDeviceOwner(), epKey);
+ private void registerEndpointAndStoreMapping(RegisterEndpointInput regEpInput, Port port) {
+ boolean isRegisteredEndpoint = epRegistrator.registerEndpoint(regEpInput);
+ if (isRegisteredEndpoint) {
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ UniqueId portId = new UniqueId(port.getUuid().getValue());
+ EndpointKey epKey = new EndpointKey(new L2BridgeDomainId(port.getNetworkId().getValue()),
+ new MacAddress(port.getMacAddress()));
+ LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}",
+ port.getUuid().getValue(), port.getDeviceOwner(), epKey);
EndpointByPort endpointByPort = MappingFactory.createEndpointByPort(epKey, portId);
rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.endpointByPortIid(portId), endpointByPort,
true);
rwTx.put(LogicalDatastoreType.OPERATIONAL,
NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), portByEndpoint,
true);
+ DataStoreHelper.submitToDs(rwTx);
}
}
- public static boolean addL3EndpointForExternalGateway(TenantId tenantId, L3ContextId l3ContextId,
- IpAddress ipAddress, NetworkDomainId networkContainment, ReadWriteTransaction rwTx) {
-
- EndpointL3Key epL3Key = new EndpointL3Key(ipAddress, l3ContextId);
- addNeutronExtGwGbpMapping(epL3Key, rwTx);
- List<EndpointGroupId> epgIds = new ArrayList<>();
- epgIds.add(MappingUtils.EPG_EXTERNAL_ID);
- EndpointL3 epL3 = createL3Endpoint(tenantId, epL3Key, epgIds, networkContainment);
- InstanceIdentifier<EndpointL3> iid_l3 = IidFactory.l3EndpointIid(l3ContextId, ipAddress);
- rwTx.put(LogicalDatastoreType.OPERATIONAL, iid_l3, epL3, true);
- return true;
- }
-
- private static void addNeutronExtGwGbpMapping(EndpointL3Key epL3Key, ReadWriteTransaction rwTx) {
- ExternalGatewayAsL3Endpoint externalGatewayL3Endpoint = MappingFactory.createExternalGatewayByL3Endpoint(epL3Key);
- rwTx.put(LogicalDatastoreType.OPERATIONAL, NeutronGbpIidFactory.externalGatewayAsL3Endpoint(epL3Key.getL3Context(), epL3Key.getIpAddress()),
- externalGatewayL3Endpoint, true);
- }
-
- public static boolean addL3PrefixEndpoint(L3ContextId l3ContextId, IpPrefix ipPrefix, IpAddress ipAddress, TenantId tenantId,
- EndpointService epService) {
- EndpointL3PrefixKey epL3PrefixKey = new EndpointL3PrefixKey( ipPrefix, l3ContextId);
- EndpointL3Key epL3Key = null;
- List<EndpointL3Key> l3Gateways = new ArrayList<>();
- if (ipAddress != null) {
- epL3Key = new EndpointL3Key(ipAddress, l3ContextId);
- l3Gateways.add(epL3Key);
- }
- try {
- RegisterL3PrefixEndpointInput registerL3PrefixEpRpcInput = createRegisterL3PrefixEndpointInput(epL3PrefixKey, l3Gateways,tenantId);
-
- RpcResult<Void> rpcResult = epService.registerL3PrefixEndpoint(registerL3PrefixEpRpcInput).get();
- if (!rpcResult.isSuccessful()) {
- LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerL3PrefixEpRpcInput);
- return false;
- }
- } catch (InterruptedException | ExecutionException e) {
- LOG.error("addPort - RPC invocation failed.", e);
- return false;
- }
- return true;
-
- }
-
- private static boolean validateForwardingCtx(ForwardingCtx fwCtx) {
- if (fwCtx.getL2FloodDomain() == null) {
- LOG.warn("Illegal state - l2-flood-domain does not exist.");
- return false;
- }
- if (fwCtx.getL2BridgeDomain() == null) {
- LOG.warn("Illegal state - l2-bridge-domain does not exist.");
- return false;
- }
- if (fwCtx.getL3Context() == null) {
- LOG.warn("Illegal state - l3-context does not exist.");
- return false;
- }
- return true;
- }
-
@Override
- public int canUpdate(NeutronPort delta, NeutronPort original) {
- LOG.trace("catUpdate port - delta: {} original: {}", delta, original);
- if (delta.getFixedIPs() == null || delta.getFixedIPs().isEmpty()) {
- return StatusCode.OK;
- }
- // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
- List<Neutron_IPs> fixedIPs = delta.getFixedIPs();
- if (fixedIPs != null && fixedIPs.size() > 1) {
- LOG.warn("Neutron mapper does not support multiple IPs on the same port.");
- return StatusCode.BAD_REQUEST;
- }
- boolean wasRouterPort = isRouterGatewayPort(original) || isRouterInterfacePort(original);
- boolean isRouterPort = isRouterGatewayPort(delta) || isRouterInterfacePort(delta);
- if (wasRouterPort || isRouterPort) {
- NeutronRouter router = NeutronRouterAware.getRouterForPort(delta.getDeviceID());
- if (router != null && !wasRouterPort && isRouterPort) {
- return NeutronRouterAware.
- canAttachInterface(router, createNeutronRouter_InterfaceFrom(delta), dataProvider);
- } else if (router != null && wasRouterPort && !isRouterPort) {
- return NeutronRouterAware.canDetachInterface(router, createNeutronRouter_InterfaceFrom(delta));
- }
- }
- return StatusCode.OK;
+ public void onUpdated(Port oldPort, Port newPort, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("updated port - OLD: {}\nNEW: {}", oldPort, newPort);
+ onDeleted(oldPort, oldNeutron, newNeutron);
+ onCreated(newPort, newNeutron);
}
@Override
- public void updated(NeutronPort port) {
- LOG.trace("updated port - {}", port);
- NeutronPort original = null;
- Ports ports = NeutronListener.getNeutronDataBefore().getPorts();
- boolean wasRouterPort = false;
- if (ports != null) {
- for (Port p : ports.getPort()) {
- if (p.getUuid().getValue().equals(port.getID())) {
- original = toNeutron(p);
- wasRouterPort = isRouterGatewayPort(original) || isRouterInterfacePort(original);
- }
- }
- }
- boolean isRouterPort = isRouterGatewayPort(port) || isRouterInterfacePort(port);
- if (original != null && (wasRouterPort || isRouterPort)) {
- NeutronRouter router = NeutronRouterAware.getRouterForPort(port.getDeviceID());
- if (router != null && (!wasRouterPort && isRouterPort)) {
- NeutronRouterAware.neutronRouterInterfaceAttached(router, createNeutronRouter_InterfaceFrom(port),
- dataProvider, epService);
- return;
- } else if (router != null && (wasRouterPort && !isRouterPort)) {
- NeutronRouterAware.neutronRouterInterfaceAttached(router, createNeutronRouter_InterfaceFrom(port),
- dataProvider, epService);
- return;
- }
- }
- if (isFloatingIpPort(port)) {
- LOG.trace("Port is floating ip - {}", port.getID());
- return;
- }
- if (Strings.isNullOrEmpty(port.getTenantID())) {
- LOG.trace("REMOVE ME: Tenant is null - {}", port.getID());
- return;
- }
-
- ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
- MacAddress macAddress = new MacAddress(port.getMacAddress());
- L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx);
- boolean isFwCtxValid = validateForwardingCtx(fwCtx);
- if (!isFwCtxValid) {
- rTx.close();
- return;
- }
-
- Optional<Endpoint> potentionalEp = DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL,
- IidFactory.endpointIid(fwCtx.getL2BridgeDomain().getId(), macAddress), rTx);
- if (!potentionalEp.isPresent()) {
- LOG.warn("Illegal state - endpoint {} does not exist.", new EndpointKey(fwCtx.getL2BridgeDomain().getId(),
- macAddress));
- rTx.close();
- return;
- }
-
- Endpoint ep = potentionalEp.get();
- if (isEpIpDifferentThanPortFixedIp(ep, port) || isEpgDifferentThanSecGrp(ep, port)) {
- UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(ep);
- RegisterEndpointInput registerEpRpcInput = createRegisterEndpointInput(port, fwCtx);
- try {
- RpcResult<Void> rpcResult = epService.unregisterEndpoint(unregisterEpRpcInput).get();
- if (!rpcResult.isSuccessful()) {
- LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput);
- rTx.close();
- return;
- }
- rpcResult = epService.registerEndpoint(registerEpRpcInput).get();
- if (!rpcResult.isSuccessful()) {
- LOG.warn("Illegal state - RPC registerEndpoint failed. Input of RPC: {}", registerEpRpcInput);
- rTx.close();
- return;
- }
- } catch (InterruptedException | ExecutionException e) {
- LOG.error("addPort - RPC invocation failed.", e);
- rTx.close();
+ public void onDeleted(Port port, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("deleted port - {}", port);
+ if (PortUtils.isRouterInterfacePort(port)) {
+ LOG.trace("Port is router interface port: {}", port.getUuid().getValue());
+ // router interface port can have only one IP
+ Optional<FixedIps> potentialPortIpWithSubnet = PortUtils.resolveFirstFixedIps(port);
+ if (!potentialPortIpWithSubnet.isPresent()) {
+ LOG.warn("Illegal state - router interface port does not contain fixed IPs {}",
+ port);
return;
}
- }
- rTx.close();
- }
-
- private boolean isEpIpDifferentThanPortFixedIp(Endpoint ep, NeutronPort port) {
- List<L3Address> l3Addresses = ep.getL3Address();
- List<Neutron_IPs> fixedIPs = port.getFixedIPs();
- if ((l3Addresses == null || l3Addresses.isEmpty()) && (fixedIPs == null || fixedIPs.isEmpty())) {
- return false;
- }
- if (l3Addresses != null && !l3Addresses.isEmpty() && fixedIPs != null && !fixedIPs.isEmpty()) {
- if (fixedIPs.get(0).getIpAddress().equals(Utils.getStringIpAddress(l3Addresses.get(0).getIpAddress()))) {
- return false;
- }
- }
- return true;
- }
-
- private boolean isEpgDifferentThanSecGrp(Endpoint ep, NeutronPort port) {
- List<EndpointGroupId> epgIds = ep.getEndpointGroups();
- List<NeutronSecurityGroup> secGroups = port.getSecurityGroups();
- if ((epgIds == null || epgIds.isEmpty()) && (secGroups == null || secGroups.isEmpty())) {
- return false;
- }
- if (epgIds != null && !epgIds.isEmpty() && secGroups != null && !secGroups.isEmpty()) {
- if (epgIds.size() != secGroups.size()) {
- return true;
- }
- Collection<EndpointGroupId> epgIdsFromSecGroups = Collections2.transform(secGroups,
- new Function<NeutronSecurityGroup, EndpointGroupId>() {
-
- @Override
- public EndpointGroupId apply(NeutronSecurityGroup input) {
- return new EndpointGroupId(input.getSecurityGroupUUID());
- }
- });
- // order independent equals
- Set<EndpointGroupId> one = new HashSet<>(epgIds);
- Set<EndpointGroupId> two = new HashSet<>(epgIdsFromSecGroups);
- if (one.equals(two)) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public int canDelete(NeutronPort port) {
- LOG.trace("canDelete port - {}", port);
- NeutronRouter router = (isRouterGatewayPort(port) || isRouterInterfacePort(port)) ? NeutronRouterAware.getRouterForPort(port.getDeviceID()) : null;
- if (router != null) {
- return NeutronRouterAware.canDetachInterface(router, createNeutronRouter_InterfaceFrom(port));
- }
- return StatusCode.OK;
- }
-
- @Override
- public void deleted(NeutronPort port) {
- LOG.trace("deleted port - {}", port);
- if (isRouterInterfacePort(port) || isRouterGatewayPort(port)) {
- NeutronRouter router = NeutronRouterAware.getRouterForPort(port.getDeviceID());
- if (router != null) {
- NeutronRouterAware.neutronRouterInterfaceDetached(router, createNeutronRouter_InterfaceFrom(port),
- dataProvider, epService);
+ FixedIps portIpWithSubnet = potentialPortIpWithSubnet.get();
+ L3ContextId l3Context = new L3ContextId(port.getNetworkId().getValue());
+ // change L3Context for all EPs with same subnet as router port
+ changeL3ContextForEpsInSubnet(portIpWithSubnet.getSubnetId(), oldNeutron.getPorts(), l3Context);
+ // set L3Context as parent for bridge domain which is parent of subnet
+ TenantId tenantId = new TenantId(port.getTenantId().getValue());
+ Optional<Subnet> potentialRouterPortSubnet = SubnetUtils.findSubnet(portIpWithSubnet.getSubnetId(), oldNeutron.getSubnets());
+ if (!potentialRouterPortSubnet.isPresent()) {
+ LOG.warn("Illegal state - router interface port is in subnet which does not exist. {}",
+ port);
return;
}
- }
- if (isFloatingIpPort(port)) {
- LOG.trace("Port is floating ip - {} device id - {}", port.getID(), port.getDeviceID());
- return;
- }
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(port.getTenantID()));
- L2FloodDomainId l2FdId = new L2FloodDomainId(port.getNetworkUUID());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
- boolean isFwCtxValid = validateForwardingCtx(fwCtx);
- if (!isFwCtxValid) {
- rwTx.cancel();
- return;
- }
-
- UnregisterEndpointInput unregisterEpRpcInput = createUnregisterEndpointInput(port, fwCtx);
- boolean isEndpointUnregistered = false;
- try {
- isEndpointUnregistered = epService.unregisterEndpoint(unregisterEpRpcInput).get().isSuccessful();
- } catch (InterruptedException | ExecutionException e) {
- LOG.error("unregisterEndpoint - RPC invocation failed.", e);
- }
- if (isEndpointUnregistered) {
- EndpointKey epKey = new EndpointKey(fwCtx.getL2BridgeDomain().getId(), new MacAddress(port.getMacAddress()));
- deleteNeutronGbpMapping(port, epKey, rwTx);
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ Subnet routerPortSubnet = potentialRouterPortSubnet.get();
+ L2BridgeDomainId l2BdId = new L2BridgeDomainId(routerPortSubnet.getNetworkId().getValue());
+ L2BridgeDomain l2Bd = new L2BridgeDomainBuilder().setId(l2BdId).setParent(l3Context).build();
+ rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd);
+ // remove virtual router IP for subnet
+ org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet subnet =
+ NeutronSubnetAware.createSubnet(routerPortSubnet, null);
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet);
DataStoreHelper.submitToDs(rwTx);
+ } else if (PortUtils.isDhcpPort(port)) {
+ LOG.trace("Port is DHCP port: {}", port.getUuid().getValue());
+ UnregisterEndpointInput unregEpInput = createUnregisterEndpointInput(port, oldNeutron);
+ unregisterEndpointAndRemoveMapping(unregEpInput, port);
+ } else if (PortUtils.isNormalPort(port)) {
+ LOG.trace("Port is normal port: {}", port.getUuid().getValue());
+ UnregisterEndpointInput unregEpInput = createUnregisterEndpointInput(port, oldNeutron);
+ unregisterEndpointAndRemoveMapping(unregEpInput, port);
+ } else if (PortUtils.isRouterGatewayPort(port)) {
+ // do nothing because actual trigger is detaching of port from router
+ LOG.trace("Port is router gateway port: {}", port.getUuid().getValue());
+ } else if (PortUtils.isFloatingIpPort(port)) {
+ // do nothing because trigger is floating IP
+ LOG.trace("Port is floating ip: {}", port.getUuid().getValue());
} else {
- LOG.warn("Illegal state - RPC unregisterEndpoint failed. Input of RPC: {}", unregisterEpRpcInput);
- rwTx.cancel();
- }
- }
-
- private static void deleteNeutronGbpMapping(NeutronPort port, EndpointKey epKey, ReadWriteTransaction rwTx) {
- UniqueId portId = new UniqueId(port.getID());
- if (!isRouterInterfacePort(port) && !isRouterGatewayPort(port) && !isFloatingIpPort(port)) {
- LOG.trace("Adding Port-Endpoint mapping for port {} (device owner {}) and endpoint {}", port.getID(),
- port.getDeviceOwner(), epKey);
- DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
- NeutronGbpIidFactory.endpointByPortIid(portId), rwTx);
- DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
- NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx);
- }
- }
-
- private static RegisterL3PrefixEndpointInput createRegisterL3PrefixEndpointInput(EndpointL3PrefixKey key, List<EndpointL3Key> endpointL3Keys, TenantId tenantId) {
- List<EndpointL3Gateways> l3Gateways = new ArrayList<EndpointL3Gateways>();
- for (EndpointL3Key epL3Key : endpointL3Keys) {
- EndpointL3Gateways l3Gateway = new EndpointL3GatewaysBuilder().setIpAddress(epL3Key.getIpAddress())
- .setL3Context(epL3Key.getL3Context())
- .build();
- l3Gateways.add(l3Gateway);
+ LOG.warn("Unknown port: {}", port);
}
- RegisterL3PrefixEndpointInputBuilder inputBuilder = new RegisterL3PrefixEndpointInputBuilder()
- .setL3Context(key.getL3Context())
- .setIpPrefix(key.getIpPrefix())
- .setEndpointGroup(MappingUtils.EPG_EXTERNAL_ID)
- .setTenant(tenantId)
- .setEndpointL3Gateways(l3Gateways)
- .setTimestamp(System.currentTimeMillis());
- return inputBuilder.build();
- }
-
- private static EndpointL3 createL3Endpoint(TenantId tenantId, EndpointL3Key epL3Key,
- List<EndpointGroupId> epgIds, NetworkDomainId containment) {
-
- EndpointL3Builder epL3Builder = new EndpointL3Builder()
- .setTenant(tenantId)
- .setNetworkContainment(containment)
- .setIpAddress(epL3Key.getIpAddress())
- .setL3Context(epL3Key.getL3Context())
- .setEndpointGroups(epgIds)
- .setTimestamp(System.currentTimeMillis());
-
- return epL3Builder.build();
}
- private static RegisterEndpointInput createRegisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) {
- List<EndpointGroupId> epgIds = new ArrayList<>();
- if (isDhcpPort(port)) {
- epgIds.add(NetworkService.EPG_ID);
- }
-
- List<NeutronSecurityGroup> securityGroups = port.getSecurityGroups();
- if ((securityGroups == null || securityGroups.isEmpty())) {
- if (!isDhcpPort(port)) {
- LOG.warn(
- "Port {} does not contain any security group. The port should belong to 'default' security group at least.",
- port.getID());
- }
- } else {
- for (NeutronSecurityGroup secGrp : securityGroups) {
- epgIds.add(new EndpointGroupId(secGrp.getSecurityGroupUUID()));
- }
- epgIds.add(NetworkClient.EPG_ID);
- }
- RegisterEndpointInputBuilder inputBuilder = new RegisterEndpointInputBuilder().setL2Context(
- fwCtx.getL2BridgeDomain().getId())
+ private UnregisterEndpointInput createUnregisterEndpointInput(Port port, Neutron neutron) {
+ UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
+ L2 l2Ep = new L2Builder().setL2Context(new L2BridgeDomainId(port.getNetworkId().getValue()))
.setMacAddress(new MacAddress(port.getMacAddress()))
- .setTenant(new TenantId(Utils.normalizeUuid(port.getTenantID())))
- .setEndpointGroups(epgIds)
- .setTimestamp(System.currentTimeMillis());
- List<Neutron_IPs> fixedIPs = port.getFixedIPs();
- // TODO Li msunal this getting of just first IP has to be rewrite when OFOverlay renderer
- // will support l3-endpoints. Then we will register L2 and L3 endpoints separately.
- Neutron_IPs firstIp = MappingUtils.getFirstIp(fixedIPs);
- if (firstIp != null) {
- inputBuilder.setNetworkContainment(new SubnetId(firstIp.getSubnetUUID()));
- L3Address l3Address = new L3AddressBuilder().setIpAddress(Utils.createIpAddress(firstIp.getIpAddress()))
- .setL3Context(fwCtx.getL3Context().getId())
+ .build();
+ inputBuilder.setL2(ImmutableList.of(l2Ep));
+ // we've registered EP with only first IP so remove only EP with first IP
+ Optional<FixedIps> potentialFirstIp = PortUtils.resolveFirstFixedIps(port);
+ if (!potentialFirstIp.isPresent()) {
+ FixedIps firstIp = potentialFirstIp.get();
+ L3Address l3Address = resolveL3AddressFromPort(port, firstIp, neutron);
+ L3 l3 = new L3Builder().setIpAddress(l3Address.getIpAddress())
+ .setL3Context(l3Address.getL3Context())
.build();
- inputBuilder.setL3Address(ImmutableList.of(l3Address));
- }
- if (!Strings.isNullOrEmpty(port.getName())) {
-
+ inputBuilder.setL3(ImmutableList.of(l3));
}
return inputBuilder.build();
}
- public static boolean isDhcpPort(NeutronPort port) {
- return DEVICE_OWNER_DHCP.equals(port.getDeviceOwner());
- }
-
- public static boolean isRouterInterfacePort(NeutronPort port) {
- return DEVICE_OWNER_ROUTER_IFACE.equals(port.getDeviceOwner());
- }
-
- public static boolean isRouterGatewayPort(NeutronPort port) {
- return DEVICE_OWNER_ROUTER_GATEWAY.equals(port.getDeviceOwner());
- }
-
- public static boolean isFloatingIpPort(NeutronPort port) {
- return DEVICE_OWNER_FLOATING_IP.equals(port.getDeviceOwner());
+ private void unregisterEndpointAndRemoveMapping(UnregisterEndpointInput unregEpInput, Port port) {
+ boolean isUnregisteredEndpoint = epRegistrator.unregisterEndpoint(unregEpInput);
+ if (isUnregisteredEndpoint) {
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ UniqueId portId = new UniqueId(port.getUuid().getValue());
+ EndpointKey epKey = new EndpointKey(new L2BridgeDomainId(port.getNetworkId().getValue()),
+ new MacAddress(port.getMacAddress()));
+ LOG.trace("Removing Port-Endpoint mapping for port {} (device owner {}) and endpoint {}",
+ port.getUuid().getValue(), port.getDeviceOwner(), epKey);
+ DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
+ NeutronGbpIidFactory.endpointByPortIid(portId), rwTx);
+ DataStoreHelper.removeIfExists(LogicalDatastoreType.OPERATIONAL,
+ NeutronGbpIidFactory.portByEndpointIid(epKey.getL2Context(), epKey.getMacAddress()), rwTx);
+ DataStoreHelper.submitToDs(rwTx);
+ }
}
- private UnregisterEndpointInput createUnregisterEndpointInput(Endpoint ep) {
- UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
- L2 l2Ep = new L2Builder().setL2Context(ep.getL2Context()).setMacAddress(ep.getMacAddress()).build();
- inputBuilder.setL2(ImmutableList.of(l2Ep));
- // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
- // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should
- // be registered separately.
- if (ep.getL3Address() != null && !ep.getL3Address().isEmpty()) {
- List<L3> l3Eps = new ArrayList<>();
- for (L3Address ip : ep.getL3Address()) {
- l3Eps.add(new L3Builder().setL3Context(ip.getL3Context()).setIpAddress(ip.getIpAddress()).build());
+ private static L3Address resolveL3AddressFromPort(Port port, FixedIps portFixedIPs, Neutron neutron) {
+ Set<Port> routerIfacePorts = PortUtils.findRouterInterfacePorts(neutron.getPorts());
+ for (Port routerIfacePort : routerIfacePorts) {
+ Uuid routerIfacePortSubnet = routerIfacePort.getFixedIps().get(0).getSubnetId();
+ // if port is in the same subnet as router interface then we want to use L3Context of
+ // router
+ if (portFixedIPs.getSubnetId().equals(routerIfacePortSubnet)) {
+ L3ContextId epL3ContextId = new L3ContextId(routerIfacePort.getDeviceId());
+ LOG.trace("Router interface port was found in the same subnet as port have {}", port);
+ return new L3AddressBuilder().setL3Context(epL3ContextId)
+ .setIpAddress(portFixedIPs.getIpAddress())
+ .build();
}
- inputBuilder.setL3(l3Eps);
}
- return inputBuilder.build();
- }
-
- private UnregisterEndpointInput createUnregisterEndpointInput(NeutronPort port, ForwardingCtx fwCtx) {
- UnregisterEndpointInputBuilder inputBuilder = new UnregisterEndpointInputBuilder();
- L2 l2Ep = new L2Builder().setL2Context(fwCtx.getL2BridgeDomain().getId())
- .setMacAddress(new MacAddress(port.getMacAddress()))
+ return new L3AddressBuilder().setL3Context(new L3ContextId(port.getNetworkId().getValue()))
+ .setIpAddress(portFixedIPs.getIpAddress())
.build();
- inputBuilder.setL2(ImmutableList.of(l2Ep));
- // TODO Li msunal this has to be rewrite when OFOverlay renderer will support l3-endpoints.
- // Endpoint probably will not have l3-addresses anymore, because L2 and L3 endpoints should
- // be registered separately.
- if (port.getFixedIPs() != null && !port.getFixedIPs().isEmpty()) {
- inputBuilder.setL3(createL3s(port.getFixedIPs(), fwCtx.getL3Context().getId()));
- }
- return inputBuilder.build();
}
- private List<L3> createL3s(List<Neutron_IPs> neutronIps, L3ContextId l3ContextId) {
- List<L3> l3s = new ArrayList<>();
- for (Neutron_IPs fixedIp : neutronIps) {
- String ip = fixedIp.getIpAddress();
- L3 l3 = new L3Builder().setIpAddress(Utils.createIpAddress(ip)).setL3Context(l3ContextId).build();
- l3s.add(l3);
- }
- return l3s;
- }
}
import static com.google.common.base.Preconditions.checkNotNull;
-import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
+import java.util.concurrent.ExecutionException;
import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
-import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.groupbasedpolicy.dto.IndexedTenant;
+import org.opendaylight.groupbasedpolicy.neutron.gbp.util.NeutronGbpIidFactory;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.EndpointRegistrator;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronMapperIidFactory;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.PortUtils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SubnetUtils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.INeutronPortCRUD;
-import org.opendaylight.neutron.spi.INeutronSubnetCRUD;
-import org.opendaylight.neutron.spi.NeutronCRUDInterfaces;
-import org.opendaylight.neutron.spi.NeutronPort;
-import org.opendaylight.neutron.spi.NeutronRoute;
-import org.opendaylight.neutron.spi.NeutronRouter;
-import org.opendaylight.neutron.spi.NeutronRouter_Interface;
-import org.opendaylight.neutron.spi.NeutronRouter_NetworkReference;
-import org.opendaylight.neutron.spi.NeutronSubnet;
-import org.opendaylight.neutron.spi.Neutron_IPs;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.EndpointService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.UnregisterEndpointInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.unregister.endpoint.input.L3Builder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3Key;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.mappings.neutron.by.gbp.mappings.external.gateways.as.l3.endpoints.ExternalGatewayAsL3Endpoint;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.TenantBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.ForwardingContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.SubnetBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.l3.attributes.Routes;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.Interfaces;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.router.external_gateway_info.ExternalFixedIps;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-public class NeutronRouterAware implements MappingProcessor<Router, NeutronRouter> {
+public class NeutronRouterAware implements NeutronAware<Router> {
private static final Logger LOG = LoggerFactory.getLogger(NeutronRouterAware.class);
- private static final String DEFAULT_ROUTE = "0.0.0.0/0";
+ public static final InstanceIdentifier<Router> ROUTER_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class).child(Routers.class).child(Router.class).build();
private final DataBroker dataProvider;
- private final EndpointService epService;
+ private final EndpointRegistrator epRegistrator;
- public NeutronRouterAware(DataBroker dataProvider, EndpointService epService) {
+ public NeutronRouterAware(DataBroker dataProvider, EndpointRegistrator epRegistrator) {
this.dataProvider = checkNotNull(dataProvider);
- this.epService = checkNotNull(epService);
+ this.epRegistrator = checkNotNull(epRegistrator);
}
@Override
- public NeutronRouter convertToNeutron(Router router) {
- return toNeutron(router);
- }
-
- private static NeutronRouter toNeutron(Router router) {
- NeutronRouter result = new NeutronRouter();
- result.setID(router.getUuid().getValue());
- result.setName(router.getName());
- result.setTenantID(router.getTenantId());
- result.setAdminStateUp(router.isAdminStateUp());
- result.setStatus(router.getStatus());
- result.setDistributed(router.isDistributed());
- if (router.getGatewayPortId() != null) {
- result.setGatewayPortId(router.getGatewayPortId().getValue());
- }
- if (router.getRoutes() != null) {
- List<NeutronRoute> routes = new ArrayList<NeutronRoute>();
- for (Routes route : router.getRoutes()) {
- NeutronRoute routerRoute = new NeutronRoute();
- routerRoute.setDestination(String.valueOf(route.getDestination().getValue()));
- routerRoute.setNextHop(String.valueOf(route.getNexthop().getValue()));
- routes.add(routerRoute);
- }
- result.setRoutes(routes);
- }
- if (router.getExternalGatewayInfo() != null) {
- NeutronRouter_NetworkReference extGwInfo = new NeutronRouter_NetworkReference();
- extGwInfo.setNetworkID(router.getExternalGatewayInfo().getExternalNetworkId().getValue());
- extGwInfo.setEnableSNAT(router.getExternalGatewayInfo().isEnableSnat());
- if (router.getExternalGatewayInfo().getExternalFixedIps() != null) {
- List<Neutron_IPs> fixedIPs = new ArrayList<Neutron_IPs>();
- for (ExternalFixedIps mdFixedIP : router.getExternalGatewayInfo().getExternalFixedIps()) {
- Neutron_IPs fixedIP = new Neutron_IPs();
- fixedIP.setSubnetUUID(mdFixedIP.getSubnetId().getValue());
- fixedIP.setIpAddress(String.valueOf(mdFixedIP.getIpAddress().getValue()));
- fixedIPs.add(fixedIP);
- }
- extGwInfo.setExternalFixedIPs(fixedIPs);
- }
- result.setExternalGatewayInfo(extGwInfo);
- }
- if (router.getInterfaces() != null) {
- Map<String, NeutronRouter_Interface> interfaces = new HashMap<String, NeutronRouter_Interface>();
- for (Interfaces mdInterface : router.getInterfaces()) {
- NeutronRouter_Interface pojoInterface = new NeutronRouter_Interface();
- String id = mdInterface.getUuid().getValue();
- pojoInterface.setID(id);
- pojoInterface.setTenantID(mdInterface.getTenantId());
- pojoInterface.setSubnetUUID(mdInterface.getSubnetId().getValue());
- pojoInterface.setPortUUID(mdInterface.getPortId().getValue());
- interfaces.put(id, pojoInterface);
- }
- result.setInterfaces(interfaces);
- }
- return result;
- }
-
- @Override
- public int canCreate(NeutronRouter router) {
- LOG.trace("canCreate router - {}", router);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void created(NeutronRouter router) {
+ public void onCreated(Router router, Neutron neutron) {
LOG.trace("created router - {}", router);
- // TODO Li msunal external gateway
- }
-
- @Override
- public int canUpdate(NeutronRouter delta, NeutronRouter original) {
- LOG.trace("canUpdate router - delta: {} original: {}", delta, original);
- // TODO Li msunal external gateway
- return StatusCode.OK;
}
@Override
- public void updated(NeutronRouter router) {
- LOG.trace("updated router - {}", router);
- if (router.getExternalGatewayInfo() == null || router.getExternalGatewayInfo().getExternalFixedIPs() == null) {
- LOG.trace("neutronRouterUpdated - not an external Gateway");
- return;
- }
-
- NeutronCRUDInterfaces neutronCRUDInterface = new NeutronCRUDInterfaces().fetchINeutronPortCRUD(this);
- INeutronPortCRUD portInterface = neutronCRUDInterface.getPortInterface();
- if (portInterface == null) {
- LOG.warn("Illegal state - No provider for {}", INeutronPortCRUD.class.getName());
- return;
- }
+ public void onUpdated(Router oldRouter, Router newRouter, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("updated router - OLD: {}\nNEW: {}", oldRouter, newRouter);
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID()));
- L3ContextId l3ContextIdFromRouterId = new L3ContextId(router.getID());
- InstanceIdentifier<L3Context> l3ContextIidForRouterId = IidFactory.l3ContextIid(tenantId,
- l3ContextIdFromRouterId);
- Optional<L3Context> potentialL3ContextForRouter = DataStoreHelper.readFromDs(
- LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, rwTx);
+ TenantId tenantId = new TenantId(newRouter.getTenantId().getValue());
+ L3ContextId l3ContextIdFromRouterId = new L3ContextId(newRouter.getUuid().getValue());
+ InstanceIdentifier<L3Context> l3ContextIidForRouterId =
+ IidFactory.l3ContextIid(tenantId, l3ContextIdFromRouterId);
+ Optional<L3Context> potentialL3ContextForRouter =
+ DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, rwTx);
L3Context l3Context = null;
if (potentialL3ContextForRouter.isPresent()) {
l3Context = potentialL3ContextForRouter.get();
} else { // add L3 context if missing
- l3Context = createL3ContextFromRouter(router);
+ l3Context = createL3ContextFromRouter(newRouter);
rwTx.put(LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, l3Context);
}
- neutronCRUDInterface = neutronCRUDInterface.fetchINeutronSubnetCRUD(this);
- INeutronSubnetCRUD subnetInterface = neutronCRUDInterface.getSubnetInterface();
- if (subnetInterface == null) {
- LOG.warn("Illegal state - No provider for {}", INeutronSubnetCRUD.class.getName());
- return;
- }
- NeutronSubnet defaultSubnet = subnetInterface.getSubnet(router.getExternalGatewayInfo()
- .getExternalFixedIPs()
- .get(0)
- .getSubnetUUID());
- IpAddress defaultGateway = null;
- if (defaultSubnet != null) {
- defaultGateway = Utils.createIpAddress(defaultSubnet.getGatewayIP());
- //Create L3Endpoint for defaultGateway and write to externalGateways to L3Endpoints in neutron-gbp datastore
- NetworkDomainId containment = new NetworkDomainId(defaultSubnet.getID());
- NeutronPortAware.addL3EndpointForExternalGateway(tenantId, l3Context.getId(), defaultGateway, containment ,rwTx);
- }
- // Create L3Prefix Endpoints for all routes
- if (router.getRoutes().isEmpty()) {
- NeutronRoute defaultRoute = new NeutronRoute();
- defaultRoute.setDestination(DEFAULT_ROUTE);
- defaultRoute.setNextHop(Utils.getStringIpAddress(defaultGateway));
- router.setRoutes(ImmutableList.of(defaultRoute));
-
- }
- if (defaultGateway != null) {
- for (NeutronRoute route : router.getRoutes()) {
- IpPrefix ipPrefix = Utils.createIpPrefix(route.getDestination());
- boolean addedL3Prefix = NeutronPortAware.addL3PrefixEndpoint(l3ContextIdFromRouterId, ipPrefix,
- defaultGateway, tenantId, epService);
- if (!addedL3Prefix) {
- LOG.warn("Could not add EndpointL3Prefix for Neutron route {} for router {}", route, router.getID());
- rwTx.cancel();
- return;
- }
- }
- }
- for (Neutron_IPs externalFixedIp : router.getExternalGatewayInfo().getExternalFixedIPs()) {
- NeutronPort routerPort = portInterface.getPort(router.getGatewayPortId());
- IpAddress ipAddress = Utils.createIpAddress(routerPort.getFixedIPs().get(0).getIpAddress());
- // External subnet associated with gateway port should use the gateway IP not router IP.
- NeutronSubnet neutronSubnet = subnetInterface.getSubnet(externalFixedIp.getSubnetUUID());
- ipAddress = Utils.createIpAddress(neutronSubnet.getGatewayIP());
- SubnetId subnetId = new SubnetId(externalFixedIp.getSubnetUUID());
- Subnet subnet = resolveSubnetWithVirtualRouterIp(tenantId, subnetId, ipAddress, rwTx);
- if (subnet == null) {
+ if (newRouter.getGatewayPortId() != null && oldRouter.getGatewayPortId() == null) {
+ // external network is attached to router
+ Uuid gatewayPortId = newRouter.getGatewayPortId();
+ Optional<Port> potentialGwPort = PortUtils.findPort(gatewayPortId, newNeutron.getPorts());
+ if (!potentialGwPort.isPresent()) {
+ LOG.warn("Illegal state - router gateway port {} does not exist for router {}.",
+ gatewayPortId.getValue(), newRouter);
rwTx.cancel();
return;
}
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet);
-
- if (Strings.isNullOrEmpty(routerPort.getTenantID())) {
- routerPort.setTenantID(router.getTenantID());
- }
- boolean isSuccessful = setNewL3ContextToEpsFromSubnet(tenantId, l3Context, subnet, rwTx, epService);
- if (!isSuccessful) {
+ Port gwPort = potentialGwPort.get();
+ List<FixedIps> fixedIpsFromGwPort = gwPort.getFixedIps();
+ if (fixedIpsFromGwPort == null || fixedIpsFromGwPort.isEmpty()) {
+ LOG.warn("Illegal state - router gateway port {} does not contain fixed IPs {}",
+ gatewayPortId.getValue(), gwPort);
rwTx.cancel();
return;
}
- }
- DataStoreHelper.submitToDs(rwTx);
- }
-
- @Override
- public int canDelete(NeutronRouter router) {
- LOG.trace("canDelete router - {}", router);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void deleted(NeutronRouter router) {
- LOG.trace("deleted router - {}", router);
- }
-
-
- static int canAttachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface, DataBroker dataProvider) {
- LOG.trace("canAttachInterface - router: {} interface: {}", router, routerInterface);
- try (ReadOnlyTransaction rTx = dataProvider.newReadOnlyTransaction()) {
- L3ContextId l3ContextIdFromRouterId = new L3ContextId(router.getID());
- TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID()));
- SubnetId subnetId = new SubnetId(routerInterface.getSubnetUUID());
- Optional<Subnet> potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.subnetIid(tenantId, subnetId), rTx);
+ // router can have only one external network
+ FixedIps ipWithSubnetFromGwPort = fixedIpsFromGwPort.get(0);
+ Optional<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet> potentialSubnet = SubnetUtils.findSubnet(ipWithSubnetFromGwPort.getSubnetId(), newNeutron.getSubnets());
if (!potentialSubnet.isPresent()) {
- LOG.warn("Illegal state - subnet {} does not exist.", subnetId.getValue());
- return StatusCode.NOT_FOUND;
+ LOG.warn("Illegal state - Subnet {} does not exist for router {}.",
+ ipWithSubnetFromGwPort.getSubnetId(), newRouter);
+ rwTx.cancel();
+ return;
}
- Subnet subnet = potentialSubnet.get();
- L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rTx);
- if (fwCtx.getL3Context() != null && fwCtx.getL3Context().getId().equals(l3ContextIdFromRouterId)) {
- // TODO Be msunal
- LOG.warn("Illegal state - Neutron mapper does not support multiple router interfaces in the same subnet yet.");
- return StatusCode.FORBIDDEN;
+ IpAddress gatewayIp = potentialSubnet.get().getGatewayIp();
+ boolean registeredExternalGateway = epRegistrator.registerL3EndpointAsExternalGateway(tenantId, gatewayIp,
+ l3ContextIdFromRouterId, new NetworkDomainId(ipWithSubnetFromGwPort.getSubnetId().getValue()));
+ if (!registeredExternalGateway) {
+ LOG.warn("Could not add L3Prefix as gateway of default route. Gateway port {}", gwPort);
+ rwTx.cancel();
+ return;
}
- return StatusCode.OK;
- }
- }
+ EndpointL3Key epL3Key = new EndpointL3Key(gatewayIp, l3ContextIdFromRouterId);
+ addNeutronExtGwGbpMapping(epL3Key, rwTx);
- static NeutronRouter getRouterForPort(String uuid) {
- Routers routers = NeutronListener.getNeutronDataAfter().getRouters();
- if (routers != null) {
- for (Router router : routers.getRouter()) {
- if (router.getUuid().getValue().equals(uuid)) {
- return toNeutron(router);
- }
+ boolean registeredDefaultRoute = epRegistrator.registerExternalL3PrefixEndpoint(MappingUtils.DEFAULT_ROUTE,
+ l3ContextIdFromRouterId, gatewayIp, tenantId);
+ if (!registeredDefaultRoute) {
+ LOG.warn("Could not add EndpointL3Prefix as default route. Gateway port {}", gwPort);
+ rwTx.cancel();
+ return;
}
- }
- return null;
- }
-
- static void neutronRouterInterfaceAttached(NeutronRouter router, NeutronRouter_Interface routerInterface, DataBroker dataProvider, EndpointService epService) {
- LOG.trace("neutronRouterInterfaceAttached - router: {} interface: {}", router, routerInterface);
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID()));
- L3ContextId l3ContextIdFromRouterId = new L3ContextId(router.getID());
- InstanceIdentifier<L3Context> l3ContextIidForRouterId = IidFactory.l3ContextIid(tenantId,
- l3ContextIdFromRouterId);
- Optional<L3Context> potentialL3ContextForRouter = DataStoreHelper.readFromDs(
- LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, rwTx);
- L3Context l3Context = null;
- if (potentialL3ContextForRouter.isPresent()) {
- l3Context = potentialL3ContextForRouter.get();
- } else { // add L3 context if missing
- l3Context = createL3ContextFromRouter(router);
- rwTx.put(LogicalDatastoreType.CONFIGURATION, l3ContextIidForRouterId, l3Context);
- }
- // Based on Neutron Northbound - Port representing router interface
- // contains exactly on fixed IP
- NeutronPort routerPort = null;
- Ports ports = NeutronListener.getNeutronDataAfter().getPorts();
- if(ports != null) {
- for(Port port : ports.getPort()) {
- if(port.getUuid().getValue().equals(routerInterface.getPortUUID())) {
- routerPort = NeutronPortAware.toNeutron(port);
- break;
- }
+ Subnet subnetWithGw =
+ new SubnetBuilder().setId(new SubnetId(ipWithSubnetFromGwPort.getSubnetId().getValue()))
+ .setVirtualRouterIp(gatewayIp)
+ .build();
+ rwTx.merge(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetWithGw.getId()),
+ subnetWithGw);
+ L2BridgeDomainId l2BdId = new L2BridgeDomainId(potentialSubnet.get().getNetworkId().getValue());
+ Optional<L2BridgeDomain> optBd = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
+ IidFactory.l2BridgeDomainIid(tenantId, l2BdId), rwTx);
+ if (!optBd.isPresent()) {
+ LOG.warn(
+ "Could not read L2-Bridge-Domain {} Modifiaction of it's parent to L3-Context of router {} aborted.",
+ l2BdId, newRouter.getUuid());
+ rwTx.cancel();
+ return;
}
+ L2BridgeDomain l2BdWithGw = new L2BridgeDomainBuilder(optBd.get())
+ .setParent(new L3ContextId(l3ContextIdFromRouterId.getValue()))
+ .build();
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId),
+ l2BdWithGw);
}
- if (routerPort == null) {
- rwTx.cancel();
- return;
- }
- SubnetId subnetId = new SubnetId(routerInterface.getSubnetUUID());
- IpAddress ipAddress = Utils.createIpAddress(routerPort.getFixedIPs().get(0).getIpAddress());
- Subnet subnet = resolveSubnetWithVirtualRouterIp(tenantId, subnetId, ipAddress, rwTx);
- if (subnet == null) {
- rwTx.cancel();
- return;
- }
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet);
-
- boolean isSuccessful = setNewL3ContextToEpsFromSubnet(tenantId, l3Context, subnet, rwTx, epService);
- if (!isSuccessful) {
- rwTx.cancel();
- return;
- }
-
DataStoreHelper.submitToDs(rwTx);
}
- private static @Nonnull L3Context createL3ContextFromRouter(NeutronRouter router) {
+ private static @Nonnull L3Context createL3ContextFromRouter(Router router) {
Name l3ContextName = null;
if (!Strings.isNullOrEmpty(router.getName())) {
l3ContextName = new Name(router.getName());
}
- return new L3ContextBuilder().setId(new L3ContextId(router.getID()))
+ return new L3ContextBuilder().setId(new L3ContextId(router.getUuid().getValue()))
.setName(l3ContextName)
- .setDescription(new Description(MappingUtils.NEUTRON_ROUTER + router.getID()))
+ .setDescription(new Description(MappingUtils.NEUTRON_ROUTER + router.getUuid().getValue()))
.build();
}
- private static @Nullable Subnet resolveSubnetWithVirtualRouterIp(TenantId tenantId, SubnetId subnetId,
- IpAddress ipAddress, ReadTransaction rTx) {
- Optional<Subnet> potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.subnetIid(tenantId, subnetId), rTx);
- if (!potentialSubnet.isPresent()) {
- LOG.warn("Illegal state - subnet {} does not exist.", subnetId.getValue());
- return null;
- }
-
- // TODO: Li alagalah: Add gateways and prefixes instead of
- // VirtualRouterID
- return new SubnetBuilder(potentialSubnet.get()).setVirtualRouterIp(ipAddress).build();
- }
-
- public static boolean setNewL3ContextToEpsFromSubnet(TenantId tenantId, L3Context l3Context, Subnet subnet,
- ReadWriteTransaction rwTx, EndpointService epService) {
- if (subnet.getParent() == null) {
- LOG.warn("Illegal state - subnet {} does not have a parent.", subnet.getId().getValue());
- return false;
- }
-
- L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
- if (fwCtx.getL2BridgeDomain() == null) {
- LOG.warn("Illegal state - l2-flood-domain {} does not have a parent.", l2FdId.getValue());
- return false;
- }
-
- L2BridgeDomain l2BridgeDomain = new L2BridgeDomainBuilder(fwCtx.getL2BridgeDomain()).setParent(
- l3Context.getId()).build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BridgeDomain.getId()),
- l2BridgeDomain);
-
- List<L3> l3Eps = new ArrayList<>();
- L3ContextId oldL3ContextId = fwCtx.getL3Context().getId();
- NeutronSubnet neutronSubnet = new NeutronSubnet();
- Subnets subnets = NeutronListener.getNeutronDataAfter().getSubnets();
- for(org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet s : subnets.getSubnet()) {
- if(s.getUuid().getValue().equals(subnet.getId().getValue())) {
- neutronSubnet = NeutronSubnetAware.toNeutron(s);
- break;
- }
- }
- List<NeutronPort> portsInNeutronSubnet = neutronSubnet.getPortsInSubnet();
- if (portsInNeutronSubnet != null) {
- for (NeutronPort port : portsInNeutronSubnet) {
- if (NeutronPortAware.isRouterGatewayPort(port) || NeutronPortAware.isRouterInterfacePort(port)) {
- continue;
- }
- boolean isPortAdded = NeutronPortAware.addNeutronPort(port, rwTx, epService);
- if (!isPortAdded) {
- return false;
- }
- // TODO Li msunal this has to be rewrite when OFOverlay renderer
- // will support l3-endpoints.
- Neutron_IPs firstIp = MappingUtils.getFirstIp(port.getFixedIPs());
- if (firstIp != null) {
- l3Eps.add(new L3Builder().setL3Context(oldL3ContextId)
- .setIpAddress(Utils.createIpAddress(firstIp.getIpAddress()))
- .build());
- }
- }
- }
- if (neutronSubnet.getGatewayIP() != null) {
- l3Eps.add(new L3Builder().setL3Context(oldL3ContextId)
- .setIpAddress(Utils.createIpAddress(neutronSubnet.getGatewayIP()))
- .build());
- }
-
- if (!l3Eps.isEmpty()) {
- epService.unregisterEndpoint(new UnregisterEndpointInputBuilder().setL3(l3Eps).build());
- }
- return true;
+ private static void addNeutronExtGwGbpMapping(EndpointL3Key epL3Key, ReadWriteTransaction rwTx) {
+ ExternalGatewayAsL3Endpoint externalGatewayL3Endpoint =
+ MappingFactory.createExternalGatewayByL3Endpoint(epL3Key);
+ rwTx.put(LogicalDatastoreType.OPERATIONAL,
+ NeutronGbpIidFactory.externalGatewayAsL3Endpoint(epL3Key.getL3Context(), epL3Key.getIpAddress()),
+ externalGatewayL3Endpoint, true);
}
- public static int canDetachInterface(NeutronRouter router, NeutronRouter_Interface routerInterface) {
- LOG.trace("canDetachInterface - router: {} interface: {}", router, routerInterface);
- // nothing to consider
- return StatusCode.OK;
+ @Override
+ public void onDeleted(Router router, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("deleted router - {}", router);
}
- public static void neutronRouterInterfaceDetached(NeutronRouter router, NeutronRouter_Interface routerInterface, DataBroker dataProvider, EndpointService epService) {
- LOG.trace("neutronRouterInterfaceDetached - router: {} interface: {}", router, routerInterface);
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- TenantId tenantId = new TenantId(Utils.normalizeUuid(router.getTenantID()));
- L3ContextId l3ContextId = new L3ContextId(router.getID());
- SubnetId subnetId = new SubnetId(routerInterface.getSubnetUUID());
- DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
- IidFactory.l3ContextIid(tenantId, l3ContextId), rwTx);
-
- Optional<Subnet> potentialSubnet = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.subnetIid(tenantId, subnetId), rwTx);
- if (!potentialSubnet.isPresent()) {
- LOG.warn("Illegal state - subnet {} does not exist.", subnetId.getValue());
- rwTx.cancel();
- return;
- }
-
- Subnet subnet = new SubnetBuilder(potentialSubnet.get()).setVirtualRouterIp(null).build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetId), subnet);
-
- L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
- if (fwCtx.getL2BridgeDomain() == null) {
- LOG.warn("Illegal state - l2-flood-domain {} does not have a parent.", l2FdId.getValue());
- rwTx.cancel();
- return;
- }
-
- Optional<NetworkMapping> potentialNetworkMapping = DataStoreHelper.readFromDs(LogicalDatastoreType.OPERATIONAL,
- NeutronMapperIidFactory.networkMappingIid(l2FdId), rwTx);
- if (!potentialNetworkMapping.isPresent()) {
- LOG.warn("Illegal state - network-mapping {} does not exist.", l2FdId.getValue());
- rwTx.cancel();
- return;
- }
-
- L2BridgeDomain l2BridgeDomain = new L2BridgeDomainBuilder(fwCtx.getL2BridgeDomain()).setParent(
- potentialNetworkMapping.get().getL3ContextId()).build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BridgeDomain.getId()),
- l2BridgeDomain);
- NeutronSubnet neutronSubnet = new NeutronSubnet();
- Subnets subnets = NeutronListener.getNeutronDataAfter().getSubnets();
- for (org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet s : subnets.getSubnet()) {
- if (s.getUuid().getValue().equals(subnet.getId().getValue())) {
- neutronSubnet = NeutronSubnetAware.toNeutron(s);
- break;
- }
- }
- List<NeutronPort> portsInNeutronSubnet = neutronSubnet.getPortsInSubnet();
- for (NeutronPort port : portsInNeutronSubnet) {
- if (NeutronPortAware.isRouterGatewayPort(port) || NeutronPortAware.isRouterInterfacePort(port)) {
- continue;
- }
- boolean isPortAdded = NeutronPortAware.addNeutronPort(port, rwTx, epService);
- if (!isPortAdded) {
- rwTx.cancel();
- return;
- }
- }
- }
}
--- /dev/null
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
+import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
+import org.opendaylight.groupbasedpolicy.util.IidFactory;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroupBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.ExternalImplicitGroupBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+
+public class NeutronSecurityGroupAware implements NeutronAware<SecurityGroup> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityGroupAware.class);
+ public static final InstanceIdentifier<SecurityGroup> SECURITY_GROUP_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class).child(SecurityGroups.class).child(SecurityGroup.class).build();
+ private final DataBroker dataProvider;
+
+ public NeutronSecurityGroupAware(DataBroker dataProvider) {
+ this.dataProvider = checkNotNull(dataProvider);
+ }
+
+ @Override
+ public void onCreated(SecurityGroup createdSecGroup, Neutron neutron) {
+ LOG.trace("created securityGroup - {}", createdSecGroup);
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ boolean isSecGroupCreated = addNeutronSecurityGroup(createdSecGroup, rwTx);
+ if (isSecGroupCreated) {
+ DataStoreHelper.submitToDs(rwTx);
+ } else {
+ rwTx.cancel();
+ }
+ }
+
+ public boolean addNeutronSecurityGroup(SecurityGroup secGroup, ReadWriteTransaction rwTx) {
+ TenantId tId = new TenantId(secGroup.getTenantId().getValue());
+ EndpointGroupId epgId = new EndpointGroupId(secGroup.getUuid().getValue());
+ if (epgId.getValue().equals(MappingUtils.EIG_UUID.getValue())) {
+ ExternalImplicitGroup eig = new ExternalImplicitGroupBuilder().setId(epgId).build();
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.externalImplicitGroupIid(tId, epgId), eig, true);
+ }
+ EndpointGroupBuilder epgBuilder = new EndpointGroupBuilder().setId(epgId);
+ if (!Strings.isNullOrEmpty(secGroup.getName())) {
+ try {
+ epgBuilder.setName(new Name(secGroup.getName()));
+ } catch (Exception e) {
+ LOG.info("Name '{}' of Neutron Security-group '{}' is ignored.", secGroup.getName(),
+ secGroup.getUuid().getValue());
+ LOG.debug("Name exception", e);
+ }
+ }
+ if (!Strings.isNullOrEmpty(secGroup.getDescription())) {
+ try {
+ epgBuilder.setDescription(new Description(secGroup.getDescription()));
+ } catch (Exception e) {
+ LOG.info("Description '{}' of Neutron Security-group '{}' is ignored.",
+ secGroup.getDescription(), secGroup.getUuid().getValue());
+ LOG.debug("Description exception", e);
+ }
+ }
+ epgBuilder.setIntraGroupPolicy(IntraGroupPolicy.RequireContract);
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tId, epgId),
+ epgBuilder.build(), true);
+ return true;
+ }
+
+ @Override
+ public void onUpdated(SecurityGroup oldItem, SecurityGroup newItem, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.warn("updated securityGroup - Never should be called "
+ + "- neutron API does not allow UPDATE on neutron security group. \nSecurity group: {}", newItem);
+ }
+
+ @Override
+ public void onDeleted(SecurityGroup deletedSecGroup, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("deleted securityGroup - {}", deletedSecGroup);
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ TenantId tenantId = new TenantId(deletedSecGroup.getTenantId().getValue());
+ EndpointGroupId epgId = new EndpointGroupId(deletedSecGroup.getUuid().getValue());
+ Optional<EndpointGroup> potentialEpg = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
+ IidFactory.endpointGroupIid(tenantId, epgId), rwTx);
+ if (!potentialEpg.isPresent()) {
+ LOG.warn("Illegal state - Endpoint group {} does not exist.", epgId.getValue());
+ rwTx.cancel();
+ return;
+ }
+
+ DataStoreHelper.submitToDs(rwTx);
+ }
+
+}
import static com.google.common.base.Preconditions.checkNotNull;
-import java.util.ArrayList;
-import java.util.List;
-
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.EndpointRegistrator;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils.ForwardingCtx;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NetworkUtils;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronSubnet;
-import org.opendaylight.neutron.spi.NeutronSubnetIPAllocationPool;
-import org.opendaylight.neutron.spi.NeutronSubnet_HostRoute;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContextId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.SubnetBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Base;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Off;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Slaac;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateful;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.Dhcpv6Stateless;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.IpVersionV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.AllocationPools;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnet.attributes.HostRoutes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableBiMap;
-public class NeutronSubnetAware implements MappingProcessor<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet, NeutronSubnet> {
+public class NeutronSubnetAware implements
+ NeutronAware<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet> {
private final static Logger LOG = LoggerFactory.getLogger(NeutronSubnetAware.class);
+ public static final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet> SUBNET_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class)
+ .child(Subnets.class)
+ .child(org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet.class)
+ .build();
private final DataBroker dataProvider;
- private final NeutronNetworkDao networkDao;
+ private final EndpointRegistrator epRegistrator;
- public NeutronSubnetAware(DataBroker dataProvider, NeutronNetworkDao networkDao) {
+ public NeutronSubnetAware(DataBroker dataProvider, EndpointRegistrator epRegistrator) {
this.dataProvider = checkNotNull(dataProvider);
- this.networkDao = checkNotNull(networkDao);
+ this.epRegistrator = checkNotNull(epRegistrator);
}
- // copied from Neutron's NeutronSubnetInterface
- static final ImmutableBiMap<Class<? extends IpVersionBase>,Integer> IPV_MAP
- = new ImmutableBiMap.Builder<Class<? extends IpVersionBase>,Integer>()
- .put(IpVersionV4.class, 4)
- .put(IpVersionV6.class, 6)
- .build();
-
- // copied from Neutron's NeutronSubnetInterface
- private static final ImmutableBiMap<Class<? extends Dhcpv6Base>,String> DHCPV6_MAP
- = new ImmutableBiMap.Builder<Class<? extends Dhcpv6Base>,String>()
- .put(Dhcpv6Off.class,"off")
- .put(Dhcpv6Stateful.class,"dhcpv6-stateful")
- .put(Dhcpv6Slaac.class,"slaac")
- .put(Dhcpv6Stateless.class,"dhcpv6-stateless")
- .build();
-
@Override
- public NeutronSubnet convertToNeutron(
- org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet subnet) {
- return toNeutron(subnet);
- }
+ public void onCreated(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet neutronSubnet,
+ Neutron neutron) {
+ LOG.trace("created subnet - {}", neutronSubnet);
+ ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ TenantId tenantId = new TenantId(neutronSubnet.getTenantId().getValue());
- @SuppressWarnings("deprecation")
- static NeutronSubnet toNeutron(
- org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet subnet) {
- NeutronSubnet result = new NeutronSubnet();
- result.setName(subnet.getName());
- result.setTenantID(subnet.getTenantId());
- result.setNetworkUUID(subnet.getNetworkId().getValue());
- result.setIpVersion(IPV_MAP.get(subnet.getIpVersion()));
- result.setCidr(subnet.getCidr());
- if (subnet.getGatewayIp() != null) {
- result.setGatewayIP(String.valueOf(subnet.getGatewayIp().getValue()));
- }
- if (subnet.getIpv6RaMode() != null) {
- result.setIpV6RaMode(DHCPV6_MAP.get(subnet.getIpv6RaMode()));
- }
- if (subnet.getIpv6AddressMode() != null) {
- result.setIpV6AddressMode(DHCPV6_MAP.get(subnet.getIpv6AddressMode()));
- }
- result.setEnableDHCP(subnet.isEnableDhcp());
- if (subnet.getAllocationPools() != null) {
- List<NeutronSubnetIPAllocationPool> allocationPools = new ArrayList<NeutronSubnetIPAllocationPool>();
- for (AllocationPools allocationPool : subnet.getAllocationPools()) {
- NeutronSubnetIPAllocationPool pool = new NeutronSubnetIPAllocationPool();
- pool.setPoolStart(allocationPool.getStart());
- pool.setPoolEnd(allocationPool.getEnd());
- allocationPools.add(pool);
- }
- result.setAllocationPools(allocationPools);
- }
- if (subnet.getDnsNameservers() != null) {
- List<String> dnsNameServers = new ArrayList<String>();
- for (IpAddress dnsNameServer : subnet.getDnsNameservers()) {
- dnsNameServers.add(String.valueOf(dnsNameServer.getValue()));
- }
- result.setDnsNameservers(dnsNameServers);
+ Optional<Network> potentialNetwork =
+ NetworkUtils.findNetwork(neutronSubnet.getNetworkId(), neutron.getNetworks());
+ if (!potentialNetwork.isPresent()) {
+ LOG.warn("Illegal state - network {} does not exist for subnet {}.",
+ neutronSubnet.getNetworkId().getValue(), neutronSubnet);
+ rwTx.cancel();
+ return;
}
- if (subnet.getHostRoutes() != null) {
- List<NeutronSubnet_HostRoute> hostRoutes = new ArrayList<NeutronSubnet_HostRoute>();
- for (HostRoutes hostRoute : subnet.getHostRoutes()) {
- NeutronSubnet_HostRoute nsHostRoute = new NeutronSubnet_HostRoute();
- nsHostRoute.setDestination(String.valueOf(hostRoute.getDestination().getValue()));
- nsHostRoute.setNextHop(String.valueOf(hostRoute.getNexthop().getValue()));
- hostRoutes.add(nsHostRoute);
+
+ Network networkOfSubnet = potentialNetwork.get();
+ Subnet subnet = null;
+ if (NetworkUtils.isProviderPhysicalNetwork(networkOfSubnet)) {
+ // add virtual router IP only in case it is provider physical network
+ subnet = createSubnet(neutronSubnet, neutronSubnet.getGatewayIp());
+ IpAddress gatewayIp = neutronSubnet.getGatewayIp();
+ boolean registeredDefaultRoute = epRegistrator.registerExternalL3PrefixEndpoint(MappingUtils.DEFAULT_ROUTE,
+ new L3ContextId(neutronSubnet.getNetworkId().getValue()), gatewayIp, tenantId);
+ if (!registeredDefaultRoute) {
+ LOG.warn("Could not add EndpointL3Prefix as default route. Subnet within provider physical network {}",
+ neutronSubnet);
+ rwTx.cancel();
+ return;
}
- result.setHostRoutes(hostRoutes);
+ } else if (NetworkUtils.isRouterExternal(networkOfSubnet)) {
+ // virtual router IP is not set and it will be set when router gateway port is set
+ subnet = createSubnet(neutronSubnet, null);
+ } else {
+ // virtual router IP is not set and it will be set when router port is attached to
+ // network
+ subnet = createSubnet(neutronSubnet, null);
}
- result.setID(subnet.getUuid().getValue());
- return result;
- }
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnet.getId()), subnet, true);
- @Override
- public int canCreate(NeutronSubnet subnet) {
- LOG.trace("canCreate subnet - {}", subnet);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void created(NeutronSubnet neutronSubnet) {
- LOG.trace("created subnet - {}", neutronSubnet);
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- SubnetId subnetId = new SubnetId(Utils.normalizeUuid(neutronSubnet.getID()));
- TenantId tenantId = new TenantId(Utils.normalizeUuid(neutronSubnet.getTenantID()));
- Subnet subnet = createSubnet(neutronSubnet);
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.subnetIid(tenantId, subnetId), subnet, true);
DataStoreHelper.submitToDs(rwTx);
-
- rwTx = dataProvider.newReadWriteTransaction();
- if (networkDao.isExternalNetwork(neutronSubnet.getNetworkUUID())) {
- LOG.trace("created - adding L3 Endpoint");
- L2FloodDomainId l2FdId = new L2FloodDomainId(subnet.getParent().getValue());
- ForwardingCtx fwCtx = MappingUtils.createForwardingContext(tenantId, l2FdId, rwTx);
- IpAddress defaultGateway = Utils.createIpAddress(neutronSubnet.getGatewayIP());
- //Create L3Endpoint for defaultGateway
- NetworkDomainId containment = new NetworkDomainId(neutronSubnet.getID());
- NeutronPortAware.addL3EndpointForExternalGateway(tenantId, fwCtx.getL3Context().getId(), defaultGateway, containment ,rwTx);
- DataStoreHelper.submitToDs(rwTx);
- }
}
- private Subnet createSubnet(NeutronSubnet neutronSubnet) {
+ public static Subnet createSubnet(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet neutronSubnet,
+ IpAddress virtualRouterIp) {
SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(neutronSubnet.getID()));
- subnetBuilder.setParent(new ContextId(neutronSubnet.getNetworkUUID()));
+ subnetBuilder.setId(new SubnetId(neutronSubnet.getUuid().getValue()));
+ subnetBuilder.setParent(new ContextId(neutronSubnet.getNetworkId().getValue()));
if (!Strings.isNullOrEmpty(neutronSubnet.getName())) {
- subnetBuilder.setName(new Name(neutronSubnet.getName()));
+ try {
+ subnetBuilder.setName(new Name(neutronSubnet.getName()));
+ } catch (Exception e) {
+ LOG.info("Name '{}' of Neutron Subnet '{}' is ignored.", neutronSubnet.getName(),
+ neutronSubnet.getUuid().getValue());
+ LOG.debug("Name exception", e);
+ }
}
subnetBuilder.setIpPrefix(Utils.createIpPrefix(neutronSubnet.getCidr()));
+ subnetBuilder.setVirtualRouterIp(virtualRouterIp);
return subnetBuilder.build();
}
@Override
- public int canUpdate(NeutronSubnet delta, NeutronSubnet original) {
- LOG.trace("canUpdate subnet - delta: {} original: {}", delta, original);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void updated(NeutronSubnet subnet) {
- LOG.trace("updated subnet - {}", subnet);
- created(subnet);
- }
-
- @Override
- public int canDelete(NeutronSubnet subnet) {
- LOG.trace("canDelete subnet - {}", subnet);
- // nothing to consider
- return StatusCode.OK;
+ public void onUpdated(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet oldItem,
+ org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet newItem,
+ Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("updated subnet - {}", newItem);
+ onCreated(newItem, newNeutron);
}
@Override
- public void deleted(NeutronSubnet neutronSubnet) {
+ public void onDeleted(
+ org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet neutronSubnet,
+ Neutron oldNeutron, Neutron newNeutron) {
LOG.trace("deleted subnet - {}", neutronSubnet);
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- SubnetId subnetId = new SubnetId(Utils.normalizeUuid(neutronSubnet.getID()));
- TenantId tenantId = new TenantId(Utils.normalizeUuid(neutronSubnet.getTenantID()));
+ SubnetId subnetId = new SubnetId(neutronSubnet.getUuid().getValue());
+ TenantId tenantId = new TenantId(neutronSubnet.getTenantId().getValue());
Optional<Subnet> potentialSubnet = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
IidFactory.subnetIid(tenantId, subnetId), rwTx);
if (!potentialSubnet.isPresent()) {
rwTx.cancel();
return;
}
+
+ // TODO remove default gateway EP in case when subnet is in provider physical network
+
DataStoreHelper.submitToDs(rwTx);
}
+
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;
-
-/**
- * HTTP status codes
- */
-public final class StatusCode {
-
- public static final int OK = 200;
- public static final int BAD_REQUEST = 400;
- public static final int FORBIDDEN = 403;
- public static final int NOT_FOUND = 404;
- public static final int INTERNAL_SERVER_ERROR = 500;
-
- private StatusCode() {
- throw new UnsupportedOperationException("Cannot create an instance.");
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.MappingProcessor;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.StatusCode;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
-import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
-import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroupBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableListMultimap;
-import com.google.common.collect.ListMultimap;
-import com.google.common.collect.Lists;
-
-public class NeutronSecurityGroupAware implements MappingProcessor<SecurityGroup, NeutronSecurityGroup> {
-
- private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityGroupAware.class);
- private final DataBroker dataProvider;
- private final NeutronSecurityRuleAware secRuleAware;
- private final SecGroupDao secGroupDao;
-
- public NeutronSecurityGroupAware(DataBroker dataProvider, NeutronSecurityRuleAware secRuleAware,
- SecGroupDao secGroupDao) {
- this.dataProvider = checkNotNull(dataProvider);
- this.secRuleAware = checkNotNull(secRuleAware);
- this.secGroupDao = checkNotNull(secGroupDao);
- }
-
- @Override
- public NeutronSecurityGroup convertToNeutron(SecurityGroup secGroup) {
- NeutronSecurityGroup neutronSecGroup = new NeutronSecurityGroup();
- if (secGroup.getUuid() != null) {
- neutronSecGroup.setID(secGroup.getUuid().getValue());
- }
- if (secGroup.getName() != null) {
- neutronSecGroup.setSecurityGroupName(secGroup.getName());
- }
- if (secGroup.getTenantId() != null) {
- neutronSecGroup.setTenantID(secGroup.getTenantId());
- }
- if (secGroup.getSecurityRules() != null) {
- neutronSecGroup.setSecurityRules(Lists.transform(secGroup.getSecurityRules(),
- new Function<Uuid, NeutronSecurityRule>() {
-
- @Override
- public NeutronSecurityRule apply(Uuid uuid) {
- NeutronSecurityRule rule = new NeutronSecurityRule();
- rule.setID(uuid.getValue());
- return rule;
- }
- }));
- }
- return neutronSecGroup;
- }
-
- @Override
- public int canCreate(NeutronSecurityGroup securityGroup) {
- LOG.trace("canCreate securityGroup - {}", securityGroup);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void created(NeutronSecurityGroup secGroup) {
- LOG.trace("created securityGroup - {}", secGroup);
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- boolean isSecGroupCreated = addNeutronSecurityGroup(secGroup, rwTx);
- if (isSecGroupCreated) {
- DataStoreHelper.submitToDs(rwTx);
- } else {
- rwTx.cancel();
- }
- }
-
- public boolean addNeutronSecurityGroup(NeutronSecurityGroup secGroup, ReadWriteTransaction rwTx) {
- secGroupDao.addSecGroup(secGroup);
- TenantId tenantId = new TenantId(Utils.normalizeUuid(secGroup.getSecurityGroupTenantID()));
- EndpointGroupId providerEpgId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- EndpointGroupBuilder providerEpgBuilder = new EndpointGroupBuilder().setId(providerEpgId);
- if (!Strings.isNullOrEmpty(secGroup.getSecurityGroupName())) {
- try {
- providerEpgBuilder.setName(new Name(secGroup.getSecurityGroupName()));
- } catch (Exception e) {
- LOG.info("Name '{}' of Neutron Security-group '{}' is ignored.", secGroup.getSecurityGroupName(),
- secGroup.getSecurityGroupUUID());
- LOG.debug("Name exception", e);
- }
- }
- if (!Strings.isNullOrEmpty(secGroup.getSecurityGroupDescription())) {
- try {
- providerEpgBuilder.setDescription(new Description(secGroup.getSecurityGroupDescription()));
- } catch (Exception e) {
- LOG.info("Description '{}' of Neutron Security-group '{}' is ignored.",
- secGroup.getSecurityGroupDescription(), secGroup.getSecurityGroupUUID());
- LOG.debug("Description exception", e);
- }
- }
- providerEpgBuilder.setIntraGroupPolicy(IntraGroupPolicy.RequireContract);
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.endpointGroupIid(tenantId, providerEpgId),
- providerEpgBuilder.build(), true);
- List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
- SortedSecurityGroupRules sortedSecGrpRules = new SortedSecurityGroupRules(secRules);
- ListMultimap<EndpointGroupId, NeutronSecurityRule> secRuleByRemoteSecGrpId = sortedSecGrpRules.secRuleByRemoteSecGrpId;
- for (EndpointGroupId consumerEpgId : secRuleByRemoteSecGrpId.keySet()) {
- addEpgIfMissing(tenantId, consumerEpgId, rwTx);
- boolean areSecRulesAdded = addNeutronSecurityRule(secRuleByRemoteSecGrpId.get(consumerEpgId), rwTx);
- if (!areSecRulesAdded) {
- return false;
- }
- }
- ListMultimap<IpPrefix, NeutronSecurityRule> secRuleByRemoteIpPrefix = sortedSecGrpRules.secRuleByRemoteIpPrefix;
- for (IpPrefix remoteIpPrefex : secRuleByRemoteIpPrefix.keySet()) {
- boolean areSecRulesAdded = addNeutronSecurityRule(secRuleByRemoteIpPrefix.get(remoteIpPrefex), rwTx);
- if (!areSecRulesAdded) {
- return false;
- }
- }
- boolean areSecRulesAdded = addNeutronSecurityRule(sortedSecGrpRules.secRulesWithoutRemote, rwTx);
- if (!areSecRulesAdded) {
- return false;
- }
- return true;
- }
-
- public static void addEpgIfMissing(TenantId tenantId, EndpointGroupId epgId, ReadWriteTransaction rwTx) {
- InstanceIdentifier<EndpointGroup> epgIid = IidFactory.endpointGroupIid(tenantId, epgId);
- Optional<EndpointGroup> potentialConsumerEpg = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- epgIid, rwTx);
- if (!potentialConsumerEpg.isPresent()) {
- EndpointGroup epg = new EndpointGroupBuilder().setId(epgId)
- .setDescription(
- new Description(MappingUtils.NEUTRON_GROUP
- + "EPG was created just based on remote group ID from a security rule."))
- .setIntraGroupPolicy(IntraGroupPolicy.RequireContract)
- .build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, epgIid, epg);
- }
- }
-
- private boolean addNeutronSecurityRule(List<NeutronSecurityRule> secRules, ReadWriteTransaction rwTx) {
- for (NeutronSecurityRule secRule : secRules) {
- boolean isSecRuleAdded = secRuleAware.addNeutronSecurityRule(secRule, rwTx);
- if (!isSecRuleAdded) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public int canUpdate(NeutronSecurityGroup delta, NeutronSecurityGroup original) {
- LOG.warn("canUpdate securityGroup - Never should be called "
- + "- neutron API does not allow UPDATE on neutron security group. \nDelta: {} \nOriginal: {}", delta,
- original);
- return StatusCode.BAD_REQUEST;
- }
-
- @Override
- public void updated(NeutronSecurityGroup securityGroup) {
- LOG.warn("updated securityGroup - Never should be called "
- + "- neutron API does not allow UPDATE on neutron security group. \nSecurity group: {}", securityGroup);
- }
-
- @Override
- public int canDelete(NeutronSecurityGroup securityGroup) {
- LOG.trace("canDelete securityGroup - {}", securityGroup);
- // nothing to consider
- return StatusCode.OK;
- }
-
- @Override
- public void deleted(NeutronSecurityGroup secGroup) {
- LOG.trace("deleted securityGroup - {}", secGroup);
- ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- List<NeutronSecurityRule> secRules = secGroup.getSecurityRules();
- if (secRules != null) {
- boolean areSecRulesDeleted = deleteNeutronSecurityRules(secRules, rwTx);
- if (!areSecRulesDeleted) {
- rwTx.cancel();
- return;
- }
- }
-
- TenantId tenantId = new TenantId(Utils.normalizeUuid(secGroup.getSecurityGroupTenantID()));
- EndpointGroupId epgId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- secGroupDao.removeSecGroup(epgId);
-
- Optional<EndpointGroup> potentialEpg = DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION,
- IidFactory.endpointGroupIid(tenantId, epgId), rwTx);
- if (!potentialEpg.isPresent()) {
- LOG.warn("Illegal state - Endpoint group {} does not exist.", epgId.getValue());
- rwTx.cancel();
- return;
- }
-
- DataStoreHelper.submitToDs(rwTx);
- }
-
- private boolean deleteNeutronSecurityRules(List<NeutronSecurityRule> secRules, ReadWriteTransaction rwTx) {
- for (NeutronSecurityRule secRule : secRules) {
- boolean isSecRuleDeleted = secRuleAware.deleteNeutronSecurityRule(secRule, rwTx);
- if (!isSecRuleDeleted) {
- return false;
- }
- }
- return true;
- }
-
- private static final class SortedSecurityGroupRules {
-
- private final ListMultimap<EndpointGroupId, NeutronSecurityRule> secRuleByRemoteSecGrpId;
- private final ListMultimap<IpPrefix, NeutronSecurityRule> secRuleByRemoteIpPrefix;
- private final List<NeutronSecurityRule> secRulesWithoutRemote;
-
- private SortedSecurityGroupRules(List<NeutronSecurityRule> securityRules) {
- Preconditions.checkNotNull(securityRules);
- ListMultimap<EndpointGroupId, NeutronSecurityRule> tmpSecRuleByRemoteSecGrpId = ArrayListMultimap.create();
- ListMultimap<IpPrefix, NeutronSecurityRule> tmpSecRuleByRemoteIpPrefix = ArrayListMultimap.create();
- List<NeutronSecurityRule> tmpSecRulesWithoutRemote = new ArrayList<>();
- for (NeutronSecurityRule securityRule : securityRules) {
- String remoteSecGroupId = securityRule.getSecurityRemoteGroupID();
- String remoteIpPrefix = securityRule.getSecurityRuleRemoteIpPrefix();
- boolean isRemoteSecGroupId = remoteSecGroupId != null && !"null".equals(remoteSecGroupId);
- boolean isRemoteIpPrefix = remoteIpPrefix != null && !"null".equals(remoteIpPrefix);
- if (isRemoteSecGroupId && isRemoteIpPrefix) {
- throw new IllegalArgumentException("Either remote group id or ip prefix "
- + "must be speciefied in neutron security group rule." + securityRule.toString());
- }
- if (isRemoteSecGroupId) {
- tmpSecRuleByRemoteSecGrpId.put(new EndpointGroupId(remoteSecGroupId), securityRule);
- } else if (isRemoteIpPrefix) {
- tmpSecRuleByRemoteIpPrefix.put(Utils.createIpPrefix(remoteIpPrefix), securityRule);
- } else {
- tmpSecRulesWithoutRemote.add(securityRule);
- }
- }
- secRuleByRemoteSecGrpId = ImmutableListMultimap.copyOf(tmpSecRuleByRemoteSecGrpId);
- secRuleByRemoteIpPrefix = ImmutableListMultimap.copyOf(tmpSecRuleByRemoteIpPrefix);
- secRulesWithoutRemote = ImmutableList.copyOf(tmpSecRulesWithoutRemote);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
-
-import com.google.common.base.Strings;
-
-public class SecGroupDao {
-
- private final Map<EndpointGroupId, NeutronSecurityGroup> secGroupById = new HashMap<>();
-
- public void addSecGroup(NeutronSecurityGroup secGrp) {
- checkNotNull(secGrp);
- secGroupById.put(new EndpointGroupId(Utils.normalizeUuid(secGrp.getSecurityGroupUUID())), secGrp);
- }
-
- public NeutronSecurityGroup getSecGroupById(EndpointGroupId id) {
- return secGroupById.get(id);
- }
-
- /**
- * @param id {@link EndpointGroupId} EndpointGroupId
- * @return {@code empty string} if security group with given ID does not exist; returns
- * {@code name of security group} if has some; otherwise security group id
- */
- public String getNameOrIdOfSecGroup(EndpointGroupId id) {
- NeutronSecurityGroup secGrp = secGroupById.get(checkNotNull(id));
- if (secGrp == null) {
- return "";
- }
- if (!Strings.isNullOrEmpty(secGrp.getSecurityGroupName())) {
- return secGrp.getSecurityGroupName();
- }
- return id.getValue();
- }
-
- public void removeSecGroup(EndpointGroupId id) {
- secGroupById.remove(checkNotNull(id));
- }
-
-}
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.List;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SecurityRuleUtils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.ChangeActionOfSecurityGroupRulesInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.NeutronGbpMapperService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.SecurityGroupRule;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.base.Optional;
import com.google.common.util.concurrent.Futures;
public class NeutronGbpMapperServiceImpl implements NeutronGbpMapperService {
}
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
+ Optional<Neutron> potentialNeutron;
+ try {
+ potentialNeutron = rwTx.read(LogicalDatastoreType.CONFIGURATION, InstanceIdentifier.builder(Neutron.class).build()).get();
+ } catch (InterruptedException | ExecutionException e) {
+ LOG.error("Exception during neutron reading.", e);
+ return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
+ .withError(ErrorType.PROTOCOL, "Cannot read from CONF DS.")
+ .build());
+ }
+ if (!potentialNeutron.isPresent()) {
+ return Futures.immediateFuture(RpcResultBuilder.<Void>failed()
+ .withError(ErrorType.PROTOCOL, "No neutron data in CONF DS.")
+ .build());
+ }
+ Neutron neutron = potentialNeutron.get();
for (SecurityGroupRule secGrpRule : securityGroupRules) {
Uuid uuid = secGrpRule.getUuid();
+ Optional<SecurityRule> potentialSecRule = SecurityRuleUtils.findSecurityRule(uuid, neutron.getSecurityRules());
+ if (!potentialSecRule.isPresent()) {
+ LOG.warn("Security rule {} does not exist.", uuid);
+ continue;
+ }
LOG.trace("Changing action to {} in security group rule {}", input.getAction().getActionChoice(), uuid);
boolean isSuccessful =
- secRuleAware.changeActionOfNeutronSecurityRule(uuid, input.getAction().getActionChoice(), rwTx);
+ secRuleAware.changeActionOfNeutronSecurityRule(potentialSecRule.get(), input.getAction().getActionChoice(), neutron, rwTx);
if (!isSuccessful) {
rwTx.cancel();
LOG.warn("Changing action to {} in security group rule {} was not successful.",
import java.util.Set;
+import org.opendaylight.controller.config.yang.config.neutron_mapper.impl.NeutronMapperModule;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.groupbasedpolicy.api.sf.ChainActionDefinition;
-import org.opendaylight.groupbasedpolicy.dto.EgKey;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.MappingProcessor;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.StatusCode;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao;
+import org.opendaylight.groupbasedpolicy.dto.EpgKeyDto;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronAware;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SecurityGroupUtils;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.SecurityRuleUtils;
import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstanceBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmpV6;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules;
import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Strings;
+import com.google.common.base.Optional;
import com.google.common.collect.HashMultiset;
-import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multiset;
import com.google.common.collect.Sets;
-public class NeutronSecurityRuleAware implements MappingProcessor<SecurityRule, NeutronSecurityRule> {
+public class NeutronSecurityRuleAware implements NeutronAware<SecurityRule> {
private static final Logger LOG = LoggerFactory.getLogger(NeutronSecurityRuleAware.class);
+ public static final InstanceIdentifier<SecurityRule> SECURITY_RULE_WILDCARD_IID =
+ InstanceIdentifier.builder(Neutron.class).child(SecurityRules.class).child(SecurityRule.class).build();
private static final String CONTRACT_PROVIDER = "Contract provider: ";
private final DataBroker dataProvider;
- private final SecRuleDao secRuleDao;
- private final SecGroupDao secGroupDao;
private final Multiset<InstanceIdentifier<ClassifierInstance>> createdClassifierInstances;
private final Multiset<InstanceIdentifier<ActionInstance>> createdActionInstances;
final static String PROVIDED_BY = "provided_by-";
final static String POSSIBLE_CONSUMER = "possible_consumer-";
- public NeutronSecurityRuleAware(DataBroker dataProvider, SecRuleDao secRuleDao, SecGroupDao secGroupDao) {
- this(dataProvider, secRuleDao, secGroupDao, HashMultiset.<InstanceIdentifier<ClassifierInstance>>create(),
+ public NeutronSecurityRuleAware(DataBroker dataProvider) {
+ this(dataProvider, HashMultiset.<InstanceIdentifier<ClassifierInstance>>create(),
HashMultiset.<InstanceIdentifier<ActionInstance>>create());
}
@VisibleForTesting
- NeutronSecurityRuleAware(DataBroker dataProvider, SecRuleDao secRuleDao, SecGroupDao secGroupDao,
+ NeutronSecurityRuleAware(DataBroker dataProvider,
Multiset<InstanceIdentifier<ClassifierInstance>> classifierInstanceNames,
Multiset<InstanceIdentifier<ActionInstance>> createdActionInstances) {
this.dataProvider = checkNotNull(dataProvider);
- this.secRuleDao = checkNotNull(secRuleDao);
- this.secGroupDao = checkNotNull(secGroupDao);
this.createdClassifierInstances = checkNotNull(classifierInstanceNames);
this.createdActionInstances = checkNotNull(createdActionInstances);
}
- // copied from Neutron's NeutronSecurityRuleInterface
- private static final ImmutableBiMap<Class<? extends DirectionBase>,String> DIRECTION_MAP
- = new ImmutableBiMap.Builder<Class<? extends DirectionBase>,String>()
- .put(DirectionEgress.class,"egress")
- .put(DirectionIngress.class,"ingress")
- .build();
-
- // copied from Neutron's NeutronSecurityRuleInterface
- private static final ImmutableBiMap<Class<? extends EthertypeBase>,String> ETHERTYPE_MAP
- = new ImmutableBiMap.Builder<Class<? extends EthertypeBase>,String>()
- .put(EthertypeV4.class,"IPv4")
- .put(EthertypeV6.class,"IPv6")
- .build();
-
- // copied from Neutron's NeutronSecurityRuleInterface
- private static final ImmutableBiMap<Class<? extends ProtocolBase>,String> PROTOCOL_MAP
- = new ImmutableBiMap.Builder<Class<? extends ProtocolBase>,String>()
- .put(ProtocolIcmp.class,"icmp")
- .put(ProtocolTcp.class,"tcp")
- .put(ProtocolUdp.class,"udp")
- .put(ProtocolIcmpV6.class,"icmpv6")
- .build();
-
- @Override
- public NeutronSecurityRule convertToNeutron(SecurityRule rule) {
- // copied from Neutron's NeutronSecurityRuleInterface
- NeutronSecurityRule answer = new NeutronSecurityRule();
- if (rule.getTenantId() != null) {
- answer.setTenantID(rule.getTenantId());
- }
- if (rule.getDirection() != null) {
- answer.setSecurityRuleDirection(DIRECTION_MAP.get(rule.getDirection()));
- }
- if (rule.getSecurityGroupId() != null) {
- answer.setSecurityRuleGroupID(rule.getSecurityGroupId().getValue());
- }
- if (rule.getRemoteGroupId() != null) {
- answer.setSecurityRemoteGroupID(rule.getRemoteGroupId().getValue());
- }
- if (rule.getRemoteIpPrefix() != null) {
- answer.setSecurityRuleRemoteIpPrefix(new String(rule.getRemoteIpPrefix().getValue()));
- }
- if (rule.getProtocol() != null) {
- answer.setSecurityRuleProtocol(PROTOCOL_MAP.get(rule.getProtocol()));
- }
- if (rule.getEthertype() != null) {
- answer.setSecurityRuleEthertype(ETHERTYPE_MAP.get(rule.getEthertype()));
- }
- if (rule.getPortRangeMin() != null) {
- answer.setSecurityRulePortMin(rule.getPortRangeMin());
- }
- if (rule.getPortRangeMax() != null) {
- answer.setSecurityRulePortMax(rule.getPortRangeMax());
- }
- if (rule.getId() != null) {
- answer.setID(rule.getId().getValue());
- }
- return answer;
- }
-
- @Override
- public int canCreate(NeutronSecurityRule securityRule) {
- LOG.trace("canCreate securityRule - {}", securityRule);
- // nothing to consider
- return StatusCode.OK;
- }
-
@Override
- public void created(NeutronSecurityRule securityRule) {
- LOG.trace("created securityRule - {}", securityRule);
+ public void onCreated(SecurityRule secRule, Neutron neutron) {
+ LOG.trace("created securityRule - {}", secRule);
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- boolean isNeutronSecurityRuleAdded = addNeutronSecurityRule(securityRule, rwTx);
+ boolean isNeutronSecurityRuleAdded = addNeutronSecurityRule(secRule, neutron, rwTx);
if (isNeutronSecurityRuleAdded) {
DataStoreHelper.submitToDs(rwTx);
} else {
}
}
- public boolean changeActionOfNeutronSecurityRule(Uuid secRuleId, ActionChoice action, ReadWriteTransaction rwTx) {
- NeutronSecurityRule secRule = secRuleDao.getSecRuleByUuid(secRuleId);
- addSfcChainActionInstance(action, SecRuleEntityDecoder.getTenantId(secRule), rwTx);
- LOG.trace("Changing to action {} for secuirity group rule {}", action, secRule);
- return addNeutronSecurityRuleWithAction(secRule, action, rwTx);
+ public boolean addNeutronSecurityRule(SecurityRule secRule, Neutron neutron, ReadWriteTransaction rwTx) {
+ return addNeutronSecurityRuleWithAction(secRule, neutron, MappingUtils.ALLOW_ACTION_CHOICE, rwTx);
}
- private void addSfcChainActionInstance(ActionChoice action, TenantId tenantId, ReadWriteTransaction rwTx) {
- if (action instanceof SfcActionCase) {
- String sfcChainName = ((SfcActionCase) action).getSfcChainName();
- ActionName actionName = new ActionName(sfcChainName);
- ActionInstance sfcActionInstance = new ActionInstanceBuilder().setName(actionName)
- .setActionDefinitionId(ChainActionDefinition.ID)
- .setParameterValue(
- ImmutableList.of(new ParameterValueBuilder().setName(
- new ParameterName(ChainActionDefinition.SFC_CHAIN_NAME))
- .setStringValue(sfcChainName)
- .build()))
- .build();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.actionInstanceIid(tenantId, actionName),
- sfcActionInstance, true);
- }
- }
-
- public boolean addNeutronSecurityRule(NeutronSecurityRule secRule, ReadWriteTransaction rwTx) {
- return addNeutronSecurityRuleWithAction(secRule, MappingUtils.ALLOW_ACTION_CHOICE, rwTx);
- }
-
- public boolean addNeutronSecurityRuleWithAction(NeutronSecurityRule secRule, ActionChoice action,
+ public boolean addNeutronSecurityRuleWithAction(SecurityRule secRule, Neutron neutron, ActionChoice action,
ReadWriteTransaction rwTx) {
- TenantId tenantId = SecRuleEntityDecoder.getTenantId(secRule);
- EndpointGroupId providerEpgId = SecRuleEntityDecoder.getProviderEpgId(secRule);
- secRuleDao.addSecRule(secRule);
+ TenantId tenantId = new TenantId(secRule.getTenantId().getValue());
+ Uuid providerSecGroupId = secRule.getSecurityGroupId();
+ EndpointGroupId providerEpgId = new EndpointGroupId(providerSecGroupId.getValue());
- Description contractDescription = new Description(CONTRACT_PROVIDER
- + secGroupDao.getNameOrIdOfSecGroup(providerEpgId));
+ Description contractDescription = createContractDescription(secRule, neutron);
SingleRuleContract singleRuleContract = createSingleRuleContract(secRule, contractDescription, action);
Contract contract = singleRuleContract.getContract();
rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.contractIid(tenantId, contract.getId()), contract, true);
- SelectorName providerSelector = getSelectorNameWithConsumer(secRule);
- writeProviderNamedSelectorToEpg(providerSelector, contract.getId(), new EgKey(tenantId, providerEpgId), rwTx);
+ SelectorName providerSelector = getSelectorNameWithConsumer(secRule, neutron);
+ writeProviderNamedSelectorToEpg(providerSelector, contract.getId(), new EpgKeyDto(providerEpgId, tenantId), rwTx);
- if (SecRuleEntityDecoder.getConsumerEpgId(secRule) != null) {
- EndpointGroupId consumerEpgId = SecRuleEntityDecoder.getConsumerEpgId(secRule);
- designContractsBetweenProviderAndConsumer(tenantId, providerEpgId, consumerEpgId, rwTx);
- designContractsBetweenProviderAndConsumer(tenantId, consumerEpgId, providerEpgId, rwTx);
+ if (secRule.getRemoteGroupId() != null) {
+ Uuid consumerSecGroupId = secRule.getRemoteGroupId();
+ designContractsBetweenProviderAndConsumer(tenantId, providerSecGroupId, consumerSecGroupId, neutron, rwTx);
+ designContractsBetweenProviderAndConsumer(tenantId, consumerSecGroupId, providerSecGroupId, neutron, rwTx);
} else {
- for (EndpointGroupId consumerEpgId : secRuleDao.getAllOwnerSecGrps()) {
- designContractsBetweenProviderAndConsumer(tenantId, providerEpgId, consumerEpgId, rwTx);
- designContractsBetweenProviderAndConsumer(tenantId, consumerEpgId, providerEpgId, rwTx);
+ for (Uuid consumerSecGroupId : SecurityRuleUtils.findSecurityGroupsHavingSecurityRules(neutron)) {
+ designContractsBetweenProviderAndConsumer(tenantId, providerSecGroupId, consumerSecGroupId, neutron, rwTx);
+ designContractsBetweenProviderAndConsumer(tenantId, consumerSecGroupId, providerSecGroupId, neutron, rwTx);
}
}
}
@VisibleForTesting
- static SingleRuleContract createSingleRuleContract(NeutronSecurityRule secRule, Description contractDescription,
- ActionChoice action) {
- if (!Strings.isNullOrEmpty(secRule.getSecurityRuleRemoteIpPrefix())) {
+ static Description createContractDescription(SecurityRule secRule, Neutron neutron) {
+ if (NeutronMapperModule.isDebugEnabled()) {
+ Optional<SecurityGroup> providerSecGroup =
+ SecurityGroupUtils.findSecurityGroup(secRule.getSecurityGroupId(), neutron.getSecurityGroups());
+ if (!providerSecGroup.isPresent()) {
+ LOG.error("Neutron Security Group with UUID {} does not exist but it is in {}", secRule.getSecurityGroupId().getValue(),
+ secRule);
+ throw new IllegalStateException(
+ "Neutron Security Group with UUID " + secRule.getSecurityGroupId().getValue() + " does not exist.");
+ }
+ return new Description(CONTRACT_PROVIDER + SecurityGroupUtils.getNameOrUuid(providerSecGroup.get()));
+ }
+
+ return new Description(CONTRACT_PROVIDER + secRule.getSecurityGroupId());
+ }
+
+ @VisibleForTesting
+ static SingleRuleContract createSingleRuleContract(SecurityRule secRule, Description contractDescription, ActionChoice action) {
+ if (secRule.getRemoteIpPrefix() != null) {
return new SingleRuleContract(secRule, 0, contractDescription, action);
}
return new SingleRuleContract(secRule, 400, contractDescription, action);
}
@VisibleForTesting
- void designContractsBetweenProviderAndConsumer(TenantId tenantId, EndpointGroupId provEpgId,
- EndpointGroupId consEpgId, ReadWriteTransaction rwTx) {
- Set<NeutronSecurityRule> provSecRules = getProvidedSecRulesBetween(provEpgId, consEpgId);
- Set<NeutronSecurityRule> consSecRules = getProvidedSecRulesBetween(consEpgId, provEpgId);
- for (NeutronSecurityRule provSecRule : provSecRules) {
+ void designContractsBetweenProviderAndConsumer(TenantId tenantId, Uuid provSecGroupId, Uuid consSecGroupId,
+ Neutron neutron, ReadWriteTransaction rwTx) {
+ Set<SecurityRule> provSecRules = getProvidedSecRulesBetween(provSecGroupId, consSecGroupId, neutron);
+ Set<SecurityRule> consSecRules = getProvidedSecRulesBetween(consSecGroupId, provSecGroupId, neutron);
+ EndpointGroupId consEpgId = new EndpointGroupId(consSecGroupId.getValue());
+ for (SecurityRule provSecRule : provSecRules) {
if (isProviderSecRuleSuitableForConsumerSecRules(provSecRule, consSecRules)) {
- SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule);
+ SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule, neutron);
ContractId contractId = SecRuleEntityDecoder.getContractId(provSecRule);
- writeConsumerNamedSelectorToEpg(consumerSelector, contractId, new EgKey(tenantId, consEpgId), rwTx);
+ writeConsumerNamedSelectorToEpg(consumerSelector, contractId, new EpgKeyDto(consEpgId, tenantId), rwTx);
}
// TODO add case when port ranges overlap
}
}
@VisibleForTesting
- Set<NeutronSecurityRule> getProvidedSecRulesBetween(EndpointGroupId provEpgId, EndpointGroupId consEpgId) {
- return Sets.union(secRuleDao.getSecRulesBySecGrpIdAndRemoteSecGrpId(provEpgId, consEpgId),
- secRuleDao.getSecRulesWithoutRemoteSecGrpBySecGrpId(provEpgId));
+ Set<SecurityRule> getProvidedSecRulesBetween(Uuid provSecGroup, Uuid consSecGroup, Neutron neutron) {
+ return Sets.union(SecurityRuleUtils.findSecurityRulesBySecGroupAndRemoteSecGroup(provSecGroup, consSecGroup, neutron),
+ SecurityRuleUtils.findSecurityRulesBySecGroupAndRemoteSecGroup(provSecGroup, null, neutron));
}
@VisibleForTesting
- static boolean isProviderSecRuleSuitableForConsumerSecRules(NeutronSecurityRule provSecRule,
- Set<NeutronSecurityRule> consSecRules) {
+ static boolean isProviderSecRuleSuitableForConsumerSecRules(SecurityRule provSecRule,
+ Set<SecurityRule> consSecRules) {
Direction directionProvSecRule = SecRuleEntityDecoder.getDirection(provSecRule);
- for (NeutronSecurityRule consSecRule : consSecRules) {
+ for (SecurityRule consSecRule : consSecRules) {
Direction directionConsSecRule = SecRuleEntityDecoder.getDirection(consSecRule);
if (isDirectionOpposite(directionProvSecRule, directionConsSecRule)
&& isOneWithinTwo(provSecRule, consSecRule)) {
return false;
}
- private void writeProviderNamedSelectorToEpg(SelectorName providerSelector, ContractId contractId, EgKey epgKey,
+ public boolean changeActionOfNeutronSecurityRule(SecurityRule secRule, ActionChoice action, Neutron neutron, ReadWriteTransaction rwTx) {
+ addSfcChainActionInstance(action, new TenantId(secRule.getTenantId().getValue()), rwTx);
+ LOG.trace("Changing to action {} for secuirity group rule {}", action, secRule);
+ return addNeutronSecurityRuleWithAction(secRule, neutron, action, rwTx);
+ }
+
+ private void addSfcChainActionInstance(ActionChoice action, TenantId tenantId, ReadWriteTransaction rwTx) {
+ if (action instanceof SfcActionCase) {
+ String sfcChainName = ((SfcActionCase) action).getSfcChainName();
+ ActionName actionName = new ActionName(sfcChainName);
+ ActionInstance sfcActionInstance = new ActionInstanceBuilder().setName(actionName)
+ .setActionDefinitionId(ChainActionDefinition.ID)
+ .setParameterValue(
+ ImmutableList.of(new ParameterValueBuilder().setName(
+ new ParameterName(ChainActionDefinition.SFC_CHAIN_NAME))
+ .setStringValue(sfcChainName)
+ .build()))
+ .build();
+ rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.actionInstanceIid(tenantId, actionName),
+ sfcActionInstance, true);
+ }
+ }
+
+ private void writeProviderNamedSelectorToEpg(SelectorName providerSelector, ContractId contractId, EpgKeyDto epgKey,
WriteTransaction wTx) {
ProviderNamedSelector providerNamedSelector = new ProviderNamedSelectorBuilder().setName(providerSelector)
.setContract(ImmutableList.of(contractId))
.build();
wTx.put(LogicalDatastoreType.CONFIGURATION,
- IidFactory.providerNamedSelectorIid(epgKey.getTenantId(), epgKey.getEgId(),
+ IidFactory.providerNamedSelectorIid(epgKey.getTenantId(), epgKey.getEpgId(),
providerNamedSelector.getName()), providerNamedSelector, true);
}
- private void writeConsumerNamedSelectorToEpg(SelectorName consumerSelector, ContractId contractId, EgKey epgKey,
+ private void writeConsumerNamedSelectorToEpg(SelectorName consumerSelector, ContractId contractId, EpgKeyDto epgKey,
WriteTransaction wTx) {
ConsumerNamedSelector consumerNamedSelector = new ConsumerNamedSelectorBuilder().setName(consumerSelector)
.setContract(ImmutableList.of(contractId))
.build();
wTx.put(LogicalDatastoreType.CONFIGURATION,
- IidFactory.consumerNamedSelectorIid(epgKey.getTenantId(), epgKey.getEgId(),
+ IidFactory.consumerNamedSelectorIid(epgKey.getTenantId(), epgKey.getEpgId(),
consumerNamedSelector.getName()), consumerNamedSelector, true);
}
}
@Override
- public int canUpdate(NeutronSecurityRule delta, NeutronSecurityRule original) {
- LOG.warn("canUpdate securityRule - Never should be called "
- + "- neutron API does not allow UPDATE on neutron security group rule. \nDelta: {} \nOriginal: {}",
- delta, original);
- return StatusCode.BAD_REQUEST;
- }
-
- @Override
- public void updated(NeutronSecurityRule securityRule) {
+ public void onUpdated(SecurityRule oldSecRule, SecurityRule newSecRule, Neutron oldNeutron, Neutron newNeutron) {
LOG.warn("updated securityRule - Never should be called "
+ "- neutron API does not allow UPDATE on neutron security group rule. \nSecurity group rule: {}",
- securityRule);
- }
-
- @Override
- public int canDelete(NeutronSecurityRule securityRule) {
- LOG.trace("canDelete - securityRule - {}", securityRule);
- // nothing to consider
- return StatusCode.OK;
+ newSecRule);
}
@Override
- public void deleted(NeutronSecurityRule secRule) {
- LOG.trace("deleted securityRule - {}", secRule);
+ public void onDeleted(SecurityRule deletedSecRule, Neutron oldNeutron, Neutron newNeutron) {
+ LOG.trace("deleted securityRule - {}", deletedSecRule);
ReadWriteTransaction rwTx = dataProvider.newReadWriteTransaction();
- boolean isNeutronSecurityRuleDeleted = deleteNeutronSecurityRule(secRule, rwTx);
+ boolean isNeutronSecurityRuleDeleted = deleteNeutronSecurityRule(deletedSecRule, oldNeutron, rwTx);
if (isNeutronSecurityRuleDeleted) {
DataStoreHelper.submitToDs(rwTx);
} else {
}
}
- public boolean deleteNeutronSecurityRule(NeutronSecurityRule secRule, ReadWriteTransaction rwTx) {
- TenantId tenantId = SecRuleEntityDecoder.getTenantId(secRule);
- EndpointGroupId providerEpgId = SecRuleEntityDecoder.getProviderEpgId(secRule);
+ public boolean deleteNeutronSecurityRule(SecurityRule secRule, Neutron neutron, ReadWriteTransaction rwTx) {
+ TenantId tenantId = new TenantId(secRule.getTenantId().getValue());
+ Uuid providerSecGroupId = secRule.getSecurityGroupId();
+ EndpointGroupId providerEpgId = new EndpointGroupId(providerSecGroupId.getValue());
- SelectorName providerSelector = getSelectorNameWithConsumer(secRule);
- deleteProviderNamedSelectorFromEpg(providerSelector, new EgKey(tenantId, providerEpgId), rwTx);
+ SelectorName providerSelector = getSelectorNameWithConsumer(secRule, neutron);
+ deleteProviderNamedSelectorFromEpg(providerSelector, new EpgKeyDto(providerEpgId, tenantId), rwTx);
- if (SecRuleEntityDecoder.getConsumerEpgId(secRule) != null) {
- EndpointGroupId consumerEpgId = SecRuleEntityDecoder.getConsumerEpgId(secRule);
- undesignContractsBetweenProviderAndConsumer(tenantId, providerEpgId, consumerEpgId, secRule, rwTx);
- undesignContractsBetweenProviderAndConsumer(tenantId, consumerEpgId, providerEpgId, secRule, rwTx);
+ if (secRule.getRemoteGroupId() != null) {
+ Uuid consumerSecGroupId = secRule.getRemoteGroupId();
+ undesignContractsBetweenProviderAndConsumer(tenantId, providerSecGroupId, consumerSecGroupId, secRule, neutron, rwTx);
+ undesignContractsBetweenProviderAndConsumer(tenantId, consumerSecGroupId, providerSecGroupId, secRule, neutron, rwTx);
} else {
- for (EndpointGroupId consumerEpgId : secRuleDao.getAllOwnerSecGrps()) {
- undesignContractsBetweenProviderAndConsumer(tenantId, providerEpgId, consumerEpgId, secRule, rwTx);
- undesignContractsBetweenProviderAndConsumer(tenantId, consumerEpgId, providerEpgId, secRule, rwTx);
+ for (Uuid consumerSecGroupId : SecurityRuleUtils.findSecurityGroupsHavingSecurityRules(neutron)) {
+ undesignContractsBetweenProviderAndConsumer(tenantId, providerSecGroupId, consumerSecGroupId, secRule, neutron, rwTx);
+ undesignContractsBetweenProviderAndConsumer(tenantId, consumerSecGroupId, providerSecGroupId, secRule, neutron, rwTx);
}
}
- secRuleDao.removeSecRule(secRule);
ContractId contractId = SecRuleEntityDecoder.getContractId(secRule);
rwTx.delete(LogicalDatastoreType.CONFIGURATION, IidFactory.contractIid(tenantId, contractId));
}
@VisibleForTesting
- void undesignContractsBetweenProviderAndConsumer(TenantId tenantId, EndpointGroupId provEpgId,
- EndpointGroupId consEpgId, NeutronSecurityRule removedSecRule, ReadWriteTransaction rwTx) {
- Set<NeutronSecurityRule> provSecRules = getProvidedSecRulesBetween(provEpgId, consEpgId);
- Set<NeutronSecurityRule> consSecRules = getProvidedSecRulesBetween(consEpgId, provEpgId);
- for (NeutronSecurityRule provSecRule : provSecRules) {
+ void undesignContractsBetweenProviderAndConsumer(TenantId tenantId, Uuid provSecGroupId,
+ Uuid consSecGroupId, SecurityRule removedSecRule, Neutron neutron, ReadWriteTransaction rwTx) {
+ Set<SecurityRule> provSecRules = getProvidedSecRulesBetween(provSecGroupId, consSecGroupId, neutron);
+ Set<SecurityRule> consSecRules = getProvidedSecRulesBetween(consSecGroupId, provSecGroupId, neutron);
+ EndpointGroupId consEpgId = new EndpointGroupId(consSecGroupId.getValue());
+ for (SecurityRule provSecRule : provSecRules) {
if (isProvidersSecRuleSuitableForConsumersSecRulesAndGoodToRemove(provSecRule, consSecRules, removedSecRule)) {
- SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule);
- deleteConsumerNamedSelector(consumerSelector, new EgKey(tenantId, consEpgId), rwTx);
+ SelectorName consumerSelector = getSelectorNameWithProvider(provSecRule, neutron);
+ deleteConsumerNamedSelector(consumerSelector, new EpgKeyDto(consEpgId, tenantId), rwTx);
}
// TODO add case when port ranges overlap
}
}
@VisibleForTesting
- static boolean isProvidersSecRuleSuitableForConsumersSecRulesAndGoodToRemove(NeutronSecurityRule provSecRule,
- Set<NeutronSecurityRule> consSecRules, NeutronSecurityRule removedSecRule) {
+ static boolean isProvidersSecRuleSuitableForConsumersSecRulesAndGoodToRemove(SecurityRule provSecRule,
+ Set<SecurityRule> consSecRules, SecurityRule removedSecRule) {
Direction directionProvSecRule = SecRuleEntityDecoder.getDirection(provSecRule);
- for (NeutronSecurityRule consSecRule : consSecRules) {
+ for (SecurityRule consSecRule : consSecRules) {
if (isRuleIdEqual(removedSecRule, consSecRule) || isRuleIdEqual(removedSecRule, provSecRule)) {
Direction directionConsSecRule = SecRuleEntityDecoder.getDirection(consSecRule);
if (isDirectionOpposite(directionProvSecRule, directionConsSecRule)
}
@VisibleForTesting
- static boolean isRuleIdEqual(NeutronSecurityRule one, NeutronSecurityRule two) {
+ static boolean isRuleIdEqual(SecurityRule one, SecurityRule two) {
checkNotNull(one);
checkNotNull(two);
- return one.getSecurityRuleUUID().equals(two.getSecurityRuleUUID());
+ return one.getSecurityGroupId().equals(two.getSecurityGroupId());
}
- private void deleteProviderNamedSelectorFromEpg(SelectorName providerSelector, EgKey providerEpgKey,
+ private void deleteProviderNamedSelectorFromEpg(SelectorName providerSelector, EpgKeyDto providerEpgKey,
ReadWriteTransaction rwTx) {
InstanceIdentifier<ProviderNamedSelector> providerSelectorIid = IidFactory.providerNamedSelectorIid(
- providerEpgKey.getTenantId(), providerEpgKey.getEgId(), providerSelector);
+ providerEpgKey.getTenantId(), providerEpgKey.getEpgId(), providerSelector);
DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, providerSelectorIid, rwTx);
}
- private void deleteConsumerNamedSelector(SelectorName consumerSelector, EgKey consumerEpgKey,
+ private void deleteConsumerNamedSelector(SelectorName consumerSelector, EpgKeyDto consumerEpgKey,
ReadWriteTransaction rwTx) {
InstanceIdentifier<ConsumerNamedSelector> consumerSelectorIid = IidFactory.consumerNamedSelectorIid(
- consumerEpgKey.getTenantId(), consumerEpgKey.getEgId(), consumerSelector);
+ consumerEpgKey.getTenantId(), consumerEpgKey.getEpgId(), consumerSelector);
DataStoreHelper.removeIfExists(LogicalDatastoreType.CONFIGURATION, consumerSelectorIid, rwTx);
}
}
}
- private SelectorName getSelectorNameWithConsumer(NeutronSecurityRule secRule) {
+ private SelectorName getSelectorNameWithConsumer(SecurityRule secRule, Neutron neutron) {
ClauseName clauseName = SecRuleNameDecoder.getClauseName(secRule);
StringBuilder selectorNameBuilder = new StringBuilder().append(clauseName.getValue());
- EndpointGroupId consumerEpgId = SecRuleEntityDecoder.getConsumerEpgId(secRule);
- if (consumerEpgId != null) {
+ Uuid consumerSecGroupId = secRule.getRemoteGroupId();
+ if (consumerSecGroupId == null) {
+ return new SelectorName(selectorNameBuilder.toString());
+ }
+
+ // we cannot use name of security group in selector, because name can be changed
+ // therefore name is used only in debug mode
+ if (NeutronMapperModule.isDebugEnabled()) {
+ Optional<SecurityGroup> potentialConsumerSecGroup =
+ SecurityGroupUtils.findSecurityGroup(secRule.getRemoteGroupId(), neutron.getSecurityGroups());
+ if (!potentialConsumerSecGroup.isPresent()) {
+ LOG.error("Neutron Security Group with UUID {} does not exist but it is in {}",
+ consumerSecGroupId.getValue(), secRule);
+ throw new IllegalStateException(
+ "Neutron Security Group with UUID " + consumerSecGroupId.getValue() + " does not exist.");
+ }
+
selectorNameBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(POSSIBLE_CONSUMER)
- .append(secGroupDao.getNameOrIdOfSecGroup(consumerEpgId));
+ .append(SecurityGroupUtils.getNameOrUuid(potentialConsumerSecGroup.get()));
+ return new SelectorName(selectorNameBuilder.toString());
}
+
+ selectorNameBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER)
+ .append(POSSIBLE_CONSUMER)
+ .append(consumerSecGroupId.getValue());
return new SelectorName(selectorNameBuilder.toString());
}
- private SelectorName getSelectorNameWithProvider(NeutronSecurityRule secRule) {
+ private SelectorName getSelectorNameWithProvider(SecurityRule secRule, Neutron neutron) {
ClauseName clauseName = SecRuleNameDecoder.getClauseName(secRule);
- EndpointGroupId providerEpgId = SecRuleEntityDecoder.getProviderEpgId(secRule);
+ Uuid providerSecGroupId = secRule.getSecurityGroupId();
+
+ // we cannot use name of security group in selector, because name can be changed
+ // therefore name is used only in debug mode
+ if (NeutronMapperModule.isDebugEnabled()) {
+ Optional<SecurityGroup> potentialProviderSecGroup =
+ SecurityGroupUtils.findSecurityGroup(secRule.getSecurityGroupId(), neutron.getSecurityGroups());
+ if (!potentialProviderSecGroup.isPresent()) {
+ LOG.error("Neutron Security Group with UUID {} does not exist but it is in {}",
+ providerSecGroupId.getValue(), secRule);
+ throw new IllegalStateException(
+ "Neutron Security Group with UUID " + providerSecGroupId.getValue() + " does not exist.");
+ }
+ String selectorName = new StringBuilder().append(clauseName.getValue())
+ .append(MappingUtils.NAME_DOUBLE_DELIMETER)
+ .append(PROVIDED_BY)
+ .append(SecurityGroupUtils.getNameOrUuid(potentialProviderSecGroup.get()))
+ .toString();
+ return new SelectorName(selectorName);
+ }
+
String selectorName = new StringBuilder().append(clauseName.getValue())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(PROVIDED_BY)
- .append(secGroupDao.getNameOrIdOfSecGroup(providerEpgId))
+ .append(providerSecGroupId.getValue())
.toString();
return new SelectorName(selectorName);
}
}
@VisibleForTesting
- static boolean isOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) {
+ static boolean isOneWithinTwo(SecurityRule one, SecurityRule two) {
if (!isOneGroupIdWithinTwoRemoteGroupId(one, two) || !isOneGroupIdWithinTwoRemoteGroupId(two, one))
return false;
if (!SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two))
return false;
if (!SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two))
return false;
- if (!Strings.isNullOrEmpty(two.getSecurityRuleRemoteIpPrefix())
- && Strings.isNullOrEmpty(one.getSecurityRuleRemoteIpPrefix()))
+ if (two.getRemoteIpPrefix() != null
+ && one.getRemoteIpPrefix() == null)
return false;
return true;
}
@VisibleForTesting
- static boolean isOneGroupIdWithinTwoRemoteGroupId(NeutronSecurityRule one, NeutronSecurityRule two) {
- return (Strings.isNullOrEmpty(two.getSecurityRemoteGroupID()) || two.getSecurityRemoteGroupID().equals(
- one.getSecurityRuleGroupID()));
+ static boolean isOneGroupIdWithinTwoRemoteGroupId(SecurityRule one, SecurityRule two) {
+ return (two.getRemoteGroupId() == null || two.getRemoteGroupId().equals(
+ one.getSecurityGroupId()));
}
+
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.SetMultimap;
-
-public class SecRuleDao {
-
- private final SetMultimap<EndpointGroupId, NeutronSecurityRule> secRulesByOwnerSecGrpId = HashMultimap.create();
- private final SetMultimap<OwnerAndRemoteOfSecRule, NeutronSecurityRule> secRulesByRemoteSecGrpId =
- HashMultimap.create();
- private final Map<Uuid, NeutronSecurityRule> secRuleByUuid = new HashMap<>();
-
- public void addSecRule(NeutronSecurityRule secRule) {
- Preconditions.checkNotNull(secRule);
- EndpointGroupId ownerSecGrp = SecRuleEntityDecoder.getProviderEpgId(secRule);
- EndpointGroupId remoteSecGrp = SecRuleEntityDecoder.getConsumerEpgId(secRule);
- secRulesByOwnerSecGrpId.put(ownerSecGrp, secRule);
- secRulesByRemoteSecGrpId.put(new OwnerAndRemoteOfSecRule(ownerSecGrp, remoteSecGrp), secRule);
- secRuleByUuid.put(new Uuid(secRule.getID()), secRule);
- }
-
- public Set<NeutronSecurityRule> getSecRulesByOwnerSecGrpId(EndpointGroupId secGrpId) {
- return secRulesByOwnerSecGrpId.get(secGrpId);
- }
-
- public Set<NeutronSecurityRule> getSecRulesBySecGrpIdAndRemoteSecGrpId(EndpointGroupId ownerSecGrpId,
- @Nullable EndpointGroupId remoteSecGrpId) {
- return secRulesByRemoteSecGrpId.get(new OwnerAndRemoteOfSecRule(ownerSecGrpId, remoteSecGrpId));
- }
-
- public Set<NeutronSecurityRule> getSecRulesWithoutRemoteSecGrpBySecGrpId(EndpointGroupId ownerSecGrpId) {
- return secRulesByRemoteSecGrpId.get(new OwnerAndRemoteOfSecRule(ownerSecGrpId, null));
- }
-
- public NeutronSecurityRule getSecRuleByUuid(Uuid secRule) {
- return secRuleByUuid.get(secRule);
- }
-
- public Set<EndpointGroupId> getAllOwnerSecGrps() {
- return secRulesByOwnerSecGrpId.keySet();
- }
-
- public void removeSecRule(NeutronSecurityRule secRule) {
- Preconditions.checkNotNull(secRule);
- EndpointGroupId ownerSecGrp = SecRuleEntityDecoder.getProviderEpgId(secRule);
- EndpointGroupId remoteSecGrp = SecRuleEntityDecoder.getConsumerEpgId(secRule);
- secRulesByOwnerSecGrpId.remove(ownerSecGrp, secRule);
- secRulesByRemoteSecGrpId.remove(new OwnerAndRemoteOfSecRule(ownerSecGrp, remoteSecGrp), secRule);
- secRuleByUuid.remove(new Uuid(secRule.getID()));
- }
-
- static class OwnerAndRemoteOfSecRule {
-
- private final EndpointGroupId owner;
- private final EndpointGroupId remote;
-
- private OwnerAndRemoteOfSecRule(EndpointGroupId owner, EndpointGroupId remote) {
- this.owner = Preconditions.checkNotNull(owner);
- this.remote = remote;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((owner == null) ? 0 : owner.hashCode());
- result = prime * result + ((remote == null) ? 0 : remote.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- OwnerAndRemoteOfSecRule other = (OwnerAndRemoteOfSecRule) obj;
- if (owner == null) {
- if (other.owner != null)
- return false;
- } else if (!owner.equals(other.owner))
- return false;
- if (remote == null) {
- if (other.remote != null)
- return false;
- } else if (!remote.equals(other.remote))
- return false;
- return true;
- }
-
- }
-
-}
import java.util.ArrayList;\r
import java.util.List;\r
\r
-import javax.annotation.Nullable;\r
-\r
import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition;\r
import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;\r
import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition;\r
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;\r
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;\r
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;\r
-import org.opendaylight.neutron.spi.NeutronSecurityRule;\r
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;\r
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.AllowActionCase;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.SfcActionCase;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.clause.ConsumerMatchersBuilder;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;\r
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstanceBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmpV6;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;\r
\r
-import com.google.common.base.Strings;\r
import com.google.common.collect.ImmutableList;\r
\r
public class SecRuleEntityDecoder {\r
throw new UnsupportedOperationException("Cannot create an instace.");\r
}\r
\r
- public static TenantId getTenantId(NeutronSecurityRule secRule) {\r
- return new TenantId(Utils.normalizeUuid(secRule.getSecurityRuleTenantID()));\r
- }\r
-\r
- public static EndpointGroupId getProviderEpgId(NeutronSecurityRule secRule) {\r
- return new EndpointGroupId(Utils.normalizeUuid(secRule.getSecurityRuleGroupID()));\r
+ public static ContractId getContractId(SecurityRule secRule) {\r
+ return new ContractId(secRule.getId().getValue());\r
}\r
\r
- public static @Nullable EndpointGroupId getConsumerEpgId(NeutronSecurityRule secRule) {\r
- if (Strings.isNullOrEmpty(secRule.getSecurityRemoteGroupID())) {\r
- return null;\r
- }\r
- return new EndpointGroupId(Utils.normalizeUuid(secRule.getSecurityRemoteGroupID()));\r
- }\r
-\r
- public static ContractId getContractId(NeutronSecurityRule secRule) {\r
- return new ContractId(Utils.normalizeUuid(secRule.getSecurityRuleUUID()));\r
- }\r
-\r
- public static ClassifierInstance getClassifierInstance(NeutronSecurityRule secRule) {\r
+ public static ClassifierInstance getClassifierInstance(SecurityRule secRule) {\r
ClassifierInstanceBuilder classifierBuilder = new ClassifierInstanceBuilder();\r
List<ParameterValue> params = new ArrayList<>();\r
- Integer portMin = secRule.getSecurityRulePortMin();\r
- Integer portMax = secRule.getSecurityRulePortMax();\r
+ Integer portMin = secRule.getPortRangeMin();\r
+ Integer portMax = secRule.getPortRangeMax();\r
if (portMin != null && portMax != null) {\r
classifierBuilder.setClassifierDefinitionId(L4ClassifierDefinition.DEFINITION.getId());\r
if (portMin.equals(portMax)) {\r
return null;\r
}\r
\r
- public static ClassifierRef getClassifierRef(NeutronSecurityRule secRule) {\r
+ public static ClassifierRef getClassifierRef(SecurityRule secRule) {\r
checkNotNull(secRule);\r
ClassifierName classifierInstanceName = SecRuleNameDecoder.getClassifierInstanceName(secRule);\r
ClassifierRefBuilder classifierRefBuilder = new ClassifierRefBuilder()\r
\r
/**\r
* @param secRule\r
- * @return direction resolved from {@link NeutronSecurityRule#getSecurityRuleDirection()}\r
+ * @return direction resolved from {@link SecurityRule#getDirection()}\r
* @throws IllegalArgumentException if return value of\r
- * {@link NeutronSecurityRule#getSecurityRuleDirection()} is other than "ingress" or\r
- * "egress"\r
+ * {@link SecurityRule#getDirection()} is other than {@link DirectionIngress} or\r
+ * {@link DirectionEgress}\r
*/\r
- public static Direction getDirection(NeutronSecurityRule secRule) {\r
- String direction = secRule.getSecurityRuleDirection();\r
- if (NeutronUtils.INGRESS.equals(direction)) {\r
+ public static Direction getDirection(SecurityRule secRule) {\r
+ Class<? extends DirectionBase> direction = secRule.getDirection();\r
+ if (direction == null) {\r
+ throw new IllegalArgumentException("Direction cannot be null.");\r
+ }\r
+ if (direction.isAssignableFrom(DirectionIngress.class)) {\r
return Direction.In;\r
}\r
- if (NeutronUtils.EGRESS.equals(direction)) {\r
+ if (direction.isAssignableFrom(DirectionEgress.class)) {\r
return Direction.Out;\r
}\r
throw new IllegalArgumentException("Direction " + direction + " from security group rule "\r
- + secRule.getSecurityRuleUUID() + " is not supported. Direction can be only 'ingress' or 'egress'.");\r
+ + secRule + " is not supported. Direction can be only 'ingress' or 'egress'.");\r
}\r
\r
/**\r
- * @param secRule {@link NeutronSecurityRule#getSecurityRuleRemoteIpPrefix()} is used for EIC\r
+ * @param secRule {@link SecurityRule#getRemoteIpPrefix()} is used for EIC\r
* and subject selection\r
* @return clause with the subject and with a consumer matcher containing EIC\r
*/\r
- public static Clause getClause(NeutronSecurityRule secRule) {\r
+ public static Clause getClause(SecurityRule secRule) {\r
checkNotNull(secRule);\r
SubjectName subjectName = SecRuleNameDecoder.getSubjectName(secRule);\r
ClauseBuilder clauseBuilder =\r
new ClauseBuilder().setSubjectRefs(ImmutableList.of(subjectName)).setName(SecRuleNameDecoder.getClauseName(secRule));\r
- String remoteIpPrefix = secRule.getSecurityRuleRemoteIpPrefix();\r
- if (!Strings.isNullOrEmpty(remoteIpPrefix)) {\r
+ IpPrefix remoteIpPrefix = secRule.getRemoteIpPrefix();\r
+ if (remoteIpPrefix != null) {\r
clauseBuilder.setConsumerMatchers(createConsumerMatchersWithEic(remoteIpPrefix));\r
}\r
return clauseBuilder.build();\r
}\r
\r
- private static ConsumerMatchers createConsumerMatchersWithEic(String remoteIpPrefix) {\r
- IpPrefix ipPrefix = Utils.createIpPrefix(remoteIpPrefix);\r
+ private static ConsumerMatchers createConsumerMatchersWithEic(IpPrefix ipPrefix) {\r
PrefixConstraint consumerPrefixConstraint = new PrefixConstraintBuilder().setIpPrefix(ipPrefix).build();\r
EndpointIdentificationConstraints eic =\r
new EndpointIdentificationConstraintsBuilder()\r
return new ConsumerMatchersBuilder().setEndpointIdentificationConstraints(eic).build();\r
}\r
\r
- public static boolean isEtherTypeOfOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) {\r
+ public static boolean isEtherTypeOfOneWithinTwo(SecurityRule one, SecurityRule two) {\r
Long oneEtherType = getEtherType(one);\r
Long twoEtherType = getEtherType(two);\r
return twoIsNullOrEqualsOne(oneEtherType, twoEtherType);\r
}\r
\r
- public static boolean isProtocolOfOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) {\r
+ public static boolean isProtocolOfOneWithinTwo(SecurityRule one, SecurityRule two) {\r
Long oneProtocol = getProtocol(one);\r
Long twoProtocol = getProtocol(two);\r
return twoIsNullOrEqualsOne(oneProtocol, twoProtocol);\r
return false;\r
}\r
\r
- public static boolean isPortsOfOneWithinTwo(NeutronSecurityRule one, NeutronSecurityRule two) {\r
- Integer onePortMin = one.getSecurityRulePortMin();\r
- Integer onePortMax = one.getSecurityRulePortMax();\r
- Integer twoPortMin = two.getSecurityRulePortMin();\r
- Integer twoPortMax = two.getSecurityRulePortMax();\r
+ public static boolean isPortsOfOneWithinTwo(SecurityRule one, SecurityRule two) {\r
+ Integer onePortMin = one.getPortRangeMin();\r
+ Integer onePortMax = one.getPortRangeMax();\r
+ Integer twoPortMin = two.getPortRangeMin();\r
+ Integer twoPortMax = two.getPortRangeMax();\r
if (twoPortMin == null && twoPortMax == null) {\r
return true;\r
}\r
\r
/**\r
* @param secRule\r
- * @return {@code null} if {@link NeutronSecurityRule#getSecurityRuleEthertype()} is null or\r
- * empty; value of {@link EtherTypeClassifierDefinition#IPv4_VALUE} or\r
- * {@link EtherTypeClassifierDefinition#IPv6_VALUE}\r
+ * @return {@code null} if {@link SecurityRule#getEthertype()} is null; Otherwise ethertype\r
+ * number\r
* @throws IllegalArgumentException if return value of\r
- * {@link NeutronSecurityRule#getSecurityRuleEthertype()} is not empty/null and is other\r
- * than "IPv4" or "IPv6"\r
+ * {@link SecurityRule#getEthertype()} is other {@link EthertypeV4} or\r
+ * {@link EthertypeV6}\r
*/\r
- public static Long getEtherType(NeutronSecurityRule secRule) {\r
- String ethertype = secRule.getSecurityRuleEthertype();\r
- if (Strings.isNullOrEmpty(ethertype)) {\r
+ public static Long getEtherType(SecurityRule secRule) {\r
+ Class<? extends EthertypeBase> ethertype = secRule.getEthertype();\r
+ if (ethertype == null) {\r
return null;\r
}\r
- if (NeutronUtils.IPv4.equals(ethertype)) {\r
+ if (ethertype.isAssignableFrom(EthertypeV4.class)) {\r
return EtherTypeClassifierDefinition.IPv4_VALUE;\r
}\r
- if (NeutronUtils.IPv6.equals(ethertype)) {\r
+ if (ethertype.isAssignableFrom(EthertypeV6.class)) {\r
return EtherTypeClassifierDefinition.IPv6_VALUE;\r
}\r
throw new IllegalArgumentException("Ethertype " + ethertype + " is not supported.");\r
\r
/**\r
* @param secRule\r
- * @return {@code null} if {@link NeutronSecurityRule#getSecurityRuleProtocol()} is null or\r
- * empty; Otherwise protocol number\r
+ * @return {@code null} if {@link SecurityRule#getProtocol()} is null; Otherwise protocol number\r
* @throws IllegalArgumentException if return value of\r
- * {@link NeutronSecurityRule#getSecurityRuleProtocol()} is not empty/null and is other\r
- * than "tcp", "udp", "icmp", "icmpv6" or string values that can be decoded to {@link Short}.\r
+ * {@link SecurityRule#getProtocol()} is other than {@link ProtocolTcp},\r
+ * {@link ProtocolUdp}, {@link ProtocolIcmp}, {@link ProtocolIcmpV6}\r
*/\r
- public static Long getProtocol(NeutronSecurityRule secRule) {\r
- String protocol = secRule.getSecurityRuleProtocol();\r
- if (Strings.isNullOrEmpty(protocol)) {\r
+ public static Long getProtocol(SecurityRule secRule) {\r
+ Class<? extends ProtocolBase> protocol = secRule.getProtocol();\r
+ if (protocol == null) {\r
return null;\r
}\r
- if (NeutronUtils.TCP.equals(protocol)) {\r
+ if (protocol.isAssignableFrom(ProtocolTcp.class)) {\r
return IpProtoClassifierDefinition.TCP_VALUE;\r
}\r
- if (NeutronUtils.UDP.equals(protocol)) {\r
+ if (protocol.isAssignableFrom(ProtocolUdp.class)) {\r
return IpProtoClassifierDefinition.UDP_VALUE;\r
}\r
- if (NeutronUtils.ICMP.equals(protocol)) {\r
+ if (protocol.isAssignableFrom(ProtocolIcmp.class)) {\r
return IpProtoClassifierDefinition.ICMP_VALUE;\r
}\r
- if (NeutronUtils.ICMPv6.equals(protocol)) {\r
+ if (protocol.isAssignableFrom(ProtocolIcmpV6.class)) {\r
return IpProtoClassifierDefinition.ICMPv6_VALUE;\r
}\r
- Long protocolNum;\r
- try {\r
- protocolNum = Long.valueOf(protocol);\r
- } catch (NumberFormatException e) {\r
- throw new IllegalArgumentException("Neutron Security Rule Protocol value " + protocol\r
- + " is not supported.");\r
- }\r
- return protocolNum;\r
+ throw new IllegalArgumentException("Neutron Security Rule Protocol value " + protocol + " is not supported.");\r
}\r
}\r
import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;
import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;
-
-import com.google.common.base.Strings;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
public class SecRuleNameDecoder {
throw new UnsupportedOperationException("Cannot create an instance.");
}
- public static SubjectName getSubjectName(NeutronSecurityRule secRule) {
+ public static SubjectName getSubjectName(SecurityRule secRule) {
RuleName ruleName = SecRuleNameDecoder.getRuleName(secRule);
return new SubjectName(ruleName);
}
- public static RuleName getRuleName(NeutronSecurityRule secRule) {
+ public static RuleName getRuleName(SecurityRule secRule) {
ClassifierName classifierRefName = SecRuleNameDecoder.getClassifierRefName(secRule);
String ruleName = new StringBuilder(MappingUtils.ACTION_ALLOW.getName().getValue())
.append(MappingUtils.NAME_DOUBLE_DELIMETER).append(classifierRefName.getValue()).toString();
return new RuleName(ruleName);
}
- public static ClassifierName getClassifierRefName(NeutronSecurityRule secRule) {
+ public static ClassifierName getClassifierRefName(SecurityRule secRule) {
Direction direction = SecRuleEntityDecoder.getDirection(secRule);
ClassifierName classifierInstanceName = getClassifierInstanceName(secRule);
String crName = new StringBuilder().append(direction.name())
return new ClassifierName(crName);
}
- public static ClassifierName getClassifierInstanceName(NeutronSecurityRule secRule) {
+ public static ClassifierName getClassifierInstanceName(SecurityRule secRule) {
StringBuilder keyBuilder = new StringBuilder();
- Integer portMin = secRule.getSecurityRulePortMin();
- Integer portMax = secRule.getSecurityRulePortMax();
+ Integer portMin = secRule.getPortRangeMin();
+ Integer portMax = secRule.getPortRangeMax();
if (portMin != null && portMax != null) {
keyBuilder.append(L4ClassifierDefinition.DEFINITION.getName().getValue());
if (portMin.equals(portMax)) {
.append(portMax.longValue());
}
}
- String protocol = secRule.getSecurityRuleProtocol();
- if (!Strings.isNullOrEmpty(protocol)) {
+ Class<? extends ProtocolBase> protocol = secRule.getProtocol();
+ if (protocol != null) {
if (keyBuilder.length() > 0) {
keyBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER);
}
keyBuilder.append(IpProtoClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(protocol);
+ .append(protocol.getSimpleName());
}
- String ethertype = secRule.getSecurityRuleEthertype();
- if (!Strings.isNullOrEmpty(ethertype)) {
+ Class<? extends EthertypeBase> ethertype = secRule.getEthertype();
+ if (ethertype != null) {
if (keyBuilder.length() > 0) {
keyBuilder.append(MappingUtils.NAME_DOUBLE_DELIMETER);
}
keyBuilder.append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(ethertype);
+ .append(ethertype.getSimpleName());
}
return new ClassifierName(keyBuilder.toString());
}
- public static ClauseName getClauseName(NeutronSecurityRule secRule) {
- String remoteIpPrefix = secRule.getSecurityRuleRemoteIpPrefix();
+ public static ClauseName getClauseName(SecurityRule secRule) {
+ IpPrefix remoteIpPrefix = secRule.getRemoteIpPrefix();
SubjectName subjectName = getSubjectName(secRule);
- if (Strings.isNullOrEmpty(remoteIpPrefix)) {
+ if (remoteIpPrefix == null) {
return new ClauseName(subjectName);
}
- return new ClauseName(
- subjectName.getValue() + MappingUtils.NAME_DOUBLE_DELIMETER + remoteIpPrefix.replace('/', '_'));
+ return new ClauseName(subjectName.getValue() + MappingUtils.NAME_DOUBLE_DELIMETER
+ + Utils.getStringIpPrefix(remoteIpPrefix).replace('/', '_'));
}
}
import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition;
import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;
import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.SfcActionCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.RuleBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
private final ClassifierRef classifierRef;
private final Rule rule;
- public SingleClassifierRule(NeutronSecurityRule secRule, int ruleBaseOrder, ActionChoice action) {
+ public SingleClassifierRule(SecurityRule secRule, int ruleBaseOrder, ActionChoice action) {
classifierInstance = SecRuleEntityDecoder.getClassifierInstance(secRule);
classifierRef = SecRuleEntityDecoder.getClassifierRef(secRule);
rule = createRule(
return rule;
}
- private Rule createRule(int order, NeutronSecurityRule secRule, ActionChoice action) {
+ private Rule createRule(int order, SecurityRule secRule, ActionChoice action) {
return new RuleBuilder().setName(SecRuleNameDecoder.getRuleName(secRule))
.setOrder(order)
.setActionRef(ImmutableList.of(SecRuleEntityDecoder.createActionRefFromActionChoice(action)))
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.Subject;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.SubjectBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
import com.google.common.collect.ImmutableList;
private final Clause clause;
private final Contract contract;
- public SingleRuleContract(NeutronSecurityRule secRule, int subjectAndRuleOrder, @Nullable Description contractDescription, ActionChoice action) {
+ public SingleRuleContract(SecurityRule secRule, int subjectAndRuleOrder, @Nullable Description contractDescription, ActionChoice action) {
this(secRule, new SingleClassifierRule(secRule, subjectAndRuleOrder, action), contractDescription);
}
- public SingleRuleContract(NeutronSecurityRule secRule, SingleClassifierRule singleClassifierRule,
+ public SingleRuleContract(SecurityRule secRule, SingleClassifierRule singleClassifierRule,
@Nullable Description contractDescription) {
checkNotNull(secRule);
this.singleClassifierRule = checkNotNull(singleClassifierRule);
package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
-import java.util.List;
-
-import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.groupbasedpolicy.api.sf.AllowActionDefinition;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronPortAware;
-import org.opendaylight.groupbasedpolicy.util.DataStoreHelper;
-import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.Neutron_IPs;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.AllowActionCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.SfcActionCaseBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.action.choice.allow.action._case.AllowBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRefBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstanceBuilder;
-import com.google.common.base.Optional;
-
public final class MappingUtils {
public static final String NEUTRON_ROUTER = "neutron_router-";
public static final String NEUTRON_EXTERNAL = "neutron_external_network-";
public static final String NEUTRON_GROUP = "neutron_group-";
+ public static final IpPrefix DEFAULT_ROUTE = new IpPrefix(new Ipv4Prefix("0.0.0.0/0"));
public static final ActionInstance ACTION_ALLOW = new ActionInstanceBuilder().setName(
new ActionName("Allow"))
.setActionDefinitionId(AllowActionDefinition.DEFINITION.getId())
new AllowBuilder().build()).build();
public static final ActionRef ACTION_REF_ALLOW =
new ActionRefBuilder().setName(ACTION_ALLOW.getName()).setOrder(0).build();
- public static final EndpointGroupId EPG_EXTERNAL_ID = new EndpointGroupId("eeeaa3a2-e9ba-44e0-a462-bea923d30e38");
+ public static final Uuid EIG_UUID = new Uuid("eeeaa3a2-e9ba-44e0-a462-bea923d30e38");
+ public static final EndpointGroupId EPG_EXTERNAL_ID = new EndpointGroupId(EIG_UUID.getValue());
public static final String NAME_VALUE_DELIMETER = "-";
public static final String NAME_DELIMETER = "_";
return new SfcActionCaseBuilder().setSfcChainName(chainName).build();
}
- public static ForwardingCtx createForwardingContext(TenantId tenantId, L2FloodDomainId l2FdId, ReadTransaction rTx) {
- Optional<L2FloodDomain> potentialL2Fd = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.l2FloodDomainIid(tenantId, l2FdId), rTx);
- if (!potentialL2Fd.isPresent()) {
- return new ForwardingCtx(null, null, null);
- }
- L2BridgeDomainId l2BdId = potentialL2Fd.get().getParent();
- if (l2BdId == null) {
- return new ForwardingCtx(potentialL2Fd.get(), null, null);
- }
- Optional<L2BridgeDomain> potentialL2Bd = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.l2BridgeDomainIid(tenantId, l2BdId), rTx);
- if (!potentialL2Bd.isPresent()) {
- return new ForwardingCtx(potentialL2Fd.get(), null, null);
- }
- L3ContextId l3ContextId = potentialL2Bd.get().getParent();
- if (l3ContextId == null) {
- return new ForwardingCtx(potentialL2Fd.get(), potentialL2Bd.get(), null);
- }
- Optional<L3Context> potentialL3Context = DataStoreHelper.readFromDs(LogicalDatastoreType.CONFIGURATION,
- IidFactory.l3ContextIid(tenantId, l3ContextId), rTx);
- if (!potentialL3Context.isPresent()) {
- return new ForwardingCtx(potentialL2Fd.get(), potentialL2Bd.get(), null);
- }
- return new ForwardingCtx(potentialL2Fd.get(), potentialL2Bd.get(), potentialL3Context.get());
- }
-
- public static final class ForwardingCtx {
-
- private final L2FloodDomain l2FloodDomain;
- private final L2BridgeDomain l2BridgeDomain;
- private final L3Context l3Context;
-
- private ForwardingCtx(L2FloodDomain l2Fd, L2BridgeDomain l2Bd, L3Context l3Context) {
- this.l2FloodDomain = l2Fd;
- this.l2BridgeDomain = l2Bd;
- this.l3Context = l3Context;
- }
-
- public L2FloodDomain getL2FloodDomain() {
- return l2FloodDomain;
- }
-
- public L2BridgeDomain getL2BridgeDomain() {
- return l2BridgeDomain;
- }
-
- public L3Context getL3Context() {
- return l3Context;
- }
-
- }
-
- public static Neutron_IPs getFirstIp(List<Neutron_IPs> fixedIPs) {
- if (fixedIPs == null || fixedIPs.isEmpty()) {
- return null;
- }
- Neutron_IPs neutron_Ip = fixedIPs.get(0);
- if (fixedIPs.size() > 1) {
- NeutronPortAware.LOG.warn("Neutron mapper does not support multiple IPs on the same port. Only first IP is selected {}",
- neutron_Ip);
- }
- return neutron_Ip;
- }
}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.ext.rev150712.NetworkL3Extension;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.Networks;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.networks.rev150712.networks.attributes.networks.Network;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.provider.ext.rev150712.NetworkProviderExtension;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+
+public class NetworkUtils {
+
+ public static List<Network> findRouterExternalNetworks(@Nullable Networks networks) {
+ if (networks == null || networks.getNetwork() == null) {
+ return Collections.emptyList();
+ }
+ List<Network> result = new ArrayList<>();
+ for (Network network : networks.getNetwork()) {
+ if (isRouterExternal(network)) {
+ result.add(network);
+ }
+ }
+ return result;
+ }
+
+ public static Optional<Network> findNetwork(Uuid uuid, @Nullable Networks networks) {
+ if (networks == null || networks.getNetwork() == null) {
+ return Optional.absent();
+ }
+ for (Network network : networks.getNetwork()) {
+ if (network.getUuid().equals(uuid)) {
+ return Optional.of(network);
+ }
+ }
+ return Optional.absent();
+ }
+
+ public static boolean isProviderPhysicalNetwork(Network network) {
+ return (!isRouterExternal(network) && !getPhysicalNetwork(network).isEmpty());
+ }
+
+ public static boolean isRouterExternal(Network network) {
+ NetworkL3Extension l3Extension = network.getAugmentation(NetworkL3Extension.class);
+ if (l3Extension == null) {
+ return false;
+ }
+ Boolean external = l3Extension.isExternal();
+ if (external == null) {
+ return false;
+ }
+ return true;
+ }
+
+ public static @Nonnull String getPhysicalNetwork(Network network) {
+ NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class);
+ if (providerExtension == null) {
+ return "";
+ }
+ return Strings.nullToEmpty(providerExtension.getPhysicalNetwork());
+ }
+
+ public static @Nonnull String getSegmentationId(Network network) {
+ NetworkProviderExtension providerExtension = network.getAugmentation(NetworkProviderExtension.class);
+ if (providerExtension == null) {
+ return "";
+ }
+ return Strings.nullToEmpty(providerExtension.getSegmentationId());
+ }
+}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.Mappings;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.NetworkMappings;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMappingKey;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public class NeutronMapperIidFactory {
-
- public static InstanceIdentifier<NetworkMapping> networkMappingIid(UniqueId networkId) {
- return InstanceIdentifier.builder(Mappings.class)
- .child(NetworkMappings.class)
- .child(NetworkMapping.class, new NetworkMappingKey(networkId))
- .build();
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
-
-public final class NeutronUtils {
-
- public static final String EGRESS = "egress";
- public static final String INGRESS = "ingress";
- public static final String IPv6 = "IPv6";
- public static final String IPv4 = "IPv4";
- public static final String NULL = "null";
- public static final String UDP = "udp";
- public static final String TCP = "tcp";
- public static final String ICMP = "icmp";
- public static final String ICMPv6 = "icmpv6";
-
- private NeutronUtils() {
- throw new UnsupportedOperationException("Cannot create an instance.");
- }
-}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.port.attributes.FixedIps;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port;
+
+import com.google.common.base.Optional;
+
+public class PortUtils {
+
+ private static final String DEVICE_OWNER_DHCP = "network:dhcp";
+ private static final String DEVICE_OWNER_ROUTER_IFACE = "network:router_interface";
+ private static final String DEVICE_OWNER_ROUTER_GATEWAY = "network:router_gateway";
+ private static final String DEVICE_OWNER_FLOATING_IP = "network:floatingip";
+
+ public static Optional<Port> findPort(Uuid uuid, @Nullable Ports ports) {
+ if (ports == null || ports.getPort() == null) {
+ return Optional.absent();
+ }
+ for (Port port : ports.getPort()) {
+ if (port.getUuid().equals(uuid)) {
+ return Optional.of(port);
+ }
+ }
+ return Optional.absent();
+ }
+
+ public static Set<Port> findRouterInterfacePorts(@Nullable Ports ports) {
+ if (ports == null || ports.getPort() == null) {
+ return Collections.emptySet();
+ }
+ Set<Port> routerInterfacePorts = new HashSet<>();
+ for (Port port : ports.getPort()) {
+ if (isRouterInterfacePort(port)) {
+ routerInterfacePorts.add(port);
+ }
+ }
+ return routerInterfacePorts;
+ }
+
+ public static Set<Port> findPortsBySubnet(Uuid subnetUuid, @Nullable Ports ports) {
+ if (ports == null || ports.getPort() == null) {
+ return Collections.emptySet();
+ }
+ Set<Port> portsWithSubnet = new HashSet<>();
+ for (Port port : ports.getPort()) {
+ List<FixedIps> fixedIps = port.getFixedIps();
+ if (fixedIps != null && !fixedIps.isEmpty()) {
+ for (FixedIps ipWithSubnet : fixedIps) {
+ if (ipWithSubnet.getSubnetId().equals(subnetUuid)) {
+ portsWithSubnet.add(port);
+ }
+ }
+ }
+ }
+ return portsWithSubnet;
+ }
+
+ public static Optional<FixedIps> resolveFirstFixedIps(Port port) {
+ List<FixedIps> fixedIps = port.getFixedIps();
+ if (fixedIps != null && !fixedIps.isEmpty()) {
+ return Optional.of(fixedIps.get(0));
+ }
+ return Optional.absent();
+ }
+
+ public static boolean isNormalPort(Port port) {
+ if (isDhcpPort(port) || isRouterInterfacePort(port) || isRouterGatewayPort(port) || isFloatingIpPort(port)) {
+ return false;
+ }
+ return true;
+ }
+
+ public static boolean isDhcpPort(Port port) {
+ return DEVICE_OWNER_DHCP.equals(port.getDeviceOwner());
+ }
+
+ public static boolean isRouterInterfacePort(Port port) {
+ return DEVICE_OWNER_ROUTER_IFACE.equals(port.getDeviceOwner());
+ }
+
+ public static boolean isRouterGatewayPort(Port port) {
+ return DEVICE_OWNER_ROUTER_GATEWAY.equals(port.getDeviceOwner());
+ }
+
+ public static boolean isFloatingIpPort(Port port) {
+ return DEVICE_OWNER_FLOATING_IP.equals(port.getDeviceOwner());
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router;
+
+import com.google.common.base.Optional;
+
+public class RouterUtils {
+
+ public static Optional<Router> findRouter(Uuid uuid, @Nullable Routers routers) {
+ if (routers == null || routers.getRouter() == null) {
+ return Optional.absent();
+ }
+ for (Router router : routers.getRouter()) {
+ if (router.getUuid().equals(uuid)) {
+ return Optional.of(router);
+ }
+ }
+ return Optional.absent();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroups;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+
+public class SecurityGroupUtils {
+
+ public static Optional<SecurityGroup> findSecurityGroup(Uuid secGrpUuid, @Nullable SecurityGroups securityGroups) {
+ Preconditions.checkNotNull(secGrpUuid);
+ if (securityGroups == null || securityGroups.getSecurityGroup() == null) {
+ return Optional.absent();
+ }
+ for (SecurityGroup secGroup : securityGroups.getSecurityGroup()) {
+ if (secGrpUuid.equals(secGroup.getUuid())) {
+ return Optional.of(secGroup);
+ }
+ }
+ return Optional.absent();
+ }
+
+ public static String getNameOrUuid(SecurityGroup secGroup) {
+ if (!Strings.isNullOrEmpty(secGroup.getName())) {
+ return secGroup.getName();
+ }
+ return secGroup.getUuid().getValue();
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRules;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
+
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.collect.FluentIterable;
+
+public class SecurityRuleUtils {
+
+ public static Optional<SecurityRule> findSecurityRule(Uuid uuid, @Nullable SecurityRules securityRules) {
+ if (securityRules == null || securityRules.getSecurityRule() == null) {
+ return Optional.absent();
+ }
+ for (SecurityRule secRule : securityRules.getSecurityRule()) {
+ if (secRule.getId().equals(uuid)) {
+ return Optional.of(secRule);
+ }
+ }
+ return Optional.absent();
+ }
+
+ public static Set<SecurityRule> findSecurityRulesBySecGroupAndRemoteSecGroup(Uuid secGroup,
+ @Nullable Uuid remoteSecGroup, Neutron neutron) {
+ Preconditions.checkNotNull(secGroup);
+ return FluentIterable.from(findAllSecurityRules(neutron)).filter(new Predicate<SecurityRule>() {
+
+ @Override
+ public boolean apply(SecurityRule secRule) {
+ return (secRule.getSecurityGroupId().equals(secGroup)
+ && Objects.equal(secRule.getRemoteGroupId(), remoteSecGroup));
+ }
+ }).toSet();
+ }
+
+ public static Set<Uuid> findSecurityGroupsHavingSecurityRules(Neutron neutron) {
+ return FluentIterable.from(findAllSecurityRules(neutron)).transform(new Function<SecurityRule, Uuid>() {
+
+ @Override
+ public Uuid apply(SecurityRule secRule) {
+ return secRule.getSecurityGroupId();
+ }
+ }).toSet();
+ }
+
+ public static List<SecurityRule> findAllSecurityRules(Neutron neutron) {
+ Preconditions.checkNotNull(neutron);
+ SecurityRules securityRules = neutron.getSecurityRules();
+ if (securityRules == null || securityRules.getSecurityRule() == null) {
+ return Collections.emptyList();
+ }
+ return securityRules.getSecurityRule();
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
+
+import javax.annotation.Nullable;
+
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.Subnets;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.subnets.rev150712.subnets.attributes.subnets.Subnet;
+
+import com.google.common.base.Optional;
+
+public class SubnetUtils {
+
+ public static Optional<Subnet> findSubnet(Uuid uuid, @Nullable Subnets subnets) {
+ if (subnets == null || subnets.getSubnet() == null) {
+ return Optional.absent();
+ }
+ for (Subnet subnet : subnets.getSubnet()) {
+ if (subnet.getUuid().equals(uuid)) {
+ return Optional.of(subnet);
+ }
+ }
+ return Optional.absent();
+ }
+}
+++ /dev/null
-module neutron-mapper {
- yang-version 1;
-
- namespace "urn:opendaylight:groupbasedpolicy:neutron-mapper";
- prefix "gbp-neutron-mapper";
-
- import gbp-common {prefix gbp-common;}
- import endpoint {prefix gbp-endpoint;}
- import ietf-inet-types {
- prefix inet;
- revision-date 2010-09-24;
- }
-
- description
- "This module defines the mapping model between Neutron IDs and GBP IDs.
- These mappings are used just internaly and are NOT EXPORTED.";
-
- revision "2015-02-23" {
- description
- "Initial revision.";
- }
-
- grouping tenant-id-fields {
- leaf tenant-id {
- description "A unique ID for the tenant";
- mandatory true;
- type gbp-common:tenant-id;
- }
- }
-
- container mappings {
- config false;
- container network-mappings {
- list network-mapping {
- key network-id;
- leaf network-id {
- description "A unique ID for the neutron network == gbp l2-flood-domain";
- type gbp-common:unique-id;
- }
- leaf l2-bridge-domain-id {
- description "A unique ID of l2-bridge-domain generated for neutron network";
- type gbp-common:l2-bridge-domain-id;
- }
- leaf l3-context-id {
- description "A unique ID of l3-context generated for neutron network";
- type gbp-common:l3-context-id;
- }
- }
- }
- }
-
-}
\ No newline at end of file
--- /dev/null
+package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping;
+
+import static org.junit.Assert.fail;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.NeutronSecurityGroupAware;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+
+public class NeutronSecurityGroupAwareDataStoreTest extends GbpDataBrokerTest {
+
+ @Test
+ public void testAddAndDeleteNeutronSecurityGroup_noSecurityRules() throws Exception {
+ DataBroker dataBroker = getDataBroker();
+ NeutronSecurityGroupAware groupAware = new NeutronSecurityGroupAware(dataBroker);
+
+ final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+ final String secGroupId2 = "cccccccc-cccc-cccc-cccc-cccccccccccc";
+
+ SecurityGroup secGroup1 = NeutronEntityFactory.securityGroup(secGroupId1, tenantId);
+ SecurityGroup secGroup2 = NeutronEntityFactory.securityGroup(secGroupId2, tenantId);
+
+ groupAware.onCreated(secGroup1, null);
+
+ PolicyAssert.assertTenantExists(dataBroker, tenantId);
+ PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
+ PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1);
+ PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
+
+ groupAware.onDeleted(secGroup1, null, null);
+
+ PolicyAssert.assertTenantExists(dataBroker, tenantId);
+ PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
+ PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0);
+
+ groupAware.onCreated(secGroup1, null);
+ groupAware.onCreated(secGroup2, null);
+
+ PolicyAssert.assertTenantExists(dataBroker, tenantId);
+ PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
+ PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 2);
+ PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
+ PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId2);
+ PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId2);
+ PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId2);
+ PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId2, IntraGroupPolicy.RequireContract);
+
+ groupAware.onDeleted(secGroup2, null, null);
+
+ PolicyAssert.assertTenantExists(dataBroker, tenantId);
+ PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
+ PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1);
+ PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1);
+ PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
+
+ groupAware.onDeleted(secGroup1, null, null);
+
+ PolicyAssert.assertTenantExists(dataBroker, tenantId);
+ PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
+ PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0);
+ }
+
+ @Test
+ public void testConstructor_invalidArgument() throws Exception {
+ try {
+ new NeutronSecurityGroupAware(null);
+ fail(NullPointerException.class.getName() + " expected");
+ } catch (NullPointerException e) {
+ // do nothing
+ }
+ }
+
+}
+++ /dev/null
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group;
-
-import static org.junit.Assert.fail;
-
-import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.NeutronSecurityRuleAware;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleDao;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.ConfigDataStoreReader;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup.IntraGroupPolicy;
-
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-
-public class NeutronSecurityGroupAwareDataStoreTest extends GbpDataBrokerTest {
-
- @Test
- public void testAddAndDeleteNeutronSecurityGroup_noSecurityRules() throws Exception {
- DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
- NeutronSecurityGroupAware groupAware = new NeutronSecurityGroupAware(dataBroker, ruleAware, secGroupDao);
-
- final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
- final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
- final String secGroupId2 = "cccccccc-cccc-cccc-cccc-cccccccccccc";
-
- NeutronSecurityGroup secGroup1 = NeutronEntityFactory.securityGroup(secGroupId1, tenantId);
- NeutronSecurityGroup secGroup2 = NeutronEntityFactory.securityGroup(secGroupId2, tenantId);
-
- groupAware.created(secGroup1);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
-
- groupAware.deleted(secGroup1);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0);
-
- groupAware.created(secGroup1);
- groupAware.created(secGroup2);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 2);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId2);
- PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId2);
- PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId2);
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId2, IntraGroupPolicy.RequireContract);
-
- groupAware.deleted(secGroup2);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertNoProviderNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
-
- groupAware.deleted(secGroup1);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0);
- }
-
- @Test
- public void testAddAndDeleteNeutronSecurityGroup_withSecurityRules() throws Exception {
- DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
- NeutronSecurityGroupAware groupAware = new NeutronSecurityGroupAware(dataBroker, ruleAware, secGroupDao);
-
- final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
- final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
- final String secGroupId2 = "cccccccc-cccc-cccc-cccc-cccccccccccc";
- final String secRuleId1 = "dddddddd-dddd-dddd-dddd-dddddddddddd";
- final String secRuleId2 = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
-
- NeutronSecurityRule secRule1 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId1, tenantId,
- NeutronUtils.IPv4, NeutronUtils.EGRESS, secGroupId1, null);
-
- NeutronSecurityRule secRule2 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId2, tenantId,
- NeutronUtils.IPv4, NeutronUtils.INGRESS, secGroupId2, secGroupId1);
-
- NeutronSecurityGroup secGroup1 = NeutronEntityFactory.securityGroup(secGroupId1, tenantId,
- ImmutableList.of(secRule1));
-
- NeutronSecurityGroup secGroup2 = NeutronEntityFactory.securityGroup(secGroupId2, tenantId,
- ImmutableList.of(secRule2));
-
- groupAware.created(secGroup1);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1);
- Optional<Contract> contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId1);
- PolicyAssert.assertContract(contract.get(), secRule1);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 1);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
- Optional<EndpointGroup> epGroup1 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertProviderNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId1)));
- PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1);
-
- PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1);
- PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
-
- groupAware.deleted(secGroup1);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0);
-
- PolicyAssert.assertClassifierInstanceNotExists(dataBroker, secRule1);
- // TODO: Uncomment this when the life cycle of the Allow ActionInstance will be clarified.
- // PolicyAssert.assertActionInstanceNotExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
-
- groupAware.created(secGroup1);
- groupAware.created(secGroup2);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1);
- contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId1);
- PolicyAssert.assertContract(contract.get(), secRule1);
- contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId2);
- PolicyAssert.assertContract(contract.get(), secRule2);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 2);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
- epGroup1 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertProviderNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId1)));
- PolicyAssert.assertConsumerNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId2)));
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId2);
- Optional<EndpointGroup> epGroup2 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId2);
- PolicyAssert.assertProviderNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId2)));
- PolicyAssert.assertConsumerNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId1)));
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId2, IntraGroupPolicy.RequireContract);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 2);
- PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1);
- PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
-
- groupAware.deleted(secGroup2);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1);
- contract = ConfigDataStoreReader.readContract(dataBroker, tenantId, secRuleId1);
- PolicyAssert.assertContract(contract.get(), secRule1);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 1);
- PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
- epGroup1 = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertProviderNamedSelectors(epGroup1.get(), ImmutableSet.of(new ContractId(secRuleId1)));
- PolicyAssert.assertNoConsumerNamedSelectors(dataBroker, tenantId, secGroupId1);
- PolicyAssert.assertIntraGroupPolicy(dataBroker, tenantId, secGroupId1, IntraGroupPolicy.RequireContract);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 1);
-
- PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1);
- PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
-
- groupAware.deleted(secGroup1);
-
- PolicyAssert.assertTenantExists(dataBroker, tenantId);
- PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
- PolicyAssert.assertEndpointGroupCount(dataBroker, tenantId, 0);
-
- PolicyAssert.assertClassifierInstanceNotExists(dataBroker, secRule1);
- // TODO: Uncomment this when the life cycle of the Allow ActionInstance will be clarified.
- // PolicyAssert.assertActionInstanceNotExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
- }
-
- @Test
- public void testConstructor_invalidArgument() throws Exception {
- DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
- assertExceptionInConstructor(null, ruleAware, secGroupDao);
- assertExceptionInConstructor(dataBroker, null, secGroupDao);
- assertExceptionInConstructor(dataBroker, ruleAware, null);
- assertExceptionInConstructor(null, null, null);
- }
-
- private void assertExceptionInConstructor(DataBroker dataBroker, NeutronSecurityRuleAware secRuleAware,
- SecGroupDao secGroupDao) {
- try {
- new NeutronSecurityGroupAware(dataBroker, secRuleAware, secGroupDao);
- fail(NullPointerException.class.getName() + " expected");
- } catch (NullPointerException ex) {
- // do nothing
- }
- }
-}
+++ /dev/null
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
-
-public class SecGroupDaoTest {
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- private SecGroupDao secGroupDao;
-
- @Before
- public void setUp() throws Exception {
- secGroupDao = new SecGroupDao();
- }
-
- @Test
- public void testAddAndRemoveSecGroup() {
- NeutronSecurityGroup secGroup1 = NeutronEntityFactory.securityGroup("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
- NeutronSecurityGroup secGroup2 = NeutronEntityFactory.securityGroup("cccccccc-cccc-cccc-cccc-cccccccccccc",
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
-
- // one security group
- secGroupDao.addSecGroup(secGroup1);
- EndpointGroupId epGroupId1 = new EndpointGroupId(secGroup1.getSecurityGroupUUID());
- NeutronSecurityGroup daoSecGroup = secGroupDao.getSecGroupById(epGroupId1);
- assertNotNull(daoSecGroup);
- assertEquals(secGroup1, daoSecGroup);
-
- secGroupDao.removeSecGroup(epGroupId1);
- assertNull(secGroupDao.getSecGroupById(epGroupId1));
-
- // two security groups
- secGroupDao.addSecGroup(secGroup1);
- secGroupDao.addSecGroup(secGroup2);
- daoSecGroup = secGroupDao.getSecGroupById(epGroupId1);
- assertNotNull(daoSecGroup);
- assertEquals(secGroup1, daoSecGroup);
- EndpointGroupId epGroupId2 = new EndpointGroupId(secGroup2.getSecurityGroupUUID());
- daoSecGroup = secGroupDao.getSecGroupById(epGroupId2);
- assertNotNull(daoSecGroup);
- assertEquals(secGroup2, daoSecGroup);
-
- secGroupDao.removeSecGroup(epGroupId2);
- daoSecGroup = secGroupDao.getSecGroupById(epGroupId1);
- assertNotNull(daoSecGroup);
- assertEquals(secGroup1, daoSecGroup);
- assertNull(secGroupDao.getSecGroupById(epGroupId2));
-
- secGroupDao.removeSecGroup(epGroupId1);
- assertNull(secGroupDao.getSecGroupById(epGroupId1));
- assertNull(secGroupDao.getSecGroupById(epGroupId2));
- }
-
- @Test
- public void testAddSecGroup_replacementOfSecGroup() {
- NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroup("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
- secGroupDao.addSecGroup(secGroup);
- EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- NeutronSecurityGroup daoSecGroup = secGroupDao.getSecGroupById(epGroupId);
- assertNotNull(daoSecGroup);
- assertEquals(secGroup, daoSecGroup);
-
- // the same security group id but different tenant id
- secGroup = NeutronEntityFactory.securityGroup("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- "cccccccc-cccc-cccc-cccc-cccccccccccc");
- secGroupDao.addSecGroup(secGroup);
- daoSecGroup = secGroupDao.getSecGroupById(epGroupId);
- assertNotNull(daoSecGroup);
- assertEquals(secGroup, daoSecGroup);
- }
-
- @Test
- public void testAddSecGroup_nullArgument() {
- thrown.expect(NullPointerException.class);
- secGroupDao.addSecGroup(null);
- }
-
- @Test
- public void testGetNameOrIdOfSecGroup_nullArgument() {
- thrown.expect(NullPointerException.class);
- secGroupDao.getNameOrIdOfSecGroup(null);
- }
-
- @Test
- public void testGetNameOrIdOfSecGroup_unknownEpGroupId() {
- EndpointGroupId unknownEpGroupId = new EndpointGroupId("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb");
- assertEquals("", secGroupDao.getNameOrIdOfSecGroup(unknownEpGroupId));
- }
-
- @Test
- public void testGetNameOrIdOfSecGroup_secGroupNameIsNull() {
- NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroupWithName(
- "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", null);
- secGroupDao.addSecGroup(secGroup);
- EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- String secGroupNameOrId = secGroupDao.getNameOrIdOfSecGroup(epGroupId);
- assertNotNull(secGroupNameOrId);
- assertEquals(epGroupId.getValue(), secGroupNameOrId);
- }
-
- @Test
- public void testGetNameOrIdOfSecGroup_secGroupNameIsEmpty() {
- NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroupWithName(
- "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "");
- secGroupDao.addSecGroup(secGroup);
- EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- String secGroupNameOrId = secGroupDao.getNameOrIdOfSecGroup(epGroupId);
- assertNotNull(secGroupNameOrId);
- assertEquals(epGroupId.getValue(), secGroupNameOrId);
- }
-
- @Test
- public void testGetNameOrIdOfSecGroup_secGroupNameIsNotEmpty() {
- NeutronSecurityGroup secGroup = NeutronEntityFactory.securityGroupWithName(
- "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "secGroupName");
- secGroupDao.addSecGroup(secGroup);
- EndpointGroupId epGroupId = new EndpointGroupId(secGroup.getSecurityGroupUUID());
- String secGroupNameOrId = secGroupDao.getNameOrIdOfSecGroup(epGroupId);
- assertNotNull(secGroupNameOrId);
- assertEquals("secGroupName", secGroupNameOrId);
- }
-}
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import java.util.ArrayList;
+import java.util.List;
+
import org.junit.Test;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.ConfigDataStoreReader;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.Tenant;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.NeutronBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroupsBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.SecurityRulesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
/**
public final void testAddNeutronSecurityRule_rulesWithRemoteIpPrefix() throws Exception {
String tenant = "ad4c6c25-2424-4ad3-97ee-f9691ce03645";
String goldSecGrp = "fe40e28f-ad6a-4a2d-b12a-47510876344a";
- NeutronSecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, goldSecGrp,
+ SecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, EthertypeV4.class, DirectionIngress.class, goldSecGrp,
null);
- NeutronSecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, goldSecGrp,
+ SecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, EthertypeV4.class, DirectionEgress.class, goldSecGrp,
null);
String serverSecGrp = "71cf4fe5-b146-409e-8151-cd921298ce32";
- NeutronSecurityRule serverIn80Tcp10_1_1_0 = NeutronEntityFactory.securityRuleWithEtherType(
- "9dbb533d-d9b2-4dc9-bae7-ee60c8df184d", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp,
- null);
- serverIn80Tcp10_1_1_0.setSecurityRuleProtocol(NeutronUtils.TCP);
- serverIn80Tcp10_1_1_0.setSecurityRulePortMin(80);
- serverIn80Tcp10_1_1_0.setSecurityRulePortMax(80);
- serverIn80Tcp10_1_1_0.setSecurityRuleRemoteIpPrefix("10.1.1.0/24");
- NeutronSecurityRule serverInIp20_1_1_0 = NeutronEntityFactory.securityRuleWithEtherType(
- "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp,
- null);
- serverInIp20_1_1_0.setSecurityRuleRemoteIpPrefix("20.1.1.0/24");
- NeutronSecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, serverSecGrp,
+ SecurityRule serverIn80Tcp10_1_1_0 = new SecurityRuleBuilder().setId(new Uuid("9dbb533d-d9b2-4dc9-bae7-ee60c8df184d"))
+ .setTenantId(new Uuid(tenant))
+ .setEthertype(EthertypeV4.class)
+ .setProtocol(ProtocolTcp.class)
+ .setPortRangeMin(80)
+ .setPortRangeMax(80)
+ .setDirection(DirectionIngress.class)
+ .setSecurityGroupId(new Uuid(serverSecGrp))
+ .setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("10.1.1.0/24")))
+ .build();
+ SecurityRule serverInIp20_1_1_0 = new SecurityRuleBuilder().setId(new Uuid("adf7e558-de47-4f9e-a9b8-96e19db5d1ac"))
+ .setTenantId(new Uuid(tenant))
+ .setEthertype(EthertypeV4.class)
+ .setDirection(DirectionIngress.class)
+ .setSecurityGroupId(new Uuid(serverSecGrp))
+ .setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("20.1.1.0/24")))
+ .build();
+ SecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, EthertypeV4.class, DirectionEgress.class, serverSecGrp,
null);
DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(goldSecGrp, tenant));
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(serverSecGrp, tenant));
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
+ List<SecurityGroup> secGroups = new ArrayList<>();
+ secGroups.add(NeutronEntityFactory.securityGroup(goldSecGrp, tenant));
+ secGroups.add(NeutronEntityFactory.securityGroup(serverSecGrp, tenant));
+ Neutron neutron = new NeutronBuilder()
+ .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build())
+ .setSecurityRules(new SecurityRulesBuilder().setSecurityRule(
+ ImmutableList.of(goldInIpv4, goldOutIpv4, serverIn80Tcp10_1_1_0, serverInIp20_1_1_0, serverOutIpv4))
+ .build())
+ .build();
+ NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker);
ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- ruleAware.addNeutronSecurityRule(goldInIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(goldOutIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(serverIn80Tcp10_1_1_0, rwTx);
- ruleAware.addNeutronSecurityRule(serverInIp20_1_1_0, rwTx);
- ruleAware.addNeutronSecurityRule(serverOutIpv4, rwTx);
+ ruleAware.addNeutronSecurityRule(goldInIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(goldOutIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverIn80Tcp10_1_1_0, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverInIp20_1_1_0, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverOutIpv4, neutron, rwTx);
TenantId tenantId = new TenantId(tenant);
Optional<Tenant> potentialTenant = rwTx.read(LogicalDatastoreType.CONFIGURATION, IidFactory.tenantIid(tenantId))
.get();
assertTrue(potentialTenant.isPresent());
Optional<Contract> potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
Contract contract = potentialContract.get();
PolicyAssert.assertContract(contract, goldInIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, goldOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, serverOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverIn80Tcp10_1_1_0.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverIn80Tcp10_1_1_0.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContractWithEic(contract, serverIn80Tcp10_1_1_0);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverInIp20_1_1_0.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverInIp20_1_1_0.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContractWithEic(contract, serverInIp20_1_1_0);
EndpointGroup epg = potentialEpg.get();
PolicyAssert.assertConsumerNamedSelectors(
epg,
- ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()),
- new ContractId(goldOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverIn80Tcp10_1_1_0.getSecurityRuleUUID()),
- new ContractId(serverInIp20_1_1_0.getSecurityRuleUUID()),
- new ContractId(serverOutIpv4.getSecurityRuleUUID())));
+ ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()),
+ new ContractId(goldOutIpv4.getId().getValue()),
+ new ContractId(serverIn80Tcp10_1_1_0.getId().getValue()),
+ new ContractId(serverInIp20_1_1_0.getId().getValue()),
+ new ContractId(serverOutIpv4.getId().getValue())));
potentialEpg = rwTx.read(LogicalDatastoreType.CONFIGURATION,
IidFactory.endpointGroupIid(tenantId, new EndpointGroupId(serverSecGrp))).get();
assertTrue(potentialEpg.isPresent());
epg = potentialEpg.get();
PolicyAssert.assertConsumerNamedSelectors(epg, ImmutableSet.of(
- new ContractId(serverIn80Tcp10_1_1_0.getSecurityRuleUUID()),
- new ContractId(serverInIp20_1_1_0.getSecurityRuleUUID()),
- new ContractId(goldInIpv4.getSecurityRuleUUID())));
+ new ContractId(serverIn80Tcp10_1_1_0.getId().getValue()),
+ new ContractId(serverInIp20_1_1_0.getId().getValue()),
+ new ContractId(goldInIpv4.getId().getValue())));
}
@Test
public final void testAddAndDeleteNeutronSecurityRule() throws Exception {
DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
+ NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker);
final String tenantId = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
final String secGroupId1 = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
final String secRuleId1 = "dddddddd-dddd-dddd-dddd-dddddddddddd";
final String secRuleId2 = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
- NeutronSecurityRule secRule1 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId1, tenantId,
- NeutronUtils.IPv4, NeutronUtils.EGRESS, secGroupId1, secGroupId2);
- NeutronSecurityRule secRule2 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId2, tenantId,
- NeutronUtils.IPv4, NeutronUtils.INGRESS, secGroupId2, secGroupId1);
+ List<SecurityGroup> secGroups = new ArrayList<>();
+ secGroups.add(NeutronEntityFactory.securityGroup(secGroupId1, tenantId));
+ secGroups.add(NeutronEntityFactory.securityGroup(secGroupId2, tenantId));
+ SecurityRule secRule1 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId1, tenantId,
+ EthertypeV4.class, DirectionEgress.class, secGroupId1, secGroupId2);
+ SecurityRule secRule2 = NeutronEntityFactory.securityRuleWithEtherType(secRuleId2, tenantId,
+ EthertypeV4.class, DirectionIngress.class, secGroupId2, secGroupId1);
+ NeutronBuilder neutronBuilder = new NeutronBuilder()
+ .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build())
+ .setSecurityRules(new SecurityRulesBuilder()
+ .setSecurityRule(ImmutableList.of(secRule1)).build());
- ruleAware.created(secRule1);
+ ruleAware.onCreated(secRule1, neutronBuilder.build());
PolicyAssert.assertTenantExists(dataBroker, tenantId);
PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1);
PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1);
PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
- ruleAware.created(secRule2);
+ neutronBuilder.setSecurityRules(new SecurityRulesBuilder()
+ .setSecurityRule(ImmutableList.of(secRule1, secRule2)).build());
+
+ ruleAware.onCreated(secRule2, neutronBuilder.build());
PolicyAssert.assertTenantExists(dataBroker, tenantId);
PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1);
PolicyAssert.assertProviderNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId2)));
PolicyAssert.assertConsumerNamedSelectors(epGroup2.get(), ImmutableSet.of(new ContractId(secRuleId1)));
- ruleAware.deleted(secRule2);
+ ruleAware.onDeleted(secRule2, neutronBuilder.build(), null);
PolicyAssert.assertTenantExists(dataBroker, tenantId);
PolicyAssert.assertContractExists(dataBroker, tenantId, secRuleId1);
PolicyAssert.assertClassifierInstanceExists(dataBroker, secRule1);
PolicyAssert.assertActionInstanceExists(dataBroker, tenantId, MappingUtils.ACTION_ALLOW.getName());
- ruleAware.deleted(secRule1);
+ neutronBuilder.setSecurityRules(new SecurityRulesBuilder()
+ .setSecurityRule(ImmutableList.of(secRule1)).build());
+
+ ruleAware.onDeleted(secRule1, neutronBuilder.build(), null);
PolicyAssert.assertContractCount(dataBroker, tenantId, 0);
PolicyAssert.assertEndpointGroupExists(dataBroker, tenantId, secGroupId1);
public final void testAddNeutronSecurityRule_rulesWithoutRemote() throws Exception {
String tenant = "ad4c6c25-2424-4ad3-97ee-f9691ce03645";
String goldSecGrp = "fe40e28f-ad6a-4a2d-b12a-47510876344a";
- NeutronSecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, goldSecGrp,
+ SecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, EthertypeV4.class, DirectionIngress.class, goldSecGrp,
null);
- NeutronSecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, goldSecGrp,
+ SecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, EthertypeV4.class, DirectionEgress.class, goldSecGrp,
null);
String serverSecGrp = "71cf4fe5-b146-409e-8151-cd921298ce32";
- NeutronSecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, serverSecGrp,
+ SecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, EthertypeV4.class, DirectionEgress.class, serverSecGrp,
null);
- NeutronSecurityRule serverInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp,
+ SecurityRule serverInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, EthertypeV4.class, DirectionIngress.class, serverSecGrp,
null);
DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(goldSecGrp, tenant));
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(serverSecGrp, tenant));
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
+ List<SecurityGroup> secGroups = new ArrayList<>();
+ secGroups.add(NeutronEntityFactory.securityGroup(goldSecGrp, tenant));
+ secGroups.add(NeutronEntityFactory.securityGroup(serverSecGrp, tenant));
+ Neutron neutron = new NeutronBuilder()
+ .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build())
+ .setSecurityRules(new SecurityRulesBuilder()
+ .setSecurityRule(ImmutableList.of(goldInIpv4, goldOutIpv4, serverOutIpv4, serverInIpv4)).build())
+ .build();
+ NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker);
ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- ruleAware.addNeutronSecurityRule(goldInIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(goldOutIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(serverOutIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(serverInIpv4, rwTx);
+ ruleAware.addNeutronSecurityRule(goldInIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(goldOutIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverOutIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverInIpv4, neutron, rwTx);
TenantId tenantId = new TenantId(tenant);
Optional<Contract> potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
Contract contract = potentialContract.get();
PolicyAssert.assertContract(contract, goldInIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, goldOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, serverOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverInIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverInIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, serverInIpv4);
EndpointGroup epg = potentialEpg.get();
PolicyAssert.assertConsumerNamedSelectors(
epg,
- ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()),
- new ContractId(goldOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverInIpv4.getSecurityRuleUUID())));
+ ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()),
+ new ContractId(goldOutIpv4.getId().getValue()),
+ new ContractId(serverOutIpv4.getId().getValue()),
+ new ContractId(serverInIpv4.getId().getValue())));
potentialEpg = rwTx.read(LogicalDatastoreType.CONFIGURATION,
IidFactory.endpointGroupIid(tenantId, new EndpointGroupId(serverSecGrp))).get();
assertTrue(potentialEpg.isPresent());
PolicyAssert.assertConsumerNamedSelectors(
epg,
- ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()),
- new ContractId(goldOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverInIpv4.getSecurityRuleUUID())));
+ ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()),
+ new ContractId(goldOutIpv4.getId().getValue()),
+ new ContractId(serverOutIpv4.getId().getValue()),
+ new ContractId(serverInIpv4.getId().getValue())));
}
@Test
public final void testAddNeutronSecurityRule_asymmetricRulesWithoutRemote() throws Exception {
String tenant = "ad4c6c25-2424-4ad3-97ee-f9691ce03645";
String goldSecGrp = "fe40e28f-ad6a-4a2d-b12a-47510876344a";
- NeutronSecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, goldSecGrp,
+ SecurityRule goldInIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "166aedab-fdf5-4788-9e36-2b00b5f8722f", tenant, EthertypeV4.class, DirectionIngress.class, goldSecGrp,
null);
- NeutronSecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, goldSecGrp,
+ SecurityRule goldOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "dabfd4da-af89-45dd-85f8-181768c1b4c9", tenant, EthertypeV4.class, DirectionEgress.class, goldSecGrp,
null);
String serverSecGrp = "71cf4fe5-b146-409e-8151-cd921298ce32";
- NeutronSecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, serverSecGrp,
+ SecurityRule serverOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "8b9c48d3-44a8-46be-be35-6f3237d98071", tenant, EthertypeV4.class, DirectionEgress.class, serverSecGrp,
null);
- NeutronSecurityRule serverIn80TcpIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "adf7e558-de47-4f9e-a9b8-96e19db5d1ac", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, serverSecGrp,
- null);
- serverIn80TcpIpv4.setSecurityRuleProtocol(NeutronUtils.TCP);
- serverIn80TcpIpv4.setSecurityRulePortMin(80);
- serverIn80TcpIpv4.setSecurityRulePortMax(80);
+ SecurityRule serverIn80TcpIpv4 = new SecurityRuleBuilder().setId(new Uuid("adf7e558-de47-4f9e-a9b8-96e19db5d1ac"))
+ .setTenantId(new Uuid(tenant))
+ .setEthertype(EthertypeV4.class)
+ .setProtocol(ProtocolTcp.class)
+ .setPortRangeMin(80)
+ .setPortRangeMax(80)
+ .setDirection(DirectionIngress.class)
+ .setSecurityGroupId(new Uuid(serverSecGrp))
+ .build();
DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(goldSecGrp, tenant));
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(serverSecGrp, tenant));
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
+ List<SecurityGroup> secGroups = new ArrayList<>();
+ secGroups.add(NeutronEntityFactory.securityGroup(goldSecGrp, tenant));
+ secGroups.add(NeutronEntityFactory.securityGroup(serverSecGrp, tenant));
+ Neutron neutron = new NeutronBuilder()
+ .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build())
+ .setSecurityRules(new SecurityRulesBuilder()
+ .setSecurityRule(ImmutableList.of(goldInIpv4, goldOutIpv4, serverOutIpv4, serverIn80TcpIpv4)).build())
+ .build();
+ NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker);
ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- ruleAware.addNeutronSecurityRule(goldInIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(goldOutIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(serverOutIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(serverIn80TcpIpv4, rwTx);
+ ruleAware.addNeutronSecurityRule(goldInIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(goldOutIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverOutIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(serverIn80TcpIpv4, neutron, rwTx);
TenantId tenantId = new TenantId(tenant);
Optional<Contract> potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(goldInIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
Contract contract = potentialContract.get();
PolicyAssert.assertContract(contract, goldInIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(goldOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, goldOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, serverOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(serverIn80TcpIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(serverIn80TcpIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, serverIn80TcpIpv4);
EndpointGroup epg = potentialEpg.get();
PolicyAssert.assertConsumerNamedSelectors(
epg,
- ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()),
- new ContractId(goldOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverOutIpv4.getSecurityRuleUUID()),
- new ContractId(serverIn80TcpIpv4.getSecurityRuleUUID())));
+ ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()),
+ new ContractId(goldOutIpv4.getId().getValue()),
+ new ContractId(serverOutIpv4.getId().getValue()),
+ new ContractId(serverIn80TcpIpv4.getId().getValue())));
potentialEpg = rwTx.read(LogicalDatastoreType.CONFIGURATION,
IidFactory.endpointGroupIid(tenantId, new EndpointGroupId(serverSecGrp))).get();
assertTrue(potentialEpg.isPresent());
epg = potentialEpg.get();
PolicyAssert.assertConsumerNamedSelectors(
epg,
- ImmutableSet.of(new ContractId(goldInIpv4.getSecurityRuleUUID()),
- new ContractId(serverIn80TcpIpv4.getSecurityRuleUUID())));
+ ImmutableSet.of(new ContractId(goldInIpv4.getId().getValue()),
+ new ContractId(serverIn80TcpIpv4.getId().getValue())));
}
@Test
public final void testAddNeutronSecurityRule_defaultSecGrp() throws Exception {
String tenant = "111aaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
String defaultSecGrp = "111fffff-ffff-ffff-ffff-ffffffffffff";
- NeutronSecurityRule defaultInIpv4Default = NeutronEntityFactory.securityRuleWithEtherType(
- "111ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv4, NeutronUtils.INGRESS, defaultSecGrp,
+ SecurityRule defaultInIpv4Default = NeutronEntityFactory.securityRuleWithEtherType(
+ "111ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionIngress.class, defaultSecGrp,
defaultSecGrp);
- NeutronSecurityRule defaultInIpv6Default = NeutronEntityFactory.securityRuleWithEtherType(
- "222ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv6, NeutronUtils.INGRESS, defaultSecGrp,
+ SecurityRule defaultInIpv6Default = NeutronEntityFactory.securityRuleWithEtherType(
+ "222ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionIngress.class, defaultSecGrp,
defaultSecGrp);
- NeutronSecurityRule defaultOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
- "333ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv4, NeutronUtils.EGRESS, defaultSecGrp,
+ SecurityRule defaultOutIpv4 = NeutronEntityFactory.securityRuleWithEtherType(
+ "333ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionEgress.class, defaultSecGrp,
null);
- NeutronSecurityRule defaultOutIpv6 = NeutronEntityFactory.securityRuleWithEtherType(
- "444ccccc-111c-cccc-cccc-cccccccccccc", tenant, NeutronUtils.IPv6, NeutronUtils.EGRESS, defaultSecGrp,
+ SecurityRule defaultOutIpv6 = NeutronEntityFactory.securityRuleWithEtherType(
+ "444ccccc-111c-cccc-cccc-cccccccccccc", tenant, EthertypeV4.class, DirectionEgress.class, defaultSecGrp,
null);
DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- secGroupDao.addSecGroup(NeutronEntityFactory.securityGroup(defaultSecGrp, tenant));
- NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
+ List<SecurityGroup> secGroups = new ArrayList<>();
+ secGroups.add(NeutronEntityFactory.securityGroup(defaultSecGrp, tenant));
+ Neutron neutron = new NeutronBuilder()
+ .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()).build();
+ NeutronSecurityRuleAware ruleAware = new NeutronSecurityRuleAware(dataBroker);
ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- ruleAware.addNeutronSecurityRule(defaultInIpv4Default, rwTx);
- ruleAware.addNeutronSecurityRule(defaultInIpv6Default, rwTx);
- ruleAware.addNeutronSecurityRule(defaultOutIpv4, rwTx);
- ruleAware.addNeutronSecurityRule(defaultOutIpv6, rwTx);
+ ruleAware.addNeutronSecurityRule(defaultInIpv4Default, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(defaultInIpv6Default, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(defaultOutIpv4, neutron, rwTx);
+ ruleAware.addNeutronSecurityRule(defaultOutIpv6, neutron, rwTx);
TenantId tenantId = new TenantId(tenant);
Optional<Contract> potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(defaultInIpv4Default.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(defaultInIpv4Default.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
Contract contract = potentialContract.get();
PolicyAssert.assertContract(contract, defaultInIpv4Default);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(defaultInIpv6Default.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(defaultInIpv6Default.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, defaultInIpv6Default);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv4.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv4.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, defaultOutIpv4);
potentialContract = rwTx.read(LogicalDatastoreType.CONFIGURATION,
- IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv6.getSecurityRuleUUID()))).get();
+ IidFactory.contractIid(tenantId, new ContractId(defaultOutIpv6.getId().getValue()))).get();
assertTrue(potentialContract.isPresent());
contract = potentialContract.get();
PolicyAssert.assertContract(contract, defaultOutIpv6);
@Test
public void testConstructor_invalidArgument() throws Exception {
- DataBroker dataBroker = getDataBroker();
- SecRuleDao secRuleDao = new SecRuleDao();
- SecGroupDao secGroupDao = new SecGroupDao();
- assertExceptionInConstructor(null, secRuleDao, secGroupDao);
- assertExceptionInConstructor(dataBroker, null, secGroupDao);
- assertExceptionInConstructor(dataBroker, secRuleDao, null);
- assertExceptionInConstructor(null, null, null);
- }
-
- private void assertExceptionInConstructor(DataBroker dataBroker, SecRuleDao secRuleDao, SecGroupDao secGroupDao) {
try {
- new NeutronSecurityRuleAware(dataBroker, secRuleDao, secGroupDao);
+ new NeutronSecurityRuleAware(null);
fail(NullPointerException.class.getName() + " expected");
} catch (NullPointerException ex) {
// do nothing
}
}
+
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import java.util.ArrayList;
+import java.util.List;
+
import org.junit.Test;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.StatusCode;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.group.SecGroupDao;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.ConfigDataStoreReader;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest;
+import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.Neutron;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.rev150712.NeutronBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.SecurityGroupsBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
public class NeutronSecurityRuleAwareTest extends GbpDataBrokerTest {
@Test
public void testNeutronSecurityRuleCreatedAndDeleted() throws Exception {
DataBroker dataProvider = getDataBroker();
- SecGroupDao secGroupDao = new SecGroupDao();
- SecRuleDao secRuleDao = new SecRuleDao();
- NeutronSecurityRuleAware neutronSecurityRuleAware =
- new NeutronSecurityRuleAware(dataProvider, secRuleDao, secGroupDao);
+ NeutronSecurityRuleAware neutronSecurityRuleAware = new NeutronSecurityRuleAware(dataProvider);
//create security rule and put to DS
- NeutronSecurityRule neutronRule = buildNeutronSecurityRule();
- assertEquals(neutronSecurityRuleAware.canCreate(neutronRule),
- StatusCode.OK);
- neutronSecurityRuleAware.created(neutronRule);
+ SecurityRule neutronRule = buildNeutronSecurityRule();
+ List<SecurityGroup> secGroups = new ArrayList<>();
+ secGroups.add(NeutronEntityFactory.securityGroup(neutronRule.getSecurityGroupId().getValue(),
+ neutronRule.getTenantId().getValue()));
+ Neutron neutron = new NeutronBuilder()
+ .setSecurityGroups(new SecurityGroupsBuilder().setSecurityGroup(secGroups).build()).build();
+ neutronSecurityRuleAware.onCreated(neutronRule, neutron);
//read security rule
PolicyAssert.assertContractExists(dataProvider, RULE_TENANT_ID, RULE_ID);
assertNotNull(readContract);
assertEquals(readContract.getId().getValue(), RULE_ID);
- assertEquals(neutronSecurityRuleAware.canUpdate(neutronRule, neutronRule),
- StatusCode.BAD_REQUEST);
-
//delete rule
- assertEquals(neutronSecurityRuleAware.canDelete(neutronRule),
- StatusCode.OK);
- neutronSecurityRuleAware.deleted(neutronRule);
+ neutronSecurityRuleAware.onDeleted(neutronRule, neutron, null);
PolicyAssert.assertContractNotExists(dataProvider, RULE_TENANT_ID, RULE_ID);
}
- //create neutron security rule
- private NeutronSecurityRule buildNeutronSecurityRule() {
- NeutronSecurityRule neutronSecurityRule = new NeutronSecurityRule();
- neutronSecurityRule.setSecurityRuleUUID(RULE_ID);
- neutronSecurityRule.setSecurityRuleTenantID(RULE_TENANT_ID);
- neutronSecurityRule.setSecurityRuleGroupID(RULE_GROUP_ID);
- neutronSecurityRule.setSecurityRuleRemoteIpPrefix("192.0.0.1/24");
- neutronSecurityRule.setSecurityRulePortMin(1000);
- neutronSecurityRule.setSecurityRulePortMax(5000);
- neutronSecurityRule.setSecurityRuleProtocol("tcp");
- neutronSecurityRule.setSecurityRuleEthertype("IPv4");
- neutronSecurityRule.setSecurityRuleDirection("ingress");
-
- return neutronSecurityRule;
+ // create neutron security rule
+ private SecurityRule buildNeutronSecurityRule() {
+ return new SecurityRuleBuilder().setId(new Uuid(RULE_ID))
+ .setTenantId(new Uuid(RULE_TENANT_ID))
+ .setSecurityGroupId(new Uuid(RULE_GROUP_ID))
+ .setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("192.0.0.1/24")))
+ .setPortRangeMin(1000)
+ .setPortRangeMax(5000)
+ .setProtocol(ProtocolTcp.class)
+ .setEthertype(EthertypeV4.class)
+ .setDirection(DirectionIngress.class)
+ .build();
}
}
+++ /dev/null
-package org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Set;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
-
-public class SecRuleDaoTest {
-
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- private SecRuleDao secRuleDao;
-
- @Before
- public void setUp() throws Exception {
- secRuleDao = new SecRuleDao();
- }
-
- @Test
- public void testAddAndRemoveSecRule() {
- final String xSecGrpId = "cccccccc-cccc-cccc-cccc-cccccccccccc";
- final String ySecGrpId = "dddddddd-dddd-dddd-dddd-dddddddddddd";
- final String nullSecGrpId = null;
-
- EndpointGroupId xEpGrpId = new EndpointGroupId(xSecGrpId);
- EndpointGroupId yEpGrpId = new EndpointGroupId(ySecGrpId);
- EndpointGroupId nullEpGrpId = null;
-
- NeutronSecurityRule secRule1 = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa1", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", xSecGrpId, nullSecGrpId);
-
- NeutronSecurityRule secRule2 = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa2", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", xSecGrpId, xSecGrpId);
-
- NeutronSecurityRule secRule3 = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa3", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", xSecGrpId, ySecGrpId);
-
- NeutronSecurityRule secRule4 = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa4", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", ySecGrpId, nullSecGrpId);
-
- NeutronSecurityRule secRule5 = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa5", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", ySecGrpId, ySecGrpId);
-
- NeutronSecurityRule secRule6 = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa6", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", ySecGrpId, xSecGrpId);
-
- secRuleDao.addSecRule(secRule1);
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertAllOwnerSecGrps(xEpGrpId);
-
- secRuleDao.addSecRule(secRule2);
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2);
- assertAllOwnerSecGrps(xEpGrpId);
-
- secRuleDao.addSecRule(secRule3);
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2, secRule3);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId, secRule3);
- assertAllOwnerSecGrps(xEpGrpId);
-
- secRuleDao.addSecRule(secRule4);
- assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4);
- assertAllOwnerSecGrps(xEpGrpId, yEpGrpId);
-
- secRuleDao.addSecRule(secRule5);
- assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4, secRule5);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId, secRule5);
- assertAllOwnerSecGrps(xEpGrpId, yEpGrpId);
-
- secRuleDao.addSecRule(secRule6);
- assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4, secRule5, secRule6);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId, secRule5);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, xEpGrpId, secRule6);
- assertAllOwnerSecGrps(xEpGrpId, yEpGrpId);
-
- // check once more security rules with owner group id = xSecGrpId
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2, secRule3);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId, secRule3);
-
- secRuleDao.removeSecRule(secRule6);
- assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4, secRule5);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId, secRule5);
- assertAllOwnerSecGrps(xEpGrpId, yEpGrpId);
-
- secRuleDao.removeSecRule(secRule5);
- assertSecRulesByOwnerSecGrpId(yEpGrpId, secRule4);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId, secRule4);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId, secRule4);
- assertAllOwnerSecGrps(xEpGrpId, yEpGrpId);
-
- secRuleDao.removeSecRule(secRule4);
-
- // check once more security rules with owner group id = xSecGrpId
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2, secRule3);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId, secRule3);
-
- secRuleDao.removeSecRule(secRule3);
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1, secRule2);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId, secRule2);
- assertAllOwnerSecGrps(xEpGrpId);
-
- secRuleDao.removeSecRule(secRule2);
- assertSecRulesByOwnerSecGrpId(xEpGrpId, secRule1);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId, secRule1);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId, secRule1);
- assertAllOwnerSecGrps(xEpGrpId);
-
- secRuleDao.removeSecRule(secRule1);
- assertSecRulesByOwnerSecGrpId(xEpGrpId);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(xEpGrpId);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, nullEpGrpId);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, xEpGrpId);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(xEpGrpId, yEpGrpId);
- assertSecRulesByOwnerSecGrpId(yEpGrpId);
- assertSecRulesWithoutRemoteSecGrpBySecGrpId(yEpGrpId);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, nullEpGrpId);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, yEpGrpId);
- assertSecRulesBySecGrpIdAndRemoteSecGrpId(yEpGrpId, xEpGrpId);
- assertAllOwnerSecGrps();
- }
-
- @Test
- public void testAddSecGroup_nullArgument() {
- thrown.expect(NullPointerException.class);
- secRuleDao.addSecRule(null);
- }
-
- @Test
- public void testRemoveNonExistingSecRule() {
- NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- "cccccccc-cccc-cccc-cccc-cccccccccccc", "dddddddd-dddd-dddd-dddd-dddddddddddd");
- secRuleDao.removeSecRule(secRule);
- }
-
- @Test
- public void testRemoveNonExistingSecRule_remoteSecGroupIdIsNull() {
- NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
- "cccccccc-cccc-cccc-cccc-cccccccccccc", null);
- secRuleDao.removeSecRule(secRule);
- }
-
- private static void assertSecRules(Set<NeutronSecurityRule> secRules, NeutronSecurityRule... expectedSecRules) {
- assertNotNull(secRules);
- assertEquals(expectedSecRules.length, secRules.size());
- for (int i = 0; i < expectedSecRules.length; ++i) {
- assertTrue(secRules.contains(expectedSecRules[i]));
- }
- }
-
- private void assertSecRulesByOwnerSecGrpId(EndpointGroupId ownerEpGrpId, NeutronSecurityRule... expectedSecRules) {
- Set<NeutronSecurityRule> secRules = secRuleDao.getSecRulesByOwnerSecGrpId(ownerEpGrpId);
- assertSecRules(secRules, expectedSecRules);
- }
-
- private void assertSecRulesBySecGrpIdAndRemoteSecGrpId(EndpointGroupId ownerEpGrpId, EndpointGroupId remoteEpGrpId,
- NeutronSecurityRule... expectedSecRules) {
- Set<NeutronSecurityRule> secRules = secRuleDao.getSecRulesBySecGrpIdAndRemoteSecGrpId(ownerEpGrpId,
- remoteEpGrpId);
- assertSecRules(secRules, expectedSecRules);
- }
-
- private void assertSecRulesWithoutRemoteSecGrpBySecGrpId(EndpointGroupId ownerEpGrpId,
- NeutronSecurityRule... expectedSecRules) {
- Set<NeutronSecurityRule> secRules = secRuleDao.getSecRulesWithoutRemoteSecGrpBySecGrpId(ownerEpGrpId);
- assertSecRules(secRules, expectedSecRules);
- }
-
- private void assertAllOwnerSecGrps(EndpointGroupId... expectedEndpointGropuIds) {
- Set<EndpointGroupId> allOwnerSecGrps = secRuleDao.getAllOwnerSecGrps();
- assertNotNull(allOwnerSecGrps);
- assertEquals(expectedEndpointGropuIds.length, allOwnerSecGrps.size());
- for (int i = 0; i < expectedEndpointGropuIds.length; ++i) {
- assertTrue(allOwnerSecGrps.contains(expectedEndpointGropuIds[i]));
- }
- }
-}
import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;
import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.Clause;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.clause.ConsumerMatchers;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionEgress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV6;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolIcmp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolUdp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
public class SecRuleEntityDecoderTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
- private NeutronSecurityRule secRule;
+ private SecurityRuleBuilder secRuleBuilder;
@Before
public void setUp() throws Exception {
- secRule = new NeutronSecurityRule();
+ secRuleBuilder = new SecurityRuleBuilder().setId(new Uuid("01234567-abcd-ef01-0123-0123456789ab"));
}
@Test
- public final void testGetTenantId_lowercaseUuidTenantID() {
- secRule.setSecurityRuleTenantID("01234567-abcd-ef01-0123-0123456789ab");
+ public final void testGetContractId() {
Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getTenantId(secRule).getValue());
- }
-
- @Test
- public final void testGetTenantId_uppercaseUuidTenantID() {
- secRule.setSecurityRuleTenantID("01234567-ABCD-EF01-0123-0123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getTenantId(secRule).getValue());
- }
-
- @Test
- public final void testGetTenantId_mixUuidTenantID() {
- secRule.setSecurityRuleTenantID("01234567-ABCD-ef01-0123-0123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getTenantId(secRule).getValue());
- }
-
- @Test
- public final void testGetTenantId_noSlashLowercaseUuidTenantID() {
- secRule.setSecurityRuleTenantID("01234567abcdef0101230123456789ab");
- Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getTenantId(secRule).getValue());
- }
-
- @Test
- public final void testGetTenantId_noSlashUppercaseUuidTenantID() {
- secRule.setSecurityRuleTenantID("01234567ABCDEF0101230123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getTenantId(secRule).getValue());
- }
-
- @Test
- public final void testGetTenantId_noSlashMixUuidTenantID() {
- secRule.setSecurityRuleTenantID("01234567ABCDef0101230123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getTenantId(secRule).getValue());
- }
-
- @Test
- public final void testGetTenantId_emptyUuidTenantID() {
- secRule.setSecurityRuleTenantID("");
- thrown.expect(NullPointerException.class);
- SecRuleEntityDecoder.getTenantId(secRule);
- }
-
- @Test
- public final void testGetTenantId_nullUuidTenantID() {
- secRule.setSecurityRuleTenantID(null);
- thrown.expect(NullPointerException.class);
- SecRuleEntityDecoder.getTenantId(secRule);
- }
-
- @Test
- public final void testGetProviderEpgId_lowercaseUuidGroupID() {
- secRule.setSecurityRuleGroupID("01234567-abcd-ef01-0123-0123456789ab");
- Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getProviderEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetProviderEpgId_uppercaseUuidGroupID() {
- secRule.setSecurityRuleGroupID("01234567-ABCD-EF01-0123-0123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getProviderEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetProviderEpgId_mixUuidGroupID() {
- secRule.setSecurityRuleGroupID("01234567-ABCD-ef01-0123-0123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getProviderEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetProviderEpgId_noSlashLowercaseUuidGroupID() {
- secRule.setSecurityRuleGroupID("01234567abcdef0101230123456789ab");
- Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getProviderEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetProviderEpgId_noSlashUppercaseUuidGroupID() {
- secRule.setSecurityRuleGroupID("01234567ABCDEF0101230123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getProviderEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetProviderEpgId_noSlashMixUuidGroupID() {
- secRule.setSecurityRuleGroupID("01234567ABCDef0101230123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getProviderEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetProviderEpgId_emptyUuidGroupID() {
- secRule.setSecurityRuleGroupID("");
- thrown.expect(IllegalArgumentException.class);
- SecRuleEntityDecoder.getProviderEpgId(secRule);
- }
-
- @Test
- public final void testGetProviderEpgId_nullUuidGroupID() {
- secRule.setSecurityRuleGroupID(null);
- thrown.expect(NullPointerException.class);
- SecRuleEntityDecoder.getProviderEpgId(secRule);
- }
-
- @Test
- public final void testGetConsumerEpgId_lowercaseUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("01234567-abcd-ef01-0123-0123456789ab");
- Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetConsumerEpgId_uppercaseUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("01234567-ABCD-EF01-0123-0123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetConsumerEpgId_mixUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("01234567-ABCD-ef01-0123-0123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetConsumerEpgId_noSlashLowercaseUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("01234567abcdef0101230123456789ab");
- Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetConsumerEpgId_noSlashUppercaseUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("01234567ABCDEF0101230123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetConsumerEpgId_noSlashMixUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("01234567ABCDef0101230123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getConsumerEpgId(secRule).getValue());
- }
-
- @Test
- public final void testGetConsumerEpgId_emptyUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID("");
- Assert.assertSame(null, SecRuleEntityDecoder.getConsumerEpgId(secRule));
- }
-
- @Test
- public final void testGetConsumerEpgId_nullUuidRemoteGroupID() {
- secRule.setSecurityRemoteGroupID(null);
- Assert.assertSame(null, SecRuleEntityDecoder.getConsumerEpgId(secRule));
- }
-
- @Test
- public final void testGetContractId_lowercaseUuidID() {
- secRule.setSecurityRuleUUID("01234567-abcd-ef01-0123-0123456789ab");
- Assert.assertEquals("01234567-abcd-ef01-0123-0123456789ab",
- SecRuleEntityDecoder.getContractId(secRule).getValue());
- }
-
- @Test
- public final void testGetContractId_uppercaseUuidID() {
- secRule.setSecurityRuleUUID("01234567-ABCD-EF01-0123-0123456789AB");
- Assert.assertEquals("01234567-ABCD-EF01-0123-0123456789AB",
- SecRuleEntityDecoder.getContractId(secRule).getValue());
- }
-
- @Test
- public final void testGetContractId_mixUuidID() {
- secRule.setSecurityRuleUUID("01234567-ABCD-ef01-0123-0123456789Ab");
- Assert.assertEquals("01234567-ABCD-ef01-0123-0123456789Ab",
- SecRuleEntityDecoder.getContractId(secRule).getValue());
+ SecRuleEntityDecoder.getContractId(secRuleBuilder.build()).getValue());
}
@Test
public final void testGetClassifierInstance_onlyEthertype() {
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build());
Assert.assertEquals(EtherTypeClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId());
// name is ether_type_IPv4
String expectedName = new StringBuilder().append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.IPv4)
+ .append(EthertypeV4.class.getSimpleName())
.toString();
Assert.assertEquals(expectedName, ci.getName().getValue());
Assert.assertEquals(expectedName, ci.getName().getValue());
@Test
public final void testGetClassifierInstance_EthertypeAndProtocol() {
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- secRule.setSecurityRuleProtocol(NeutronUtils.TCP);
- ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ secRuleBuilder.setProtocol(ProtocolTcp.class);
+ ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build());
Assert.assertEquals(IpProtoClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId());
// name is ip_proto_tcp__ether_type_IPv4
String expectedName = new StringBuilder().append(IpProtoClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.TCP)
+ .append(ProtocolTcp.class.getSimpleName())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.IPv4)
+ .append(EthertypeV4.class.getSimpleName())
.toString();
Assert.assertEquals(expectedName, ci.getName().getValue());
List<ParameterValue> parameterValues = ci.getParameterValue();
@Test
public final void testGetClassifierInstance_EthertypeAndProtocolAndPort() {
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- secRule.setSecurityRuleProtocol(NeutronUtils.TCP);
- secRule.setSecurityRulePortMin(5);
- secRule.setSecurityRulePortMax(5);
- ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ secRuleBuilder.setProtocol(ProtocolTcp.class);
+ secRuleBuilder.setPortRangeMin(5);
+ secRuleBuilder.setPortRangeMax(5);
+ ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build());
Assert.assertEquals(L4ClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId());
// name is l4_destport-5__ip_proto-tcp__ether_type-IPv4
String expectedName = new StringBuilder().append(L4ClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_DELIMETER)
.append(L4ClassifierDefinition.DST_PORT_PARAM)
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(secRule.getSecurityRulePortMin())
+ .append(secRuleBuilder.getPortRangeMin())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(IpProtoClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.TCP)
+ .append(ProtocolTcp.class.getSimpleName())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.IPv4)
+ .append(EthertypeV4.class.getSimpleName())
.toString();
+ System.out.println(expectedName);
+ System.out.println(ci.getName().getValue());
Assert.assertEquals(expectedName, ci.getName().getValue());
List<ParameterValue> parameterValues = ci.getParameterValue();
Assert.assertNotNull(parameterValues);
@Test
public final void testGetClassifierInstance_EthertypeAndProtocolAndPorts() {
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- secRule.setSecurityRuleProtocol(NeutronUtils.TCP);
- secRule.setSecurityRulePortMin(5);
- secRule.setSecurityRulePortMax(10);
- ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRule);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ secRuleBuilder.setProtocol(ProtocolTcp.class);
+ secRuleBuilder.setPortRangeMin(5);
+ secRuleBuilder.setPortRangeMax(10);
+ ClassifierInstance ci = SecRuleEntityDecoder.getClassifierInstance(secRuleBuilder.build());
Assert.assertEquals(L4ClassifierDefinition.DEFINITION.getId(), ci.getClassifierDefinitionId());
// name is l4_destport_range_min-5_max-10__ip_proto-tcp__ether_type-IPv4
String expectedName = new StringBuilder().append(L4ClassifierDefinition.DEFINITION.getName().getValue())
.append(L4ClassifierDefinition.DST_PORT_RANGE_PARAM)
.append(SecRuleNameDecoder.MIN_PORT)
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(secRule.getSecurityRulePortMin())
+ .append(secRuleBuilder.getPortRangeMin())
.append(SecRuleNameDecoder.MAX_PORT)
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(secRule.getSecurityRulePortMax())
+ .append(secRuleBuilder.getPortRangeMax())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(IpProtoClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.TCP)
+ .append(ProtocolTcp.class.getSimpleName())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
- .append(NeutronUtils.IPv4)
+ .append(EthertypeV4.class.getSimpleName())
.toString();
Assert.assertEquals(expectedName, ci.getName().getValue());
}
@Test
public final void testGetClassifierRef() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- ClassifierName expectedName = SecRuleNameDecoder.getClassifierRefName(secRule);
- ClassifierRef cr = SecRuleEntityDecoder.getClassifierRef(secRule);
+ secRuleBuilder.setDirection(DirectionIngress.class);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ ClassifierName expectedName = SecRuleNameDecoder.getClassifierRefName(secRuleBuilder.build());
+ ClassifierRef cr = SecRuleEntityDecoder.getClassifierRef(secRuleBuilder.build());
Assert.assertEquals(expectedName, cr.getName());
}
@Test
public final void testGetDirection_directionIngress() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- Assert.assertEquals(Direction.In, SecRuleEntityDecoder.getDirection(secRule));
+ secRuleBuilder.setDirection(DirectionIngress.class);
+ Assert.assertEquals(Direction.In, SecRuleEntityDecoder.getDirection(secRuleBuilder.build()));
}
@Test
public final void testGetDirection_directionEgress() {
- secRule.setSecurityRuleDirection(NeutronUtils.EGRESS);
- Assert.assertEquals(Direction.Out, SecRuleEntityDecoder.getDirection(secRule));
+ secRuleBuilder.setDirection(DirectionEgress.class);
+ Assert.assertEquals(Direction.Out, SecRuleEntityDecoder.getDirection(secRuleBuilder.build()));
}
@Test
public final void testGetDirection_directionNull() {
- secRule.setSecurityRuleDirection(null);
+ secRuleBuilder.setDirection(null);
thrown.expect(IllegalArgumentException.class);
- SecRuleEntityDecoder.getDirection(secRule);
+ SecRuleEntityDecoder.getDirection(secRuleBuilder.build());
}
@Test
public final void testGetDirection_directionUnknown() {
- secRule.setSecurityRuleDirection("foo");
+ secRuleBuilder.setDirection(UnknownDirection.class);
thrown.expect(IllegalArgumentException.class);
- SecRuleEntityDecoder.getDirection(secRule);
+ SecRuleEntityDecoder.getDirection(secRuleBuilder.build());
+ }
+
+ private static class UnknownDirection extends DirectionBase {
}
@Test
public final void testGetClause_noRemoteIpPrefix() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRule);
- Clause clause = SecRuleEntityDecoder.getClause(secRule);
+ secRuleBuilder.setDirection(DirectionIngress.class);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRuleBuilder.build());
+ Clause clause = SecRuleEntityDecoder.getClause(secRuleBuilder.build());
Assert.assertEquals(expectedClauseName, clause.getName());
List<SubjectName> subjectRefs = clause.getSubjectRefs();
Assert.assertNotNull(subjectRefs);
Assert.assertEquals(1, subjectRefs.size());
SubjectName subjectNameFromClause = subjectRefs.get(0);
- SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRule);
+ SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRuleBuilder.build());
Assert.assertEquals(expectedSubjectName, subjectNameFromClause);
Assert.assertNull(clause.getConsumerMatchers());
Assert.assertNull(clause.getProviderMatchers());
@Test
public final void testGetClause_remoteIpPrefix() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- secRule.setSecurityRuleRemoteIpPrefix("10.0.0.0/8");
- Clause clause = SecRuleEntityDecoder.getClause(secRule);
- ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRule);
+ secRuleBuilder.setDirection(DirectionIngress.class);
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ secRuleBuilder.setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("10.0.0.0/8")));
+ Clause clause = SecRuleEntityDecoder.getClause(secRuleBuilder.build());
+ ClauseName expectedClauseName = SecRuleNameDecoder.getClauseName(secRuleBuilder.build());
Assert.assertEquals(expectedClauseName, clause.getName());
List<SubjectName> subjectRefs = clause.getSubjectRefs();
Assert.assertNotNull(subjectRefs);
Assert.assertEquals(1, subjectRefs.size());
SubjectName subjectNameFromClause = subjectRefs.get(0);
- SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRule);
+ SubjectName expectedSubjectName = SecRuleNameDecoder.getSubjectName(secRuleBuilder.build());
Assert.assertEquals(expectedSubjectName, subjectNameFromClause);
Assert.assertNull(clause.getProviderMatchers());
ConsumerMatchers consumerMatchers = clause.getConsumerMatchers();
@Test
public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeIPv4TwoEthTypeIPv4() {
- NeutronSecurityRule one = createSecRuleWithEtherType(NeutronUtils.IPv4);
- NeutronSecurityRule two = createSecRuleWithEtherType(NeutronUtils.IPv4);
+ SecurityRule one = secRuleBuilder.setEthertype(EthertypeV4.class).build();
+ SecurityRule two = secRuleBuilder.setEthertype(EthertypeV4.class).build();
assertTrue(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two));
}
@Test
public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeIPv4TwoEthTypeNull() {
- NeutronSecurityRule one = createSecRuleWithEtherType(NeutronUtils.IPv4);
- NeutronSecurityRule two = createSecRuleWithEtherType(null);
+ SecurityRule one = secRuleBuilder.setEthertype(EthertypeV4.class).build();
+ SecurityRule two = secRuleBuilder.setEthertype(null).build();
assertTrue(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two));
}
@Test
public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeNullTwoEthTypeNull() {
- NeutronSecurityRule one = createSecRuleWithEtherType(null);
- NeutronSecurityRule two = createSecRuleWithEtherType(null);
+ SecurityRule one = secRuleBuilder.setEthertype(null).build();
+ SecurityRule two = secRuleBuilder.setEthertype(null).build();
assertTrue(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two));
}
@Test
public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeIPv4TwoEthTypeIPv6() {
- NeutronSecurityRule one = createSecRuleWithEtherType(NeutronUtils.IPv4);
- NeutronSecurityRule two = createSecRuleWithEtherType(NeutronUtils.IPv6);
+ SecurityRule one = secRuleBuilder.setEthertype(EthertypeV4.class).build();
+ SecurityRule two = secRuleBuilder.setEthertype(EthertypeV6.class).build();
assertFalse(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two));
}
@Test
public final void testIsEtherTypeOfOneWithinTwo_oneEthTypeNullTwoEthTypeIPv4() {
- NeutronSecurityRule one = createSecRuleWithEtherType(null);
- NeutronSecurityRule two = createSecRuleWithEtherType(NeutronUtils.IPv4);
+ SecurityRule one = secRuleBuilder.setEthertype(null).build();
+ SecurityRule two = secRuleBuilder.setEthertype(EthertypeV4.class).build();
assertFalse(SecRuleEntityDecoder.isEtherTypeOfOneWithinTwo(one, two));
}
- private final NeutronSecurityRule createSecRuleWithEtherType(String etherType) {
- NeutronSecurityRule secRule = new NeutronSecurityRule();
- secRule.setSecurityRuleEthertype(etherType);
- return secRule;
- }
-
@Test
public void testIsProtocolOfOneWithinTwo_oneProtocolTcpTwoProtocolTcp() {
- NeutronSecurityRule one = createSecRuleWithProtocol(NeutronUtils.TCP);
- NeutronSecurityRule two = createSecRuleWithProtocol(NeutronUtils.TCP);
+ SecurityRule one = secRuleBuilder.setProtocol(ProtocolTcp.class).build();
+ SecurityRule two = secRuleBuilder.setProtocol(ProtocolTcp.class).build();
assertTrue(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two));
}
@Test
public void testIsProtocolOfOneWithinTwo_oneProtocolTcpTwoProtocolNull() {
- NeutronSecurityRule one = createSecRuleWithProtocol(NeutronUtils.TCP);
- NeutronSecurityRule two = createSecRuleWithProtocol(null);
+ SecurityRule one = secRuleBuilder.setProtocol(ProtocolTcp.class).build();
+ SecurityRule two = secRuleBuilder.setProtocol(null).build();
assertTrue(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two));
}
@Test
public void testIsProtocolOfOneWithinTwo_oneProtocolNullTwoProtocolNull() {
- NeutronSecurityRule one = createSecRuleWithProtocol(null);
- NeutronSecurityRule two = createSecRuleWithProtocol(null);
+ SecurityRule one = secRuleBuilder.setProtocol(null).build();
+ SecurityRule two = secRuleBuilder.setProtocol(null).build();
assertTrue(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two));
}
@Test
public void testIsProtocolOfOneWithinTwo_oneProtocolTcpTwoProtocolUdp() {
- NeutronSecurityRule one = createSecRuleWithProtocol(NeutronUtils.TCP);
- NeutronSecurityRule two = createSecRuleWithProtocol(NeutronUtils.UDP);
+ SecurityRule one = secRuleBuilder.setProtocol(ProtocolTcp.class).build();
+ SecurityRule two = secRuleBuilder.setProtocol(ProtocolUdp.class).build();
assertFalse(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two));
}
@Test
public void testIsProtocolOfOneWithinTwo_oneProtocolNullTwoProtocolTcp() {
- NeutronSecurityRule one = createSecRuleWithProtocol(null);
- NeutronSecurityRule two = createSecRuleWithProtocol(NeutronUtils.TCP);
+ SecurityRule one = secRuleBuilder.setProtocol(null).build();
+ SecurityRule two = secRuleBuilder.setProtocol(ProtocolTcp.class).build();
assertFalse(SecRuleEntityDecoder.isProtocolOfOneWithinTwo(one, two));
}
- private NeutronSecurityRule createSecRuleWithProtocol(String protocol) {
- NeutronSecurityRule secRule = new NeutronSecurityRule();
- secRule.setSecurityRuleProtocol(protocol);
- return secRule;
- }
-
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinGtTwoPortMinOnePortMaxLtTwoPortMax() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(6, 9);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule one = createSecRuleWithMinMaxPort(6, 9);
+ SecurityRule two = createSecRuleWithMinMaxPort(5, 10);
assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinEqTwoPortMinOnePortMaxEqTwoPortMax() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(5, 10);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule one = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule two = createSecRuleWithMinMaxPort(5, 10);
assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinTwoPortMinNullOnePortMaxTwoPortMaxNull() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(4, 9);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(null, null);
+ SecurityRule one = createSecRuleWithMinMaxPort(4, 9);
+ SecurityRule two = createSecRuleWithMinMaxPort(null, null);
assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinNullTwoPortMinNullOnePortMaxNullTwoPortMaxNull() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(null, null);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(null, null);
+ SecurityRule one = createSecRuleWithMinMaxPort(null, null);
+ SecurityRule two = createSecRuleWithMinMaxPort(null, null);
assertTrue(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinNullTwoPortMinOnePortMaxNullTwoPortMax() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(null, null);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule one = createSecRuleWithMinMaxPort(null, null);
+ SecurityRule two = createSecRuleWithMinMaxPort(5, 10);
assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinLtTwoPortMinOnePortMaxLtTwoPortMax() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(4, 9);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule one = createSecRuleWithMinMaxPort(4, 9);
+ SecurityRule two = createSecRuleWithMinMaxPort(5, 10);
assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinGtTwoPortMinOnePortMaxGtTwoPortMax() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(6, 11);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule one = createSecRuleWithMinMaxPort(6, 11);
+ SecurityRule two = createSecRuleWithMinMaxPort(5, 10);
assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
@Test
public final void testIsPortsOfOneWithinTwo_onePortMinLtTwoPortMinOnePortMaxGtTwoPortMax() {
- NeutronSecurityRule one = createSecRuleWithMinMaxPort(4, 11);
- NeutronSecurityRule two = createSecRuleWithMinMaxPort(5, 10);
+ SecurityRule one = createSecRuleWithMinMaxPort(4, 11);
+ SecurityRule two = createSecRuleWithMinMaxPort(5, 10);
assertFalse(SecRuleEntityDecoder.isPortsOfOneWithinTwo(one, two));
}
- private NeutronSecurityRule createSecRuleWithMinMaxPort(Integer portMin, Integer portMax) {
- NeutronSecurityRule secRule = new NeutronSecurityRule();
- secRule.setSecurityRulePortMin(portMin);
- secRule.setSecurityRulePortMax(portMax);
- return secRule;
+ private SecurityRule createSecRuleWithMinMaxPort(Integer portMin, Integer portMax) {
+ return secRuleBuilder.setPortRangeMin(portMin).setPortRangeMax(portMax).build();
}
@Test
public final void testGetEtherType_ethertypeIPv4() {
- secRule.setSecurityRuleEthertype("IPv4");
- Assert.assertEquals(EtherTypeClassifierDefinition.IPv4_VALUE, SecRuleEntityDecoder.getEtherType(secRule));
+ secRuleBuilder.setEthertype(EthertypeV4.class);
+ Assert.assertEquals(EtherTypeClassifierDefinition.IPv4_VALUE, SecRuleEntityDecoder.getEtherType(secRuleBuilder.build()));
}
@Test
public final void testGetEtherType_ethertypeIPv6() {
- secRule.setSecurityRuleEthertype("IPv6");
- Assert.assertEquals(EtherTypeClassifierDefinition.IPv6_VALUE, SecRuleEntityDecoder.getEtherType(secRule));
+ secRuleBuilder.setEthertype(EthertypeV6.class);
+ Assert.assertEquals(EtherTypeClassifierDefinition.IPv6_VALUE, SecRuleEntityDecoder.getEtherType(secRuleBuilder.build()));
}
@Test
public final void testGetEtherType_ethertypeNull() {
- secRule.setSecurityRuleEthertype(null);
- Assert.assertNull(SecRuleEntityDecoder.getEtherType(secRule));
- }
-
- @Test
- public final void testGetEtherType_ethertypeEmptyString() {
- secRule.setSecurityRuleEthertype("");
- Assert.assertNull(SecRuleEntityDecoder.getEtherType(secRule));
+ secRuleBuilder.setEthertype(null);
+ Assert.assertNull(SecRuleEntityDecoder.getEtherType(secRuleBuilder.build()));
}
@Test
public final void testGetEtherType_ethertypeUnknown() {
- secRule.setSecurityRuleEthertype("foo");
+ secRuleBuilder.setEthertype(UnknownEthertype.class);
thrown.expect(IllegalArgumentException.class);
- SecRuleEntityDecoder.getEtherType(secRule);
+ SecRuleEntityDecoder.getEtherType(secRuleBuilder.build());
+ }
+
+ private static class UnknownEthertype extends EthertypeBase {
}
@Test
public final void testGetProtocol_protoTcp() {
- secRule.setSecurityRuleProtocol("tcp");
- Assert.assertEquals(IpProtoClassifierDefinition.TCP_VALUE, SecRuleEntityDecoder.getProtocol(secRule));
+ secRuleBuilder.setProtocol(ProtocolTcp.class);
+ Assert.assertEquals(IpProtoClassifierDefinition.TCP_VALUE, SecRuleEntityDecoder.getProtocol(secRuleBuilder.build()));
}
@Test
public final void testGetProtocol_protoUdp() {
- secRule.setSecurityRuleProtocol("udp");
- Assert.assertEquals(IpProtoClassifierDefinition.UDP_VALUE, SecRuleEntityDecoder.getProtocol(secRule));
+ secRuleBuilder.setProtocol(ProtocolUdp.class);
+ Assert.assertEquals(IpProtoClassifierDefinition.UDP_VALUE, SecRuleEntityDecoder.getProtocol(secRuleBuilder.build()));
}
@Test
public final void testGetProtocol_protoIcmp() {
- secRule.setSecurityRuleProtocol("icmp");
- Assert.assertEquals(IpProtoClassifierDefinition.ICMP_VALUE, SecRuleEntityDecoder.getProtocol(secRule));
- }
-
- @Test
- public final void testGetProtocol_numValue() {
- secRule.setSecurityRuleProtocol("199");
- Assert.assertEquals(Long.valueOf(199) , SecRuleEntityDecoder.getProtocol(secRule));
+ secRuleBuilder.setProtocol(ProtocolIcmp.class);
+ Assert.assertEquals(IpProtoClassifierDefinition.ICMP_VALUE, SecRuleEntityDecoder.getProtocol(secRuleBuilder.build()));
}
@Test
public final void testGetProtocol_protoNull() {
- secRule.setSecurityRuleProtocol(null);
- Assert.assertNull(SecRuleEntityDecoder.getProtocol(secRule));
- }
-
- @Test
- public final void testGetProtocol_protoEmptyString() {
- secRule.setSecurityRuleProtocol("");
- Assert.assertNull(SecRuleEntityDecoder.getProtocol(secRule));
+ secRuleBuilder.setProtocol(null);
+ Assert.assertNull(SecRuleEntityDecoder.getProtocol(secRuleBuilder.build()));
}
@Test
public final void testGetProtocol_protoUnknown() {
- secRule.setSecurityRuleProtocol("foo");
+ secRuleBuilder.setProtocol(UnknownProtocol.class);
thrown.expect(IllegalArgumentException.class);
- SecRuleEntityDecoder.getProtocol(secRule);
+ SecRuleEntityDecoder.getProtocol(secRuleBuilder.build());
+ }
+
+ private static class UnknownProtocol extends ProtocolBase {
}
}
import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;
import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClauseName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
public class SecRuleNameDecoderTest {
- private NeutronSecurityRule secRule;
+ private SecurityRuleBuilder secRule;
@Before
public void setUp() throws Exception {
- secRule = new NeutronSecurityRule();
+ secRule = new SecurityRuleBuilder().setId(new Uuid("01234567-abcd-ef01-0123-0123456789ab"));
}
@Test
public final void testGetClassifierRefName() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- ClassifierName clsfInstanceName = SecRuleNameDecoder.getClassifierInstanceName(secRule);
+ secRule.setDirection(DirectionIngress.class);
+ secRule.setEthertype(EthertypeV4.class);
+ ClassifierName clsfInstanceName = SecRuleNameDecoder.getClassifierInstanceName(secRule.build());
String crName = new StringBuilder().append(Direction.In.name())
.append(MappingUtils.NAME_DOUBLE_DELIMETER)
.append(clsfInstanceName.getValue())
.toString();
ClassifierName expectedClsfRefName = new ClassifierName(crName);
- assertEquals(expectedClsfRefName, SecRuleNameDecoder.getClassifierRefName(secRule));
+ assertEquals(expectedClsfRefName, SecRuleNameDecoder.getClassifierRefName(secRule.build()));
}
@Test
public final void testGetClassifierInstanceName() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- secRule.setSecurityRuleProtocol(NeutronUtils.TCP);
- secRule.setSecurityRulePortMin(8010);
- secRule.setSecurityRulePortMax(8020);
+ secRule.setDirection(DirectionIngress.class);
+ secRule.setEthertype(EthertypeV4.class);
+ secRule.setProtocol(ProtocolTcp.class);
+ secRule.setPortRangeMin(8010);
+ secRule.setPortRangeMax(8020);
StringBuilder frmtBuilder = new StringBuilder();
frmtBuilder.append(L4ClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_DELIMETER)
.append(EtherTypeClassifierDefinition.DEFINITION.getName().getValue())
.append(MappingUtils.NAME_VALUE_DELIMETER)
.append("%s");
- String frmtClsfName = String.format(frmtBuilder.toString(), 8010, 8020, secRule.getSecurityRuleProtocol(),
- secRule.getSecurityRuleEthertype());
+ String frmtClsfName = String.format(frmtBuilder.toString(), 8010, 8020, secRule.getProtocol().getSimpleName(),
+ secRule.getEthertype().getSimpleName());
ClassifierName expectedClsfInstanceName = new ClassifierName(frmtClsfName);
- assertEquals(expectedClsfInstanceName, SecRuleNameDecoder.getClassifierInstanceName(secRule));
+ assertEquals(expectedClsfInstanceName, SecRuleNameDecoder.getClassifierInstanceName(secRule.build()));
}
@Test
public final void testGetClauseName_noRemoteIpPrefix() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule));
- assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule));
+ secRule.setDirection(DirectionIngress.class);
+ secRule.setEthertype(EthertypeV4.class);
+ ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule.build()));
+ assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule.build()));
}
@Test
public final void testGetClauseName_remoteIpPrefix() {
- secRule.setSecurityRuleDirection(NeutronUtils.INGRESS);
- secRule.setSecurityRuleEthertype(NeutronUtils.IPv4);
- secRule.setSecurityRuleRemoteIpPrefix("10.0.0.0/8");
- ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule).getValue()
+ secRule.setDirection(DirectionIngress.class);
+ secRule.setEthertype(EthertypeV4.class);
+ secRule.setRemoteIpPrefix(new IpPrefix(new Ipv4Prefix("10.0.0.0/8")));
+ ClauseName expectedClauseName = new ClauseName(SecRuleNameDecoder.getSubjectName(secRule.build()).getValue()
+ MappingUtils.NAME_DOUBLE_DELIMETER + "10.0.0.0_8");
- assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule));
+ assertEquals(expectedClauseName, SecRuleNameDecoder.getClauseName(secRule.build()));
}
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import java.lang.reflect.Method;
import java.util.Arrays;
import org.junit.Test;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierDefinitionId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.gbp.mapper.rev150513.change.action.of.security.group.rules.input.action.ActionChoice;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstanceBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
public class SingleClassifierRuleTest {
@Test
public void testConstructorAndGetters() {
- NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", NeutronUtils.IPv4,
- NeutronUtils.INGRESS, NeutronUtils.TCP, 8010, 8020);
+ SecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds(
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", EthertypeV4.class,
+ DirectionIngress.class, ProtocolTcp.class, 8010, 8020);
final int ruleOrder = 1;
singleClsfRule = new SingleClassifierRule(secRule, ruleOrder, MappingUtils.ALLOW_ACTION_CHOICE);
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.NeutronEntityFactory;
import org.opendaylight.groupbasedpolicy.neutron.mapper.test.PolicyAssert;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.NeutronUtils;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.Contract;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.Subject;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.contract.subject.Rule;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionIngress;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeV4;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolTcp;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
public class SingleRuleContractTest {
@Test
public void testConstructorAndGetters() {
- NeutronSecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds(
- "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", NeutronUtils.IPv4,
- NeutronUtils.INGRESS, NeutronUtils.TCP, 8010, 8020);
+ SecurityRule secRule = NeutronEntityFactory.securityRuleWithoutGroupIds(
+ "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb", EthertypeV4.class,
+ DirectionIngress.class, ProtocolTcp.class, 8010, 8020);
int subjectAndRuleOrder = 1;
SingleRuleContract singleRuleContract = new SingleRuleContract(secRule, subjectAndRuleOrder, new Description(
"contractDescription"), MappingUtils.ALLOW_ACTION_CHOICE);
package org.opendaylight.groupbasedpolicy.neutron.mapper.test;
-import java.util.ArrayList;
-import java.util.List;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.DirectionBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.EthertypeBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.constants.rev150712.ProtocolBase;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.groups.attributes.security.groups.SecurityGroupBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRuleBuilder;
-import org.opendaylight.neutron.spi.NeutronSecurityGroup;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
+import com.google.common.base.Strings;
public final class NeutronEntityFactory {
throw new UnsupportedOperationException("Cannot create an instance");
}
- public static NeutronSecurityGroup securityGroup(String id, String tenantId) {
- NeutronSecurityGroup secGrp = new NeutronSecurityGroup();
- secGrp.setSecurityGroupUUID(id);
- secGrp.setSecurityGroupTenantID(tenantId);
- secGrp.setSecurityRules(new ArrayList<NeutronSecurityRule>());
- return secGrp;
+ public static SecurityGroup securityGroup(String id, String tenantId) {
+ return new SecurityGroupBuilder().setUuid(new Uuid(id)).setTenantId(new Uuid(tenantId)).build();
}
- public static NeutronSecurityGroup securityGroupWithName(String id, String tenantId, String name) {
- NeutronSecurityGroup secGrp = new NeutronSecurityGroup();
- secGrp.setSecurityGroupUUID(id);
- secGrp.setSecurityGroupTenantID(tenantId);
- secGrp.setSecurityGroupName(name);
- return secGrp;
+ public static SecurityGroup securityGroupWithName(String id, String tenantId, String name) {
+ return new SecurityGroupBuilder().setUuid(new Uuid(id)).setTenantId(new Uuid(tenantId)).setName(name).build();
}
- public static NeutronSecurityGroup securityGroup(String id, String tenantId, List<NeutronSecurityRule> secRules) {
- NeutronSecurityGroup secGrp = new NeutronSecurityGroup();
- secGrp.setSecurityGroupUUID(id);
- secGrp.setSecurityGroupTenantID(tenantId);
- secGrp.setSecurityRules(secRules);
- return secGrp;
+ public static SecurityRule securityRuleWithoutGroupIds(String id, String tenant, Class<? extends EthertypeBase> etherType,
+ Class<? extends DirectionBase> direction, Class<? extends ProtocolBase> protocol, int portMin, int portMax) {
+ SecurityRuleBuilder secRule = new SecurityRuleBuilder();
+ secRule.setId(new Uuid(id));
+ secRule.setTenantId(new Uuid(tenant));
+ secRule.setEthertype(etherType);
+ secRule.setDirection(direction);
+ secRule.setProtocol(protocol);
+ secRule.setPortRangeMin(portMin);
+ secRule.setPortRangeMax(portMax);
+ return secRule.build();
}
- public static NeutronSecurityRule securityRuleWithGroupIds(String id, String tenant, String ownerGroupId,
+ public static SecurityRule securityRuleWithEtherType(String id, String tenant,
+ Class<? extends EthertypeBase> etherType, Class<? extends DirectionBase> direction, String ownerGroupId,
String remoteGroupId) {
- NeutronSecurityRule secRule = new NeutronSecurityRule();
- secRule.setSecurityRuleUUID(id);
- secRule.setSecurityRuleTenantID(tenant);
- secRule.setSecurityRuleGroupID(ownerGroupId);
- secRule.setSecurityRemoteGroupID(remoteGroupId);
- return secRule;
- }
-
- public static NeutronSecurityRule securityRuleWithoutGroupIds(String id, String tenant, String etherType,
- String direction, String protocol, int portMin, int portMax) {
- NeutronSecurityRule secRule = new NeutronSecurityRule();
- secRule.setSecurityRuleUUID(id);
- secRule.setSecurityRuleTenantID(tenant);
- secRule.setSecurityRuleEthertype(etherType);
- secRule.setSecurityRuleDirection(direction);
- secRule.setSecurityRuleProtocol(protocol);
- secRule.setSecurityRulePortMin(portMin);
- secRule.setSecurityRulePortMax(portMax);
- return secRule;
- }
-
- public static NeutronSecurityRule securityRuleWithEtherType(String id, String tenant, String etherType,
- String direction, String ownerGroupId, String remoteGroupId) {
- NeutronSecurityRule secRule = new NeutronSecurityRule();
- secRule.setSecurityRuleUUID(id);
- secRule.setSecurityRuleTenantID(tenant);
- secRule.setSecurityRuleEthertype(etherType);
- secRule.setSecurityRuleDirection(direction);
- secRule.setSecurityRuleGroupID(ownerGroupId);
- secRule.setSecurityRemoteGroupID(remoteGroupId);
- return secRule;
+ SecurityRuleBuilder securityRuleBuilder = new SecurityRuleBuilder().setId(new Uuid(id))
+ .setTenantId(new Uuid(tenant))
+ .setEthertype(etherType)
+ .setDirection(direction)
+ .setSecurityGroupId(new Uuid(ownerGroupId));
+ if (!Strings.isNullOrEmpty(remoteGroupId)) {
+ securityRuleBuilder.setRemoteGroupId(new Uuid(remoteGroupId));
+ }
+ return securityRuleBuilder.build();
}
}
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleEntityDecoder;
import org.opendaylight.groupbasedpolicy.neutron.mapper.mapping.rule.SecRuleNameDecoder;
import org.opendaylight.groupbasedpolicy.neutron.mapper.util.MappingUtils;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.util.Utils;
-import org.opendaylight.neutron.spi.NeutronSecurityRule;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpPrefix;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ActionName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Description;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.action.refs.ActionRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.has.classifier.refs.ClassifierRef;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.endpoint.group.ProviderNamedSelector;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ClassifierInstance;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.secgroups.rev150712.security.rules.attributes.security.rules.SecurityRule;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
public final class PolicyAssert {
}
}
- public static void assertContractWithEic(Contract contract, NeutronSecurityRule secRule) {
- assertEquals(new ContractId(secRule.getSecurityRuleUUID()), contract.getId());
+ public static void assertContractWithEic(Contract contract, SecurityRule secRule) {
+ assertEquals(new ContractId(secRule.getId().getValue()), contract.getId());
assertNull(contract.getQuality());
assertNull(contract.getTarget());
assertOneClauseWithEicWithOneSubject(contract, secRule);
PolicyAssert.assertOneSubjectWithOneRule(contract, secRule);
}
- private static void assertOneClauseWithEicWithOneSubject(Contract contract, NeutronSecurityRule secRule) {
+ private static void assertOneClauseWithEicWithOneSubject(Contract contract, SecurityRule secRule) {
Clause clause = assertOneItem(contract.getClause());
assertNull(clause.getAnyMatchers());
- Preconditions.checkArgument(!Strings.isNullOrEmpty(secRule.getSecurityRuleRemoteIpPrefix()));
- IpPrefix expectedIpPrefix = Utils.createIpPrefix(secRule.getSecurityRuleRemoteIpPrefix());
+ IpPrefix expectedIpPrefix = secRule.getRemoteIpPrefix();
assertNotNull(clause.getConsumerMatchers());
IpPrefix ipPrefix = clause.getConsumerMatchers()
.getEndpointIdentificationConstraints()
assertEquals(SecRuleNameDecoder.getSubjectName(secRule), subjectRef);
}
- public static void assertContract(Contract contract, NeutronSecurityRule secRule) {
- assertEquals(new ContractId(secRule.getSecurityRuleUUID()), contract.getId());
+ public static void assertContract(Contract contract, SecurityRule secRule) {
+ assertEquals(new ContractId(secRule.getId().getValue()), contract.getId());
assertNull(contract.getQuality());
assertNull(contract.getTarget());
assertOneClauseWithOneSubject(contract, secRule);
assertOneSubjectWithOneRule(contract, secRule);
}
- private static void assertOneClauseWithOneSubject(Contract contract, NeutronSecurityRule secRule) {
+ private static void assertOneClauseWithOneSubject(Contract contract, SecurityRule secRule) {
Clause clause = assertOneItem(contract.getClause());
assertClauseWithOneSubject(clause, secRule);
}
- private static void assertOneSubjectWithOneRule(Contract contract, NeutronSecurityRule secRule) {
+ private static void assertOneSubjectWithOneRule(Contract contract, SecurityRule secRule) {
Subject subject = assertOneItem(contract.getSubject());
assertSubjectWithOneRule(subject, secRule);
}
- public static void assertContract(Contract contract, NeutronSecurityRule secRule, Description contractDescription) {
- assertContract(contract, secRule);
- assertEquals(contractDescription, contract.getDescription());
- }
-
- // asserts for endpoint group
-
public static void assertEndpointGroupExists(DataBroker dataBroker, String tenantId, String endpointGroupId)
throws Exception {
Optional<EndpointGroup> epg = ConfigDataStoreReader.readEndpointGroup(dataBroker, tenantId, endpointGroupId);
// asserts for classifier
- public static void assertClassifierInstanceExists(DataBroker dataBroker, NeutronSecurityRule secRule)
+ public static void assertClassifierInstanceExists(DataBroker dataBroker, SecurityRule secRule)
throws Exception {
ClassifierInstance clsfInstance = SecRuleEntityDecoder.getClassifierInstance(secRule);
Optional<ClassifierInstance> readClsfInstance = ConfigDataStoreReader.readClassifierInstance(dataBroker,
- secRule.getSecurityRuleTenantID(), clsfInstance.getName());
+ secRule.getTenantId().getValue(), clsfInstance.getName());
assertTrue(readClsfInstance.isPresent());
}
assertTrue(classifierInstance.isPresent());
}
- public static void assertClassifierInstanceNotExists(DataBroker dataBroker, NeutronSecurityRule secRule)
+ public static void assertClassifierInstanceNotExists(DataBroker dataBroker, SecurityRule secRule)
throws Exception {
ClassifierInstance clsfInstance = SecRuleEntityDecoder.getClassifierInstance(secRule);
Optional<ClassifierInstance> readClsfInstance = ConfigDataStoreReader.readClassifierInstance(dataBroker,
- secRule.getSecurityRuleTenantID(), clsfInstance.getName());
+ secRule.getTenantId().getValue(), clsfInstance.getName());
assertFalse(readClsfInstance.isPresent());
}
// asserts for clause
- public static void assertClauseWithOneSubject(Clause clause, NeutronSecurityRule secRule) {
+ public static void assertClauseWithOneSubject(Clause clause, SecurityRule secRule) {
assertNull(clause.getAnyMatchers());
assertNull(clause.getConsumerMatchers());
assertNull(clause.getProviderMatchers());
// asserts for subject
- public static void assertSubjectWithOneRule(Subject subject, NeutronSecurityRule secRule) {
+ public static void assertSubjectWithOneRule(Subject subject, SecurityRule secRule) {
assertEquals(SecRuleNameDecoder.getSubjectName(secRule), subject.getName());
Rule rule = assertOneItem(subject.getRule());
assertRule(rule, secRule);
// asserts for rule
- public static void assertRule(Rule rule, NeutronSecurityRule secRule) {
+ public static void assertRule(Rule rule, SecurityRule secRule) {
assertEquals(SecRuleNameDecoder.getRuleName(secRule), rule.getName());
ActionRef actionRef = assertOneItem(rule.getActionRef());
assertEquals(MappingUtils.ACTION_ALLOW.getName(), actionRef.getName());
assertEquals(SecRuleEntityDecoder.getDirection(secRule), classifierRef.getDirection());
}
- public static void assertRule(Rule rule, NeutronSecurityRule secRule, int order) {
+ public static void assertRule(Rule rule, SecurityRule secRule, int order) {
assertRule(rule, secRule);
assertEquals(order, rule.getOrder().intValue());
}
+++ /dev/null
-package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.groupbasedpolicy.neutron.mapper.test.GbpDataBrokerTest;
-import org.opendaylight.groupbasedpolicy.util.IidFactory;
-import org.opendaylight.neutron.spi.Neutron_IPs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.Name;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextKey;
-
-public class MappingUtilsTest extends GbpDataBrokerTest {
-
- private final TenantId tenantId = new TenantId("00000000-0000-0000-0000-000000000001");
- private final L2FloodDomainId l2FloodDomainId = new L2FloodDomainId("00000000-0000-0000-0000-000000000002");
- private final L2BridgeDomainId l2BridgeDomainId = new L2BridgeDomainId("00000000-0000-0000-0000-000000000003");
- private final L3ContextId l3ContextId = new L3ContextId("00000000-0000-0000-0000-000000000004");
- private final String[] ips = {"170.0.0.1", "170.0.0.2", "170.0.0.3"};
- private L2FloodDomainBuilder l2FloodDomainBuilder;
- private List<Neutron_IPs> emptyList, singleIp, multiIp;
- private L2BridgeDomainBuilder l2BridgeDomainBuilder;
- private L3ContextBuilder l3ContextBuilder;
-
- @Before
- public void init() {
- l2FloodDomainBuilder = new L2FloodDomainBuilder();
- l2FloodDomainBuilder.setName(new Name("l2fdn"))
- .setKey(new L2FloodDomainKey(l2FloodDomainId));
- l2BridgeDomainBuilder = new L2BridgeDomainBuilder();
- l2BridgeDomainBuilder.setName(new Name("l2bdn"))
- .setKey(new L2BridgeDomainKey(l2BridgeDomainId));
- l3ContextBuilder = new L3ContextBuilder();
- l3ContextBuilder.setName(new Name("l3cn"))
- .setKey(new L3ContextKey(l3ContextId));
- Neutron_IPs neutronIp1 = new Neutron_IPs();
- Neutron_IPs neutronIp2 = new Neutron_IPs();
- Neutron_IPs neutronIp3 = new Neutron_IPs();
- neutronIp1.setIpAddress(ips[0]);
- neutronIp2.setIpAddress(ips[1]);
- neutronIp3.setIpAddress(ips[2]);
- emptyList = new ArrayList<>();
- singleIp = new ArrayList<>();
- singleIp.add(neutronIp1);
- multiIp = new ArrayList<>();
- multiIp.add(neutronIp1);
- multiIp.add(neutronIp2);
- multiIp.add(neutronIp3);
- }
-
- @Test
- public void testCreateForwardingContext1() {
- //case #1 - L2FloodDomain is not present in DS
- DataBroker dataBroker = getDataBroker();
- ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- MappingUtils.ForwardingCtx
- forwardingCtx =
- MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx);
- assertNotNull(forwardingCtx);
- assertNull(forwardingCtx.getL2FloodDomain());
- assertNull(forwardingCtx.getL2BridgeDomain());
- assertNull(forwardingCtx.getL3Context());
- }
-
- @Test
- public void testCreateForwardingContext2() {
- //case #2 - L2FloodDomain is present in DS, but its parent is null
- DataBroker dataBroker = getDataBroker();
- ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- l2FloodDomainBuilder.setParent(null);
- L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build();
- writeL2FloodDomain(tenantId, l2FloodDomain, rwTx);
- MappingUtils.ForwardingCtx
- forwardingCtx =
- MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx);
- assertNotNull(forwardingCtx);
- assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain));
- assertNull(forwardingCtx.getL2BridgeDomain());
- assertNull(forwardingCtx.getL3Context());
- }
-
- @Test
- public void testCreateForwardingContext3() {
- //case #3 - L2FloodDomain is present in DS with not-null parent, but L2BridgeDomain is not present in DS
- DataBroker dataBroker = getDataBroker();
- ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId());
- L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build();
- writeL2FloodDomain(tenantId, l2FloodDomain, rwTx);
- MappingUtils.ForwardingCtx
- forwardingCtx =
- MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx);
- assertNotNull(forwardingCtx);
- assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain));
- assertNull(forwardingCtx.getL2BridgeDomain());
- assertNull(forwardingCtx.getL3Context());
- }
-
- @Test
- public void testCreateForwardingContext4() {
- //case #4 - L2BridgeDomain is also present in DS but with null parent
- DataBroker dataBroker = getDataBroker();
- ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- l2BridgeDomainBuilder.setParent(null);
- l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId());
- L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build();
- L2BridgeDomain l2BridgeDomain = l2BridgeDomainBuilder.build();
- writeL2FloodDomain(tenantId, l2FloodDomain, rwTx);
- writeL2BridgeDomain(tenantId, l2BridgeDomain, rwTx);
- MappingUtils.ForwardingCtx
- forwardingCtx =
- MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx);
- assertNotNull(forwardingCtx);
- assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain));
- assertTrue(forwardingCtx.getL2BridgeDomain().equals(l2BridgeDomain));
- assertNull(forwardingCtx.getL3Context());
- }
-
- @Test
- public void testCreateForwardingContext5() {
- //case #5 - L2BridgeDomain is also present in DS with not-null parent, but L3Context is not present in DS
- DataBroker dataBroker = getDataBroker();
- ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- l2BridgeDomainBuilder.setParent(l3ContextBuilder.build().getId());
- l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId());
- L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build();
- L2BridgeDomain l2BridgeDomain = l2BridgeDomainBuilder.build();
- writeL2FloodDomain(tenantId, l2FloodDomain, rwTx);
- writeL2BridgeDomain(tenantId, l2BridgeDomain, rwTx);
- MappingUtils.ForwardingCtx
- forwardingCtx =
- MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx);
- assertNotNull(forwardingCtx);
- assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain));
- assertTrue(forwardingCtx.getL2BridgeDomain().equals(l2BridgeDomain));
- assertNull(forwardingCtx.getL3Context());
- }
-
- @Test
- public void testCreateForwardingContext6() {
- //case #6 - L3Context present in DS
- DataBroker dataBroker = getDataBroker();
- ReadWriteTransaction rwTx = dataBroker.newReadWriteTransaction();
- l2BridgeDomainBuilder.setParent(l3ContextBuilder.build().getId());
- l2FloodDomainBuilder.setParent(l2BridgeDomainBuilder.build().getId());
- L2FloodDomain l2FloodDomain = l2FloodDomainBuilder.build();
- L2BridgeDomain l2BridgeDomain = l2BridgeDomainBuilder.build();
- L3Context l3Context = l3ContextBuilder.build();
- writeL2FloodDomain(tenantId, l2FloodDomain, rwTx);
- writeL2BridgeDomain(tenantId, l2BridgeDomain, rwTx);
- writeL3Context(tenantId, l3Context, rwTx);
- MappingUtils.ForwardingCtx
- forwardingCtx =
- MappingUtils.createForwardingContext(tenantId, l2FloodDomainBuilder.build().getId(), rwTx);
- assertNotNull(forwardingCtx);
- assertTrue(forwardingCtx.getL2FloodDomain().equals(l2FloodDomain));
- assertTrue(forwardingCtx.getL2BridgeDomain().equals(l2BridgeDomain));
- assertTrue(forwardingCtx.getL3Context().equals(l3Context));
- }
-
- @Test
- public void testGetFirstIpNullIp() {
- Neutron_IPs result = MappingUtils.getFirstIp(emptyList);
- assertNull(result);
- }
-
- @Test
- public void testGetFirstIpOneIp() {
- Neutron_IPs result = MappingUtils.getFirstIp(singleIp);
- assertNotNull(result);
- assertEquals(result.getIpAddress(), ips[0]);
- }
-
- @Test
- public void testGetFirstIpMoreIps() {
- Neutron_IPs result = MappingUtils.getFirstIp(multiIp);
- assertNotNull(result);
- assertEquals(result.getIpAddress(), ips[0]);
- }
-
- private void writeL2FloodDomain(TenantId tenantId, L2FloodDomain l2Fd, ReadWriteTransaction rwTx) {
- checkNotNull(l2Fd);
- L2FloodDomainId l2FdId = l2Fd.getId();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2FloodDomainIid(tenantId, l2FdId), l2Fd);
- }
-
- private void writeL2BridgeDomain(TenantId tenantId, L2BridgeDomain l2Bd, ReadWriteTransaction rwTx) {
- checkNotNull(l2Bd);
- L2BridgeDomainId l2BdId = l2Bd.getId();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l2BridgeDomainIid(tenantId, l2BdId), l2Bd);
- }
-
- private void writeL3Context(TenantId tenantId, L3Context l3Ct, ReadWriteTransaction rwTx) {
- checkNotNull(l3Ct);
- L3ContextId l3CtId = l3Ct.getId();
- rwTx.put(LogicalDatastoreType.CONFIGURATION, IidFactory.l3ContextIid(tenantId, l3CtId), l3Ct);
- }
-
-}
+++ /dev/null
-package org.opendaylight.groupbasedpolicy.neutron.mapper.util;
-
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertTrue;
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Iterator;
-
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.Mappings;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.NetworkMappings;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.neutron.mapper.rev150223.mappings.network.mappings.NetworkMapping;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public class NeutronMapperIidFactoryTest {
-
- @Test
- public void instantiate() {
- NeutronMapperIidFactory iidFactory = new NeutronMapperIidFactory();
- assertNotNull(iidFactory);
- }
-
- @Test
- public void testEndpointByPortIid() {
- String dummyId = "00000000-0000-0000-0000-000000000001";
- InstanceIdentifier<NetworkMapping> iid = NeutronMapperIidFactory.networkMappingIid(new UniqueId(dummyId));
- assertNotNull(iid);
- assertEquals(iid.getTargetType(), NetworkMapping.class);
- assertTrue(iid.toString().contains(dummyId));
-
- Iterator<InstanceIdentifier.PathArgument> pathArguments = iid.getPathArguments().iterator();
-
- assertEquals(pathArguments.next().toString(), Mappings.class.getName());
- assertEquals(pathArguments.next().toString(), NetworkMappings.class.getName());
- assertEquals(pathArguments.next().getType().toString(), NetworkMapping.class.toString());
- }
-}
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Optional;
+
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.groupbasedpolicy.dto.EgKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.BucketId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.buckets.BucketBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.OfOverlayContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.ofoverlay.rev140528.Segmentation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.overlay.rev150105.TunnelTypeVxlan;
for (Endpoint extEp : ctx.getEndpointManager().getExtEpsNoLocForGroup(endpointGroupKey)) {
if (extEp.getNetworkContainment() != null
&& extEp.getNetworkContainment().equals(endpoint.getNetworkContainment())) {
+ Subnet subnet = ctx.getTenant(extEp.getTenant()).resolveSubnet(new SubnetId(extEp.getNetworkContainment()));
L2FloodDomain l2Fd = ctx.getTenant(extEp.getTenant())
- .resolveL2FloodDomain(extEp.getNetworkContainment());
+ .resolveL2FloodDomain(new L2FloodDomainId(subnet.getParent().getValue()));
if (l2Fd != null) {
Segmentation segmentation = l2Fd.getAugmentation(Segmentation.class);
// external endpoints do not have location augmentation
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.annotations.VisibleForTesting;
+
import org.opendaylight.groupbasedpolicy.dto.ConditionGroup;
import org.opendaylight.groupbasedpolicy.dto.EgKey;
import org.opendaylight.groupbasedpolicy.dto.EpKey;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ConditionName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.UniqueId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.EndpointGroup;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.slf4j.Logger;
// Based on network containment, determine components of
// forwarding context
- L3Context l3c = tenant.resolveL3Context(networkContainment);
- L2BridgeDomain bd = tenant.resolveL2BridgeDomain(networkContainment);
- L2FloodDomain fd = tenant.resolveL2FloodDomain(networkContainment);
+ Subnet s = ctx.getTenant(ep.getTenant()).resolveSubnet(new SubnetId(networkContainment));
+ L2FloodDomainId l2fdId = new L2FloodDomainId(s.getParent().getValue());
+ L2BridgeDomain bd = tenant.resolveL2BridgeDomain(l2fdId);
+ L2FloodDomain fd = tenant.resolveL2FloodDomain(l2fdId);
+ L3Context l3c = tenant.resolveL3Context(l2fdId);
+
// Set ordinal id's for use in flows for each forwarding context
// component
import com.google.common.base.Preconditions;
+
import org.opendaylight.groupbasedpolicy.dto.EpKey;
import org.opendaylight.groupbasedpolicy.dto.IndexedTenant;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfContext;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.l3.prefix.fields.EndpointL3Gateways;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
}
L3Context getL3ContextForSubnet(IndexedTenant indexedTenant, Subnet subnet) {
- if (indexedTenant == null) {
+ if (indexedTenant == null || subnet.getParent() == null) {
return null;
}
- return indexedTenant.resolveL3Context(subnet.getId());
+ return indexedTenant.resolveL3Context(new L2FloodDomainId(subnet.getParent().getValue()));
}
NetworkDomainId getEPNetworkContainment(Endpoint endpoint, IndexedTenant tenant) {
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.Match;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.l3endpoint.rev151217.NatAddress;
natL3Ep.getKey()));
if (natIpSubnet != null && natIpSubnet.getParent() != null) {
L2FloodDomain natEpl2Fd =
- ctx.getTenant(natL3Ep.getTenant()).resolveL2FloodDomain(natIpSubnet.getParent());
+ ctx.getTenant(natL3Ep.getTenant()).resolveL2FloodDomain(new L2FloodDomainId(natIpSubnet.getParent().getValue()));
if (natEpl2Fd != null && natEpl2Fd.getAugmentation(Segmentation.class) != null) {
Integer vlanId = natEpl2Fd.getAugmentation(Segmentation.class).getSegmentationId();
ofWriter.writeFlow(nodeId, TABLE_ID,
* for applying VLAN tag is generated. The flow matches against REG5 holding
* the L2FloodDomain and REG7 holding value of an external interface.
*/
- L2FloodDomain l2Fd = ctx.getTenant(endpoint.getTenant()).resolveL2FloodDomain(endpoint.getNetworkContainment());
+ Subnet sub = ctx.getTenant(endpoint.getTenant()).resolveSubnet(new SubnetId(endpoint.getNetworkContainment()));
+ L2FloodDomain l2Fd = ctx.getTenant(endpoint.getTenant()).resolveL2FloodDomain(new L2FloodDomainId(sub.getParent().getValue()));
if (l2Fd == null) {
return;
}
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.mapper.ingressnat;
import com.google.common.base.Preconditions;
+
import org.apache.commons.lang3.ArrayUtils;
import org.opendaylight.groupbasedpolicy.dto.IndexedTenant;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.OfWriter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.go.to.table._case.GoToTable;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoint.fields.L3Address;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointL3;
Subnet extSubnet = ExternalMapper.resolveSubnetForIpv4Address(tenant, outsideDestAddress.getIpv4Address());
L2FloodDomain l2Fd = null;
if (extSubnet != null && extSubnet.getParent() != null) {
- l2Fd = tenant.resolveL2FloodDomain(extSubnet.getParent());
+ l2Fd = tenant.resolveL2FloodDomain(new L2FloodDomainId(extSubnet.getParent().getValue()));
}
FlowBuilder flowBuilder = base(tableId).setPriority(priority);
if (l2Fd != null && l2Fd.getAugmentation(Segmentation.class) != null) {
*/
public abstract class Classifier {
+ // Messages for exceptions (also for exception tests)
+ public static final String MSG_CLASSIFICATION_CONFLICT_DETECTED = "Classification conflict detected";
+ public static final String MSG_NOT_SPECIFIED = "not specified";
+ public static final String MSG_PARAMETER_IS_NOT_PRESENT = "parameter is not present";
+ public static final String MSG_MUTUALLY_EXCLUSIVE = "mutually exclusive";
+ public static final String MSG_RANGE_VALUE_MISMATCH = "Range value mismatch.";
+ public static final String MSG_NOT_SUPPORTED = "not supported";
+ public static final String MSG_IS_MISSING = "is missing";
+ public static final String MSG_NOT_PRESENT = "not present";
+
protected final Classifier parent;
public static final EtherTypeClassifier ETHER_TYPE_CL = new EtherTypeClassifier(null);
/**
* The result represents supported parameters for the classifier by renderer
- *
+ *
* @return list of supported parameters by the classifier
*/
public abstract List<SupportedParameterValues> getSupportedParameterValues();
*/
public final ClassificationResult updateMatch(List<MatchBuilder> matches, Map<String, ParameterValue> params) {
if (params == null) {
- return new ClassificationResult("Classifier-instance with classifier-definition-id: " + this.getId()
- + ". No parameters present.");
+ return new ClassificationResult(
+ "Classifier-instance with classifier-definition-id: " + this.getId() + ". No parameters present.");
}
List<MatchBuilder> matchBuilders = matches;
try {
}
/**
- * Checks presence of required {@code params} in order to decide if classifier can update {@code matches} properly
- * in method {@link #update(List, Map)}
- * @param params inserted parameters, not null
- * @throws IllegalArgumentException when any of required {@code params} is not present, see {@link #updateMatch(List, Map)}
+ * Checks presence of required {@code params} in order to decide if classifier can update
+ * {@code matches} properly
+ * in method {@link #update(List, Map)}
+ *
+ * @param params inserted parameters, not null
+ * @throws IllegalArgumentException when any of required {@code params} is not present, see
+ * {@link #updateMatch(List, Map)}
*/
protected abstract void checkPresenceOfRequiredParams(Map<String, ParameterValue> params);
public List<SupportedParameterValues> getSupportedParameterValues() {
List<SupportedIntValue> values = ImmutableList.of(
- new SupportedIntValueBuilder().setValue(EtherTypeClassifierDefinition.ARP_VALUE)
- .build(),
- new SupportedIntValueBuilder().setValue(EtherTypeClassifierDefinition.IPv4_VALUE)
- .build(),
- new SupportedIntValueBuilder().setValue(EtherTypeClassifierDefinition.IPv6_VALUE)
- .build());
+ new SupportedIntValueBuilder().setValue(EtherTypeClassifierDefinition.ARP_VALUE).build(),
+ new SupportedIntValueBuilder().setValue(EtherTypeClassifierDefinition.IPv4_VALUE).build(),
+ new SupportedIntValueBuilder().setValue(EtherTypeClassifierDefinition.IPv6_VALUE).build());
SupportedParameterValuesBuilder b = new SupportedParameterValuesBuilder();
b.setParameterName(new ParameterName(EtherTypeClassifierDefinition.ETHERTYPE_PARAM));
b.setParameterType(new IntBuilder().setSupportedIntValue(values).build());
protected void checkPresenceOfRequiredParams(Map<String, ParameterValue> params) {
if (params.get(EtherTypeClassifierDefinition.ETHERTYPE_PARAM) == null) {
throw new IllegalArgumentException(
- "Parameter " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " not specified.");
+ "Parameter " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " " + MSG_NOT_SPECIFIED);
}
if (params.get(EtherTypeClassifierDefinition.ETHERTYPE_PARAM).getIntValue() == null) {
throw new IllegalArgumentException(
- "Value of " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " parameter is not present.");
+ "Value of " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " " + MSG_PARAMETER_IS_NOT_PRESENT);
}
}
@Override
- protected List<MatchBuilder> update(List<MatchBuilder> matches,
- Map<String, ParameterValue> params) {
+ protected List<MatchBuilder> update(List<MatchBuilder> matches, Map<String, ParameterValue> params) {
Long type = params.get(EtherTypeClassifierDefinition.ETHERTYPE_PARAM).getIntValue();
for (MatchBuilder match : matches) {
EthernetMatchBuilder em;
private void equalOrNotSetValidation(EthernetType ethTypeInMatch, long paramValue) {
if (ethTypeInMatch != null) {
- if (paramValue != ethTypeInMatch.getType().getValue().longValue()) {
- throw new IllegalArgumentException(
- "Classification conflict detected at " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " parameter for values " + ethTypeInMatch
- .getType()
- .getValue() + " and " + paramValue + ". It is not allowed " + "to assign different values to the same parameter among all the classifiers within one rule.");
+ if (paramValue != ethTypeInMatch.getType().getValue()) {
+ throw new IllegalArgumentException(MSG_CLASSIFICATION_CONFLICT_DETECTED + " at "
+ + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " parameter for values "
+ + ethTypeInMatch.getType().getValue() + " and " + paramValue + ". It is not allowed "
+ + "to assign different values to the same parameter among all the classifiers within one rule.");
}
}
}
public List<SupportedParameterValues> getSupportedParameterValues() {
List<SupportedIntValue> values = ImmutableList.of(
- new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.ICMP_VALUE)
- .build(),
- new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.SCTP_VALUE)
- .build(),
- new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.TCP_VALUE)
- .build(),
- new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.UDP_VALUE)
- .build());
+ new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.ICMP_VALUE).build(),
+ new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.SCTP_VALUE).build(),
+ new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.TCP_VALUE).build(),
+ new SupportedIntValueBuilder().setValue(IpProtoClassifierDefinition.UDP_VALUE).build());
SupportedParameterValuesBuilder b = new SupportedParameterValuesBuilder();
b.setParameterName(new ParameterName(IpProtoClassifierDefinition.PROTO_PARAM));
b.setParameterType(new IntBuilder().setSupportedIntValue(values).build());
@Override
protected void checkPresenceOfRequiredParams(Map<String, ParameterValue> params) {
if (params.get(IpProtoClassifierDefinition.PROTO_PARAM) == null) {
- throw new IllegalArgumentException("Parameter " + IpProtoClassifierDefinition.PROTO_PARAM
- + " not specified.");
+ throw new IllegalArgumentException(
+ "Parameter " + IpProtoClassifierDefinition.PROTO_PARAM + " " + MSG_NOT_SPECIFIED);
}
if (params.get(IpProtoClassifierDefinition.PROTO_PARAM).getIntValue() == null) {
- throw new IllegalArgumentException("Value of " + IpProtoClassifierDefinition.PROTO_PARAM
- + " parameter is not present.");
+ throw new IllegalArgumentException(
+ "Value of " + IpProtoClassifierDefinition.PROTO_PARAM + " " + MSG_PARAMETER_IS_NOT_PRESENT);
}
}
private void equalOrNotSetValidation(Short protoInMatch, long paramValue) {
if (protoInMatch != null) {
if (paramValue != protoInMatch.longValue()) {
- throw new IllegalArgumentException("Classification conflict detected at " + IpProtoClassifierDefinition.PROTO_PARAM
- + " parameter for values " + protoInMatch.shortValue() + " and " + paramValue
- + ". It is not allowed "
+ throw new IllegalArgumentException(MSG_CLASSIFICATION_CONFLICT_DETECTED + " at "
+ + IpProtoClassifierDefinition.PROTO_PARAM + " parameter for values " + protoInMatch + " and "
+ + paramValue + ". It is not allowed "
+ "to assign different values to the same parameter among all the classifiers within one rule.");
}
}
try {
readEthType = match.getEthernetMatch().getEthernetType().getType().getValue();
} catch (NullPointerException e) {
- throw new IllegalArgumentException("Parameter " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM
- + " is missing.");
+ throw new IllegalArgumentException(
+ "Parameter " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM + " " + MSG_IS_MISSING);
}
if (!FlowUtils.IPv4.equals(readEthType) && !FlowUtils.IPv6.equals(readEthType)) {
throw new IllegalArgumentException("Parameter " + EtherTypeClassifierDefinition.ETHERTYPE_PARAM
/**
* Return the IpProtocol value. May return null.
+ *
* @param params the parameters of classifier-instance inserted by user
* @return the IpProtocol value
*/
if (params.get(portParam) != null) {
StringBuilder paramLog = new StringBuilder();
if (params.get(portParam).getIntValue() == null) {
- paramLog.append("Value of ")
- .append(portParam)
- .append(" parameter is not specified.");
+ paramLog.append("Value of ").append(portParam).append(" parameter " + MSG_NOT_SPECIFIED);
throw new IllegalArgumentException(paramLog.toString());
}
- if(params.get(portRangeParam) != null) {
+ if (params.get(portRangeParam) != null) {
paramLog.append("Source port parameters ")
.append(portParam)
.append(" and ")
.append(portRangeParam)
- .append(" are mutually exclusive.");
+ .append(" are " + MSG_MUTUALLY_EXCLUSIVE);
throw new IllegalArgumentException(paramLog.toString());
}
}
private void validateRangeValue(RangeValue rangeValueParam) {
if (rangeValueParam == null) {
- throw new IllegalArgumentException("Range parameter is specifiet but value is not present.");
+ throw new IllegalArgumentException(
+ "Range parameter is specified but value is " + Classifier.MSG_NOT_PRESENT);
}
final Long min = rangeValueParam.getMin();
final Long max = rangeValueParam.getMax();
if (min > max) {
- throw new IllegalArgumentException("Range value mismatch. " + min + " is greater than MAX " + max + ".");
+ throw new IllegalArgumentException(
+ MSG_RANGE_VALUE_MISMATCH + " MIN " + min + " is greater than MAX " + max + ".");
}
}
public List<MatchBuilder> update(List<MatchBuilder> matches, Map<String, ParameterValue> params) {
Set<Long> sPorts = new HashSet<>();
Set<Long> dPorts = new HashSet<>();
- addToPortSet(params, L4ClassifierDefinition.SRC_PORT_PARAM, L4ClassifierDefinition.SRC_PORT_RANGE_PARAM, sPorts);
- addToPortSet(params, L4ClassifierDefinition.DST_PORT_PARAM, L4ClassifierDefinition.DST_PORT_RANGE_PARAM, dPorts);
+ addToPortSet(params, L4ClassifierDefinition.SRC_PORT_PARAM, L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
+ sPorts);
+ addToPortSet(params, L4ClassifierDefinition.DST_PORT_PARAM, L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
+ dPorts);
List<MatchBuilder> newMatches = new ArrayList<>();
for (MatchBuilder matchBuilder : matches) {
Layer4Match l4Match = matchBuilder.getLayer4Match();
return newMatches;
}
- private void addToPortSet(Map<String, ParameterValue> params, String portParam, String portRangeParam, Set<Long> portSet) {
+ private void addToPortSet(Map<String, ParameterValue> params, String portParam, String portRangeParam,
+ Set<Long> portSet) {
if (params.get(portParam) != null) {
portSet.add(params.get(portParam).getIntValue());
} else if (params.get(portRangeParam) != null) {
return new SctpMatchBuilder().build();
}
throw new IllegalArgumentException("Parameter " + IpProtoClassifierDefinition.PROTO_PARAM + ": value " + ipProto
- + " is not supported.");
+ + " is " + Classifier.MSG_NOT_SUPPORTED);
}
private Set<Long> createSetFromRange(RangeValue rangeValueParam) {
if (!sPorts.isEmpty() && dPorts.isEmpty()) {
for (Long srcPort : sPorts) {
equalOrNotSetValidation(udpMatch.getUdpSourcePort(), srcPort.longValue());
- udpMatches.add(new UdpMatchBuilder(udpMatch).setUdpSourcePort(new PortNumber(srcPort.intValue())).build());
+ udpMatches
+ .add(new UdpMatchBuilder(udpMatch).setUdpSourcePort(new PortNumber(srcPort.intValue())).build());
}
} else if (sPorts.isEmpty() && !dPorts.isEmpty()) {
for (Long dstPort : dPorts) {
if (!sPorts.isEmpty() && dPorts.isEmpty()) {
for (Long srcPort : sPorts) {
equalOrNotSetValidation(tcpMatch.getTcpSourcePort(), srcPort.longValue());
- tcpMatches.add(new TcpMatchBuilder(tcpMatch).setTcpSourcePort(new PortNumber(srcPort.intValue())).build());
+ tcpMatches
+ .add(new TcpMatchBuilder(tcpMatch).setTcpSourcePort(new PortNumber(srcPort.intValue())).build());
}
} else if (sPorts.isEmpty() && !dPorts.isEmpty()) {
for (Long dstPort : dPorts) {
if (!sPorts.isEmpty() && dPorts.isEmpty()) {
for (Long srcPort : sPorts) {
equalOrNotSetValidation(sctpMatch.getSctpSourcePort(), srcPort.longValue());
- sctpMatches.add(new SctpMatchBuilder(sctpMatch).setSctpSourcePort(new PortNumber(srcPort.intValue()))
- .build());
+ sctpMatches
+ .add(new SctpMatchBuilder(sctpMatch).setSctpSourcePort(new PortNumber(srcPort.intValue())).build());
}
} else if (sPorts.isEmpty() && !dPorts.isEmpty()) {
for (Long dstPort : dPorts) {
equalOrNotSetValidation(sctpMatch.getSctpDestinationPort(), dstPort.longValue());
- sctpMatches.add(new SctpMatchBuilder(sctpMatch).setSctpDestinationPort(new PortNumber(dstPort.intValue()))
- .build());
+ sctpMatches.add(new SctpMatchBuilder(sctpMatch)
+ .setSctpDestinationPort(new PortNumber(dstPort.intValue())).build());
}
} else if (!sPorts.isEmpty() && !dPorts.isEmpty()) {
for (Long srcPort : sPorts) {
for (Long dstPort : dPorts) {
equalOrNotSetValidation(sctpMatch.getSctpSourcePort(), srcPort.longValue());
equalOrNotSetValidation(sctpMatch.getSctpDestinationPort(), dstPort.longValue());
- sctpMatches.add(new SctpMatchBuilder(sctpMatch).setSctpSourcePort(new PortNumber(srcPort.intValue()))
- .setSctpDestinationPort(new PortNumber(dstPort.intValue()))
- .build());
+ sctpMatches
+ .add(new SctpMatchBuilder(sctpMatch).setSctpSourcePort(new PortNumber(srcPort.intValue()))
+ .setSctpDestinationPort(new PortNumber(dstPort.intValue()))
+ .build());
}
}
}
private void equalOrNotSetValidation(PortNumber portInMatch, long paramValue) {
if (portInMatch != null) {
if (paramValue != portInMatch.getValue().longValue()) {
- throw new IllegalArgumentException("Classification conflict detected for port values "
+ throw new IllegalArgumentException(Classifier.MSG_CLASSIFICATION_CONFLICT_DETECTED + " for port values "
+ portInMatch.getValue().longValue() + " and " + paramValue + ". It is not allowed "
+ "to assign different values to the same parameter among all the classifiers within one rule.");
}
try {
proto = Long.valueOf(match.getIpMatch().getIpProtocol().longValue());
} catch (NullPointerException e) {
- throw new IllegalArgumentException("Parameter " + IpProtoClassifierDefinition.PROTO_PARAM + " is missing.");
+ throw new IllegalArgumentException(
+ "Parameter " + IpProtoClassifierDefinition.PROTO_PARAM + " " + MSG_IS_MISSING);
}
- if (!IpProtoClassifierDefinition.TCP_VALUE.equals(proto) && !IpProtoClassifierDefinition.UDP_VALUE.equals(proto)
+ if (!IpProtoClassifierDefinition.TCP_VALUE.equals(proto)
+ && !IpProtoClassifierDefinition.UDP_VALUE.equals(proto)
&& !IpProtoClassifierDefinition.SCTP_VALUE.equals(proto)) {
throw new IllegalArgumentException("Value of parameter " + IpProtoClassifierDefinition.PROTO_PARAM
- + " is not supported.");
+ + " is " + Classifier.MSG_NOT_SUPPORTED);
}
}
}
// TODO missing impl for case when classifier is changed or removed
}
- private Map<InstanceIdentifier<Classifier>, Classifier> resolveClassifiers(ResolvedPolicy resolvedPolicy,
+ // TODO move to some util class
+ public static Map<InstanceIdentifier<Classifier>, Classifier> resolveClassifiers(ResolvedPolicy resolvedPolicy,
InstanceIdentifier<ResolvedPolicy> resolvedPolicyIid) {
List<PolicyRuleGroupWithEndpointConstraints> policyRgWithEcs =
resolvedPolicy.getPolicyRuleGroupWithEndpointConstraints();
private static final Pattern REPLACE_PATTERN = Pattern.compile("^\\w+:(\\w+):.*");
static final String API_FLOW = "/flow/";
static final String SUFFIX_JSON = "/json";
+ static final String KEYS_SPLIT_REGEX = ",";
private transient Direction direction;
private String name;
private String[] keyNames;
private int keyNum;
- private FlowCache() {
- }
+ private FlowCache() {}
private FlowCache(FlowCacheBuilder builder) {
this.name = builder.getName();
this.definition = builder.getDefinition();
this.direction = builder.getDirection();
- this.keyNames = this.definition.getKeys().split(",");
+ this.keyNames = this.definition.getKeys().split(KEYS_SPLIT_REGEX);
this.keyNum = this.keyNames.length;
for (int i = 0; i < this.keyNum; i++) {
keyNames[i] = parseNullableKeyName(keyNames[i]);
public static class FlowCacheDefinitionBuilder {
- private String value;
+ private String value = "";
private boolean log = false;
private final FlowCacheKeysBuilder keysBuilder = new FlowCacheKeysBuilder();
private final FlowCacheFilterBuilder filterBuilder = new FlowCacheFilterBuilder();
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;
import java.util.List;
+import java.util.Objects;
import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition;
import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;
public static FlowCache createFlowCache(InstanceIdentifier<Classifier> classifierIid, Classifier classifier,
FlowCacheCons.Value value) {
- FlowCacheDefinition flowCacheDefinition = creteFlowCacheDefinition(classifier, value);
+ FlowCacheDefinition flowCacheDefinition = createFlowCacheDefinition(classifier, value);
if (flowCacheDefinition == null) {
LOG.info("Cannot create flow cache for statistics of classifier {}\n{}", classifierIid, classifier);
return null;
.build();
}
- public static FlowCacheDefinition creteFlowCacheDefinition(Classifier classifier, FlowCacheCons.Value value) {
+ public static FlowCacheDefinition createFlowCacheDefinition(Classifier classifier,
+ FlowCacheCons.Value value) {
FlowCacheDefinitionBuilder fcdBuilder = new FlowCacheDefinitionBuilder();
if (L4ClassifierDefinition.ID.equals(classifier.getClassifierDefinitionId())) {
addEthTypeInfoToFlowCache(classifier, fcdBuilder);
private static boolean addTcpUdpPortKeys(Long ipProto, Long port, boolean isDstPort,
FlowCacheDefinitionBuilder fcdBuilder) {
if (isDstPort) {
- if (ipProto == IpProtoClassifierDefinition.TCP_VALUE) {
+ if (Objects.equals(ipProto, IpProtoClassifierDefinition.TCP_VALUE)) {
fcdBuilder.getKeysBuilder().addValue(FlowCacheCons.Key.TCP_DST_PORT.get());
fcdBuilder.getFilterBuilder().addValue(FlowCacheCons.Key.TCP_DST_PORT.get() + FlowCacheCons.EQ + port);
- } else if (ipProto == IpProtoClassifierDefinition.UDP_VALUE) {
+ } else if (Objects.equals(ipProto, IpProtoClassifierDefinition.UDP_VALUE)) {
fcdBuilder.getKeysBuilder().addValue(FlowCacheCons.Key.UDP_DST_PORT.get());
fcdBuilder.getFilterBuilder().addValue(FlowCacheCons.Key.UDP_DST_PORT.get() + FlowCacheCons.EQ + port);
} else {
return false;
}
} else {
- if (ipProto == IpProtoClassifierDefinition.TCP_VALUE) {
+ if (Objects.equals(ipProto, IpProtoClassifierDefinition.TCP_VALUE)) {
fcdBuilder.getKeysBuilder().addValue(FlowCacheCons.Key.TCP_SRC_PORT.get());
fcdBuilder.getFilterBuilder().addValue(FlowCacheCons.Key.TCP_SRC_PORT.get() + FlowCacheCons.EQ + port);
- } else if (ipProto == IpProtoClassifierDefinition.UDP_VALUE) {
+ } else if (Objects.equals(ipProto, IpProtoClassifierDefinition.UDP_VALUE)) {
fcdBuilder.getKeysBuilder().addValue(FlowCacheCons.Key.UDP_SRC_PORT.get());
fcdBuilder.getFilterBuilder().addValue(FlowCacheCons.Key.UDP_SRC_PORT.get() + FlowCacheCons.EQ + port);
} else {
return values;
}
+ /**
+ * Sets FlowCache's "key" values by copying {@code String}s from {@code values},
+ * to avoid immutable list put as a parameter.
+ * {@code null}s are omitted.
+ *
+ * @param values List of String
+ * @return FlowCacheKeysBuilder
+ */
public FlowCacheKeysBuilder setValues(List<String> values) {
- this.values = Preconditions.checkNotNull(values);
+ Preconditions.checkNotNull(values);
+ for (String value : values) {
+ if (value != null) {
+ this.values.add(value);
+ }
+ }
return this;
}
List<Flow> flows = new ArrayList<>();\r
Action segReg = nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1L));\r
Action scgReg = nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0xffffff));\r
- Action bdReg = nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0L));\r
- Action fdReg = nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0L));\r
- Action vrfReg = nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0L));\r
+ Action bdReg = nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3L));\r
+ Action fdReg = nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4L));\r
+ Action vrfReg = nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5L));\r
for (L3Address address : networkElements.getDstEp().getL3Address()) {\r
Layer3Match l3Match = new Ipv4MatchBuilder().setIpv4Source(new Ipv4Prefix(address.getIpAddress()\r
.getIpv4Address().getValue() + IP_PREFIX_32)).build();\r
MatchBuilder matchBuilder = new MatchBuilder().setInPort(CONNECTOR_2);\r
addNxNsiMatch(matchBuilder, (short) 250);\r
addNxNspMatch(matchBuilder, 27L);\r
- addNxTunIdMatch(matchBuilder, 0);\r
+ addNxTunIdMatch(matchBuilder, 4);\r
Match match = matchBuilder.build();\r
FlowId flowId = FlowIdUtils.newFlowId((short) 2, "chainbroadcast", match);\r
FlowBuilder flowBuilder = base((short) 2).setId(flowId).setPriority(150).setMatch(match)\r
- .setInstructions(instructions(applyActionIns(nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0))),\r
+ .setInstructions(instructions(applyActionIns(nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4))),\r
gotoTableIns(ctx.getPolicyManager().getTABLEID_DESTINATION_MAPPER())));\r
return flowBuilder.build();\r
}\r
Action outputAction = FlowUtils.createActionResubmit(null, (short) 0);\r
\r
MatchBuilder matchBuilder = new MatchBuilder();\r
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, 0L));\r
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, 5L));\r
addNxTunIdMatch(matchBuilder, matchTunnelId);\r
addNxNspMatch(matchBuilder, 27L);\r
addNxNsiMatch(matchBuilder, (short) 255);\r
OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder();
ofOverlayContextBuilder.setNodeId(NODE_ID);
endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
- endpointBuilder.setNetworkContainment(NET_DOMAIN_ID);
+ endpointBuilder.setNetworkContainment(SUBNET_0);
endpointBuilder.setTenant(buildTenant().getId());
Endpoint endpoint = endpointBuilder.build();
groupTable.sync(endpoint, ofWriter);
verify(optionalFlowCapableNode, times(1)).isPresent();
- verify(ofWriter, times(1)).writeGroup(NODE_ID, new GroupId(0L));
+ verify(ofWriter, times(1)).writeGroup(NODE_ID, new GroupId(4L));
}
@Test
NodeId nodeWithoutTunnel = new NodeId("nodeIdWithoutTunnel");
NodeId nodeIdIpV6 = new NodeId("nodeIdIpV6");
NodeId nodeIdIpV4 = new NodeId("nodeIdIpV4");
- Endpoint endpoint = buildEndpoint(IPV4_0, MAC_0, new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue())).build();
+ Endpoint endpoint = buildEndpoint(IPV4_0, MAC_0, new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue()))
+ .build();
when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant());
when(ctx.getEndpointManager()).thenReturn(endpointManager);
@Test
public void syncGroups_externalEpsWithoutLocation() throws Exception {
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_0, new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue()));
- endpointBuilder.setNetworkContainment(L2FD_ID);
+ endpointBuilder.setNetworkContainment(SUBNET_1);
Endpoint endpoint = endpointBuilder.build();
when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant());
// Endpoints
Collection<Endpoint> endpoints = new HashSet<>();
EndpointBuilder noLocEndpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1);
- noLocEndpointBuilder.setNetworkContainment(L2FD_ID);
endpoints.add(noLocEndpointBuilder.build());
when(ctx.getSwitchManager()).thenReturn(switchManager);
protected static final EndpointGroupId ENDPOINT_GROUP_0 = new EndpointGroupId("eg0");\r
protected static final EndpointGroupId ENDPOINT_GROUP_1 = new EndpointGroupId("eg1");\r
protected static final EndpointGroupId ENDPOINT_GROUP_2 = new EndpointGroupId("eg2");\r
- protected static final NetworkDomainId NET_DOMAIN_ID = new NetworkDomainId("ndId");\r
+ protected static final SubnetId NET_DOMAIN_ID = new SubnetId("ndId");\r
protected static final L2BridgeDomainId L2BD_ID = new L2BridgeDomainId("l2bdId");\r
protected static final L2FloodDomainId L2FD_ID = new L2FloodDomainId("l2fdId");\r
protected static final L2FloodDomainId L2_FD_ID_EXT = new L2FloodDomainId("externalL2fdId");\r
if (l2bd != null) {\r
endpointL3Builder.setL2Context(new L2BridgeDomainId(l2bd));\r
}\r
+ if(ip.equals(IPV4_0)) {\r
+ endpointL3Builder.setNetworkContainment(SUBNET_0);\r
+ }\r
+ else if(ip.equals(IPV4_1)) {\r
+ endpointL3Builder.setNetworkContainment(SUBNET_1);\r
+ }\r
+ else if(ip.equals(IPV4_2)) {\r
+ endpointL3Builder.setNetworkContainment(SUBNET_2);\r
+ }\r
return endpointL3Builder;\r
}\r
\r
endpointBuilder.setL2Context(new L2BridgeDomainId(L2BD_ID));\r
endpointBuilder.setEndpointGroup(ENDPOINT_GROUP_0);\r
endpointBuilder.addAugmentation(OfOverlayContext.class, getOfOverlayContext(connector).build());\r
- endpointBuilder.setNetworkContainment(NET_DOMAIN_ID);\r
+ if(l3IpAddress.equals(IPV4_0)) {\r
+ endpointBuilder.setNetworkContainment(SUBNET_0);\r
+ }\r
+ else if(l3IpAddress.equals(IPV4_1)) {\r
+ endpointBuilder.setNetworkContainment(SUBNET_1);\r
+ }\r
+ else if(l3IpAddress.equals(IPV4_2)) {\r
+ endpointBuilder.setNetworkContainment(SUBNET_2);\r
+ }\r
return endpointBuilder;\r
}\r
\r
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createExternalL2Flow(tableId, 100, endpointBuilder.build(), externalConnectors, ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_1.getValue()));
Endpoint endpoint = endpointBuilder.build();
+
MatchBuilder matchBuilder = new MatchBuilder()
.setEthernetMatch(ethernetMatch(null, endpoint.getMacAddress(), null));
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 0));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 3));
Match match = matchBuilder.build();
List<Action> applyActions = new ArrayList<>();
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createExternalL2Flow(tableId, 100, endpointBuilder.build(), externalConnectors, ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors,
ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
Endpoint gateway = gatewayBuilder.build();
Endpoint endpoint = endpointBuilder.build();
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
- l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_0)));
+ l3AddressBuilder.setIpAddress(new IpAddress(IPV4_0));
Set<NodeConnectorId> externalConnectors = new HashSet<>();
externalConnectors.add(new NodeConnectorId(CONNECTOR_0));
externalConnectors.add(new NodeConnectorId(CONNECTOR_1));
flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors,
ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
Endpoint gateway = gatewayBuilder.build();
Endpoint endpoint = endpointBuilder.build();
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
- l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_0)));
+ l3AddressBuilder.setIpAddress(new IpAddress(IPV4_0));
Set<NodeConnectorId> externalConnectors = new HashSet<>();
externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue()));
externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_1.getValue()));
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlSrcAction(new MacAddress(MAC_0)));
- l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0)));
+ l3ApplyActions.add(setDlSrcAction(MAC_0));
+ l3ApplyActions.add(setDlDstAction(MAC_0));
List<Action> applyActions = new ArrayList<>();
applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1)));
applyActions.add(nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(0)));
MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, MAC_1, IPv4))
.setLayer3Match(new Ipv4MatchBuilder()
.setIpv4Destination(new Ipv4Prefix(IPV4_0.getValue() + IP_PREFIX_32)).build());
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
int order = 0;
flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors,
ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
externalConnectors.add(new NodeConnectorId(OPENFLOW + CONNECTOR_1.getValue()));
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlSrcAction(new MacAddress(MAC_0)));
- l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0)));
+ l3ApplyActions.add(setDlSrcAction(MAC_0));
+ l3ApplyActions.add(setDlDstAction(MAC_0));
List<Action> applyActions = new ArrayList<>();
applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1)));
applyActions.add(nxLoadRegAction(NxmNxReg3.class, BigInteger.valueOf(0)));
flows.createExternalL3RoutedFlow(tableId, 90, endpoint, gateway, l3AddressBuilder.build(), externalConnectors,
ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
flows.createLocalL2Flow(tableId, 80, endpoint, ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
public void createLocalL2Flow() {
NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue());
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_0, connectorId);
+ endpointBuilder.setNetworkContainment(SUBNET_0);
Endpoint endpoint = endpointBuilder.build();
List<Action> applyActions = new ArrayList<>();
MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, endpoint.getMacAddress(),
null));
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 0));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 3));
Match match = matchBuilder.build();
Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "localL2", match), tableId, 80, match,
flows.createLocalL2Flow(tableId, 80, endpoint, ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder();
ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_1));
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, connectorId);
+ endpointBuilder.setNetworkContainment(SUBNET_0);
endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId());
endpointBuilder.setMacAddress(null);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(SUBNET_0));
+ destSubnetBuilder.setId(SUBNET_1);
Subnet destSubnet = destSubnetBuilder.build();
when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant());
ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_1));
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, connectorId);
endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
+ endpointBuilder.setNetworkContainment(SUBNET_0);
endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId());
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(L3C_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant());
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
+ localSubnetBuilder.setId(SUBNET_0).setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(CONTEXT_ID));
+ destSubnetBuilder.setId(SUBNET_1);
Subnet destSubnet = destSubnetBuilder.build();
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createLocalL3RoutedFlow(tableId, 80, endpoint, l3Address, localSubnet, destSubnet, ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, connectorId);
endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId());
+ endpointBuilder.setNetworkContainment(SUBNET_0);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(CONTEXT_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
- l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_0)));
+ l3AddressBuilder.setIpAddress(new IpAddress((IPV4_0)));
L3Address l3Address = l3AddressBuilder.build();
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlDstAction((new MacAddress(MAC_1))));
+ l3ApplyActions.add(setDlDstAction((MAC_1)));
l3ApplyActions.add(decNwTtlAction());
l3ApplyActions.add(setDlSrcAction(destMac));
l3instructions.add(applyActionsIns);
l3instructions.add(gotoTable);
- MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, new MacAddress(destMac), IPv4))
+ MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, destMac, IPv4))
.setLayer3Match(new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(IPV4_0.getValue() + IP_PREFIX_32)).build());
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
instructionsBuilder.setInstruction(l3instructions);
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createLocalL3RoutedFlow(tableId, 80, endpoint, l3Address, localSubnet, destSubnet, ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1,MAC_1, connectorId);
endpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
endpointBuilder.setTenant(getTestIndexedTenant().getTenant().getId());
+ endpointBuilder.setNetworkContainment(SUBNET_0);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(CONTEXT_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
- l3AddressBuilder.setIpAddress(new IpAddress(new Ipv6Address(IPV6_1)));
+ l3AddressBuilder.setIpAddress(new IpAddress((IPV6_1)));
L3Address l3Address = l3AddressBuilder.build();
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlDstAction((new MacAddress(MAC_1))));
+ l3ApplyActions.add(setDlDstAction(MAC_1));
l3ApplyActions.add(decNwTtlAction());
l3ApplyActions.add(setDlSrcAction(destMac));
l3instructions.add(applyActionsIns);
l3instructions.add(gotoTable);
- MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, new MacAddress(destMac), IPv6))
+ MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, destMac, IPv6))
.setLayer3Match(new Ipv6MatchBuilder().setIpv6Destination(new Ipv6Prefix(IPV6_1.getValue() + IP_PREFIX_128)).build());
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
instructionsBuilder.setInstruction(l3instructions);
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createLocalL3RoutedFlow(tableId, 80, endpoint, l3Address, localSubnet, destSubnet, ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
flows.createRemoteL2Flow(tableId, 70, endpointBuilder.build(), null, null, new NodeConnectorId(CONNECTOR_1),
ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
instructionsBuilder.setInstruction(instructions);
MatchBuilder matchBuilder = new MatchBuilder()
- .setEthernetMatch(ethernetMatch(null, new MacAddress(MAC_0), null));
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 0));
+ .setEthernetMatch(ethernetMatch(null, MAC_0, null));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg4.class, (long) 3));
Match match = matchBuilder.build();
Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "remoteL2", match), tableId, 70, match,
flows.createRemoteL2Flow(tableId, 70, endpointBuilder.build(), peerEndpointBuilder.build(), ipAddress,
connectorId, ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
flows.createRemoteL2Flow(tableId, 70, endpointBuilder.build(), peerEndpointBuilder.build(), ipAddress,
connectorId, ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(L3C_ID));
+ destSubnetBuilder.setId(SUBNET_0);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1)));
+ localSubnetBuilder.setId(SUBNET_1);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1));
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant());
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, null, destSubnet, null, null, localSubnet, ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(2)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
@Test
public void createRemoteL3RoutedFlow_noIp() {
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1, MAC_1, CONNECTOR_0);
+ endpointBuilder.setNetworkContainment(SUBNET_0);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(L3C_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1)));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1));
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant());
when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, null, destSubnet, null, null, localSubnet, ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
@Test
public void createRemoteL3RoutedFlow_incorrectPortId() {
- IpAddress ipAddress = new IpAddress(new Ipv4Address(IPV4_0));
+ IpAddress ipAddress = new IpAddress(IPV4_0);
NodeConnectorId connectorId = new NodeConnectorId(CONNECTOR_0);
EndpointBuilder endpointBuilder = buildEndpoint(IPV6_1,MAC_1,CONNECTOR_0);
+ endpointBuilder.setNetworkContainment(SUBNET_0);
Endpoint endpoint = endpointBuilder.build();
+
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(L3C_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(SUBNET_0));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1)));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1));
Subnet localSubnet = localSubnetBuilder.build();
when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant());
flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, null, destSubnet, ipAddress, connectorId, localSubnet,
ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
@Test
public void createRemoteL3RoutedFlow_ipV4() {
MacAddress routerMac = DestinationMapper.ROUTER_MAC;
- IpAddress ipAddress = new IpAddress(new Ipv4Address(IPV4_1));
+ IpAddress ipAddress = new IpAddress(IPV4_1);
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
- l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_1)));
+ l3AddressBuilder.setIpAddress(new IpAddress(IPV4_1));
L3Address l3Address = l3AddressBuilder.build();
NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue());
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_1, CONNECTOR_0);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(L3C_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(SUBNET_0));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1)));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1));
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlSrcAction(new MacAddress(routerMac)));
- l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_1)));
+ l3ApplyActions.add(setDlSrcAction(routerMac));
+ l3ApplyActions.add(setDlDstAction(MAC_1));
l3ApplyActions.add(decNwTtlAction());
List<Action> applyActions = new ArrayList<>();
applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1)));
InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
instructionsBuilder.setInstruction(l3instructions);
- MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, new MacAddress(routerMac), IPv4))
+ MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, routerMac, IPv4))
.setLayer3Match(new Ipv4MatchBuilder().setIpv4Destination(new Ipv4Prefix(IPV4_1.getValue() + IP_PREFIX_32)).build());
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "remoteL3", match), tableId, 60, match,
flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, l3Address, destSubnet, ipAddress, connectorId, localSubnet,
ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(eq(NODE_ID), eq(tableId), eq(flow));
public void createRemoteL3RoutedFlow_ipV6() {
IpAddress ipAddress = new IpAddress(new Ipv6Address(IPV6_1));
L3AddressBuilder l3AddressBuilder = new L3AddressBuilder();
- l3AddressBuilder.setIpAddress(new IpAddress(new Ipv4Address(IPV4_1)));
+ l3AddressBuilder.setIpAddress(new IpAddress(IPV4_1));
L3Address l3Address = l3AddressBuilder.build();
NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0);
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_1, CONNECTOR_0);
Endpoint endpoint = endpointBuilder.build();
SubnetBuilder destSubnetBuilder = new SubnetBuilder();
- destSubnetBuilder.setId(new SubnetId(L3C_ID));
+ destSubnetBuilder.setId(SUBNET_1);
+ destSubnetBuilder.setParent(L2FD_ID);
Subnet destSubnet = destSubnetBuilder.build();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(SUBNET_0));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_1)));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setParent(L2FD_ID);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_1));
Subnet localSubnet = localSubnetBuilder.build();
when(ctx.getTenant(Mockito.any(TenantId.class))).thenReturn(getTestIndexedTenant());
flows.createRemoteL3RoutedFlow(tableId, 60, endpoint, l3Address, destSubnet, ipAddress, connectorId, localSubnet,
ofWriter);
- verify(ctx, times(3)).getTenant(any(TenantId.class));
+ verify(ctx, times(4)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verifyZeroInteractions(ofWriter);
public void createRouterArpFlow_ipV4() throws Exception {
IndexedTenant tenant = getTestIndexedTenant();
SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(L3C_ID));
- subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0)));
+ subnetBuilder.setId(SUBNET_0);
+ subnetBuilder.setParent(L2FD_ID);
+ subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_0));
MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null, null, ARP))
.setLayer3Match(new ArpMatchBuilder().setArpOp(1)
.setArpTargetTransportAddress(new Ipv4Prefix(IPV4_0.getValue() + IP_PREFIX_32)).build());
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 1));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
List<Action> actions = new ArrayList<>();
actions.add(nxMoveEthSrcToEthDstAction());
- actions.add(setDlSrcAction(new MacAddress(DestinationMapper.ROUTER_MAC)));
+ actions.add(setDlSrcAction(DestinationMapper.ROUTER_MAC));
actions.add(nxLoadArpOpAction(BigInteger.valueOf(2L)));
actions.add(nxMoveArpShaToArpThaAction());
actions.add(nxLoadArpShaAction(new BigInteger(1, bytesFromHexString(DestinationMapper.ROUTER_MAC.getValue()))));
public void createRouterArpFlow_ipV6() throws Exception {
IndexedTenant tenant = getTestIndexedTenant();
SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(L3C_ID));
- subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv6Address(IPV6_1)));
+ subnetBuilder.setId(SUBNET_1);
+ subnetBuilder.setParent(L2FD_ID);
+ subnetBuilder.setVirtualRouterIp(new IpAddress(IPV6_1));
when(ctx.getEndpointManager()).thenReturn(endpointManager);
OrdinalFactory.EndpointFwdCtxOrdinals ordinals = utils.getEndpointOrdinals(endpointBuilder.build());
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(1)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
MatchBuilder matchBuilder = new MatchBuilder()
.setEthernetMatch(new EthernetMatchBuilder()
- .setEthernetDestination(new EthernetDestinationBuilder().setAddress(new MacAddress(MAC_0))
- .setMask(new MacAddress(MAC_0)).build())
+ .setEthernetDestination(new EthernetDestinationBuilder().setAddress(MAC_0)
+ .setMask(MAC_0).build())
.build());
addNxRegMatch(matchBuilder, FlowUtils.RegMatch.of(NxmNxReg5.class, (long) ordinals.getFdId()));
Match match = matchBuilder.build();
Flow flow = buildFlow(FlowIdUtils.newFlowId(tableId, "broadcast", match), tableId, 40, match,
instructionsBuilder.build()).build();
- flows.createBroadcastFlow(40, ordinals, new MacAddress(MAC_0), ofWriter);
+ flows.createBroadcastFlow(40, ordinals, MAC_0, ofWriter);
verify(ofWriter, times(1)).writeFlow(any(NodeId.class), anyShort(), eq(flow));
}
IndexedTenant tenant = getTestIndexedTenant();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0)));
+ localSubnetBuilder.setId(SUBNET_1);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress((IPV4_0)));
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
when(ctx.getEndpointManager()).thenReturn(endpointManager);
@Test
public void createL3PrefixFlow_externalExceptionCaught() {
EndpointBuilder gatewayEpBuilder = buildEndpoint(IPV4_0, MAC_0, CONNECTOR_0);
-
OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder();
ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_1));
gatewayEpBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
IndexedTenant tenant = new IndexedTenant(tenantBuilder.build());
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0)));
+ localSubnetBuilder.setId(SUBNET_1);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_0));
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
Set<NodeConnectorId> externalPorts = new HashSet<>();
IndexedTenant tenant = getTestIndexedTenant();
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_0)));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setParent(L2FD_ID);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_0));
Subnet localSubnet = localSubnetBuilder.build();
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0)));
+ l3ApplyActions.add(setDlDstAction(MAC_0));
l3ApplyActions.add(decNwTtlAction());
List<Action> applyActions = new ArrayList<>();
applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1)));
instructionsBuilder.setInstruction(l3instructions);
MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null,
- new MacAddress(DestinationMapper.ROUTER_MAC), IPv4));
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0));
+ DestinationMapper.ROUTER_MAC, IPv4));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
Integer prefixLength = Integer.valueOf(l3Prefix.getIpPrefix().getIpv4Prefix().getValue().split("/")[1]);
flows.createL3PrefixFlow(tableId, 30, gatewayEp.build(), l3Prefix, tenant, localSubnet, null,
ofWriter);
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(2)).getEndpointManager();
verify(ctx, times(1)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(any(NodeId.class), anyShort(), eq(flow));
public void createL3PrefixFlow_externalIpv6() throws Exception {
NodeConnectorId connectorId = new NodeConnectorId(OPENFLOW + CONNECTOR_0.getValue());
EndpointBuilder gatewayEpBuilder = buildEndpoint(IPV6_1, MAC_0, connectorId);
+ gatewayEpBuilder.setNetworkContainment(SUBNET_0);
OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder();
ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(OPENFLOW + CONNECTOR_1));
IndexedTenant tenant = new IndexedTenant(tenantBuilder.build());
SubnetBuilder localSubnetBuilder = new SubnetBuilder();
- localSubnetBuilder.setId(new SubnetId(L3C_ID));
- localSubnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv6Address(IPV6_2)));
+ localSubnetBuilder.setId(SUBNET_0);
+ localSubnetBuilder.setVirtualRouterIp(new IpAddress(IPV6_2));
+ localSubnetBuilder.setParent(L2FD_ID);
Subnet localSubnet = localSubnetBuilder.build();
Set<NodeConnectorId> externalPorts = new HashSet<>();
EndpointL3Prefix l3Prefix = l3PrefixBuilder.build();
List<Action> l3ApplyActions = new ArrayList<>();
- l3ApplyActions.add(setDlDstAction(new MacAddress(MAC_0)));
+ l3ApplyActions.add(setDlDstAction(MAC_0));
l3ApplyActions.add(decNwTtlAction());
List<Action> applyActions = new ArrayList<>();
applyActions.add(nxLoadRegAction(NxmNxReg2.class, BigInteger.valueOf(1)));
instructionsBuilder.setInstruction(l3instructions);
MatchBuilder matchBuilder = new MatchBuilder().setEthernetMatch(ethernetMatch(null,
- new MacAddress(DestinationMapper.ROUTER_MAC), IPv6));
- addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 0));
+ DestinationMapper.ROUTER_MAC, IPv6));
+ addNxRegMatch(matchBuilder, RegMatch.of(NxmNxReg6.class, (long) 5));
Match match = matchBuilder.build();
Integer prefixLength = Integer.valueOf(l3Prefix.getIpPrefix().getIpv6Prefix().getValue().split("/")[1]);
flows.createL3PrefixFlow(tableId, 30, gatewayEpBuilder.build(), l3Prefix, tenant, localSubnet, externalPorts,
ofWriter);
- verify(ctx, times(4)).getTenant(any(TenantId.class));
+ verify(ctx, times(6)).getTenant(any(TenantId.class));
verify(ctx, times(3)).getEndpointManager();
verify(ctx, times(2)).getCurrentPolicy();
verify(ofWriter, times(1)).writeFlow(any(NodeId.class), anyShort(), eq(flow));
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContextId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2FloodDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L3ContextId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.NetworkDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubnetId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.TenantBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.ForwardingContextBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.PolicyBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomain;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2BridgeDomainBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomain;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L2FloodDomainBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3Context;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.L3ContextBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.forwarding.context.Subnet;
destinationMapper.syncFlows(flows, endpointBuilder.build(), null, ofWriter);
// Verify usage
- verify(ctx, times(2)).getTenant(any(TenantId.class));
+ verify(ctx, times(3)).getTenant(any(TenantId.class));
verify(ctx, times(5)).getEndpointManager();
verify(ctx, times(2)).getPolicyManager();
verify(ctx, times(2)).getCurrentPolicy();
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1);
// Peer endpoint
EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0);
+ peerEndpointBuilder.setNetworkContainment(new SubnetId(SUBNET_1));
// External Implicit groups
List<ExternalImplicitGroup> externalImplicitGroups = new ArrayList<>();
ExternalImplicitGroupBuilder externalImplicitGroupBuilder = new ExternalImplicitGroupBuilder();
destinationMapper.syncEndpointFlows(flows, NODE_ID, endpointBuilder.build(), ofWriter);
// Verify usage
- verify(ctx, times(11)).getTenant(any(TenantId.class));
- verify(ctx, times(6)).getEndpointManager();
+ verify(ctx, times(14)).getTenant(any(TenantId.class));
+ verify(ctx, times(7)).getEndpointManager();
verify(ctx, times(1)).getPolicyManager();
verify(ctx, times(4)).getCurrentPolicy();
verify(flows, times(1)).createExternalL2Flow(anyShort(), anyInt(), any(Endpoint.class),
// Endpoint
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1);
endpointBuilder.setL3Address(getL3AddressList(IPV4_1, L3C_ID));
- endpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0));
Endpoint endpoint = endpointBuilder.build();
// Peer
EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0);
- peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0));
// External implicit groups
List<Subnet> subnets = new ArrayList<>();
SubnetBuilder subnetBuilder = new SubnetBuilder();
forwardingContextBuilder.setSubnet(subnets);
forwardingContextBuilder.setL3Context(l3Contexts);
TenantBuilder peerTenantBuilder = buildTenant();
- peerTenantBuilder.setForwardingContext(forwardingContextBuilder.build());
+ peerTenantBuilder.setForwardingContext(buildTenant().getForwardingContext());
peerTenantBuilder.setPolicy(new PolicyBuilder()
.setSubjectFeatureInstances(getSubjectFeatureInstances())
.setEndpointGroup(getEndpointGroups())
.setExternalImplicitGroup(externalImplicitGroups)
.build());
Tenant peerTenant = peerTenantBuilder.build();
- peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_1));
Endpoint peerEndpoint = peerEndpointBuilder.build();
Collection<Endpoint> peerEndpoints = new ArrayList<>();
peerEndpoints.add(peerEndpoint);
destinationMapper.syncEndpointFlows(flows, NODE_ID, endpoint, ofWriter);
// Verify usage
- verify(ctx, times(13)).getTenant(any(TenantId.class));
+ verify(ctx, times(16)).getTenant(any(TenantId.class));
verify(ctx, times(9)).getEndpointManager();
verify(ctx, times(1)).getPolicyManager();
verify(ctx, times(4)).getCurrentPolicy();
endpointBuilder.setNetworkContainment(SUBNET_0);
// Peer
EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0);
+ peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0));
// Subnets, l3Context and forwarding context
- List<Subnet> subnets = new ArrayList<>();
- SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(SUBNET_0));
- subnetBuilder.setParent(new ContextId(L3C_ID));
- subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_2)));
- subnets.add(subnetBuilder.build());
List<L3Context> l3Contexts = new ArrayList<>();
L3ContextBuilder l3ContextBuilder = new L3ContextBuilder();
l3ContextBuilder.setId(L3C_ID);
l3Contexts.add(l3ContextBuilder.build());
+
+ List<L2BridgeDomain> l2BDomains = new ArrayList<>();
+ L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder();
+ l2bdBuilder.setId(L2BD_ID);
+ l2bdBuilder.setParent(L3C_ID);
+ l2BDomains.add(l2bdBuilder.build());
+
+ List<L2FloodDomain> l2FDomains = new ArrayList<>();
+ L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder();
+ l2fdBuilder.setId(L2FD_ID);
+ l2fdBuilder.setParent(L2BD_ID);
+ l2FDomains.add(l2fdBuilder.build());
+
+ List<Subnet> subnets = new ArrayList<>();
+ SubnetBuilder subnetBuilder = new SubnetBuilder();
+ subnetBuilder.setId(SUBNET_0);
+ subnetBuilder.setParent(L2FD_ID);
+ subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2));
+ subnets.add(subnetBuilder.build());
+
ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder();
forwardingContextBuilder.setSubnet(subnets);
forwardingContextBuilder.setL3Context(l3Contexts);
+ forwardingContextBuilder.setL2BridgeDomain(l2BDomains);
+ forwardingContextBuilder.setL2FloodDomain(l2FDomains);
TenantBuilder peerTenantBuilder = new TenantBuilder(getTestIndexedTenant().getTenant());
- peerTenantBuilder.setForwardingContext(forwardingContextBuilder.build());
+ peerTenantBuilder.setForwardingContext(buildTenant().getForwardingContext());
Tenant peerTenant = peerTenantBuilder.build();
- peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0));
Endpoint peerEndpoint = peerEndpointBuilder.build();
Collection<Endpoint> peerEndpoints = new ArrayList<>();
peerEndpoints.add(peerEndpoint);
destinationMapper.syncFlows(flows, endpointBuilder.build(), NODE_ID, ofWriter);
// Verify usage
- verify(ctx, times(18)).getTenant(any(TenantId.class));
+ verify(ctx, times(24)).getTenant(any(TenantId.class));
verify(ctx, times(9)).getEndpointManager();
verify(ctx, times(2)).getPolicyManager();
verify(ctx, times(4)).getCurrentPolicy();
// Peer
EndpointBuilder peerEndpointBuilder = buildEndpoint(IPV4_2, MAC_0, CONNECTOR_0);
// Subnets, l3Context and forwarding context
- List<Subnet> subnets = new ArrayList<>();
- SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(SUBNET_0));
- subnetBuilder.setParent(new ContextId(L3C_ID));
- subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_2)));
- subnets.add(subnetBuilder.build());
+
List<L3Context> l3Contexts = new ArrayList<>();
L3ContextBuilder l3ContextBuilder = new L3ContextBuilder();
l3ContextBuilder.setId(L3C_ID);
l3Contexts.add(l3ContextBuilder.build());
+ List<L2BridgeDomain> l2BDomains = new ArrayList<>();
+ L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder();
+ l2bdBuilder.setId(L2BD_ID);
+ l2bdBuilder.setParent(L3C_ID);
+ l2BDomains.add(l2bdBuilder.build());
+ List<L2FloodDomain> l2FDomains = new ArrayList<>();
+ L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder();
+ l2fdBuilder.setId(L2FD_ID);
+ l2fdBuilder.setParent(L2BD_ID);
+ l2FDomains.add(l2fdBuilder.build());
+ List<Subnet> subnets = new ArrayList<>();
+ SubnetBuilder subnetBuilder = new SubnetBuilder();
+ subnetBuilder.setId(SUBNET_0);
+ subnetBuilder.setParent(L2FD_ID);
+ subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2));
+ subnets.add(subnetBuilder.build());
ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder();
forwardingContextBuilder.setSubnet(subnets);
forwardingContextBuilder.setL3Context(l3Contexts);
+ forwardingContextBuilder.setL2BridgeDomain(l2BDomains);
+ forwardingContextBuilder.setL2FloodDomain(l2FDomains);
TenantBuilder peerTenantBuilder = buildTenant();
peerTenantBuilder.setForwardingContext(forwardingContextBuilder.build());
Tenant peerTenant = peerTenantBuilder.build();
OfOverlayContextBuilder ofOverlayContextBuilder = new OfOverlayContextBuilder();
ofOverlayContextBuilder.setNodeConnectorId(new NodeConnectorId(CONNECTOR_0));
ofOverlayContextBuilder.setNodeId(new NodeId("remoteNodeID"));
- peerEndpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0));
+ peerEndpointBuilder.setNetworkContainment(SUBNET_0);
+ endpointBuilder.setNetworkContainment(SUBNET_0);
peerEndpointBuilder.addAugmentation(OfOverlayContext.class, ofOverlayContextBuilder.build());
Endpoint peerEndpoint = peerEndpointBuilder.build();
Collection<Endpoint> peerEndpoints = new ArrayList<>();
destinationMapper.syncEndpointFlows(flows, NODE_ID, endpointBuilder.build(), ofWriter);
// Verify usage
- verify(ctx, times(13)).getTenant(any(TenantId.class));
- verify(ctx, times(5)).getEndpointManager();
+ verify(ctx, times(15)).getTenant(any(TenantId.class));
+ verify(ctx, times(6)).getEndpointManager();
verify(ctx, times(1)).getPolicyManager();
verify(ctx, times(3)).getCurrentPolicy();
l3ContextBuilder.setId(L3C_ID);
l3Contexts.add(l3ContextBuilder.build());
HashSet<Subnet> subnets = new HashSet<>();
+ List<L2BridgeDomain> l2BDomains = new ArrayList<>();
+ L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder();
+ l2bdBuilder.setId(L2BD_ID);
+ l2bdBuilder.setParent(L3C_ID);
+ l2BDomains.add(l2bdBuilder.build());
+ List<L2FloodDomain> l2FDomains = new ArrayList<>();
+ L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder();
+ l2fdBuilder.setId(L2FD_ID);
+ l2fdBuilder.setParent(L2BD_ID);
+ l2FDomains.add(l2fdBuilder.build());
SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(SUBNET_0));
- subnetBuilder.setParent(new ContextId(L3C_ID));
- subnetBuilder.setVirtualRouterIp(new IpAddress(new Ipv4Address(IPV4_2)));
+ subnetBuilder.setId(SUBNET_0);
+ subnetBuilder.setParent(L2FD_ID);
+ subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2));
subnets.add(subnetBuilder.build());
ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder();
forwardingContextBuilder.setSubnet(new ArrayList<>(subnets));
forwardingContextBuilder.setL3Context(l3Contexts);
+ forwardingContextBuilder.setL2BridgeDomain(l2BDomains);
+ forwardingContextBuilder.setL2FloodDomain(l2FDomains);
TenantBuilder tenantBuilder = buildTenant();
tenantBuilder.setForwardingContext(forwardingContextBuilder.build());
Tenant tenant = tenantBuilder.build();
L3ContextBuilder l3ContextBuilder = new L3ContextBuilder();
l3ContextBuilder.setId(L3C_ID);
l3Contexts.add(l3ContextBuilder.build());
+ List<L2BridgeDomain> l2BDomains = new ArrayList<>();
+ L2BridgeDomainBuilder l2bdBuilder = new L2BridgeDomainBuilder();
+ l2bdBuilder.setId(L2BD_ID);
+ l2bdBuilder.setParent(L3C_ID);
+ l2BDomains.add(l2bdBuilder.build());
+ List<L2FloodDomain> l2FDomains = new ArrayList<>();
+ L2FloodDomainBuilder l2fdBuilder = new L2FloodDomainBuilder();
+ l2fdBuilder.setId(L2FD_ID);
+ l2fdBuilder.setParent(L2BD_ID);
+ l2FDomains.add(l2fdBuilder.build());
HashSet<Subnet> subnets = new HashSet<>();
SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(SUBNET_0));
- subnetBuilder.setParent(new ContextId(L3C_ID));
+ subnetBuilder.setId(SUBNET_0);
+ subnetBuilder.setParent(L2FD_ID);
subnetBuilder.setVirtualRouterIp(new IpAddress(IPV4_2));
subnets.add(subnetBuilder.build());
+
ForwardingContextBuilder forwardingContextBuilder = new ForwardingContextBuilder();
forwardingContextBuilder.setL3Context(l3Contexts);
forwardingContextBuilder.setSubnet(new ArrayList<>(subnets));
+ forwardingContextBuilder.setL2BridgeDomain(l2BDomains);
+ forwardingContextBuilder.setL2FloodDomain(l2FDomains);
TenantBuilder tenantBuilder = buildTenant();
tenantBuilder.setForwardingContext(forwardingContextBuilder.build());
Tenant tenant = tenantBuilder.build();
Collection<Endpoint> endpoints = new ArrayList<>();
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1);
- endpointBuilder.setNetworkContainment(new NetworkDomainId(SUBNET_0));
+ endpointBuilder.setNetworkContainment(SUBNET_0);
Endpoint endpoint = endpointBuilder.build();
endpoints.add(endpoint);
destinationMapper.syncL3PrefixFlow(flows, l3Prefixes, null, NODE_ID, ofWriter);
- verify(ctx, times(5)).getTenant(any(TenantId.class));
+ verify(ctx, times(6)).getTenant(any(TenantId.class));
verify(ctx, times(4)).getEndpointManager();
verify(ctx, times(1)).getSwitchManager();
verify(ctx, times(1)).getPolicyManager();
@Test
public void getL3ContextForSubnet_l3Context() {
SubnetBuilder subnetBuilder = new SubnetBuilder();
- subnetBuilder.setId(new SubnetId(L3C_ID));
+ subnetBuilder.setId(SUBNET_0);
+ subnetBuilder.setParent(L2FD_ID);
// expected result
L3ContextBuilder expectedL3Context = new L3ContextBuilder();
TenantBuilder tenantBuilder = new TenantBuilder(buildTenant().build());
Tenant tenant = tenantBuilder.build();
epWithSubnet.setTenant(tenant.getId());
- epWithSubnet.setNetworkContainment(new NetworkDomainId(SUBNET_0));
epWithSubnet.setTenant(tenant.getId());
- epWithSubnet.setNetworkContainment(new NetworkDomainId(SUBNET_1));
endpoints.add(epWithoutSubnet.build());
endpoints.add(epWithSubnet.build());
OrdinalFactory.EndpointFwdCtxOrdinals ordinals = utils.getEndpointOrdinals(endpointBuilder.build());
assertEquals(ordinals.getEp().toString(), new EpKey(new L2ContextId(L2BD_ID), new MacAddress(MAC_0)).toString());
- assertEquals(ordinals.getNetworkContainment(), NET_DOMAIN_ID);
+ assertEquals(ordinals.getNetworkContainment(), SUBNET_0);
}
@Test
Tenant tenant = tenantBuilder.build();
// L2 Endpoint
EndpointBuilder endpointBuilder = buildEndpoint(IPV4_0, MAC_0, CONNECTOR_0)
- .setNetworkContainment(L2_FD_ID_EXT)
.setL2Context(L2BD_ID);
// L3 Endpoint with Nat
EndpointL3Builder endpointL3Builder = buildL3Endpoint(natAddr, IPV4_1, MAC_0, null)
mapper.sync(endpointBuilder.build(), ofWriter);
- verify(ofWriter, times(4)).writeFlow(any(NodeId.class), any(Short.class), any(Flow.class));
+ verify(ofWriter, times(3)).writeFlow(any(NodeId.class), any(Short.class), any(Flow.class));
}
@Test
when(ctx.getEndpointManager()).thenReturn(endpointManager);
when(ctx.getTenant(any(TenantId.class))).thenReturn(getTestIndexedTenant());
+ when(ctx.getCurrentPolicy()).thenReturn(policyInfo);
+ when(ctx.getSwitchManager()).thenReturn(switchManager);
when(endpointManager.getEndpointNodeId(any(Endpoint.class))).thenReturn(NODE_ID);
mapper.sync(endpointBuilder.build(), ofWriter);
InOrder order = inOrder(ctx);
order.verify(ctx, times(1)).getEndpointManager();
order.verify(ctx, times(1)).getCurrentPolicy();
- verify(ctx, times(2)).getTenant(TENANT_ID);
+ verify(ctx, times(3)).getTenant(TENANT_ID);
assertNotNull(ordinals);
List<Instruction> instructions = new ArrayList<>();
FlowUtils.setDlDstAction(new MacAddress(MAC_0))};
Action[] ordinalsAction = {FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)),
FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)),
+ FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)),
+ FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)),
+ FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)),
FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false)};
instructions.add(new InstructionBuilder().setOrder(0)
.setInstruction(FlowUtils.applyActionIns(ArrayUtils.addAll(ipActions, ordinalsAction))).build());
InOrder order = inOrder(ctx);
order.verify(ctx, times(1)).getEndpointManager();
order.verify(ctx, times(1)).getCurrentPolicy();
- verify(ctx, times(2)).getTenant(TENANT_ID);
+ verify(ctx, times(3)).getTenant(TENANT_ID);
assertNotNull(ordinals);
List<Instruction> instructions = new ArrayList<>();
Action[] ordinalsAction = {FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)),
FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)),
+ FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)),
+ FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)),
+ FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)),
FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false)};
instructions.add(new InstructionBuilder().setOrder(0)
.setInstruction(FlowUtils.applyActionIns(ArrayUtils.addAll(ordinalsAction))).build());
InOrder order = inOrder(ctx);
order.verify(ctx, times(1)).getEndpointManager();
order.verify(ctx, times(1)).getCurrentPolicy();
- verify(ctx, times(2)).getTenant(TENANT_ID);
+ verify(ctx, times(3)).getTenant(TENANT_ID);
assertNotNull(ordinals);
List<Instruction> instructions = new ArrayList<>();
Action[] ordinalsAction = {FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1)),
FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0)),
- FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0)),
+ FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3)),
+ FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4)),
+ FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5)),
FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false)};
instructions.add(new InstructionBuilder().setOrder(0)
.setInstruction(FlowUtils.applyActionIns(ArrayUtils.addAll(ordinalsAction))).build());
InOrder order = inOrder(ctx);
order.verify(ctx, times(1)).getEndpointManager();
order.verify(ctx, times(1)).getCurrentPolicy();
- verify(ctx, times(2)).getTenant(TENANT_ID);
+ verify(ctx, times(3)).getTenant(TENANT_ID);
assertNotNull(ordinals);
Action reg0 = FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1));
Action reg1 = FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0));
- Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0));
- Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0));
- Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0));
+ Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3));
+ Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4));
+ Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5));
Action tunnelId = FlowUtils.nxLoadTunIdAction(BigInteger.valueOf(ordinals.getTunnelId()), false);
InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
List<Instruction> instructions = new ArrayList<>();
InOrder order = inOrder(ctx);
order.verify(ctx, times(1)).getEndpointManager();
order.verify(ctx, times(1)).getCurrentPolicy();
- verify(ctx, times(2)).getTenant(TENANT_ID);
+ verify(ctx, times(3)).getTenant(TENANT_ID);
assertNotNull(ordinals);
Action reg0 = FlowUtils.nxLoadRegAction(NxmNxReg0.class, BigInteger.valueOf(1));
Action reg1 = FlowUtils.nxLoadRegAction(NxmNxReg1.class, BigInteger.valueOf(0xffffff));
- Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(0));
- Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0));
- Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(0));
+ Action reg4 = FlowUtils.nxLoadRegAction(NxmNxReg4.class, BigInteger.valueOf(3));
+ Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4));
+ Action reg6 = FlowUtils.nxLoadRegAction(NxmNxReg6.class, BigInteger.valueOf(5));
InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
List<Instruction> instructions = new ArrayList<>();
InstructionBuilder ordinalsInstruction = new InstructionBuilder();
InOrder order = inOrder(ctx);
order.verify(ctx, times(1)).getEndpointManager();
order.verify(ctx, times(1)).getCurrentPolicy();
- verify(ctx, times(2)).getTenant(TENANT_ID);
+ verify(ctx, times(3)).getTenant(TENANT_ID);
assertNotNull(ordinals);
- Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(0));
+ Action reg5 = FlowUtils.nxLoadRegAction(NxmNxReg5.class, BigInteger.valueOf(4));
InstructionsBuilder instructionsBuilder = new InstructionsBuilder();
List<Instruction> instructions = new ArrayList<>();
InstructionBuilder ordinalsInstruction = new InstructionBuilder();
MatchBuilder matchBuilder = new MatchBuilder();
matchBuilder.setInPort(new NodeConnectorId(CONNECTOR_1));
- FlowUtils.addNxTunIdMatch(matchBuilder, 0);
+ FlowUtils.addNxTunIdMatch(matchBuilder, 4);
Match match = matchBuilder.build();
Flow testFlow = buildFlow(FlowIdUtils.newFlowId(tableId, "tunnelFdId", match), tableId, 80, match,
// List of other endpoints (one entry is good enough)
HashSet<Endpoint> otherEndpoints = new HashSet<>();
Endpoint otherEndpoint = buildEndpoint(IPV4_1, MAC_1, CONNECTOR_1).build();
- EndpointBuilder otherEndpointBuilder = new EndpointBuilder(otherEndpoint);
- otherEndpointBuilder.setEndpointGroup(ENDPOINT_GROUP_0);
+ EndpointBuilder otherEndpointBuilder = new EndpointBuilder(otherEndpoint).setEndpointGroup(ENDPOINT_GROUP_0);
List<EndpointGroupId> endpointGroupIds = new ArrayList<>();
endpointGroupIds.add(ENDPOINT_GROUP_1);
endpointGroupIds.add(ENDPOINT_GROUP_2);
// Verify method usage
verify(ctx, times(3)).getEndpointManager();
- verify(ctx, times(5)).getTenant(Mockito.any(TenantId.class));
+ verify(ctx, times(7)).getTenant(Mockito.any(TenantId.class));
verify(ctx.getPolicyManager(), times(1)).getTABLEID_DESTINATION_MAPPER();
verify(ctx.getSwitchManager(), times(1)).getTunnelPort(NODE_ID, TunnelTypeVxlan.class);
verify(ctx.getEndpointManager(), times(1)).getEndpointsForGroup(Mockito.any(EgKey.class));
sourceMapper.syncFlows(flows, endpointBuilder.build(), NODE_ID, ofWriter);
// Verify OfContext method usage
- verify(ctx, times(3)).getTenant(Mockito.any(TenantId.class));
+ verify(ctx, times(4)).getTenant(Mockito.any(TenantId.class));
verify(ctx.getPolicyManager(), times(1)).getTABLEID_DESTINATION_MAPPER();
verify(ctx.getSwitchManager(), times(1)).getTunnelPort(NODE_ID, TunnelTypeVxlan.class);
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf;
+import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
-import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.endpoint.EndpointManager;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.OrdinalFactory.EndpointFwdCtxOrdinals;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.mapper.policyenforcer.NetworkElements;
+import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.RspName;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfcName;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.common.rev151017.SfpName;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePath;
+import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.rsp.rev140701.rendered.service.paths.RenderedServicePathBuilder;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPath;
+import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.sfc.sfp.rev140701.service.function.paths.ServiceFunctionPathBuilder;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.ActionBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.L2BridgeDomainId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.Endpoint;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.endpoint.rev140421.endpoints.EndpointBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.tenants.tenant.policy.subject.feature.instances.ActionInstance;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-
@RunWith(PowerMockRunner.class)
@PrepareForTest(ChainAction.class)
public class ChainActionTest {
private Endpoint endpoint;
private EndpointManager endpointManager;
private EgKey egKey;
- private TenantId tenant = new TenantId("e09a2308-6ffa-40af-92a2-69f54b2cf3e4");
+ private TenantId tenantId = new TenantId("e09a2308-6ffa-40af-92a2-69f54b2cf3e4");
@SuppressWarnings("unchecked")
@Before
- public void initialise() throws Exception {
+ public void init() throws Exception {
chainAction = new ChainAction();
- sfcPath = mock(ServiceFunctionPath.class);
- when(sfcPath.getName()).thenReturn(new SfpName("sfcPathName"));
- when(sfcPath.isSymmetric()).thenReturn(true);
+ sfcPath = new ServiceFunctionPathBuilder().setName(new SfpName("sfcPathName")).setSymmetric(true).build();
+ rsp = new RenderedServicePathBuilder().setName(new RspName("rspName")).build();
+ endpoint = new EndpointBuilder().setL2Context(new L2BridgeDomainId("L2context"))
+ .setMacAddress(new MacAddress("01:23:45:67:89:ab"))
+ .setTenant(tenantId)
+ .build();
ctx = mock(OfContext.class);
dataBroker = mock(DataBroker.class);
when(rTx.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(checkedFuture);
optRsp = mock(Optional.class);
when(checkedFuture.checkedGet()).thenReturn(optRsp);
- rsp = mock(RenderedServicePath.class);
when(optRsp.isPresent()).thenReturn(true).thenReturn(false);
when(optRsp.get()).thenReturn(rsp);
endpointFwdCtxOrdinals = mock(EndpointFwdCtxOrdinals.class);
when(netElements.getSrcEpOrdinals()).thenReturn(endpointFwdCtxOrdinals);
when(netElements.getDstEpOrdinals()).thenReturn(endpointFwdCtxOrdinals);
- endpoint = mock(Endpoint.class);
when(netElements.getSrcEp()).thenReturn(endpoint);
- when(netElements.getSrcEp().getTenant()).thenReturn(tenant);
endpointManager = mock(EndpointManager.class);
when(ctx.getEndpointManager()).thenReturn(endpointManager);
egKey = mock(EgKey.class);
- Set<EgKey> keysForEndpoint = new HashSet<EgKey>();
+ Set<EgKey> keysForEndpoint = new HashSet<>();
keysForEndpoint.add(egKey);
when(endpointManager.getEgKeysForEndpoint(any(Endpoint.class))).thenReturn(keysForEndpoint);
}
@Test
- public void staticTest() {
- Assert.assertNotNull(chainAction.getId());
- Assert.assertNotNull(chainAction.getActionDef());
+ public void testGetters() {
+ assertEquals(ChainActionDefinition.ID, chainAction.getId());
+ assertEquals(ChainActionDefinition.DEFINITION, chainAction.getActionDef());
}
@Test
- public void updateActionTestDirectionOutOpendaylightSfcNull() {
+ public void testUpdateAction_DirectionOut_OpendaylightSfcNull() {
ActionBuilder actionBuilder = mock(ActionBuilder.class);
- List<ActionBuilder> actions = Arrays.asList(actionBuilder);
- Map<String, Object> params = new HashMap<String, Object>();
+ List<ActionBuilder> actions = Collections.singletonList(actionBuilder);
+ Map<String, Object> params = new HashMap<>();
String chainName = "chainName";
params.put(ChainActionDefinition.SFC_CHAIN_NAME, chainName);
- Integer order = Integer.valueOf(0);
+ Integer order = 0;
OfWriter ofWriter = mock(OfWriter.class);
PowerMockito.mockStatic(ChainAction.class);
- when(ChainAction.getSfcPath(new SfcName(chainName))).thenReturn(sfcPath);
+ SfcName sfcName = new SfcName(chainName);
+ when(ChainAction.getSfcPath(eq(sfcName))).thenReturn(sfcPath);
chainAction.setResolvedSymmetricChains(Collections.singletonList(chainName));
List<ActionBuilder> result =
}
@Test
- public void updateActionTestParamsNull() {
+ public void testUpdateAction_ParamsNull() {
ActionBuilder actionBuilder = mock(ActionBuilder.class);
- List<ActionBuilder> actions = Arrays.asList(actionBuilder);
- Integer order = Integer.valueOf(0);
+ List<ActionBuilder> actions = Collections.singletonList(actionBuilder);
+ Integer order = 0;
OfWriter ofWriter = mock(OfWriter.class);
List<ActionBuilder> result =
}
@Test
- public void updateActionTestChainNameNull() {
+ public void testUpdateAction_ChainNameNull() {
ActionBuilder actionBuilder = mock(ActionBuilder.class);
- List<ActionBuilder> actions = Arrays.asList(actionBuilder);
- Map<String, Object> params = new HashMap<String, Object>();
+ List<ActionBuilder> actions = Collections.singletonList(actionBuilder);
+ Map<String, Object> params = new HashMap<>();
params.put(ChainActionDefinition.SFC_CHAIN_NAME, null);
- Integer order = Integer.valueOf(0);
+ Integer order = 0;
NetworkElements netElements = mock(NetworkElements.class);
OfWriter ofWriter = mock(OfWriter.class);
}
@Test
- public void updateActionTest() {
+ public void testUpdateAction() {
ActionBuilder actionBuilder = mock(ActionBuilder.class);
- List<ActionBuilder> actions = Arrays.asList(actionBuilder);
- Map<String, Object> params = new HashMap<String, Object>();
+ List<ActionBuilder> actions = Collections.singletonList(actionBuilder);
+ Map<String, Object> params = new HashMap<>();
String chainName = "chainName";
params.put(ChainActionDefinition.SFC_CHAIN_NAME, chainName);
- Integer order = Integer.valueOf(0);
+ Integer order = 0;
OfWriter ofWriter = mock(OfWriter.class);
+ ServiceFunctionPath sfcPathNameNull = new ServiceFunctionPathBuilder().setName(null).setSymmetric(true).build();
+
PowerMockito.mockStatic(ChainAction.class);
- when(ChainAction.getSfcPath(new SfcName(chainName))).thenReturn(sfcPath);
- when(sfcPath.getName()).thenReturn(null);
+ when(ChainAction.getSfcPath(new SfcName(chainName))).thenReturn(sfcPathNameNull);
List<ActionBuilder> result =
chainAction.updateAction(actions, params, order, netElements, ofWriter, ctx, Direction.Out);
}
@Test
- public void isValidTestParameterValueNull() {
- ActionInstance actionInstance = mock(ActionInstance.class);
- Assert.assertFalse(chainAction.validate(actionInstance).isValid());
+ public void testIsValid_ParameterValueNull() {
+ ActionInstance actionInstance = mock(ActionInstance.class);
+ Assert.assertFalse(chainAction.validate(actionInstance).isValid());
}
}
/*
* Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
+ *
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
public class ClassificationResultTest {
- private ClassificationResult result;
-
- private MatchBuilder matchBuilder;
private List<MatchBuilder> matches;
private String errorMessage = "errorMessage";
@Before
- public void initialise() {
- matchBuilder = mock(MatchBuilder.class);
- matches = Arrays.asList(matchBuilder);
+ public void init() {
+ MatchBuilder matchBuilder = mock(MatchBuilder.class);
+ matches = Collections.singletonList(matchBuilder);
}
@Test
- public void getMatchBuildersTestSuccess() {
- result = new ClassificationResult(matches);
- Assert.assertEquals(matches, result.getMatchBuilders());
+ public void testGetMatchBuilders_Success() {
+ ClassificationResult result = new ClassificationResult(matches);
+ assertEquals(matches, result.getMatchBuilders());
}
@Test(expected = IllegalStateException.class)
- public void getMatchBuildersTestFailure() {
- result = new ClassificationResult(errorMessage);
+ public void testGetMatchBuilders_Failure() {
+ ClassificationResult result = new ClassificationResult(errorMessage);
result.getMatchBuilders();
}
@Test
- public void getErrorMessageTest() {
- result = new ClassificationResult(errorMessage);
- Assert.assertEquals(errorMessage, result.getErrorMessage());
- result = new ClassificationResult(matches);
- Assert.assertTrue(result.getErrorMessage().isEmpty());
+ public void testGetErrorMessage() {
+ ClassificationResult result1 = new ClassificationResult(errorMessage);
+ assertEquals(errorMessage, result1.getErrorMessage());
+
+ ClassificationResult result2 = new ClassificationResult(matches);
+ assertTrue(result2.getErrorMessage().isEmpty());
}
@Test
- public void isSuccessfullTest() {
- result = new ClassificationResult(errorMessage);
- Assert.assertFalse(result.isSuccessfull());
- result = new ClassificationResult(matches);
- Assert.assertTrue(result.isSuccessfull());
+ public void testIsSuccessfull() {
+ ClassificationResult result1 = new ClassificationResult(errorMessage);
+ assertFalse(result1.isSuccessfull());
+
+ ClassificationResult result2 = new ClassificationResult(matches);
+ assertTrue(result2.isSuccessfull());
}
}
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.Collections;
Map<String, ParameterValue> params;
@Before
- public void setUp() {
+ public void init() {
matches = new ArrayList<>(Collections.singletonList(new MatchBuilder()));
params = new HashMap<>();
}
@Test
- public void updateMatchTest() {
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
- params.putAll(ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM,
- FlowUtils.IPv4));
+ public void testUpdateMatch() {
+ Long dstRangeStart = 8079L;
+ Long dstRangeEnd = 8081L;
+ Long singlePort = 80L;
+ params.putAll(
+ ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, FlowUtils.IPv4));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
- params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.SRC_PORT_PARAM, 80));
+ params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.SRC_PORT_PARAM, singlePort));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
+
ClassificationResult result = Classifier.L4_CL.updateMatch(matches, params);
+
assertEquals(true, result.isSuccessfull());
assertEquals(3, result.getMatchBuilders().size());
Set<Long> dstPorts = new HashSet<>();
for (MatchBuilder match : result.getMatchBuilders()) {
- assertEquals(true, ClassifierTestUtils.IPV4_ETH_TYPE.equals(match.getEthernetMatch().getEthernetType()));
- assertEquals(true, new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpSourcePort()
- .getValue()
- .intValue() == 80);
- dstPorts.add(Long.valueOf(new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpDestinationPort()
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, match.getEthernetMatch().getEthernetType());
+ assertSame(singlePort.intValue(),
+ new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpSourcePort().getValue());
+ dstPorts.add(new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpDestinationPort()
.getValue()
- .longValue()));
+ .longValue());
}
- for (Long i = dstRangeStart; i <= dstRangeEnd; i++) {
- assertEquals(true, dstPorts.contains((i)));
+ for (Long dstPort = dstRangeStart; dstPort <= dstRangeEnd; dstPort++) {
+ assertTrue(dstPorts.contains(dstPort));
}
}
}
import java.util.Map;
+import com.google.common.collect.ImmutableMap;
import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.flow.FlowUtils;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValue;
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.TcpMatchBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder;
-import com.google.common.collect.ImmutableMap;
-
public class ClassifierTestUtils {
static final EthernetType IPV4_ETH_TYPE = new EthernetTypeBuilder().setType(new EtherType(FlowUtils.IPv4)).build();
static final EthernetType IPV6_ETH_TYPE = new EthernetTypeBuilder().setType(new EtherType(FlowUtils.IPv6)).build();
- static final Long TCP = Long.valueOf(6);
- static final Long UDP = Long.valueOf(17);
- static final Long SCTP = Long.valueOf(132);
+ static final Long TCP = 6L;
+ static final Long UDP = 17L;
+ static final Long SCTP = 132L;
static Map<String, ParameterValue> createRangeValueParam(String paramName, long min, long max) {
- return ImmutableMap.<String, ParameterValue> of(paramName,
- new ParameterValueBuilder()
- .setRangeValue(new RangeValueBuilder()
- .setMin(min)
- .setMax(max)
- .build())
- .build());
+ return ImmutableMap.of(paramName, new ParameterValueBuilder()
+ .setRangeValue(new RangeValueBuilder().setMin(min).setMax(max).build()).build());
}
static Map<String, ParameterValue> createIntValueParam(String paramName, long value) {
- return ImmutableMap.<String, ParameterValue> of(paramName,
- new ParameterValueBuilder()
- .setIntValue(value)
- .build());
+ return ImmutableMap.of(paramName, new ParameterValueBuilder().setIntValue(value).build());
}
- static final EthernetMatch createEthernetMatch(EthernetType ethType) {
- return new EthernetMatchBuilder()
- .setEthernetType(ethType)
- .build();
+ static EthernetMatch createEthernetMatch(EthernetType ethType) {
+ return new EthernetMatchBuilder().setEthernetType(ethType).build();
}
- static final IpMatch createIpMatch(short ipProtoValue) {
- return new IpMatchBuilder()
- .setIpProtocol(ipProtoValue)
- .build();
+ static IpMatch createIpMatch(short ipProtoValue) {
+ return new IpMatchBuilder().setIpProtocol(ipProtoValue).build();
}
- static final Layer4Match createUdpDstPort(int portNumber) {
- return new UdpMatchBuilder()
- .setUdpDestinationPort(new PortNumber(portNumber))
- .build();
+ static Layer4Match createUdpDstPort(int portNumber) {
+ return new UdpMatchBuilder().setUdpDestinationPort(new PortNumber(portNumber)).build();
}
- static final Layer4Match createUdpSrcPort(int portNumber) {
- return new UdpMatchBuilder()
- .setUdpSourcePort(new PortNumber(portNumber))
- .build();
+ static Layer4Match createUdpSrcPort(int portNumber) {
+ return new UdpMatchBuilder().setUdpSourcePort(new PortNumber(portNumber)).build();
}
- final Layer4Match createTcpDstPort(int portNumber) {
- return new TcpMatchBuilder()
- .setTcpDestinationPort(new PortNumber(portNumber))
- .build();
+ static Layer4Match createTcpDstPort(int portNumber) {
+ return new TcpMatchBuilder().setTcpDestinationPort(new PortNumber(portNumber)).build();
}
- final Layer4Match createTcpSrcPort(int portNumber) {
- return new TcpMatchBuilder()
- .setTcpSourcePort(new PortNumber(portNumber))
- .build();
+ static Layer4Match createTcpSrcPort(int portNumber) {
+ return new TcpMatchBuilder().setTcpSourcePort(new PortNumber(portNumber)).build();
}
- final static Layer4Match createSctpDstPort(int portNumber) {
- return new SctpMatchBuilder()
- .setSctpDestinationPort(new PortNumber(portNumber))
- .build();
+ static Layer4Match createSctpDstPort(int portNumber) {
+ return new SctpMatchBuilder().setSctpDestinationPort(new PortNumber(portNumber)).build();
}
- final static Layer4Match createSctpSrcPort(int portNumber) {
- return new SctpMatchBuilder()
- .setSctpSourcePort(new PortNumber(portNumber))
- .build();
+ static Layer4Match createSctpSrcPort(int portNumber) {
+ return new SctpMatchBuilder().setSctpSourcePort(new PortNumber(portNumber)).build();
}
-}
\ No newline at end of file
+}
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
+import com.google.common.collect.ImmutableMap;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValue;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValueBuilder;
-import com.google.common.collect.ImmutableMap;
-
public class EtherTypeClassifierTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
- List<MatchBuilder> matches;
- Map<String, ParameterValue> params;
+ @Test
+ public void testUpdate() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(
+ new MatchBuilder().setIpMatch(ClassifierTestUtils.createIpMatch(ClassifierTestUtils.TCP.shortValue())));
+ params.putAll(
+ ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, FlowUtils.IPv4));
- @Before
- public void setUp() {
- matches = new ArrayList<>();
- params = new HashMap<>();
- }
+ List<MatchBuilder> updated = Classifier.ETHER_TYPE_CL.update(matches, params);
- @Test
- public void setValueTest() {
- matches.add(new MatchBuilder().setIpMatch(ClassifierTestUtils.createIpMatch(ClassifierTestUtils.TCP.shortValue())));
- params.putAll(ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM,
- FlowUtils.IPv4));
- matches = Classifier.ETHER_TYPE_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV4_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- assertEquals(true, ClassifierTestUtils.TCP.equals(matches.get(0).getIpMatch().getIpProtocol().longValue()));
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ assertSame(ClassifierTestUtils.TCP, first.getIpMatch().getIpProtocol().longValue());
}
@Test
- public void overrideByTheSameValueTest() {
- matches.add(new MatchBuilder().setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)).setIpMatch(
- ClassifierTestUtils.createIpMatch(ClassifierTestUtils.UDP.shortValue())));
- params.putAll(ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM,
- FlowUtils.IPv6));
- matches = Classifier.ETHER_TYPE_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV6_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- assertEquals(true, ClassifierTestUtils.UDP.equals(matches.get(0).getIpMatch().getIpProtocol().longValue()));
+ public void testUpdate_overrideBySameValue() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE))
+ .setIpMatch(ClassifierTestUtils.createIpMatch(ClassifierTestUtils.UDP.shortValue())));
+ params.putAll(
+ ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, FlowUtils.IPv6));
+
+ List<MatchBuilder> updated = Classifier.ETHER_TYPE_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV6_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ assertSame(ClassifierTestUtils.UDP, first.getIpMatch().getIpProtocol().longValue());
}
@Test
- public void overrideByDifferentValueTest() {
- matches.add(new MatchBuilder().setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)).setIpMatch(
- ClassifierTestUtils.createIpMatch(ClassifierTestUtils.SCTP.shortValue())));
- params.putAll(ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM,
- FlowUtils.IPv6));
+ public void testUpdate_overrideByDifferentValue() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE))
+ .setIpMatch(ClassifierTestUtils.createIpMatch(ClassifierTestUtils.SCTP.shortValue())));
+ params.putAll(
+ ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, FlowUtils.IPv6));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Classification conflict detected");
- matches = Classifier.ETHER_TYPE_CL.update(matches, params);
+ thrown.expectMessage(Classifier.MSG_CLASSIFICATION_CONFLICT_DETECTED);
+ Classifier.ETHER_TYPE_CL.update(matches, params);
}
@Test
- public void checkPresenceOfRequiredParameters1Test() {
+ public void testCheckPresenceOfRequiredParameters_EtherTypeMissing() {
+ Map<String, ParameterValue> params = new HashMap<>();
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not specified.");
+ thrown.expectMessage(Classifier.MSG_NOT_SPECIFIED);
Classifier.ETHER_TYPE_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void checkPresenceOfRequiredParameters2Test() {
- params.putAll(ImmutableMap.<String, ParameterValue>of(EtherTypeClassifierDefinition.ETHERTYPE_PARAM,
- new ParameterValueBuilder().build()));
+ public void testCheckPresenceOfRequiredParameters_EtherTypeNull() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(
+ ImmutableMap.of(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, new ParameterValueBuilder().build()));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Value of ethertype parameter is not present");
+ thrown.expectMessage(Classifier.MSG_PARAMETER_IS_NOT_PRESENT);
Classifier.ETHER_TYPE_CL.checkPresenceOfRequiredParams(params);
}
}
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertSame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.junit.Before;
+import com.google.common.collect.ImmutableMap;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValue;
import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValueBuilder;
-import com.google.common.collect.ImmutableMap;
-
public class IpProtoClassifierTest {
- List<MatchBuilder> matches;
- Map<String, ParameterValue> params;
-
@Rule
public ExpectedException thrown = ExpectedException.none();
- @Before
- public void setUp() {
- matches = new ArrayList<>();
- params = new HashMap<>();
- }
-
@Test
- public void setValueTest() {
- matches.add(new MatchBuilder().setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
+ public void testUpdate() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
- matches = Classifier.IP_PROTO_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV4_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- assertEquals(true, ClassifierTestUtils.TCP.equals(matches.get(0).getIpMatch().getIpProtocol().longValue()));
+
+ List<MatchBuilder> updated = Classifier.IP_PROTO_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ assertSame(ClassifierTestUtils.TCP, first.getIpMatch().getIpProtocol().longValue());
}
@Test
- public void overrideByTheSameValueTest() {
- matches.add(new MatchBuilder().setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)).setIpMatch(
- ClassifierTestUtils.createIpMatch(ClassifierTestUtils.UDP.shortValue())));
+ public void testUpdate_overrideBySameValue() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE))
+ .setIpMatch(ClassifierTestUtils.createIpMatch(ClassifierTestUtils.UDP.shortValue())));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.UDP));
- matches = Classifier.IP_PROTO_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV6_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- assertEquals(true, ClassifierTestUtils.UDP.equals(matches.get(0).getIpMatch().getIpProtocol().longValue()));
+
+ List<MatchBuilder> updated = Classifier.IP_PROTO_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV6_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ assertSame(ClassifierTestUtils.UDP, first.getIpMatch().getIpProtocol().longValue());
}
@Test
- public void overrideByDifferentValueTest() {
- matches.add(new MatchBuilder().setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)).setIpMatch(
- ClassifierTestUtils.createIpMatch(ClassifierTestUtils.SCTP.shortValue())));
+ public void testUpdate_overrideByDifferentValue() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE))
+ .setIpMatch(ClassifierTestUtils.createIpMatch(ClassifierTestUtils.SCTP.shortValue())));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Classification conflict detected");
- matches = Classifier.IP_PROTO_CL.update(matches, params);
+ thrown.expectMessage(Classifier.MSG_CLASSIFICATION_CONFLICT_DETECTED);
+ Classifier.IP_PROTO_CL.update(matches, params);
}
@Test
- public void checkPresenceOfRequiredParameters1Test() {
- params.putAll(ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM,
- FlowUtils.IPv4));
+ public void testCheckPresenceOfRequiredParameters_ProtoMissing() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(
+ ClassifierTestUtils.createIntValueParam(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, FlowUtils.IPv4));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not specified");
+ thrown.expectMessage(Classifier.MSG_NOT_SPECIFIED);
Classifier.IP_PROTO_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void checkPresenceOfRequiredParameters2Test() {
- params.putAll(ImmutableMap.<String, ParameterValue>of(IpProtoClassifierDefinition.PROTO_PARAM,
- new ParameterValueBuilder().build()));
+ public void testCheckPresenceOfRequiredParameters_ProtoNull() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(ImmutableMap.of(IpProtoClassifierDefinition.PROTO_PARAM, new ParameterValueBuilder().build()));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Value of proto parameter is not present");
+ thrown.expectMessage(Classifier.MSG_PARAMETER_IS_NOT_PRESENT);
Classifier.IP_PROTO_CL.checkPresenceOfRequiredParams(params);
}
}
package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.sf;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.tuple.Pair;
-import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatch;
import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.match.layer._4.match.UdpMatchBuilder;
-import com.google.common.collect.ImmutableMap;
-
public class L4ClassifierTest {
- List<MatchBuilder> matches;
-
- Map<String, ParameterValue> params;
+ private static final long LESSER_RANGE_START = 79L;
+ private static final long LESSER_RANGE_END = 81L;
+ private static final long GREATER_RANGE_START = 8079L;
+ private static final long GREATER_RANGE_END = 8081L;
+ private static final long SINGLE_PORT = 80L;
+ private static final int SINGLE_PORT_INT = 80;
@Rule
public ExpectedException thrown = ExpectedException.none();
- @Before
- public void setUp() {
- params = new HashMap<>();
- matches = new ArrayList<>();
- }
-
@Test
- public void setTcpSrcPortTest() {
- matches.add(new MatchBuilder().setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
- Long sPort = Long.valueOf(80);
+ public void testUpdate_TcpSrcPort() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
+ Long sPort = SINGLE_PORT;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.SRC_PORT_PARAM, sPort));
- matches = Classifier.L4_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV4_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- TcpMatch match = new TcpMatchBuilder((TcpMatch) matches.get(0).getLayer4Match()).build();
- assertEquals(true, sPort.equals(match.getTcpSourcePort().getValue().longValue()));
- assertEquals(true, match.getTcpDestinationPort() == null);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ TcpMatch match = new TcpMatchBuilder((TcpMatch) first.getLayer4Match()).build();
+ assertSame(sPort, match.getTcpSourcePort().getValue().longValue());
+ assertNull(match.getTcpDestinationPort());
}
@Test
- public void setTcpDstPortTest() {
- Long dPort = Long.valueOf(80);
- matches.add(new MatchBuilder().setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)));
+ public void testUpdate_TcpDstPort() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ Long dPort = SINGLE_PORT;
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.DST_PORT_PARAM, dPort));
- matches = Classifier.L4_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV6_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- TcpMatch match = new TcpMatchBuilder((TcpMatch) matches.get(0).getLayer4Match()).build();
- assertEquals(true, dPort.equals(match.getTcpDestinationPort().getValue().longValue()));
- assertEquals(true, match.getTcpSourcePort() == null);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV6_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ TcpMatch match = new TcpMatchBuilder((TcpMatch) first.getLayer4Match()).build();
+ assertSame(dPort, match.getTcpDestinationPort().getValue().longValue());
+ assertNull(match.getTcpSourcePort());
}
@Test
- public void setTcpSrcPortDstPortRangeTest() {
- matches.add(new MatchBuilder().setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
- Long srcPort = Long.valueOf(80);
+ public void testUpdate_TcpSrcPort_DstPortRange() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
+ Long srcPort = SINGLE_PORT;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.SRC_PORT_PARAM, srcPort));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
- matches = Classifier.L4_CL.update(matches, params);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
Set<Long> dstPorts = new HashSet<>();
- for (MatchBuilder match : matches) {
- assertEquals(true, ClassifierTestUtils.IPV4_ETH_TYPE.equals(match.getEthernetMatch().getEthernetType()));
- assertEquals(true,
- Long.valueOf(new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpSourcePort().getValue())
- .equals(srcPort));
+ for (MatchBuilder match : updated) {
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, match.getEthernetMatch().getEthernetType());
+ assertEquals(srcPort,
+ Long.valueOf(new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpSourcePort().getValue()));
dstPorts.add(new TcpMatchBuilder((TcpMatch) match.getLayer4Match()).getTcpDestinationPort()
.getValue()
.longValue());
}
- for (Long i = dstRangeStart; i <= dstRangeEnd; i++) {
- assertEquals(true, dstPorts.contains((i)));
+ for (Long port = dstRangeStart; port <= dstRangeEnd; port++) {
+ assertTrue(dstPorts.contains((port)));
}
}
@Test
- public void overrideDstPortWithTheSameValueTest() {
- Long dPort = Long.valueOf(80);
- matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createUdpDstPort(80)).setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)));
+ public void testUpdate_OverrideDstPortWithTheSameValue() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ Long dPort = SINGLE_PORT;
+ matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createUdpDstPort(SINGLE_PORT_INT))
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.UDP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.DST_PORT_PARAM, dPort));
- matches = Classifier.L4_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV6_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- UdpMatch match = new UdpMatchBuilder((UdpMatch) matches.get(0).getLayer4Match()).build();
- assertEquals(true, dPort.equals(match.getUdpDestinationPort().getValue().longValue()));
- assertEquals(true, match.getUdpSourcePort() == null);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV6_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ UdpMatch match = new UdpMatchBuilder((UdpMatch) first.getLayer4Match()).build();
+ assertSame(dPort, match.getUdpDestinationPort().getValue().longValue());
+ assertNull(match.getUdpSourcePort());
}
@Test
- public void addUdpSrcPortRangeTest() {
- matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createUdpDstPort(80)).setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
- Long srcRangeStart = Long.valueOf(8079);
- Long srcRangeEnd = Long.valueOf(8081);
+ public void testUpdate_AddUdpSrcPortRange() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createUdpDstPort(SINGLE_PORT_INT))
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
+ Long srcRangeStart = GREATER_RANGE_START;
+ Long srcRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.UDP));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
srcRangeStart, srcRangeEnd));
- matches = Classifier.L4_CL.update(matches, params);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(3, updated.size());
Set<Long> srcPorts = new HashSet<>();
- for (MatchBuilder match : matches) {
- assertEquals(true, ClassifierTestUtils.IPV4_ETH_TYPE.equals(match.getEthernetMatch().getEthernetType()));
- assertEquals(true, new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpDestinationPort()
- .getValue()
- .intValue() == 80);
- assertEquals(true, new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpDestinationPort()
- .getValue()
- .longValue() == 80);
- srcPorts.add(new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpSourcePort()
+ for (MatchBuilder match : updated) {
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, match.getEthernetMatch().getEthernetType());
+ assertSame(SINGLE_PORT_INT,
+ new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpDestinationPort().getValue());
+ assertEquals(SINGLE_PORT_INT, new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpDestinationPort()
.getValue()
.longValue());
+ srcPorts
+ .add(new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpSourcePort()
+ .getValue()
+ .longValue());
}
- for (Long i = srcRangeStart; i <= srcRangeEnd; i++) {
- assertEquals(true, srcPorts.contains((i)));
+ for (Long port = srcRangeStart; port <= srcRangeEnd; port++) {
+ assertTrue(srcPorts.contains((port)));
}
}
@Test
- public void setUdpSrcPortRangeDstPortTest() {
- matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createUdpDstPort(80)).setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)));
- Long dPort = Long.valueOf(80);
- Long srcRangeStart = Long.valueOf(8079);
- Long srcRangeEnd = Long.valueOf(8081);
+ public void testUpdate_UdpSrcPortRange_DstPort() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createUdpDstPort(SINGLE_PORT_INT))
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV6_ETH_TYPE)));
+ Long dPort = SINGLE_PORT;
+ Long srcRangeStart = GREATER_RANGE_START;
+ Long srcRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.UDP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.DST_PORT_PARAM, dPort));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
srcRangeStart, srcRangeEnd));
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
- matches = Classifier.L4_CL.update(matches, params);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(3, updated.size());
Set<Long> srcPorts = new HashSet<>();
- for (MatchBuilder match : matches) {
- assertEquals(true, ClassifierTestUtils.IPV6_ETH_TYPE.equals(match.getEthernetMatch().getEthernetType()));
- assertEquals(
- true,
- dPort.equals(new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpDestinationPort()
- .getValue()
- .longValue()));
- srcPorts.add(Long.valueOf(new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpSourcePort()
+ for (MatchBuilder match : updated) {
+ assertEquals(ClassifierTestUtils.IPV6_ETH_TYPE, match.getEthernetMatch().getEthernetType());
+ assertSame(dPort, new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpDestinationPort()
.getValue()
- .longValue()));
+ .longValue());
+ srcPorts
+ .add(new UdpMatchBuilder((UdpMatch) match.getLayer4Match()).getUdpSourcePort()
+ .getValue()
+ .longValue());
}
- for (Long i = srcRangeStart; i <= srcRangeEnd; i++) {
- assertEquals(true, srcPorts.contains((i)));
+ for (Long port = srcRangeStart; port <= srcRangeEnd; port++) {
+ assertTrue(srcPorts.contains((port)));
}
}
@Test
- public void overrideSrcPortWithTheSameValueTest() {
- Long sPort = Long.valueOf(80);
+ public void testUpdate_OverrideSrcPortWithTheSameValue() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ Long sPort = SINGLE_PORT;
matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createSctpSrcPort(sPort.intValue()))
.setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.SCTP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.SRC_PORT_PARAM, sPort));
- matches = Classifier.L4_CL.update(matches, params);
- assertEquals(true,
- ClassifierTestUtils.IPV4_ETH_TYPE.equals(matches.get(0).getEthernetMatch().getEthernetType()));
- SctpMatch match = new SctpMatchBuilder((SctpMatch) matches.get(0).getLayer4Match()).build();
- assertEquals(true, sPort.equals(match.getSctpSourcePort().getValue().longValue()));
- assertEquals(true, match.getSctpDestinationPort() == null);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(1, updated.size());
+ MatchBuilder first = updated.get(0);
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, first.getEthernetMatch().getEthernetType());
+ SctpMatch match = new SctpMatchBuilder((SctpMatch) first.getLayer4Match()).build();
+ assertSame(sPort, match.getSctpSourcePort().getValue().longValue());
+ assertNull(match.getSctpDestinationPort());
}
@Test
- public void addSctpDstPortRangeTest() {
- matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createSctpSrcPort(80)).setEthernetMatch(
- ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
+ public void testUpdate_AddSctpDstPortRange() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createSctpSrcPort(SINGLE_PORT_INT))
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.SCTP));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
- matches = Classifier.L4_CL.update(matches, params);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(3, updated.size());
Set<Long> dstPorts = new HashSet<>();
- for (MatchBuilder match : matches) {
- assertEquals(true, ClassifierTestUtils.IPV4_ETH_TYPE.equals(match.getEthernetMatch().getEthernetType()));
- assertEquals(true, new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpSourcePort()
- .getValue()
- .intValue() == 80);
- dstPorts.add(Long.valueOf(new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpDestinationPort()
+ for (MatchBuilder match : updated) {
+ assertEquals(ClassifierTestUtils.IPV4_ETH_TYPE, match.getEthernetMatch().getEthernetType());
+ assertSame(SINGLE_PORT_INT,
+ new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpSourcePort().getValue());
+ dstPorts.add(new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpDestinationPort()
.getValue()
- .longValue()));
+ .longValue());
}
- for (Long i = dstRangeStart; i <= dstRangeEnd; i++) {
- assertEquals(true, dstPorts.contains((i)));
+ for (Long port = dstRangeStart; port <= dstRangeEnd; port++) {
+ assertTrue(dstPorts.contains((port)));
}
}
@Test
- public void setSctpSrcPortRangeDstPortRangeTest() {
- matches.add(new MatchBuilder().setEthernetMatch(ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
- Long srcRangeStart = Long.valueOf(79);
- Long srcRangeEnd = Long.valueOf(81);
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
+ public void testUpdate_Sctp_SrcPortRange_DstPortRange() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder()
+ .setEthernetMatch(
+ ClassifierTestUtils.createEthernetMatch(ClassifierTestUtils.IPV4_ETH_TYPE)));
+ Long srcRangeStart = LESSER_RANGE_START;
+ Long srcRangeEnd = LESSER_RANGE_END;
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.SCTP));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
- matches = Classifier.L4_CL.update(matches, params);
+
+ List<MatchBuilder> updated = Classifier.L4_CL.update(matches, params);
+
+ assertEquals(9, updated.size());
Set<Pair<Long, Long>> set = new HashSet<>();
- for (MatchBuilder match : matches) {
- Long srcPort = Long.valueOf(new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpSourcePort()
+ for (MatchBuilder match : updated) {
+ Long srcPort =
+ new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpSourcePort().getValue().longValue();
+ Long dstPort = new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpDestinationPort()
.getValue()
- .longValue());
- Long dstPort = Long.valueOf(new SctpMatchBuilder((SctpMatch) match.getLayer4Match()).getSctpDestinationPort()
- .getValue()
- .longValue());
+ .longValue();
set.add(Pair.of(srcPort, dstPort));
}
- for (Long i = srcRangeStart; i <= srcRangeEnd; i++) {
- for (Long j = dstRangeStart; j <= dstRangeEnd; j++) {
- assertEquals(true, set.contains(Pair.of(i, j)));
+ for (Long sPort = srcRangeStart; sPort <= srcRangeEnd; sPort++) {
+ for (Long dPort = dstRangeStart; dPort <= dstRangeEnd; dPort++) {
+ assertTrue(set.contains(Pair.of(sPort, dPort)));
}
}
}
@Test
- public void srcPortSrtPortRangeMutualExclusionTest() {
- matches.add(new MatchBuilder());
- Long srcRangeStart = Long.valueOf(8079);
- Long srcRangeEnd = Long.valueOf(8081);
- Long srcPort = Long.valueOf(80);
+ public void testCheckPresenceOfRequiredParams_SrcPort_SrtPortRange_MutualExclusion() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ Long srcRangeStart = GREATER_RANGE_START;
+ Long srcRangeEnd = GREATER_RANGE_END;
+ Long srcPort = SINGLE_PORT;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.SCTP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.SRC_PORT_PARAM, srcPort));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
srcRangeStart, srcRangeEnd));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("mutually exclusive");
+ thrown.expectMessage(Classifier.MSG_MUTUALLY_EXCLUSIVE);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void dstPortSrtPortRangeMutualExclusionTest() {
- matches.add(new MatchBuilder());
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
- Long dstPort = Long.valueOf(80);
+ public void testCheckPresenceOfRequiredParams_DstPort_DstPortRange_MutualExclusion() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
+ Long dstPort = SINGLE_PORT;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.UDP));
params.putAll(ClassifierTestUtils.createIntValueParam(L4ClassifierDefinition.DST_PORT_PARAM, dstPort));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("mutually exclusive");
+ thrown.expectMessage(Classifier.MSG_MUTUALLY_EXCLUSIVE);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void rangeValueMismatchTest() {
- matches.add(new MatchBuilder());
- Long dstRangeStart = Long.valueOf(8081);
- Long dstRangeEnd = Long.valueOf(8079);
+ public void testCheckPresenceOfRequiredParams_RangeValueMismatch() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ Long dstRangeStart = GREATER_RANGE_END;
+ Long dstRangeEnd = GREATER_RANGE_START;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.TCP));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Range value mismatch");
+ thrown.expectMessage(Classifier.MSG_RANGE_VALUE_MISMATCH);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void unsupportedProtocolTest() {
+ public void testUpdate_UnsupportedProtocol() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
matches.add(new MatchBuilder());
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM, 136));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not supported");
- matches = Classifier.L4_CL.update(matches, params);
+ thrown.expectMessage(Classifier.MSG_NOT_SUPPORTED);
+ Classifier.L4_CL.update(matches, params);
}
@Test
- public void classificationConflictTest() {
- matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createSctpDstPort(80)));
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
+ public void testUpdate_ClassificationConflict() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
+ matches.add(new MatchBuilder().setLayer4Match(ClassifierTestUtils.createSctpDstPort(SINGLE_PORT_INT)));
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createIntValueParam(IpProtoClassifierDefinition.PROTO_PARAM,
ClassifierTestUtils.UDP));
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Classification conflict");
- matches = Classifier.L4_CL.update(matches, params);
+ thrown.expectMessage(Classifier.MSG_CLASSIFICATION_CONFLICT_DETECTED);
+ Classifier.L4_CL.update(matches, params);
}
@Test
- public void noProtoTest() {
+ public void testUpdate_NoProto() {
+ List<MatchBuilder> matches = new ArrayList<>();
+ Map<String, ParameterValue> params = new HashMap<>();
matches.add(new MatchBuilder());
- Long dstRangeStart = Long.valueOf(8079);
- Long dstRangeEnd = Long.valueOf(8081);
+ Long dstRangeStart = GREATER_RANGE_START;
+ Long dstRangeEnd = GREATER_RANGE_END;
params.putAll(ClassifierTestUtils.createRangeValueParam(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
dstRangeStart, dstRangeEnd));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage(IpProtoClassifierDefinition.PROTO_PARAM + " is missing");
- matches = Classifier.L4_CL.update(matches, params);
+ thrown.expectMessage(Classifier.MSG_IS_MISSING);
+ Classifier.L4_CL.update(matches, params);
}
@Test
- public void checkPresenceOfRequiredParameters1Test() {
- params.putAll(ImmutableMap.<String, ParameterValue>of(L4ClassifierDefinition.SRC_PORT_PARAM,
- new ParameterValueBuilder().build()));
+ public void testCheckPresenceOfRequiredParameters_SrcPortNotSet() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(ImmutableMap.of(L4ClassifierDefinition.SRC_PORT_PARAM, new ParameterValueBuilder().build()));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not specified");
+ thrown.expectMessage(Classifier.MSG_NOT_SPECIFIED);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void checkPresenceOfRequiredParameters2Test() {
- params.putAll(ImmutableMap.<String, ParameterValue>of(L4ClassifierDefinition.DST_PORT_PARAM,
- new ParameterValueBuilder().build()));
+ public void testCheckPresenceOfRequiredParameters_DstPortNotSet() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(ImmutableMap.of(L4ClassifierDefinition.DST_PORT_PARAM, new ParameterValueBuilder().build()));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not specified");
+ thrown.expectMessage(Classifier.MSG_NOT_SPECIFIED);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void checkPresenceOfRequiredParameters3Test() {
- params.putAll(ImmutableMap.<String, ParameterValue>of(L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
+ public void testCheckPresenceOfRequiredParameters_SrcRangeNotSet() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(ImmutableMap.of(L4ClassifierDefinition.SRC_PORT_RANGE_PARAM,
new ParameterValueBuilder().build()));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not present");
+ thrown.expectMessage(Classifier.MSG_NOT_PRESENT);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
@Test
- public void checkPresenceOfRequiredParameters4Test() {
- params.putAll(ImmutableMap.<String, ParameterValue>of(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
+ public void testCheckPresenceOfRequiredParameters_DstRangeNotSet() {
+ Map<String, ParameterValue> params = new HashMap<>();
+ params.putAll(ImmutableMap.of(L4ClassifierDefinition.DST_PORT_RANGE_PARAM,
new ParameterValueBuilder().build()));
+
thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("not present");
+ thrown.expectMessage(Classifier.MSG_NOT_PRESENT);
Classifier.L4_CL.checkPresenceOfRequiredParams(params);
}
}
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;\r
+\r
+import static org.mockito.Mockito.mock;\r
+\r
+import java.util.concurrent.ScheduledExecutorService;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.groupbasedpolicy.api.StatisticsManager;\r
+\r
+public class OFStatisticsManagerTest {\r
+\r
+ ScheduledExecutorService executor;\r
+ StatisticsManager statisticsManager;\r
+\r
+ @Before\r
+ public void init() {\r
+ executor = mock(ScheduledExecutorService.class);\r
+ statisticsManager = mock(StatisticsManager.class);\r
+ }\r
+\r
+ @Test\r
+ public void testConstructor() throws Exception {\r
+ new OFStatisticsManager(executor, statisticsManager);\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics;\r
+\r
+import static org.mockito.Matchers.any;\r
+import static org.mockito.Matchers.anyMap;\r
+import static org.mockito.Matchers.anySet;\r
+import static org.mockito.Matchers.anyString;\r
+import static org.mockito.Mockito.doNothing;\r
+import static org.mockito.Mockito.mock;\r
+import static org.mockito.Mockito.when;\r
+\r
+import javax.ws.rs.core.MultivaluedMap;\r
+\r
+import java.util.concurrent.ExecutorService;\r
+import java.util.concurrent.ScheduledExecutorService;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.groupbasedpolicy.api.StatisticsManager;\r
+\r
+public class ReadGbpFlowCacheTaskTest {\r
+\r
+ ReadGbpFlowCacheTask task;\r
+\r
+ @Before\r
+ public void init() {\r
+ StatisticsManager statisticsManager = mock(StatisticsManager.class);\r
+ ScheduledExecutorService executor = mock(ScheduledExecutorService.class);\r
+ JsonRestClientResponse response = mock(JsonRestClientResponse.class);\r
+ when(response.getJsonResponse()).thenReturn("[{\"one\":1, \"two\":2, \"three\":3}]");\r
+ when(response.getStatusCode()).thenReturn(200);\r
+ SFlowRTConnection connection = mock(SFlowRTConnection.class);\r
+ when(connection.get(anyString(), any(MultivaluedMap.class))).thenReturn(response);\r
+ when(connection.getExecutor()).thenReturn(executor);\r
+ doNothing().when(executor).execute(any(Runnable.class));\r
+\r
+ task = new ReadGbpFlowCacheTask("cache1", connection, statisticsManager, 100, 0.1, "sum");\r
+ }\r
+\r
+ @Test\r
+ public void testRun() {\r
+\r
+ task.run();\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.fail;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection.Direction;\r
+\r
+public class FlowCacheBuilderTest {\r
+\r
+ private static final String NAME_1 = "name_1";\r
+ private static final Direction direction = Direction.Bidirectional;\r
+ private static final String VALUE_1 = "value_1";\r
+ private FlowCacheDefinition flowCacheDefinition;\r
+ private FlowCache.FlowCacheBuilder builder;\r
+\r
+ @Before\r
+ public void init() {\r
+ builder = new FlowCache.FlowCacheBuilder();\r
+ flowCacheDefinition = FlowCacheDefinition.builder().setValue(VALUE_1).build();\r
+ }\r
+\r
+ @Test\r
+ public void testConstructor() {\r
+ FlowCache.FlowCacheBuilder b = null;\r
+ try {\r
+ b = new FlowCache.FlowCacheBuilder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(b);\r
+ }\r
+\r
+ @Test\r
+ public void testSetName() {\r
+ builder.setName(NAME_1);\r
+\r
+ assertEquals(NAME_1, builder.getName());\r
+ }\r
+\r
+ @Test\r
+ public void testSetDefinition() {\r
+ builder.setDefinition(flowCacheDefinition);\r
+\r
+ assertEquals(VALUE_1, builder.getDefinition().getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testSetDirection() {\r
+ builder.setDirection(direction);\r
+\r
+ assertEquals(direction, builder.getDirection());\r
+ }\r
+\r
+ @Test\r
+ public void testBuild() {\r
+ FlowCache cache = builder.setName(NAME_1)\r
+ .setDefinition(flowCacheDefinition)\r
+ .setDirection(direction)\r
+ .build();\r
+\r
+ assertNotNull(cache);\r
+ assertEquals(NAME_1, cache.getName());\r
+ assertEquals(flowCacheDefinition, cache.getDefinition());\r
+ assertEquals(direction, cache.getDirection());\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertFalse;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertNull;\r
+import static org.junit.Assert.assertTrue;\r
+import static org.junit.Assert.fail;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+\r
+public class FlowCacheDefinitionBuilderTest {\r
+\r
+ private static final String VALUE = "value-1";\r
+\r
+ private FlowCacheDefinition.FlowCacheDefinitionBuilder builder;\r
+\r
+ @Before\r
+ public void init() {\r
+ builder = new FlowCacheDefinition.FlowCacheDefinitionBuilder();\r
+ }\r
+\r
+ @Test\r
+ public void testConstructor() {\r
+ FlowCacheDefinition.FlowCacheDefinitionBuilder b = null;\r
+ try {\r
+ b = new FlowCacheDefinition.FlowCacheDefinitionBuilder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(b);\r
+ assertFalse(b.isLog());\r
+ assertNotNull(b.getFilterBuilder());\r
+ assertNotNull(b.getKeysBuilder());\r
+ assertNotNull(b.getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testSetValue() {\r
+ builder.setValue(VALUE);\r
+ assertEquals(VALUE, builder.getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testSetLog() {\r
+ builder.setLog(true);\r
+ assertTrue(builder.isLog());\r
+ }\r
+\r
+ @Test\r
+ public void testBuild() {\r
+ builder.setValue(VALUE).setLog(true);\r
+ FlowCacheDefinition definition = builder.build();\r
+\r
+ assertEquals(VALUE, definition.getValue());\r
+ assertTrue(definition.getLog());\r
+ assertNotNull(definition.getKeys());\r
+ assertNotNull(definition.getFilter());\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.fail;\r
+\r
+import org.junit.Test;\r
+\r
+public class FlowCacheDefinitionTest {\r
+\r
+ @Test\r
+ public void testBuilder() {\r
+ FlowCacheDefinition.FlowCacheDefinitionBuilder builder = null;\r
+ try {\r
+ builder = FlowCacheDefinition.builder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(builder);\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertTrue;\r
+\r
+import java.util.ArrayList;\r
+import java.util.Arrays;\r
+import java.util.List;\r
+\r
+import com.google.common.collect.ImmutableList;\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.groupbasedpolicy.api.sf.EtherTypeClassifierDefinition;\r
+import org.opendaylight.groupbasedpolicy.api.sf.IpProtoClassifierDefinition;\r
+import org.opendaylight.groupbasedpolicy.api.sf.L4ClassifierDefinition;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.ResolvedPolicyClassifierListener;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.FlowCacheCons;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util.IidSflowNameUtil;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test.TestUtils;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierDefinitionId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ParameterName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValue;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.subject.feature.instance.ParameterValueBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.Classifier;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.ClassifierBuilder;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.ResolvedPolicy;\r
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;\r
+\r
+public class FlowCacheFactoryTest {\r
+\r
+ private final EndpointGroupId consumerEpgId = new EndpointGroupId("consumerEpg1");\r
+ private final EndpointGroupId providerEpgId = new EndpointGroupId("providerEpg1");\r
+ private final ContractId contractId = new ContractId("contract1");\r
+ private final TenantId tenantId = new TenantId("tenant1");\r
+ private final ClassifierName classifierName = ClassifierName.getDefaultInstance("classifier1");\r
+ private final SubjectName subjectName = SubjectName.getDefaultInstance("subject1");\r
+ private final RuleName ruleName = new RuleName("rule1");\r
+\r
+ private InstanceIdentifier<ResolvedPolicy> rpIid;\r
+ private String expectedName;\r
+\r
+ @Before\r
+ public void init() {\r
+ rpIid = InstanceIdentifier.create(ResolvedPolicy.class);\r
+ expectedName = tenantId.getValue() + IidSflowNameUtil.KEY_DELIMETER + contractId.getValue()\r
+ + IidSflowNameUtil.KEY_DELIMETER + subjectName.getValue() + IidSflowNameUtil.DELIMETER\r
+ + ruleName.getValue() + IidSflowNameUtil.DELIMETER + classifierName.getValue()\r
+ + IidSflowNameUtil.DELIMETER + FlowCacheCons.Value.BYTES.get();\r
+ }\r
+\r
+ @Test\r
+ public void testCreateFlowCache_EtherTypeClassifier_IPv4() {\r
+ ParameterValueList parameterValues = new ParameterValueList();\r
+ parameterValues.addEthertype(EtherTypeClassifierDefinition.IPv4_VALUE);\r
+\r
+ Classifier classifier = newEtherTypeClassifier(parameterValues);\r
+ ResolvedPolicy rp = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifier);\r
+\r
+ FlowCache flowCache = callCreateFlowCache(rp, classifier);\r
+\r
+ assertNotNull(flowCache);\r
+\r
+ List<String> keys = Arrays.asList(flowCache.getKeyNames());\r
+ List<String> expectedKeys = ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCache.getName());\r
+ assertEquals(expectedKeys.size(), keys.size());\r
+ assertTrue(keys.containsAll(expectedKeys));\r
+ }\r
+\r
+ @Test\r
+ public void testCreateFlowCache_IpProtoClassifier_TCP_IPv4() {\r
+\r
+ ParameterValueList parameterValues = new ParameterValueList();\r
+ parameterValues.addEthertype(EtherTypeClassifierDefinition.IPv4_VALUE)\r
+ .addProto(IpProtoClassifierDefinition.TCP_VALUE);\r
+\r
+ Classifier classifier = newIpProtoClassifier(parameterValues);\r
+ ResolvedPolicy rp = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifier);\r
+\r
+ FlowCache flowCache = callCreateFlowCache(rp, classifier);\r
+\r
+ assertNotNull(flowCache);\r
+\r
+ List<String> keys = Arrays.asList(flowCache.getKeyNames());\r
+ List<String> expectedKeys =\r
+ ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(), FlowCacheCons.Key.IP_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCache.getName());\r
+ assertEquals(expectedKeys.size(), keys.size());\r
+ assertTrue(keys.containsAll(expectedKeys));\r
+ }\r
+\r
+ @Test\r
+ public void testCreateFlowCache_IpProtoClassifier_UDP_noEthertype() {\r
+ ParameterValueList parameterValues = new ParameterValueList();\r
+ parameterValues.addProto(IpProtoClassifierDefinition.UDP_VALUE);\r
+\r
+ Classifier classifier = newIpProtoClassifier(parameterValues);\r
+ ResolvedPolicy rp = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifier);\r
+\r
+ FlowCache flowCache = callCreateFlowCache(rp, classifier);\r
+\r
+ assertNotNull(flowCache);\r
+\r
+ List<String> keys = Arrays.asList(flowCache.getKeyNames());\r
+ List<String> expectedKeys =\r
+ ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(), FlowCacheCons.Key.IP_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCache.getName());\r
+ assertEquals(expectedKeys.size(), keys.size());\r
+ assertTrue(keys.containsAll(expectedKeys));\r
+ }\r
+\r
+ @Test\r
+ public void testCreateFlowCache_L4Classifier_dstPort() {\r
+ ParameterValueList parameterValues = new ParameterValueList();\r
+ parameterValues.addEthertype(EtherTypeClassifierDefinition.IPv4_VALUE)\r
+ .addProto(IpProtoClassifierDefinition.TCP_VALUE)\r
+ .addDstPort((long) 80);\r
+ Classifier classifier = newL4Classifier(parameterValues);\r
+ ResolvedPolicy rp = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifier);\r
+\r
+ FlowCache flowCache = callCreateFlowCache(rp, classifier);\r
+\r
+ assertNotNull(flowCache);\r
+\r
+ List<String> keys = Arrays.asList(flowCache.getKeyNames());\r
+ List<String> expectedKeys = ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_PROTOCOL.get(), FlowCacheCons.Key.TCP_DST_PORT.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCache.getName());\r
+ assertEquals(expectedKeys.size(), keys.size());\r
+ assertTrue(keys.containsAll(expectedKeys));\r
+\r
+ ParameterValueList parameterValuesUDP = new ParameterValueList();\r
+ parameterValuesUDP.addEthertype(EtherTypeClassifierDefinition.IPv4_VALUE)\r
+ .addProto(IpProtoClassifierDefinition.UDP_VALUE)\r
+ .addDstPort((long) 80);\r
+ Classifier classifierUDP = newL4Classifier(parameterValuesUDP);\r
+ ResolvedPolicy rpUDP = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifierUDP);\r
+\r
+ FlowCache flowCacheUDP = callCreateFlowCache(rpUDP, classifierUDP);\r
+\r
+ assertNotNull(flowCacheUDP);\r
+\r
+ List<String> keysUDP = Arrays.asList(flowCacheUDP.getKeyNames());\r
+ List<String> expectedKeysUDP = ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_PROTOCOL.get(), FlowCacheCons.Key.UDP_DST_PORT.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCacheUDP.getName());\r
+ assertEquals(expectedKeysUDP.size(), keysUDP.size());\r
+ assertTrue(keysUDP.containsAll(expectedKeysUDP));\r
+ }\r
+\r
+ @Test\r
+ public void testCreateFlowCache_L4Classifier_srcPort() {\r
+ ParameterValueList parameterValues = new ParameterValueList();\r
+ parameterValues.addEthertype(EtherTypeClassifierDefinition.IPv4_VALUE)\r
+ .addProto(IpProtoClassifierDefinition.TCP_VALUE)\r
+ .addSrcPort((long) 80);\r
+ Classifier classifier = newL4Classifier(parameterValues);\r
+ ResolvedPolicy rp = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifier);\r
+\r
+ FlowCache flowCache = callCreateFlowCache(rp, classifier);\r
+\r
+ assertNotNull(flowCache);\r
+\r
+ List<String> keys = Arrays.asList(flowCache.getKeyNames());\r
+ List<String> expectedKeys = ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_PROTOCOL.get(), FlowCacheCons.Key.TCP_SRC_PORT.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCache.getName());\r
+ assertEquals(expectedKeys.size(), keys.size());\r
+ assertTrue(keys.containsAll(expectedKeys));\r
+\r
+ ParameterValueList parameterValuesUDP = new ParameterValueList();\r
+ parameterValuesUDP.addEthertype(EtherTypeClassifierDefinition.IPv4_VALUE)\r
+ .addProto(IpProtoClassifierDefinition.UDP_VALUE)\r
+ .addSrcPort((long) 80);\r
+ Classifier classifierUDP = newL4Classifier(parameterValuesUDP);\r
+ ResolvedPolicy rpUDP = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName, consumerEpgId,\r
+ providerEpgId, classifierUDP);\r
+\r
+ FlowCache flowCacheUDP = callCreateFlowCache(rpUDP, classifierUDP);\r
+\r
+ assertNotNull(flowCacheUDP);\r
+\r
+ List<String> keysUDP = Arrays.asList(flowCacheUDP.getKeyNames());\r
+ List<String> expectedKeysUDP = ImmutableList.of(FlowCacheCons.Key.ETH_PROTOCOL.get(),\r
+ FlowCacheCons.Key.IP_PROTOCOL.get(), FlowCacheCons.Key.UDP_SRC_PORT.get(),\r
+ FlowCacheCons.Key.IP_SOURCE.get(), FlowCacheCons.Key.IP_DESTINATION.get());\r
+\r
+ assertEquals(expectedName, flowCacheUDP.getName());\r
+ assertEquals(expectedKeysUDP.size(), keysUDP.size());\r
+ assertTrue(keysUDP.containsAll(expectedKeysUDP));\r
+ }\r
+\r
+ private Classifier newClassifier(ClassifierDefinitionId classifierDefinitionId,\r
+ ParameterValueList parameterValues) {\r
+ return new ClassifierBuilder().setName(classifierName)\r
+ .setClassifierDefinitionId(classifierDefinitionId)\r
+ .setParameterValue(parameterValues)\r
+ .build();\r
+ }\r
+\r
+ private Classifier newEtherTypeClassifier(ParameterValueList parameterValues) {\r
+ return newClassifier(EtherTypeClassifierDefinition.ID, parameterValues);\r
+ }\r
+\r
+ private Classifier newIpProtoClassifier(ParameterValueList parameterValues) {\r
+ return newClassifier(IpProtoClassifierDefinition.ID, parameterValues);\r
+ }\r
+\r
+ private Classifier newL4Classifier(ParameterValueList parameterValues) {\r
+ return newClassifier(L4ClassifierDefinition.ID, parameterValues);\r
+ }\r
+\r
+ private FlowCache callCreateFlowCache(ResolvedPolicy rp, Classifier classifier) {\r
+ return FlowCacheFactory.createFlowCache(\r
+ TestUtils.getClassifierIid(ResolvedPolicyClassifierListener.resolveClassifiers(rp, rpIid)), classifier,\r
+ FlowCacheCons.Value.BYTES);\r
+ }\r
+\r
+ @SuppressWarnings("serial")\r
+ private class ParameterValueList extends ArrayList<ParameterValue> {\r
+\r
+ ParameterValueList() {\r
+ super();\r
+ }\r
+\r
+ private ParameterValueList addEthertype(Long value) {\r
+ this.add(newParameterValue(EtherTypeClassifierDefinition.ETHERTYPE_PARAM, value));\r
+ return this;\r
+ }\r
+\r
+ private ParameterValueList addProto(Long value) {\r
+ this.add(newParameterValue(IpProtoClassifierDefinition.PROTO_PARAM, value));\r
+ return this;\r
+ }\r
+\r
+ private ParameterValueList addDstPort(Long value) {\r
+ this.add(newParameterValue(L4ClassifierDefinition.DST_PORT_PARAM, value));\r
+ return this;\r
+ }\r
+\r
+ private ParameterValueList addSrcPort(Long value) {\r
+ this.add(newParameterValue(L4ClassifierDefinition.SRC_PORT_PARAM, value));\r
+ return this;\r
+ }\r
+\r
+ private ParameterValue newParameterValue(String parameterName, Long intValue) {\r
+ return new ParameterValueBuilder().setName(new ParameterName(parameterName)).setIntValue(intValue).build();\r
+ }\r
+\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertFalse;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertTrue;\r
+import static org.junit.Assert.fail;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+\r
+public class FlowCacheFilterBuilderTest {\r
+\r
+ private static final String VALUE_1 = "value_1";\r
+ private static final String VALUE_2 = "value_2";\r
+ private static final String VALUE_3 = "value_3";\r
+ private static final List<String> LIST = new ArrayList<>();\r
+\r
+ private FlowCacheFilter.FlowCacheFilterBuilder builder;\r
+\r
+ @Before\r
+ public void init() {\r
+ builder = new FlowCacheFilter.FlowCacheFilterBuilder();\r
+ LIST.add(VALUE_1);\r
+ LIST.add(VALUE_2);\r
+ }\r
+\r
+ @Test\r
+ public void testConstructor() {\r
+ FlowCacheFilter.FlowCacheFilterBuilder b = null;\r
+ try {\r
+ b = new FlowCacheFilter.FlowCacheFilterBuilder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(b);\r
+ assertNotNull(b.getValues());\r
+ assertTrue(b.getValues().isEmpty());\r
+ }\r
+\r
+ @Test\r
+ public void testSetValues() {\r
+ builder.setValues(LIST);\r
+\r
+ assertFalse(builder.getValues().isEmpty());\r
+ assertEquals(LIST.size(), builder.getValues().size());\r
+ assertEquals(LIST.get(0), builder.getValues().get(0));\r
+ }\r
+\r
+ @Test\r
+ public void testAddValue() {\r
+ builder.setValues(LIST);\r
+ int expectedSize = LIST.size() + 1;\r
+\r
+ builder.addValue(VALUE_3);\r
+\r
+ assertEquals(expectedSize, builder.getValues().size());\r
+ }\r
+\r
+ @Test\r
+ public void testBuild() {\r
+ builder.setValues(LIST);\r
+\r
+ FlowCacheFilter filter = builder.build();\r
+\r
+ assertTrue(filter.getValue().contains(VALUE_1));\r
+ assertTrue(filter.getValue().contains(VALUE_2));\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.fail;\r
+\r
+import org.junit.Test;\r
+\r
+public class FlowCacheFilterTest {\r
+\r
+ @Test\r
+ public void testBuilder() {\r
+ FlowCacheFilter.FlowCacheFilterBuilder builder = null;\r
+ try {\r
+ builder = FlowCacheFilter.builder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(builder);\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertFalse;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.assertTrue;\r
+import static org.junit.Assert.fail;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+\r
+public class FlowCacheKeysBuilderTest {\r
+\r
+ private static final String VALUE_1 = "value_1";\r
+ private static final String VALUE_2 = "value_2";\r
+ private static final String VALUE_3 = "value_3";\r
+ private static final List<String> LIST = new ArrayList<>();\r
+\r
+ private FlowCacheKeys.FlowCacheKeysBuilder builder;\r
+\r
+ @Before\r
+ public void init() {\r
+ builder = new FlowCacheKeys.FlowCacheKeysBuilder();\r
+ LIST.add(VALUE_1);\r
+ LIST.add(VALUE_2);\r
+ }\r
+\r
+ @Test\r
+ public void testConstructor() {\r
+ FlowCacheKeys.FlowCacheKeysBuilder b = null;\r
+ try {\r
+ b = new FlowCacheKeys.FlowCacheKeysBuilder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(b);\r
+ assertNotNull(b.getValues());\r
+ assertTrue(b.getValues().isEmpty());\r
+ }\r
+\r
+ @Test\r
+ public void testSetValues() {\r
+ builder.setValues(LIST);\r
+\r
+ assertFalse(builder.getValues().isEmpty());\r
+ assertEquals(LIST.size(), builder.getValues().size());\r
+ assertEquals(LIST.get(0), builder.getValues().get(0));\r
+ }\r
+\r
+ @Test\r
+ public void testAddValue() {\r
+ builder.setValues(LIST);\r
+ int expectedSize = LIST.size() + 1;\r
+\r
+ builder.addValue(VALUE_3);\r
+\r
+ assertEquals(expectedSize, builder.getValues().size());\r
+ }\r
+\r
+ @Test\r
+ public void testBuild() {\r
+ builder.setValues(LIST);\r
+\r
+ FlowCacheKeys keys = builder.build();\r
+\r
+ assertTrue(keys.getValue().contains(VALUE_1));\r
+ assertTrue(keys.getValue().contains(VALUE_2));\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.fail;\r
+\r
+import org.junit.Test;\r
+\r
+public class FlowCacheKeysTest {\r
+\r
+ @Test\r
+ public void testBuilder() {\r
+ FlowCacheKeys.FlowCacheKeysBuilder builder = null;\r
+ try {\r
+ builder = FlowCacheKeys.builder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(builder);\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.flowcache;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.junit.Assert.assertNotNull;\r
+import static org.junit.Assert.fail;\r
+\r
+import java.util.ArrayList;\r
+import java.util.List;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.policy.rev140421.HasDirection;\r
+\r
+public class FlowCacheTest {\r
+\r
+ private static final String KEY_1 = "key_1";\r
+ private static final String KEY_2 = "key_2";\r
+ private static final String NAME_1 = "name_1";\r
+ private static final HasDirection.Direction direction = HasDirection.Direction.Bidirectional;\r
+ private static final String VALUE_1 = "value_1";\r
+ private static FlowCacheDefinition flowCacheDefinition;\r
+ private List<String> keysValues;\r
+ private String json;\r
+\r
+ @Before\r
+ public void init() {\r
+ keysValues = new ArrayList<>();\r
+ keysValues.add(KEY_1);\r
+ keysValues.add(KEY_2);\r
+\r
+ FlowCacheDefinition.FlowCacheDefinitionBuilder flowCacheDefinitionBuilder = FlowCacheDefinition.builder();\r
+ flowCacheDefinitionBuilder.getKeysBuilder().setValues(keysValues);\r
+ flowCacheDefinition = flowCacheDefinitionBuilder.setValue(VALUE_1).setLog(true).build();\r
+\r
+ json = "{\"keys\":\"" + KEY_1 + "," + KEY_2 + "\"," + "\"value\":\"" + VALUE_1 + "\","\r
+ + "\"filter\":\"\",\"log\":true}";\r
+ }\r
+\r
+ @Test\r
+ public void testBuilder() {\r
+ FlowCache.FlowCacheBuilder builder = null;\r
+ try {\r
+ builder = FlowCache.builder();\r
+ } catch (Exception e) {\r
+ fail("Exception thrown: " + e.getMessage());\r
+ }\r
+ assertNotNull(builder);\r
+ }\r
+\r
+ @Test\r
+ public void testConstructor_Implicitely() {\r
+ FlowCache flowCache =\r
+ FlowCache.builder().setDefinition(flowCacheDefinition).setDirection(direction).setName(NAME_1).build();\r
+\r
+ assertEquals(keysValues.size(), flowCache.getKeyNum());\r
+ assertEquals(keysValues.get(0), flowCache.getKeyNames()[0]);\r
+ assertEquals(keysValues.get(1), flowCache.getKeyNames()[1]);\r
+ assertEquals(FlowCache.API_FLOW + NAME_1 + FlowCache.SUFFIX_JSON, flowCache.getPath());\r
+ assertEquals(json, flowCache.getJsonDefinition());\r
+\r
+ }\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.util;\r
+\r
+import static org.junit.Assert.assertEquals;\r
+import static org.mockito.Mockito.mock;\r
+import static org.mockito.Mockito.when;\r
+\r
+import org.junit.Before;\r
+import org.junit.Test;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.statistics.ResolvedPolicyClassifierListener;\r
+import org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test.TestUtils;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ClassifierName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.Classifier;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.ClassifierKey;\r
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.ResolvedPolicy;\r
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;\r
+\r
+public class IidSflowNameUtilTest {\r
+\r
+ private final EndpointGroupId consumerEpgId = new EndpointGroupId("consumerEpg1");\r
+ private final EndpointGroupId providerEpgId = new EndpointGroupId("providerEpg1");\r
+ private final ContractId contractId = new ContractId("contract1");\r
+ private final TenantId tenantId = new TenantId("tenant1");\r
+ private final ClassifierName classifierName = ClassifierName.getDefaultInstance("classifier1");\r
+ private final SubjectName subjectName = SubjectName.getDefaultInstance("subject1");\r
+ private final RuleName ruleName = new RuleName("rule1");\r
+ private InstanceIdentifier<ResolvedPolicy> rpIid;\r
+ private String testName;\r
+ private ResolvedPolicy resolvedPolicy;\r
+\r
+ @Before\r
+ public void init() {\r
+ Classifier classifier = mock(Classifier.class);\r
+ when(classifier.getKey()).thenReturn(new ClassifierKey(classifierName));\r
+\r
+ resolvedPolicy = TestUtils.newResolvedPolicy(tenantId, contractId, subjectName, ruleName,\r
+ consumerEpgId, providerEpgId, classifier);\r
+\r
+ rpIid = InstanceIdentifier.create(ResolvedPolicy.class);\r
+ testName =\r
+ tenantId.getValue() + IidSflowNameUtil.KEY_DELIMETER + contractId.getValue() + IidSflowNameUtil.KEY_DELIMETER + subjectName\r
+ .getValue() + IidSflowNameUtil.DELIMETER + ruleName.getValue() + IidSflowNameUtil.DELIMETER + classifierName\r
+ .getValue() + IidSflowNameUtil.DELIMETER + FlowCacheCons.Value.BYTES.get();\r
+ }\r
+\r
+ @Test\r
+ public void testCreateFlowCacheName() {\r
+ InstanceIdentifier<Classifier> classifierIid = TestUtils.getClassifierIid(\r
+ ResolvedPolicyClassifierListener.resolveClassifiers(resolvedPolicy, rpIid));\r
+\r
+ assertEquals(testName,\r
+ IidSflowNameUtil.createFlowCacheName(classifierIid, FlowCacheCons.Value.BYTES));\r
+ }\r
+\r
+ @Test\r
+ public void testResolveContractIdFromFlowCacheName() {\r
+ assertEquals(contractId.getValue(),\r
+ IidSflowNameUtil.resolveContractIdFromFlowCacheName(testName).getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testResolveSubjectNameFromFlowCacheName() {\r
+ assertEquals(subjectName.getValue(),\r
+ IidSflowNameUtil.resolveSubjectNameFromFlowCacheName(testName).getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testResolveRuleNameFromFlowCacheName() {\r
+ assertEquals(ruleName.getValue(),\r
+ IidSflowNameUtil.resolveRuleNameFromFlowCacheName(testName).getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testResolveClassifierNameFromFlowCacheName() {\r
+ assertEquals(classifierName.getValue(),\r
+ IidSflowNameUtil.resolveClassifierNameFromFlowCacheName(testName).getValue());\r
+ }\r
+\r
+ @Test\r
+ public void testResolveFlowCacheValue() {\r
+ assertEquals(FlowCacheCons.Value.BYTES.get(),\r
+ IidSflowNameUtil.resolveFlowCacheValue(testName));\r
+ }\r
+\r
+}\r
--- /dev/null
+package org.opendaylight.groupbasedpolicy.renderer.ofoverlay.test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import com.google.common.collect.ImmutableList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.ContractId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.EndpointGroupId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.RuleName;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.SubjectName;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.common.rev140421.TenantId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.classifiers.Classifier;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.has.resolved.rules.ResolvedRuleBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.ResolvedPolicy;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.ResolvedPolicyBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.resolved.policy.PolicyRuleGroupWithEndpointConstraints;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.resolved.policy.PolicyRuleGroupWithEndpointConstraintsBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.resolved.policy.policy.rule.group.with.endpoint.constraints.PolicyRuleGroup;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.groupbasedpolicy.resolved.policy.rev150828.resolved.policies.resolved.policy.policy.rule.group.with.endpoint.constraints.PolicyRuleGroupBuilder;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public class TestUtils {
+
+ // taken from org.opendaylight.groupbasedpolicy.renderer.faas.FaasPolicyManagerTest
+ // by Khaldoon Al-zoubi; modified as necessary
+ public static ResolvedPolicy newResolvedPolicy(TenantId tenantId, ContractId contractId, SubjectName subjectName,
+ RuleName ruleName, EndpointGroupId consumerEpgId, EndpointGroupId providerEpgId, Classifier classifier) {
+ ResolvedPolicyBuilder builder = new ResolvedPolicyBuilder();
+ builder.setConsumerEpgId(consumerEpgId);
+ builder.setConsumerTenantId(tenantId);
+ builder.setProviderEpgId(providerEpgId);
+ builder.setProviderTenantId(tenantId);
+ List<PolicyRuleGroupWithEndpointConstraints> pRulesGrpsWEp = new ArrayList<>();
+ PolicyRuleGroupWithEndpointConstraintsBuilder pRulesGrpWEp =
+ new PolicyRuleGroupWithEndpointConstraintsBuilder();
+ List<PolicyRuleGroup> pRulesGrps = new ArrayList<>();
+ PolicyRuleGroupBuilder pRulesGrp = new PolicyRuleGroupBuilder();
+ pRulesGrp.setContractId(contractId);
+ pRulesGrp.setTenantId(tenantId);
+ pRulesGrp.setSubjectName(subjectName);
+ pRulesGrp.setResolvedRule(ImmutableList
+ .of(new ResolvedRuleBuilder().setName(ruleName).setClassifier(ImmutableList.of(classifier)).build()));
+ pRulesGrps.add(pRulesGrp.build());
+ pRulesGrpWEp.setPolicyRuleGroup(pRulesGrps);
+ pRulesGrpsWEp.add(pRulesGrpWEp.build());
+ builder.setPolicyRuleGroupWithEndpointConstraints(pRulesGrpsWEp);
+ return builder.build();
+ }
+
+ public static InstanceIdentifier<Classifier> getClassifierIid(
+ Map<InstanceIdentifier<Classifier>, Classifier> resolvedClassifiers) {
+ Map.Entry<InstanceIdentifier<Classifier>, Classifier> firstEntry =
+ resolvedClassifiers.entrySet().iterator().next();
+ return firstEntry.getKey();
+ }
+}