[SEBA-42] Operational Status Multicast Source

Change-Id: I420254a9a62d1ac9c9f4cab04fc2a44a81f2eb16
diff --git a/src/main/java/org/opencord/cordmcast/CordMcast.java b/src/main/java/org/opencord/cordmcast/CordMcast.java
index 108ceda..0d20e9c 100644
--- a/src/main/java/org/opencord/cordmcast/CordMcast.java
+++ b/src/main/java/org/opencord/cordmcast/CordMcast.java
@@ -87,9 +87,10 @@
 import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
 import static org.onlab.util.Tools.get;
 import static org.onlab.util.Tools.groupedThreads;
-import static org.opencord.cordmcast.OsgiPropertyConstants.DEFAULT_VLAN_ENABLED;
+
 import static org.opencord.cordmcast.OsgiPropertyConstants.DEFAULT_PRIORITY;
 import static org.opencord.cordmcast.OsgiPropertyConstants.PRIORITY;
+import static org.opencord.cordmcast.OsgiPropertyConstants.DEFAULT_VLAN_ENABLED;
 import static org.opencord.cordmcast.OsgiPropertyConstants.VLAN_ENABLED;
 import static org.slf4j.LoggerFactory.getLogger;
 
@@ -145,7 +146,11 @@
     @Reference(cardinality = ReferenceCardinality.MANDATORY)
     protected SadisService sadisService;
 
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CordMcastStatisticsService cordMcastStatisticsService;
+
     protected McastListener listener = new InternalMulticastListener();
+
     private InternalNetworkConfigListener configListener =
             new InternalNetworkConfigListener();
 
@@ -220,10 +225,26 @@
 
         McastConfig config = networkConfig.getConfig(coreAppId, CORD_MCAST_CONFIG_CLASS);
         updateConfig(config);
-
         log.info("Started");
     }
 
+    @Modified
+    public void modified(ComponentContext context) {
+        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
+
+        String s = get(properties, VLAN_ENABLED);
+        vlanEnabled = isNullOrEmpty(s) ? DEFAULT_VLAN_ENABLED : Boolean.parseBoolean(s.trim());
+
+        try {
+            s = get(properties, PRIORITY);
+            priority = isNullOrEmpty(s) ? DEFAULT_PRIORITY : Integer.parseInt(s.trim());
+        } catch (NumberFormatException ne) {
+            log.error("Unable to parse configuration parameter for priority", ne);
+            priority = DEFAULT_PRIORITY;
+        }
+        cordMcastStatisticsService.setVlanValue(assignedVlan());
+    }
+
     @Deactivate
     public void deactivate() {
         componentConfigService.unregisterProperties(getClass(), false);
@@ -274,28 +295,10 @@
         return VlanId.vlanId(mcastVlan);
     }
 
