[CORD-46] Create a broadcast group for each subnet

DONE
- Expose subnet-to-ports information from DeviceProperties and DeviceConfiguration
- Create subnetNextObjectiveStore to store <DeviceId, IpPrefix> to nextId mapping
- Implement broadcast NextObjective in SpringOpenTTP
      Use ALL group type to achieve broadcast

TODO (not in this submission)
- Push ARP table for a host when its location is learned
- Push default ARP table miss rule. Action = to the broadcast group

Change-Id: I2de28095e85289e75af3fc7a02c811b270b342ad
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java
index c960adc..a5c1090 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultEdgeGroupHandler.java
@@ -52,9 +52,12 @@
                                   LinkService linkService,
                                   FlowObjectiveService flowObjService,
                                   EventuallyConsistentMap<
-                                  NeighborSetNextObjectiveStoreKey,
-                                  Integer> nsNextObjStore) {
-        super(deviceId, appId, config, linkService, flowObjService, nsNextObjStore);
+                                          NeighborSetNextObjectiveStoreKey,
+                                          Integer> nsNextObjStore,
+                                  EventuallyConsistentMap<SubnetNextObjectiveStoreKey,
+                                          Integer> subnetNextObjStore) {
+        super(deviceId, appId, config, linkService, flowObjService,
+              nsNextObjStore, subnetNextObjStore);
     }
 
     @Override
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java
index 9bbde2f..2606f48 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultGroupHandler.java
@@ -25,10 +25,11 @@
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Random;
 import java.util.Set;
 import java.util.stream.Collectors;
 
+import org.onlab.packet.Ip4Prefix;
+import org.onlab.packet.IpPrefix;
 import org.onlab.packet.MacAddress;
 import org.onlab.packet.MplsLabel;
 import org.onlab.util.KryoNamespace;
@@ -74,7 +75,8 @@
     //        new HashMap<NeighborSet, Integer>();
     protected EventuallyConsistentMap<
         NeighborSetNextObjectiveStoreKey, Integer> nsNextObjStore = null;
-    protected Random rand = new Random();
+    protected EventuallyConsistentMap<
+            SubnetNextObjectiveStoreKey, Integer> subnetNextObjStore = null;
 
     protected KryoNamespace.Builder kryo = new KryoNamespace.Builder()
             .register(URI.class).register(HashSet.class)
@@ -89,8 +91,10 @@
                                   LinkService linkService,
                                   FlowObjectiveService flowObjService,
                                   EventuallyConsistentMap<
-                                  NeighborSetNextObjectiveStoreKey,
-                                  Integer> nsNextObjStore) {
+                                          NeighborSetNextObjectiveStoreKey,
+                                          Integer> nsNextObjStore,
+                                  EventuallyConsistentMap<SubnetNextObjectiveStoreKey,
+                                          Integer> subnetNextObjStore) {
         this.deviceId = checkNotNull(deviceId);
         this.appId = checkNotNull(appId);
         this.deviceConfig = checkNotNull(config);
@@ -101,6 +105,7 @@
         nodeMacAddr = checkNotNull(config.getDeviceMac(deviceId));
         this.flowObjectiveService = flowObjService;
         this.nsNextObjStore = nsNextObjStore;
+        this.subnetNextObjStore = subnetNextObjStore;
 
         populateNeighborMaps();
     }
@@ -115,7 +120,8 @@
      * @param config interface to retrieve the device properties
      * @param linkService link service object
      * @param flowObjService flow objective service object
-     * @param nsNextObjStore next objective store map
+     * @param nsNextObjStore NeighborSet next objective store map
+     * @param subnetNextObjStore subnet next objective store map
      * @return default group handler type
      */
     public static DefaultGroupHandler createGroupHandler(DeviceId deviceId,
@@ -123,18 +129,23 @@
                                                          DeviceProperties config,
                                                          LinkService linkService,
                                                          FlowObjectiveService flowObjService,
-                                                         EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey,
-                                                                 Integer> nsNextObjStore) {
+                                                         EventuallyConsistentMap<
+                                                                 NeighborSetNextObjectiveStoreKey,
+                                                                 Integer> nsNextObjStore,
+                                                         EventuallyConsistentMap<SubnetNextObjectiveStoreKey,
+                                                                 Integer> subnetNextObjStore) {
         if (config.isEdgeDevice(deviceId)) {
             return new DefaultEdgeGroupHandler(deviceId, appId, config,
                                                linkService,
                                                flowObjService,
-                                               nsNextObjStore);
+                                               nsNextObjStore,
+                                               subnetNextObjStore);
         } else {
             return new DefaultTransitGroupHandler(deviceId, appId, config,
                                                   linkService,
                                                   flowObjService,
-                                                  nsNextObjStore);
+                                                  nsNextObjStore,
+                                                  subnetNextObjStore);
         }
     }
 
