Fix for ONOS-5032 and ONOS-5034

Change-Id: Ib964252dd05754ce7069a7a82ccb1d1c29bfa978
diff --git a/core/net/BUCK b/core/net/BUCK
index 73bbe7d..773b20a 100644
--- a/core/net/BUCK
+++ b/core/net/BUCK
@@ -12,6 +12,7 @@
     '//core/common:onos-core-common',
     '//core/store/dist:onos-core-dist',
     '//core/store/dist:onos-core-dist-tests',
+    '//utils/osgi:onlab-osgi-tests',
 ]
 
 osgi_jar_with_tests (
diff --git a/core/net/pom.xml b/core/net/pom.xml
index d30f7a6..57a39e8 100644
--- a/core/net/pom.xml
+++ b/core/net/pom.xml
@@ -125,6 +125,13 @@
             <groupId>org.onosproject</groupId>
             <artifactId>onos-incubator-net</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onlab-osgi</artifactId>
+            <version>${project.version}</version>
+            <classifier>tests</classifier>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
 
 </project>
diff --git a/core/net/src/main/java/org/onosproject/net/host/impl/HostManager.java b/core/net/src/main/java/org/onosproject/net/host/impl/HostManager.java
index bdb5e43..27b9b7a 100644
--- a/core/net/src/main/java/org/onosproject/net/host/impl/HostManager.java
+++ b/core/net/src/main/java/org/onosproject/net/host/impl/HostManager.java
@@ -106,6 +106,15 @@
             label = "Enable removal of duplicate ip address")
 
     private boolean allowDuplicateIps = true;
+
+    @Property(name = "monitorHosts", boolValue = false,
+            label = "Enable/Disable monitoring of hosts")
+    private boolean monitorHosts = false;
+
+    @Property(name = "probeRate", longValue = 30000,
+            label = "Set the probe Rate in milli seconds")
+    private long probeRate = 30000;
+
     private HostMonitor monitor;
 
 
@@ -114,17 +123,71 @@
         store.setDelegate(delegate);
         eventDispatcher.addSink(HostEvent.class, listenerRegistry);
         cfgService.registerProperties(getClass());
-        modified(context);
         networkConfigService.addListener(networkConfigListener);
         monitor = new HostMonitor(packetService, this, interfaceService, edgePortService);
+        monitor.setProbeRate(probeRate);
         monitor.start();
+        modified(context);
+        cfgService.registerProperties(getClass());
         log.info("Started");
     }
 
+    @Deactivate
+    public void deactivate() {
+        store.unsetDelegate(delegate);
+        eventDispatcher.removeSink(HostEvent.class);
+        networkConfigService.removeListener(networkConfigListener);
+        cfgService.unregisterProperties(getClass(), false);
+        monitor.shutdown();
+        log.info("Stopped");
+    }
+
     @Modified
     public void modified(ComponentContext context) {
+        boolean oldValue = monitorHosts;
+        readComponentConfiguration(context);
+        if (probeRate > 0) {
+            monitor.setProbeRate(probeRate);
+        } else {
+            log.warn("probeRate cannot be lessthan 0");
+        }
+
+        if (oldValue != monitorHosts) {
+            if (monitorHosts) {
+                startMonitoring();
+            } else {
+                stopMonitoring();
+            }
+        }
+    }
+
+    /**
+     * Extracts properties from the component configuration context.
+     *
+     * @param context the component context
+     */
+    private void readComponentConfiguration(ComponentContext context) {
         Dictionary<?, ?> properties = context.getProperties();
         Boolean flag;
+
+        flag = Tools.isPropertyEnabled(properties, "monitorHosts");
+        if (flag == null) {
+            log.info("monitorHosts is not enabled " +
+                             "using current value of {}", monitorHosts);
+        } else {
+            monitorHosts = flag;
+            log.info("Configured. monitorHosts {}",
+            monitorHosts ? "enabled" : "disabled");
+        }
+
+        Long longValue = Tools.getLongProperty(properties, "probeRate");
+        if (longValue == null || longValue == 0) {
+            log.info("probeRate is not set sing default value of {}", probeRate);
+        } else {
+            probeRate = longValue;
+            log.info("Configured. probeRate {}", probeRate);
+        }
+
         flag = Tools.isPropertyEnabled(properties, "allowDuplicateIps");
         if (flag == null) {
             log.info("Removal of duplicate ip address is not configured");
@@ -133,14 +196,32 @@
             log.info("Removal of duplicate ip address is {}",
                      allowDuplicateIps ? "disabled" : "enabled");
         }
+
+
     }
 
-    @Deactivate
-    public void deactivate() {
-        store.unsetDelegate(delegate);
-        eventDispatcher.removeSink(HostEvent.class);
-        networkConfigService.removeListener(networkConfigListener);
-        log.info("Stopped");
+    /**
+     * Starts monitoring the hosts by IP Address.
+     *
+     */
+    private void startMonitoring() {
+        store.getHosts().forEach(host -> {
+                    host.ipAddresses().forEach(ip -> {
+                           monitor.addMonitoringFor(ip);
+            });
+        });
+    }
+
+    /**
+     * Stops monitoring the hosts by IP Address.
+     *
+     */
+    private void stopMonitoring() {
+        store.getHosts().forEach(host -> {
+                    host.ipAddresses().forEach(ip -> {
+                           monitor.stopMonitoring(ip);
+            });
+        });
     }
 
     @Override
@@ -244,8 +325,15 @@
             }
             store.createOrUpdateHost(provider().id(), hostId,
                                      hostDescription, replaceIps);
