ONOS-4018 - Enhance the DistributedRegionStore to make sure that a
device ID appears in at most one Region's list of devices.
Change-Id: I6d30fab2c09544c68f49b11682f08ee8ded060fe
diff --git a/core/store/dist/src/main/java/org/onosproject/store/region/impl/DistributedRegionStore.java b/core/store/dist/src/main/java/org/onosproject/store/region/impl/DistributedRegionStore.java
index 6243dac..009f5d0 100644
--- a/core/store/dist/src/main/java/org/onosproject/store/region/impl/DistributedRegionStore.java
+++ b/core/store/dist/src/main/java/org/onosproject/store/region/impl/DistributedRegionStore.java
@@ -169,6 +169,16 @@
@Override
public void addDevices(RegionId regionId, Collection<DeviceId> deviceIds) {
+ // Devices can only be a member in one region. Remove the device if it belongs to
+ // a different region than the region for which we are attempting to add it.
+ for (DeviceId deviceId : deviceIds) {
+ Region region = getRegionForDevice(deviceId);
+ if ((region != null) && (!regionId.id().equals(region.id().id()))) {
+ Set<DeviceId> deviceIdSet1 = ImmutableSet.of(deviceId);
+ removeDevices(region.id(), deviceIdSet1);
+ }
+ }
+
membershipRepo.compute(regionId, (id, existingDevices) -> {
if (existingDevices == null) {
return ImmutableSet.copyOf(deviceIds);
diff --git a/core/store/dist/src/test/java/org/onosproject/store/region/impl/DistributedRegionStoreTest.java b/core/store/dist/src/test/java/org/onosproject/store/region/impl/DistributedRegionStoreTest.java
index df3f048..5612e38 100644
--- a/core/store/dist/src/test/java/org/onosproject/store/region/impl/DistributedRegionStoreTest.java
+++ b/core/store/dist/src/test/java/org/onosproject/store/region/impl/DistributedRegionStoreTest.java
@@ -137,6 +137,15 @@
deviceIds = store.getRegionDevices(RID1);
assertEquals("incorrect device count", 3, deviceIds.size());
+ // Test adding DID3 to RID2 but it is already in RID1.
+ // DID3 will be removed from RID1 and added to RID2.
+ Region r2 = store.createRegion(RID2, "R2", CAMPUS, MASTERS);
+ store.addDevices(RID2, ImmutableSet.of(DID3));
+ deviceIds = store.getRegionDevices(RID1);
+ assertEquals("incorrect device count", 2, deviceIds.size());
+ deviceIds = store.getRegionDevices(RID2);
+ assertEquals("incorrect device count", 1, deviceIds.size());
+
store.removeDevices(RID1, ImmutableSet.of(DID2, DID3));
deviceIds = store.getRegionDevices(RID1);
assertEquals("incorrect device count", 1, deviceIds.size());