@@ -323,6 +334,44 @@
     }
 
     /**
+     * Returns the next objective associated with the neighborset.
+     * If there is no next objective for this neighborset, this API
+     * would create a next objective and return.
+     *
+     * @param prefix subnet information
+     * @return int if found or -1
+     */
+    public int getSubnetNextObjectiveId(IpPrefix prefix) {
+        Integer nextId = subnetNextObjStore.
+                get(new SubnetNextObjectiveStoreKey(deviceId, prefix));
+        if (nextId == null) {
+            log.trace("getSubnetNextObjectiveId in device{}: Next objective id "
+                              + "not found for {} and creating", deviceId, prefix);
+            log.trace("getSubnetNextObjectiveId: subnetNextObjStore contents for device {}: {}",
+                      deviceId,
+                      subnetNextObjStore.entrySet()
+                              .stream()
+                              .filter((subnetStoreEntry) ->
+                                              (subnetStoreEntry.getKey().deviceId().equals(deviceId)))
+                              .collect(Collectors.toList()));
+            createGroupsFromSubnetConfig();
+            nextId = subnetNextObjStore.
+                    get(new SubnetNextObjectiveStoreKey(deviceId, prefix));
+            if (nextId == null) {
+                log.warn("subnetNextObjStore: unable to create next objective");
+                return -1;
+            } else {
+                log.debug("subnetNextObjStore in device{}: Next objective id {} "
+                                  + "created for {}", deviceId, nextId, prefix);
+            }
+        } else {
+            log.trace("subnetNextObjStore in device{}: Next objective id {} "
+                              + "found for {}", deviceId, nextId, prefix);
+        }
+        return nextId;
+    }
+
+    /**
      * Checks if the next objective ID (group) for the neighbor set exists or not.
      *
      * @param ns neighbor set to check
@@ -486,6 +535,35 @@
         }
     }
 
+    public void createGroupsFromSubnetConfig() {
+        Map<Ip4Prefix, List<PortNumber>> subnetPortMap =
+                this.deviceConfig.getSubnetPortsMap(this.deviceId);
+
+        // Construct a broadcast group for each subnet
+        subnetPortMap.forEach((subnet, ports) -> {
+            int nextId = flowObjectiveService.allocateNextId();
+
+            NextObjective.Builder nextObjBuilder = DefaultNextObjective
+                    .builder().withId(nextId)
+                    .withType(NextObjective.Type.BROADCAST).fromApp(appId);
+
+            ports.forEach(port -> {
+                TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();
+                tBuilder.setOutput(port);
+                nextObjBuilder.addTreatment(tBuilder.build());
+            });
+
+            NextObjective nextObj = nextObjBuilder.add();
+            flowObjectiveService.next(deviceId, nextObj);
+            log.debug("createGroupFromSubnetConfig: Submited "
+                              + "next objective {} in device {}",
+                      nextId, deviceId);
+            SubnetNextObjectiveStoreKey key =
+                    new SubnetNextObjectiveStoreKey(deviceId, subnet);
+            subnetNextObjStore.put(key, nextId);
+        });
+    }
+
     public GroupKey getGroupKey(Object obj) {
         return new DefaultGroupKey(kryo.build().serialize(obj));
     }
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java
index 3cb73ab..b009e86 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DefaultTransitGroupHandler.java
@@ -45,9 +45,12 @@
                                   LinkService linkService,
                                   FlowObjectiveService flowObjService,
                                   EventuallyConsistentMap<
-                                  NeighborSetNextObjectiveStoreKey,
-                                  Integer> nsNextObjStore) {
-        super(deviceId, appId, config, linkService, flowObjService, nsNextObjStore);
+                                        NeighborSetNextObjectiveStoreKey,
+                                        Integer> nsNextObjStore,
+                                  EventuallyConsistentMap<SubnetNextObjectiveStoreKey,
+                                        Integer> subnetNextObjStore) {
+        super(deviceId, appId, config, linkService, flowObjService,
+              nsNextObjStore, subnetNextObjStore);
     }
 
     @Override
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/DeviceProperties.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/DeviceProperties.java
index 497f525..d28d38d 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/DeviceProperties.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/DeviceProperties.java
@@ -16,9 +16,12 @@
 package org.onosproject.segmentrouting.grouphandler;
 
 import java.util.List;
+import java.util.Map;
 
+import org.onlab.packet.Ip4Prefix;
 import org.onlab.packet.MacAddress;
 import org.onosproject.net.DeviceId;
+import org.onosproject.net.PortNumber;
 
 /**
  * Mechanism through which group handler module retrieves
@@ -33,6 +36,7 @@
      * @return segment id of a device
      */
     int getSegmentId(DeviceId deviceId);
