[ONOS-6054] Implement DistributMappingStore with unit test

Change-Id: Ie12ab37bcdafabcad1935edff2f91dcd882c6705
diff --git a/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java b/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java
index d0f085a..0125fe5 100644
--- a/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java
+++ b/apps/mappingmanagement/mgr/src/main/java/org/onosproject/mapping/impl/DistributedMappingStore.java
@@ -15,20 +15,44 @@
  */
 package org.onosproject.mapping.impl;
 
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Maps;
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
 import org.apache.felix.scr.annotations.Service;
+import org.onosproject.mapping.DefaultMapping;
+import org.onosproject.mapping.DefaultMappingEntry;
 import org.onosproject.mapping.Mapping;
-import org.onosproject.mapping.MappingEvent;
 import org.onosproject.mapping.MappingEntry;
+import org.onosproject.mapping.MappingEvent;
+import org.onosproject.mapping.MappingId;
+import org.onosproject.mapping.MappingKey;
 import org.onosproject.mapping.MappingStore;
 import org.onosproject.mapping.MappingStoreDelegate;
+import org.onosproject.mapping.MappingTreatment;
+import org.onosproject.mapping.MappingValue;
+import org.onosproject.mapping.actions.MappingAction;
+import org.onosproject.mapping.addresses.MappingAddress;
+import org.onosproject.mapping.instructions.MappingInstruction;
 import org.onosproject.net.DeviceId;
+import org.onosproject.net.device.DeviceService;
 import org.onosproject.store.AbstractStore;
-import org.osgi.service.component.ComponentContext;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
 import org.slf4j.Logger;
 
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
 import static org.slf4j.LoggerFactory.getLogger;
 
 /**
@@ -42,73 +66,186 @@
 
     private final Logger log = getLogger(getClass());
 
+    private ConsistentMap<MappingId, Mapping> database;
+    private ConsistentMap<MappingId, Mapping> cache;
+
+    private Map<MappingId, Mapping> databaseMap;
+    private Map<MappingId, Mapping> cacheMap;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected StorageService storageService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected DeviceService deviceService;
+
+    private final MapEventListener<MappingId, Mapping> listener = new InternalListener();
+
     @Activate
-    public void activate(ComponentContext context) {
+    public void activate() {
+
+        Serializer serializer = Serializer.using(KryoNamespaces.API,
+                                                    Mapping.class,
+                                                    DefaultMapping.class,
+                                                    MappingId.class,
+                                                    MappingEvent.Type.class,
+                                                    MappingKey.class,
+                                                    MappingValue.class,
+                                                    MappingAddress.class,
+                                                    MappingAddress.Type.class,
+                                                    MappingAction.class,
+                                                    MappingAction.Type.class,
+                                                    MappingTreatment.class,
+                                                    MappingInstruction.class,
+                                                    MappingInstruction.Type.class);
+
+        database = storageService.<MappingId, Mapping>consistentMapBuilder()
+                        .withName("onos-mapping-database")
+                        .withSerializer(serializer)
+                        .build();
+
+        cache = storageService.<MappingId, Mapping>consistentMapBuilder()
+                        .withName("onos-mapping-cache")
+                        .withSerializer(serializer)
+                        .build();
+
+        database.addListener(listener);
+        cache.addListener(listener);
+        databaseMap = database.asJavaMap();
+        cacheMap = cache.asJavaMap();
         log.info("Started");
     }
 
     @Deactivate
-    public void deactivate(ComponentContext context) {
+    public void deactivate() {
+        database.removeListener(listener);
+        cache.removeListener(listener);
         log.info("Stopped");
     }
 
-    @Override
-    public void setDelegate(MappingStoreDelegate delegate) {
-
+    /**
+     * Obtains map representation of mapping store.
+     *
+     * @param type mapping store type
+     * @return map representation of mapping store
+     */
+    private Map<MappingId, Mapping> getStoreMap(Type type) {
+        switch (type) {
+            case MAP_DATABASE:
+                return databaseMap;
+            case MAP_CACHE:
+                return cacheMap;
+            default:
+                log.warn("Unrecognized map store type {}", type);
+                return Maps.newConcurrentMap();
+        }
     }
 