-    private VlanId assignedVlan() {
+    protected VlanId assignedVlan() {
         return vlanEnabled ? multicastVlan() : VlanId.NONE;
     }
 
-    @Modified
-    public void modified(ComponentContext context) {
-        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
-
-        try {
-            String s = get(properties, "vlanEnabled");
-            vlanEnabled = isNullOrEmpty(s) ? DEFAULT_VLAN_ENABLED : Boolean.parseBoolean(s.trim());
-
-            s = get(properties, "priority");
-            priority = isNullOrEmpty(s) ? DEFAULT_PRIORITY : Integer.parseInt(s.trim());
-
-        } catch (Exception e) {
-            log.error("Unable to parse configuration parameter.", e);
-            vlanEnabled = false;
-            priority = DEFAULT_PRIORITY;
-        }
-    }
-
     private class InternalMulticastListener implements McastListener {
         @Override
         public void event(McastEvent event) {
@@ -427,6 +430,7 @@
     }
 
     private void addSink(McastRoute route, ConnectPoint sink) {
+
         if (!isLocalLeader(sink.deviceId())) {
             log.debug("Not the leader of {}. Skip sink_added event for the sink {} and group {}",
                       sink.deviceId(), sink, route.group());
diff --git a/src/main/java/org/opencord/cordmcast/CordMcastStatistics.java b/src/main/java/org/opencord/cordmcast/CordMcastStatistics.java
new file mode 100644
index 0000000..6bdb702
--- /dev/null
+++ b/src/main/java/org/opencord/cordmcast/CordMcastStatistics.java
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * 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.opencord.cordmcast;
+
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.VlanId;
+
+/**
+ * POJO Class to store group data from mcast event.
+ */
+public class CordMcastStatistics {
+    //Group Address
+    private IpAddress groupAddress;
+    //Set of source address in a group.
+    private String sourceAddress;
+    //vlan id used in mcast event.
+    private VlanId vlanId;
+
+    public CordMcastStatistics(IpAddress groupAddress, String sourceAddresss, VlanId vlanId) {
+        this.vlanId = vlanId;
+        this.sourceAddress = sourceAddresss;
+        this.groupAddress = groupAddress;
+    }
+
+    public IpAddress getGroupAddress() {
+        return groupAddress;
+    }
+
+    public void setGroupAddress(IpAddress groupAddress) {
+        this.groupAddress = groupAddress;
+    }
+
+    public String getSourceAddress() {
+        return sourceAddress;
+    }
+
+    public void setSourceAddress(String sourceAddress) {
+        this.sourceAddress = sourceAddress;
+    }
+
+    public VlanId getVlanId() {
+        return vlanId;
+    }
+
+    public void setVlanId(VlanId vlanId) {
+        this.vlanId = vlanId;
+    }
+}
diff --git a/src/main/java/org/opencord/cordmcast/CordMcastStatisticsEvent.java b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsEvent.java
new file mode 100644
index 0000000..52581d9
--- /dev/null
+++ b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsEvent.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * 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.opencord.cordmcast;
+
+import org.onosproject.event.AbstractEvent;
+
+import java.util.List;
+
+/**
+ * Event indicating Mcast statistics data.
+ */
+public class CordMcastStatisticsEvent extends
+        AbstractEvent<CordMcastStatisticsEvent.Type, List<CordMcastStatistics>> {
+
+    // Mcast event type.
+    public enum Type {
+        STATUS_UPDATE
+    }
+
+    public CordMcastStatisticsEvent(Type type, List<CordMcastStatistics> stats) {
+        super(type, stats);
+    }
+}
diff --git a/src/main/java/org/opencord/cordmcast/CordMcastStatisticsEventListener.java b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsEventListener.java
new file mode 100644
index 0000000..30177ae
--- /dev/null
+++ b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsEventListener.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * 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.opencord.cordmcast;
+
+import org.onosproject.event.EventListener;
+
+/**
+ * Listener for Mcast statistics events.
+ */
+public interface CordMcastStatisticsEventListener extends
+        EventListener<CordMcastStatisticsEvent> {
+
+}
diff --git a/src/main/java/org/opencord/cordmcast/CordMcastStatisticsManager.java b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsManager.java
new file mode 100644
index 0000000..80dc6f3
--- /dev/null
+++ b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsManager.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * 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.opencord.cordmcast;
+
+
+import org.onlab.packet.VlanId;
+import org.onlab.util.SafeRecurringTask;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.event.AbstractListenerManager;
+import org.onosproject.mcast.api.McastRoute;
+import org.onosproject.mcast.api.MulticastRouteService;
+import org.osgi.service.component.ComponentContext;
+import org.osgi.service.component.annotations.Modified;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Dictionary;
+import java.util.Set;
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Properties;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+import static com.google.common.base.Strings.isNullOrEmpty;
+import static org.onlab.util.Tools.get;
+import static org.opencord.cordmcast.OsgiPropertyConstants.EVENT_GENERATION_PERIOD;
+import static org.opencord.cordmcast.OsgiPropertyConstants.EVENT_GENERATION_PERIOD_DEFAULT;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * For managing CordMcastStatisticsEvent.
+ */
+@Component(immediate = true, property = { EVENT_GENERATION_PERIOD + ":Integer=" + EVENT_GENERATION_PERIOD_DEFAULT, })
+public class CordMcastStatisticsManager
+        extends AbstractListenerManager<CordMcastStatisticsEvent, CordMcastStatisticsEventListener>
+        implements CordMcastStatisticsService {
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected MulticastRouteService mcastService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected ComponentConfigService componentConfigService;
+
+    CordMcastStatisticsEventListener listener;
+
+    /**
+     * Multicast Statistics generation time interval.
+     **/
+    private int eventGenerationPeriodInSeconds = EVENT_GENERATION_PERIOD_DEFAULT;
+    private final Logger log = getLogger(getClass());
+    private ScheduledFuture<?> scheduledFuture = null;
+    private ScheduledExecutorService executor;
+
+    private VlanId vlanId;
+
+    @Activate
+    public void activate(ComponentContext context) {
+        eventDispatcher.addSink(CordMcastStatisticsEvent.class, listenerRegistry);
+        executor = Executors.newScheduledThreadPool(1);
+        componentConfigService.registerProperties(getClass());
+        modified(context);
+        log.info("CordMcastStatisticsManager activated.");
+    }
+
+    @Modified
+    public void modified(ComponentContext context) {
+        Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
+        try {
+            String s = get(properties, EVENT_GENERATION_PERIOD);
+            eventGenerationPeriodInSeconds =
+                    isNullOrEmpty(s) ? EVENT_GENERATION_PERIOD_DEFAULT : Integer.parseInt(s.trim());
+        } catch (NumberFormatException ne) {
+            log.error("Unable to parse configuration parameter for eventGenerationPeriodInSeconds", ne);
+            eventGenerationPeriodInSeconds = EVENT_GENERATION_PERIOD_DEFAULT;
+        }
+        if (scheduledFuture != null) {
+            scheduledFuture.cancel(true);
+        }
+        scheduledFuture = executor.scheduleAtFixedRate(SafeRecurringTask.wrap(this::publishEvent),
+                0, eventGenerationPeriodInSeconds, TimeUnit.SECONDS);
+    }
+
+    @Deactivate
+    public void deactivate() {
+        eventDispatcher.removeSink(CordMcastStatisticsEvent.class);
+        scheduledFuture.cancel(true);
+        executor.shutdown();
+    }
+
+    public List<CordMcastStatistics> getMcastDetails() {
+        List<CordMcastStatistics> mcastData = new ArrayList<CordMcastStatistics>();
+        Set<McastRoute> routes = mcastService.getRoutes();
+        routes.forEach(route -> {
+            mcastData.add(new CordMcastStatistics(route.group(),
+                    route.source().isEmpty() ? "*" : route.source().get().toString(),
+                    vlanId));
+        });
+        return mcastData;
+    }
+
+    @Override
+    public void setVlanValue(VlanId vlanValue) {
+        vlanId = vlanValue;
+    }
+
+    /**
+     * pushing mcast stat data as event.
+     */
+    protected void publishEvent() {
+        log.debug("pushing cord mcast event to kafka");
+        List<CordMcastStatistics> routeList = getMcastDetails();
+        routeList.forEach(mcastStats -> {
+            log.debug("Group: " +
+                    (mcastStats.getGroupAddress() != null ? mcastStats.getGroupAddress().toString() : "null") +
+                    " | Source: " +
+                    (mcastStats.getSourceAddress() != null ? mcastStats.getSourceAddress().toString() : "null") +
+                    " | Vlan: " +
+                    (mcastStats.getVlanId() != null ? mcastStats.getVlanId().toString() : "null"));
+        });
+        post(new CordMcastStatisticsEvent(CordMcastStatisticsEvent.Type.STATUS_UPDATE, routeList));
+    }
+}
diff --git a/src/main/java/org/opencord/cordmcast/CordMcastStatisticsService.java b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsService.java
new file mode 100644
index 0000000..bf8a819
--- /dev/null
+++ b/src/main/java/org/opencord/cordmcast/CordMcastStatisticsService.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2018-present Open Networking Foundation
+ *
+ * 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.opencord.cordmcast;
+
+import org.onlab.packet.VlanId;
+import org.onosproject.event.ListenerService;
+
+/**
+ * Service for interacting with CordMcastStatisticsEvent data.
+ */
+public interface CordMcastStatisticsService
+        extends ListenerService<CordMcastStatisticsEvent, CordMcastStatisticsEventListener> {
+
+
+    /**
+     * To set current vlanValue in Statistics Service.
+     * @param vlanValue current vlan value.
+     */
+    public void setVlanValue(VlanId vlanValue);
+}
diff --git a/src/main/java/org/opencord/cordmcast/OsgiPropertyConstants.java b/src/main/java/org/opencord/cordmcast/OsgiPropertyConstants.java
index 0910d94..7600ba1 100644
--- a/src/main/java/org/opencord/cordmcast/OsgiPropertyConstants.java
+++ b/src/main/java/org/opencord/cordmcast/OsgiPropertyConstants.java
@@ -29,4 +29,7 @@
 
     public static final String PRIORITY = "priority";
     public static final int DEFAULT_PRIORITY = 500;
+
+    public static final String EVENT_GENERATION_PERIOD = "eventGenerationPeriodInSeconds";
+    public static final int EVENT_GENERATION_PERIOD_DEFAULT = 30;
 }