+
     /**
      * Returns the Mac address of a device to be used in group creation.
      *
@@ -40,6 +44,7 @@
      * @return mac address of a device
      */
     MacAddress getDeviceMac(DeviceId deviceId);
+
     /**
      * Indicates whether a device is edge device or transit/core device.
      *
@@ -47,6 +52,7 @@
      * @return boolean
      */
     boolean isEdgeDevice(DeviceId deviceId);
+
     /**
      * Returns all segment IDs to be considered in building auto
      *
@@ -54,4 +60,16 @@
      * @return list of segment IDs
      */
     List<Integer> getAllDeviceSegmentIds();
+
+    /**
+     * Returns subnet-to-ports mapping of given device.
+     *
+     * For each entry of the map
+     * Key: a subnet
+     * Value: a list of ports, which are bound to the subnet
+     *
+     * @param deviceId device identifier
+     * @return a map that contains all subnet-to-ports mapping of given device
+     */
+    Map<Ip4Prefix, List<PortNumber>> getSubnetPortsMap(DeviceId deviceId);
 }
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java
index e7e8783..e47a662 100644
--- a/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/PolicyGroupHandler.java
@@ -54,7 +54,8 @@
      * @param config interface to retrieve the device properties
      * @param linkService link service object
      * @param flowObjService flow objective service object
-     * @param nsNextObjStore next objective store map
+     * @param nsNextObjStore NeighborSet next objective store map
+     * @param subnetNextObjStore subnet next objective store map
      */
     public PolicyGroupHandler(DeviceId deviceId,
                               ApplicationId appId,
@@ -62,8 +63,11 @@
                               LinkService linkService,
                               FlowObjectiveService flowObjService,
                               EventuallyConsistentMap<NeighborSetNextObjectiveStoreKey,
-                                      Integer> nsNextObjStore) {
-        super(deviceId, appId, config, linkService, flowObjService, nsNextObjStore);
+                                      Integer> nsNextObjStore,
+                              EventuallyConsistentMap<SubnetNextObjectiveStoreKey,
+                                      Integer> subnetNextObjStore) {
+        super(deviceId, appId, config, linkService, flowObjService,
+              nsNextObjStore, subnetNextObjStore);
     }
 
     public PolicyGroupIdentifier createPolicyGroupChain(String id,
diff --git a/src/main/java/org/onosproject/segmentrouting/grouphandler/SubnetNextObjectiveStoreKey.java b/src/main/java/org/onosproject/segmentrouting/grouphandler/SubnetNextObjectiveStoreKey.java
new file mode 100644
index 0000000..d6b16c7
--- /dev/null
+++ b/src/main/java/org/onosproject/segmentrouting/grouphandler/SubnetNextObjectiveStoreKey.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2014-2015 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.segmentrouting.grouphandler;
+
+import org.onlab.packet.IpPrefix;
+import org.onosproject.net.DeviceId;
+
+import java.util.Objects;
+
+/**
+ * Class definition of Key for Subnet to NextObjective store.
+ */
+public class SubnetNextObjectiveStoreKey {
+    private final DeviceId deviceId;
+    private final IpPrefix prefix;
+
+    public SubnetNextObjectiveStoreKey(DeviceId deviceId,
+                                       IpPrefix prefix) {
+        this.deviceId = deviceId;
+        this.prefix = prefix;
+    }
+
+    /**
+     * Gets device id in this SubnetNextObjectiveStoreKey.
+     *
+     * @return device id
+     */
+    public DeviceId deviceId() {
+        return this.deviceId;
+    }
+
+    /**
+     * Gets subnet information in this SubnetNextObjectiveStoreKey.
+     *
+     * @return subnet information
+     */
+    public IpPrefix prefix() {
+        return this.prefix;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (!(o instanceof SubnetNextObjectiveStoreKey)) {
+            return false;
+        }
+        SubnetNextObjectiveStoreKey that =
+                (SubnetNextObjectiveStoreKey) o;
+        return (Objects.equals(this.deviceId, that.deviceId) &&
+                Objects.equals(this.prefix, that.prefix));
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(deviceId, prefix);
+    }
+
+    @Override
+    public String toString() {
+        return "Device: " + deviceId + " Subnet: " + prefix;
+    }
+}