+
+            if (monitorHosts) {
+                hostDescription.ipAddress().forEach(ip -> {
+                    monitor.addMonitoringFor(ip);
+                });
+            }
         }
 
+
         // When a new IP is detected, remove that IP on other hosts if it exists
         public void removeDuplicates(HostId hostId, HostDescription desc) {
             desc.ipAddress().forEach(ip -> {
@@ -258,9 +346,7 @@
                     }
                 });
             });
-        }
-
-
+         }
 
 
         // returns a HostDescription made from the union of the BasicHostConfig
@@ -276,6 +362,12 @@
         public void hostVanished(HostId hostId) {
             checkNotNull(hostId, HOST_ID_NULL);
             checkValidity();
+            Host host = store.getHost(hostId);
+            if (monitorHosts) {
+                host.ipAddresses().forEach(ip -> {
+                    monitor.stopMonitoring(ip);
+                });
+            }
             store.removeHost(hostId);
         }
 
@@ -323,3 +415,4 @@
         }
     }
 }
+
diff --git a/core/net/src/main/java/org/onosproject/net/host/impl/HostMonitor.java b/core/net/src/main/java/org/onosproject/net/host/impl/HostMonitor.java
index c2bac09..747c8eb 100644
--- a/core/net/src/main/java/org/onosproject/net/host/impl/HostMonitor.java
+++ b/core/net/src/main/java/org/onosproject/net/host/impl/HostMonitor.java
@@ -150,6 +150,13 @@
         hostProviders.put(provider.id(), provider);
     }
 
+    /*
+     * Sets the probe rate.
+     */
+    void setProbeRate(long probeRate) {
+        this.probeRate = probeRate;
+    }
+
     @Override
     public void run(Timeout timeout) throws Exception {
         monitoredAddresses.forEach(this::probe);
diff --git a/core/net/src/test/java/org/onosproject/net/host/impl/HostManagerTest.java b/core/net/src/test/java/org/onosproject/net/host/impl/HostManagerTest.java
index 1eb014f..dd97d21 100644
--- a/core/net/src/test/java/org/onosproject/net/host/impl/HostManagerTest.java
+++ b/core/net/src/test/java/org/onosproject/net/host/impl/HostManagerTest.java
@@ -98,12 +98,14 @@
     protected TestHostProvider provider;
     protected HostProviderService providerService;
 
-    private static final ComponentContextAdapter REMOVE_DUPS =
+    private static final ComponentContextAdapter REMOVE_DUPS_MONITOR =
             new ComponentContextAdapter() {
                 @Override
                 public Dictionary getProperties() {
                     Hashtable<String, String> props = new Hashtable<>();
                     props.put("allowDuplicateIps", "true");
+                    props.put("monitorHosts", "true");
+                    props.put("probeRate", "40000");
                     return props;
                 }
             };
@@ -116,28 +118,27 @@
         registry = mgr;
         mgr.networkConfigService = new TestNetworkConfigService();
         mgr.cfgService = new ComponentConfigAdapter();
-        mgr.activate(REMOVE_DUPS);
+
+        mgr.activate(REMOVE_DUPS_MONITOR);
+
         mgr.addListener(listener);
 
         provider = new TestHostProvider();
         providerService = registry.register(provider);
-        assertTrue("provider should be registered",
-                   registry.getProviders().contains(provider.id()));
+        assertTrue("provider should be registered", registry.getProviders().contains(provider.id()));
     }
 
     @After
     public void tearDown() {
         registry.unregister(provider);
-        assertFalse("provider should not be registered",
-                    registry.getProviders().contains(provider.id()));
+        assertFalse("provider should not be registered", registry.getProviders().contains(provider.id()));
 
         mgr.removeListener(listener);
         mgr.deactivate();
         injectEventDispatcher(mgr, null);
     }
 
-    private void detect(HostId hid, MacAddress mac, VlanId vlan,
-                        HostLocation loc, IpAddress ip) {
+    private void detect(HostId hid, MacAddress mac, VlanId vlan, HostLocation loc, IpAddress ip) {
         HostDescription descr = new DefaultHostDescription(mac, vlan, loc, ip);
         providerService.hostDetected(hid, descr, false);
         assertNotNull("host should be found", mgr.getHost(hid));
@@ -217,8 +218,7 @@
         assertNull("host should have been removed", mgr.getHost(HID3));
     }
 
-    private void validateHosts(
-            String msg, Iterable<Host> hosts, HostId... ids) {
+    private void validateHosts(String msg, Iterable<Host> hosts, HostId... ids) {
         Set<HostId> hids = Sets.newHashSet(ids);
         for (Host h : hosts) {
             assertTrue(msg, hids.remove(h.id()));
@@ -252,8 +252,7 @@
         assertTrue("incorrect host location", mgr.getConnectedHosts(DID2).isEmpty());
     }
 
-    private static class TestHostProvider extends AbstractProvider
-            implements HostProvider {
+    private static class TestHostProvider extends AbstractProvider implements HostProvider {
 
         protected TestHostProvider() {
             super(PID);
@@ -284,3 +283,4 @@
     private class TestNetworkConfigService extends NetworkConfigServiceAdapter {
     }
 }
+