-    @Override
-    public void unsetDelegate(MappingStoreDelegate delegate) {
-
-    }
-
-    @Override
-    public boolean hasDelegate() {
-        return false;
+    /**
+     * Obtains mapping store.
+     *
+     * @param type mapping store type
+     * @return mapping store
+     */
+    private ConsistentMap<MappingId, Mapping> getStore(Type type) {
+        switch (type) {
+            case MAP_DATABASE:
+                return database;
+            case MAP_CACHE:
+                return cache;
+            default:
+                throw new IllegalArgumentException("Wrong mapping store " + type);
+        }
     }
 
     @Override
     public int getMappingCount(Type type) {
-        return 0;
+        AtomicInteger sum = new AtomicInteger(0);
+        deviceService.getDevices().forEach(device ->
+                sum.addAndGet(Iterables.size(getMappingEntries(type, device.id()))));
+        return sum.get();
     }
 
     @Override
     public MappingEntry getMappingEntry(Type type, Mapping mapping) {
-        return null;
+
+        return new DefaultMappingEntry(getStoreMap(type).get(mapping.id()));
     }
 
     @Override
     public Iterable<MappingEntry> getMappingEntries(Type type, DeviceId deviceId) {
-        return null;
+
+        Map<MappingId, Mapping> storeMap = getStoreMap(type);
+        return ImmutableList.copyOf(storeMap.values().stream()
+                                             .filter(m -> m.deviceId() == deviceId)
+                                             .map(DefaultMappingEntry::new)
+                                             .collect(Collectors.toList()));
     }
 
     @Override
     public void storeMapping(Type type, Mapping mapping) {
 
+        getStore(type).put(mapping.id(), mapping);
     }
 
     @Override
     public void deleteMapping(Type type, Mapping mapping) {
 
+        getStore(type).remove(mapping.id());
     }
 
     @Override
     public MappingEvent addOrUpdateMappingEntry(Type type, MappingEntry entry) {
+        // TODO: this will be implemented when management plane is ready
+        log.error("This method will be available when management plane is ready");
         return null;
     }
 
     @Override
     public MappingEvent removeMappingEntry(Type type, MappingEntry entry) {
+        // TODO: this will be implemented when management plane is ready
+        log.error("This method will be available when management plane is ready");
         return null;
     }
 
     @Override
     public MappingEvent pendingMappingEntry(Type type, MappingEntry entry) {
+        // TODO: this will be implemented when management plane is ready
+        log.error("This method will be available when management plane is ready");
         return null;
     }
 
     @Override
     public void purgeMappingEntries(Type type) {
+        getStore(type).clear();
+    }
 
+    /**
+     * Event listener to notify delegates about mapping events.
+     */
+    private class InternalListener implements MapEventListener<MappingId, Mapping> {
+
+        @Override
+        public void event(MapEvent<MappingId, Mapping> event) {
+            final MappingEvent.Type type;
+            final Mapping mapping;
+
+            switch (event.type()) {
+                case INSERT:
+                    type = MappingEvent.Type.MAPPING_ADDED;
+                    mapping = event.newValue().value();
+                    break;
+                case UPDATE:
+                    type = MappingEvent.Type.MAPPING_UPDATED;
+                    mapping = event.newValue().value();
+                    break;
+                case REMOVE:
+                    type = MappingEvent.Type.MAPPING_REMOVED;
+                    mapping = event.oldValue().value();
+                    break;
+                default:
+                    throw new IllegalArgumentException("Wrong event type " + event.type());
+            }
+            notifyDelegate(new MappingEvent(type, mapping));
+        }
     }
 }
