[CORD-2362] dhcp relay v6 counters implementation

Change-Id: I1ec322d6d77ff62ec4ad91632349e3a2c0d058f3
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRecord.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRecord.java
index 6f620db..44c6c3c 100644
--- a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRecord.java
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRecord.java
@@ -53,8 +53,16 @@
     private IpPrefix pdPrefix;
     private DHCP6.MsgType ip6Status;
 
+
     private long lastSeen;
+    private long lastIp6Update;
+    private long lastPdUpdate;
+
     private boolean directlyConnected;
+    private long addrPrefTime;
+    private long pdPrefTime;
+    private DhcpRelayCounters v6Counters;
+
 
     /**
      * Creates a DHCP record for a host (mac + vlan).
@@ -69,6 +77,7 @@
         this.vlanId = hostId.vlanId();
         this.lastSeen = System.currentTimeMillis();
         this.directlyConnected = false;
+        this.v6Counters = new DhcpRelayCounters();
     }
 
     /**
@@ -200,6 +209,84 @@
     }
 
     /**
+     * Gets the latest time this record updated with ip6 Address.
+     *
+     * @return the last time received DHCP packet provide ip6 Address
+     */
+    public long getLastIp6Update() {
+        return lastIp6Update;
+    }
+
+    /**
+     * Updates the update time of this record is given ip6 Address.
+     *
+     * @return the DHCP record
+     */
+    public DhcpRecord updateLastIp6Update() {
+        lastIp6Update = System.currentTimeMillis();
+        return this;
+    }
+
+    /**
+     * Gets the latest time this record updated with pd Prefix.
+     *
+     * @return the last time received DHCP packet provide pd Prefix
+     */
+    public long getLastPdUpdate() {
+        return lastPdUpdate;
+    }
+
+    /**
+     * Updates the update time of this record is given pd Prefix.
+     *
+     * @return the DHCP record
+     */
+    public DhcpRecord updateLastPdUpdate() {
+        lastPdUpdate = System.currentTimeMillis();
+        return this;
+    }
+
+    /**
+     * Gets the IP Address preferred time for this record.
+     *
+     * @return the preferred lease time for this ip address
+     */
+    public long addrPrefTime() {
+        return addrPrefTime;
+    }
+
+    /**
+     * Updates the IP Address preferred time of this record.
+     *
+     * @param prefTime preferred liftme
+     * @return the DHCP record
+     */
+    public DhcpRecord updateAddrPrefTime(long prefTime) {
+        addrPrefTime = prefTime;
+        return this;
+    }
+
+    /**
+     * Gets the PD Prefix preferred time for this record.
+     *
+     * @return the preferred lease time for this PD prefix
+     */
+    public long pdPrefTime() {
+        return pdPrefTime;
+    }
+
+    /**
+     * Updates the PD Prefix preferred time of this record.
+     *
+     * @param prefTime preferred liftme
+     * @return the DHCP record
+     */
+    public DhcpRecord updatePdPrefTime(long prefTime) {
+        pdPrefTime = prefTime;
+        return this;
+    }
+
+    /**
      * Indicated that the host is direct connected to the network or not.
      *
      * @return true if the host is directly connected to the network; false otherwise
@@ -301,6 +388,15 @@
     }
 
     /**
+     * Gets dhcp relay counters.
+     *
+     * @return the counter object
+     */
+    public DhcpRelayCounters getV6Counters() {
+        return v6Counters;
+    }
+
+    /**
      * Clone this DHCP record.
      *
      * @return the DHCP record which cloned
@@ -317,13 +413,20 @@
         newRecord.pdPrefix = pdPrefix;
         newRecord.ip6Status = ip6Status;
         newRecord.lastSeen = lastSeen;
+        newRecord.lastIp6Update = lastIp6Update;
+        newRecord.lastPdUpdate = lastPdUpdate;
+        newRecord.addrPrefTime = addrPrefTime;
+        newRecord.pdPrefTime = pdPrefTime;
+        newRecord.v6Counters = v6Counters;
+
         return newRecord;
     }
 
     @Override
     public int hashCode() {
         return Objects.hash(locations, macAddress, vlanId, ip4Address, ip4Status,
-                            nextHop, nextHopTemp, ip6Address, pdPrefix, ip6Status, lastSeen);
+                nextHop, nextHopTemp, ip6Address, pdPrefix, ip6Status, lastSeen,
+                lastIp6Update, lastPdUpdate, addrPrefTime, pdPrefTime, v6Counters);
     }
 
     @Override
@@ -346,7 +449,12 @@
                 Objects.equals(pdPrefix, that.pdPrefix) &&
                 Objects.equals(ip6Status, that.ip6Status) &&
                 Objects.equals(lastSeen, that.lastSeen) &&
-                Objects.equals(directlyConnected, that.directlyConnected);
+                Objects.equals(lastIp6Update, that.lastIp6Update) &&
+                Objects.equals(lastPdUpdate, that.lastPdUpdate) &&
+                Objects.equals(directlyConnected, that.directlyConnected) &&
+                Objects.equals(addrPrefTime, that.addrPrefTime) &&
+                Objects.equals(pdPrefTime, that.pdPrefTime) &&
+                Objects.equals(v6Counters, that.v6Counters);
     }
 
     @Override
@@ -363,7 +471,12 @@
                 .add("pdPrefix", pdPrefix)
                 .add("ip6State", ip6Status)
                 .add("lastSeen", lastSeen)
+                .add("lastIp6Update", lastIp6Update)
+                .add("lastPdUpdate", lastPdUpdate)
                 .add("directlyConnected", directlyConnected)
+                .add("addPrefTime", addrPrefTime)
+                .add("pdPrefTime", pdPrefTime)
+                .add("v6Counters", v6Counters)
                 .toString();
     }
 }
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayCounters.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayCounters.java
new file mode 100644
index 0000000..2a69c21
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayCounters.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2017-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.onosproject.dhcprelay.store;
+
+
+import com.google.common.collect.ImmutableSet;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+public class DhcpRelayCounters {
+    // common counters
+
+    // IpV6 specific counters
+    public static final String SOLICIT = "SOLICIT";
+    public static final String ADVERTISE = "ADVERTISE";
+    public static final String REQUEST = "REQUEST";
+    public static final String CONFIRM = "CONFIRM";
+    public static final String RENEW = "RENEW";
+    public static final String REBIND = "REBIND";
+    public static final String REPLY = "REPLY";
+    public static final String RELEASE = "RELEASE";
+    public static final String DECLINE = "DECLINE";
+    public static final String RECONFIGURE = "RECONFIGURE";
+    public static final String INFORMATION_REQUEST = "INFORMATION_REQUEST";
+    public static final String RELAY_FORW = "RELAY_FORW";
+    public static final String RELAY_REPL = "RELAY_REPL";
+
+    public static final String NO_LINKLOCAL_GW = "No link-local in Gateway";
+    public static final String NO_LINKLOCAL_FAIL = "No link-local in CLIENT_ID";
+    public static final String NO_CLIENTID_FAIL = "No CLIENT_ID Found";
+    public static final String SVR_CFG_FAIL = "Server Config Error";
+    public static final String OPTION_MISSING_FAIL = "Expected Option missing";
+    public static final String NO_MATCHING_INTF = "No matching Inteface";
+    public static final String NO_CLIENT_INTF_MAC = "No client interface mac";
+    public static final String NO_SERVER_INFO = "No Server info found";
+    public static final String NO_SERVER_IP6ADDR = "No Server ip6 addr found";
+
+    public static final String INVALID_PACKET = "Invalid Packet";
+
+    public static final Set<String> SUPPORTED_COUNTERS =
+            ImmutableSet.of(SOLICIT, ADVERTISE, REQUEST, CONFIRM, RENEW,
+                    REBIND, REPLY, RELEASE, DECLINE, RECONFIGURE,
+                    INFORMATION_REQUEST, RELAY_FORW, RELAY_REPL,
+                    NO_LINKLOCAL_GW, NO_LINKLOCAL_FAIL, NO_CLIENTID_FAIL, SVR_CFG_FAIL, OPTION_MISSING_FAIL,
+                    NO_MATCHING_INTF, NO_CLIENT_INTF_MAC, NO_SERVER_INFO, NO_SERVER_IP6ADDR,
+                    INVALID_PACKET);
+
+    // TODO Use AtomicInteger for the counters
+    private Map<String, Integer> countersMap = new ConcurrentHashMap<>();
+    public long lastUpdate;
+
+    public void resetCounters() {
+        countersMap.forEach((name, value) -> {
+            countersMap.put(name, 0);
+        });
+    }
+    public boolean incrementCounter(String name) {
+        boolean counterValid = false;
+        if (SUPPORTED_COUNTERS.contains(name)) {
+            Integer counter = countersMap.get(name);
+            if (counter != null) {
+                counter = counter + 1;
+                countersMap.put(name, counter);
+            } else {
+                // this is the first time
+                countersMap.put(name, 1);
+            }
+            lastUpdate = System.currentTimeMillis();
+            counterValid = true;
+        }
+        return counterValid;
+    }
+    public Map<String, Integer> getCounters() {
+        return countersMap;
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(countersMap, lastUpdate);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof DhcpRelayCounters)) {
+            return false;
+        }
+        DhcpRelayCounters that = (DhcpRelayCounters) obj;
+        return Objects.equals(countersMap, that.countersMap) &&
+                Objects.equals(lastUpdate, that.lastUpdate);
+    }
+}
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayCountersStore.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayCountersStore.java
new file mode 100644
index 0000000..3534871
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayCountersStore.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2017-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.onosproject.dhcprelay.store;
+
+
+import java.util.Optional;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Stores DHCP Relay Counters records.
+ */
+public interface DhcpRelayCountersStore {
+
+    /**
+     * Creates or updates DHCP record for specific host id (mac + vlan).
+     *
+     * @param counterClass class of counters (direct, indirect, global)
+     * @param counterName name of counter
+     */
+    void incrementCounter(String counterClass, String counterName);
+
+    /**
+     * Gets the DHCP counter record for a given counter class.
+     *
+     * @param counterClass the class of counters (direct, indirect, global)
+     * @return the DHCP counter record for a given counter class; empty if record not exists
+     */
+    Optional<DhcpRelayCounters> getCounters(String counterClass);
+
+    /**
+     * Gets all classes of DHCP counters record from store.
+     *
+     * @return all classes of DHCP counters records from store
+     */
+    Set<Map.Entry<String, DhcpRelayCounters>> getAllCounters();
+
+    /**
+     * Resets counter value for a given counter class.
+     *
+     * @param counterClass the class of counters (direct, indirect, global)
+     */
+    void resetCounters(String counterClass);
+
+    /**
+     * Resets counter value for a all counter classes.
+     *
+     */
+    void resetAllCounters();
+
+}
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayCountersStore.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayCountersStore.java
new file mode 100644
index 0000000..4b7b26c
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayCountersStore.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2017-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.onosproject.dhcprelay.store;
+
+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.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.onosproject.store.serializers.KryoNamespaces;
+
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import org.onosproject.store.service.Versioned;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+@Component(immediate = true)
+@Service
+public class DistributedDhcpRelayCountersStore implements DhcpRelayCountersStore {
+    private static final KryoNamespace.Builder APP_KYRO = KryoNamespace.newBuilder()
+            .register(KryoNamespaces.API)
+            .register(DhcpRelayCounters.class);
+
+    private Logger log = LoggerFactory.getLogger(getClass());
+    private ConsistentMap<String, DhcpRelayCounters> counters;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected StorageService storageService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected CoreService coreService;
+
+
+    @Activate
+    protected void activated() {
+        ApplicationId appId = coreService.getAppId("org.onosproject.Dhcp6HandlerImpl");
+        counters = storageService.<String, DhcpRelayCounters>consistentMapBuilder()
+                .withSerializer(Serializer.using(APP_KYRO.build()))
+                .withName("Dhcp-Relay-Counters")
+                .withApplicationId(appId)
+                .withPurgeOnUninstall()
+                .build();
+    }
+
+    @Deactivate
+    protected void deactivated() {
+        counters.destroy().join();
+    }
+    @Override
+    public void incrementCounter(String coutnerClass, String counterName) {
+        DhcpRelayCounters countersRecord;
+
+        Versioned<DhcpRelayCounters> vCounters = counters.get(coutnerClass);
+        if (vCounters == null) {
+            countersRecord = new DhcpRelayCounters();
+        } else {
+            countersRecord = vCounters.value();
+        }
+        countersRecord.incrementCounter(counterName);
+        counters.put(coutnerClass, countersRecord);
+    }
+
+    @Override
+    public Set<Map.Entry<String, DhcpRelayCounters>> getAllCounters() {
+        final Set<Map.Entry<String, DhcpRelayCounters>> result =
+                new HashSet<Map.Entry<String, DhcpRelayCounters>>();
+        Set<Map.Entry<String, Versioned<DhcpRelayCounters>>> tmpCounters = counters.entrySet();
+        tmpCounters.forEach(entry -> {
+            String key = entry.getKey();
+            DhcpRelayCounters value = entry.getValue().value();
+            ConcurrentHashMap<String, DhcpRelayCounters> newMap = new ConcurrentHashMap();
+            newMap.put(key, value);
+
+            for (Map.Entry m: newMap.entrySet()) {
+                result.add(m);
+            }
+        });
+        return  result;
+    }
+    @Override
+    public Optional<DhcpRelayCounters> getCounters(String counterClass) {
+        DhcpRelayCounters countersRecord;
+        checkNotNull(counterClass, "counter class can't be null");
+        Versioned<DhcpRelayCounters> vCounters = counters.get(counterClass);
+        if (vCounters == null) {
+            return Optional.empty();
+        }
+        return Optional.of(vCounters.value());
+    }
+    @Override
+    public void resetAllCounters() {
+        counters.clear();
+    }
+
+    @Override
+    public void resetCounters(String counterClass) {
+        checkNotNull(counterClass, "counter class can't be null");
+        DhcpRelayCounters countersRecord = counters.get(counterClass).value();
+        countersRecord.resetCounters();
+        counters.put(counterClass, countersRecord);
+    }
+
+}
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayStore.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayStore.java
index 38c0580..884d9cc 100644
--- a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayStore.java
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayStore.java
@@ -52,6 +52,7 @@
             .register(DhcpRecord.class)
             .register(DHCP.MsgType.class)
             .register(DHCP6.MsgType.class)
+            .register(DhcpRelayCounters.class)
             .build();
 
     private Logger log = getLogger(getClass());