diff --git a/apps/mappingmanagement/mgr/src/test/java/org/onosproject/mapping/impl/DistributedMappingStoreTest.java b/apps/mappingmanagement/mgr/src/test/java/org/onosproject/mapping/impl/DistributedMappingStoreTest.java
new file mode 100644
index 0000000..57b7ed3
--- /dev/null
+++ b/apps/mappingmanagement/mgr/src/test/java/org/onosproject/mapping/impl/DistributedMappingStoreTest.java
@@ -0,0 +1,171 @@
+/*
+ * Copyright 2017-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.mapping.impl;
+
+import com.google.common.collect.Lists;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.packet.ChassisId;
+import org.onlab.packet.IpPrefix;
+import org.onosproject.mapping.DefaultMapping;
+import org.onosproject.mapping.DefaultMappingKey;
+import org.onosproject.mapping.DefaultMappingTreatment;
+import org.onosproject.mapping.DefaultMappingValue;
+import org.onosproject.mapping.Mapping;
+import org.onosproject.mapping.MappingKey;
+import org.onosproject.mapping.MappingTreatment;
+import org.onosproject.mapping.MappingValue;
+import org.onosproject.mapping.actions.MappingAction;
+import org.onosproject.mapping.actions.MappingActions;
+import org.onosproject.mapping.addresses.MappingAddress;
+import org.onosproject.mapping.addresses.MappingAddresses;
+import org.onosproject.net.Annotations;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.DefaultDevice;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.device.DeviceServiceAdapter;
+import org.onosproject.net.provider.ProviderId;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.hamcrest.Matchers.is;
+import static org.onosproject.mapping.MappingStore.Type.MAP_DATABASE;
+
+/**
+ * Unit tests for DistributedMappingStore.
+ */
+public class DistributedMappingStoreTest {
+    private static final DeviceId DEVICE_ID_1 = DeviceId.deviceId("foo");
+    private static final DeviceId DEVICE_ID_2 = DeviceId.deviceId("bar");
+    private static final String IP_ADDRESS = "1.2.3.4/24";
+
+    private DistributedMappingStore mappingStore;
+    private Mapping mapping1;
+    private Mapping mapping2;
+
+    private Device device1;
+    private Device device2;
+
+    /**
+     * Sets up the storage service test harness.
+     */
+    @Before
+    public void setUp() {
+        mappingStore = new DistributedMappingStore();
+        mappingStore.storageService = new TestStorageService();
+        mappingStore.deviceService = new InternalDeviceServiceAdapter();
+        mappingStore.setDelegate(event -> {
+        });
+
+        IpPrefix ipPrefix = IpPrefix.valueOf(IP_ADDRESS);
+        MappingAddress address = MappingAddresses.ipv4MappingAddress(ipPrefix);
+
+        MappingKey key = DefaultMappingKey.builder()
+                .withAddress(address)
+                .build();
+
+        MappingAction action = MappingActions.noAction();
+        MappingTreatment treatment = DefaultMappingTreatment.builder()
+                .withAddress(address)
+                .setUnicastPriority(10)
+                .setUnicastWeight(10)
+                .build();
+
+        MappingValue value = DefaultMappingValue.builder()
+                .withAction(action)
+                .add(treatment)
+                .build();
+
+        device1 = new MockDevice(ProviderId.NONE, DEVICE_ID_1, Device.Type.OTHER,
+                "foo.inc", "0", "0", "0", null,
+                DefaultAnnotations.builder().build());
+
+        device2 = new MockDevice(ProviderId.NONE, DEVICE_ID_2, Device.Type.OTHER,
+                "foo.inc", "0", "0", "0", null,
+                DefaultAnnotations.builder().build());
+
+        mapping1 = DefaultMapping.builder()
+                .forDevice(DEVICE_ID_1)
+                .withId(1000L)
+                .withKey(key)
+                .withValue(value)
+                .build();
+
+        mapping2 = DefaultMapping.builder()
+                .forDevice(DEVICE_ID_2)
+                .withId(2000L)
+                .withKey(key)
+                .withValue(value)
+                .build();
+
+        mappingStore.activate();
+    }
+
+    private class InternalDeviceServiceAdapter extends DeviceServiceAdapter {
+
+        List<Device> devices = Lists.newArrayList();
+
+        @Override
+        public Iterable<Device> getDevices() {
+            devices.add(device1);
+            devices.add(device2);
+            return devices;
+        }
+    }
+
+    private class MockDevice extends DefaultDevice {
+        public MockDevice(ProviderId providerId, DeviceId id, Type type,
+                          String manufacturer, String hwVersion, String swVersion,
+                          String serialNumber, ChassisId chassisId, Annotations... annotations) {
+            super(providerId, id, type, manufacturer, hwVersion, swVersion, serialNumber,
+                    chassisId, annotations);
+        }
+    }
+
+    /**
+     * Tears down the mapping1 store.
+     */
+    @After
+    public void tearDown() {
+        mappingStore.deactivate();
+    }
+
+    /**
+     * Tests adding, removing and getting.
+     */
+    @Test
+    public void basics() {
+        mappingStore.storeMapping(MAP_DATABASE, mapping1);
+        mappingStore.storeMapping(MAP_DATABASE, mapping2);
+
+        assertThat("There should be one mapping1 in the map database.",
+                mappingStore.getMappingCount(MAP_DATABASE), is(2));
+        assertTrue("There should be one mapping1 in the map database.",
+                mapping1.equals(mappingStore.getMappingEntries(MAP_DATABASE, DEVICE_ID_1)
+                        .iterator().next()));
+        assertTrue("The mapping1 should be identical.",
+                mappingStore.getMappingEntry(MAP_DATABASE, mapping1).equals(mapping1));
+        mappingStore.deleteMapping(MAP_DATABASE, mapping1);
+        assertFalse("There should not be any mapping1 in the map database.",
+                mappingStore.getMappingEntries(MAP_DATABASE, DEVICE_ID_1).iterator().hasNext());
+    }
+}