[CORD-1433] DHCP Relay Store

Change-Id: Ibb92e07d570c631ea35ce1b826e4ee630ba8f5db
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
new file mode 100644
index 0000000..b7d9992
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRecord.java
@@ -0,0 +1,318 @@
+/*
+ * 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.dhcprelay.store;
+
+import com.google.common.base.MoreObjects;
+import com.google.common.collect.Sets;
+import org.onlab.packet.DHCP;
+import org.onlab.packet.DHCP6;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.Ip6Address;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.VlanId;
+import org.onosproject.net.HostId;
+import org.onosproject.net.HostLocation;
+
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+
+/**
+ * A class to record DHCP from DHCP relay application.
+ */
+public class DhcpRecord {
+    private final Set<HostLocation> locations;
+    private final MacAddress macAddress;
+    private final VlanId vlanId;
+    private MacAddress nextHop;
+
+    private Ip4Address ip4Address;
+    private DHCP.MsgType ip4Status;
+
+    private Ip6Address ip6Address;
+    private DHCP6.MsgType ip6Status;
+
+    private long lastSeen;
+    private boolean directlyConnected;
+
+    /**
+     * Creates a DHCP record for a host (mac + vlan).
+     *
+     * @param hostId the host id for the host
+     */
+    public DhcpRecord(HostId hostId) {
+        checkNotNull(hostId, "Host id can't be null");
+
+        this.locations = Sets.newHashSet();
+        this.macAddress = hostId.mac();
+        this.vlanId = hostId.vlanId();
+        this.lastSeen = System.currentTimeMillis();
+        this.directlyConnected = false;
+    }
+
+    /**
+     * Gets host locations.
+     *
+     * @return the locations of host
+     */
+    public Set<HostLocation> locations() {
+        return locations;
+    }
+
+    /**
+     * Adds a location to record.
+     *
+     * @param location the location
+     * @return the DHCP record
+     */
+    public DhcpRecord addLocation(HostLocation location) {
+        locations.add(location);
+        return this;
+    }
+
+    /**
+     * Removes a location from record.
+     *
+     * @param location the location
+     * @return the DHCP record
+     */
+    public DhcpRecord removeLocation(HostLocation location) {
+        locations.remove(location);
+        return this;
+    }
+
+    /**
+     * Gets host mac address of this record.
+     *
+     * @return the host mac address
+     */
+    public MacAddress macAddress() {
+        return macAddress;
+    }
+
+    /**
+     * Gets host vlan id of this record.
+     *
+     * @return the host id.
+     */
+    public VlanId vlanId() {
+        return vlanId;
+    }
+
+    /**
+     * Gets IPv4 address which assigned to the host.
+     *
+     * @return the IP address assigned to the host
+     */
+    public Optional<Ip4Address> ip4Address() {
+        return Optional.ofNullable(ip4Address);
+    }
+
+    /**
+     * Sets IPv4 address.
+     *
+     * @param ip4Address the IPv4 address
+     * @return the DHCP record
+     */
+    public DhcpRecord ip4Address(Ip4Address ip4Address) {
+        this.ip4Address = ip4Address;
+        return this;
+    }
+
+    /**
+     * Gets IPv6 address which assigned to the host.
+     *
+     * @return the IP address assigned to the host
+     */
+    public Optional<Ip6Address> ip6Address() {
+        return Optional.ofNullable(ip6Address);
+    }
+
+    /**
+     * Sets IPv6 address.
+     *
+     * @param ip6Address the IPv6 address
+     * @return the DHCP record
+     */
+    public DhcpRecord ip6Address(Ip6Address ip6Address) {
+        this.ip6Address = ip6Address;
+        return this;
+    }
+
+    /**
+     * Gets the latest time this record updated.
+     *
+     * @return the last time host send or receive DHCP packet
+     */
+    public long lastSeen() {
+        return lastSeen;
+    }
+
+    /**
+     * Updates the update time of this record.
+     *
+     * @return the DHCP record
+     */
+    public DhcpRecord updateLastSeen() {
+        lastSeen = System.currentTimeMillis();
+        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
+     */
+    public boolean directlyConnected() {
+        return directlyConnected;
+    }
+
+    /**
+     * Sets the flag which indicated that the host is directly connected to the
+     * network.
+     *
+     * @param directlyConnected the flag to set
+     * @return the DHCP record
+     */
+    public DhcpRecord setDirectlyConnected(boolean directlyConnected) {
+        this.directlyConnected = directlyConnected;
+        return this;
+    }
+
+    /**
+     * Gets the DHCPv4 status of this record.
+     *
+     * @return the DHCPv4 status; empty if not exists
+     */
+    public Optional<DHCP.MsgType> ip4Status() {
+        return Optional.ofNullable(ip4Status);
+    }
+
+    /**
+     * Sets status of DHCPv4.
+     *
+     * @param ip4Status the status
+     * @return the DHCP record
+     */
+    public DhcpRecord ip4Status(DHCP.MsgType ip4Status) {
+        this.ip4Status = ip4Status;
+        return this;
+    }
+
+    /**
+     * Gets the DHCPv6 status of this record.
+     *
+     * @return the DHCPv6 status; empty if not exists
+     */
+    public Optional<DHCP6.MsgType> ip6Status() {
+        return Optional.ofNullable(ip6Status);
+    }
+
+    /**
+     * Sets status of DHCPv6.
+     *
+     * @param ip6Status the DHCPv6 status
+     * @return the DHCP record
+     */
+    public DhcpRecord ip6Status(DHCP6.MsgType ip6Status) {
+        this.ip6Status = ip6Status;
+        return this;
+    }
+
+    /**
+     * Gets nextHop mac address.
+     *
+     * @return the IPv4 nextHop mac address; empty if not exists
+     */
+    public Optional<MacAddress> nextHop() {
+        return Optional.ofNullable(nextHop);
+    }
+
+    /**
+     * Sets nextHop mac address.
+     *
+     * @param nextHop the IPv4 nextHop mac address
+     * @return the DHCP record
+     */
+    public DhcpRecord nextHop(MacAddress nextHop) {
+        this.nextHop = nextHop;
+        return this;
+    }
+
+    /**
+     * Clone this DHCP record.
+     *
+     * @return the DHCP record which cloned
+     */
+    public DhcpRecord clone() {
+        DhcpRecord newRecord = new DhcpRecord(HostId.hostId(macAddress, vlanId));
+        locations.forEach(newRecord::addLocation);
+        newRecord.directlyConnected = directlyConnected;
+        newRecord.nextHop = nextHop;
+        newRecord.ip4Address = ip4Address;
+        newRecord.ip4Status = ip4Status;
+        newRecord.ip6Address = ip6Address;
+        newRecord.ip6Status = ip6Status;
+        newRecord.lastSeen = lastSeen;
+        return newRecord;
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(locations, macAddress, vlanId, ip4Address, ip4Status,
+                            nextHop, ip6Address, ip6Status, lastSeen);
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!(obj instanceof DhcpRecord)) {
+            return false;
+        }
+        DhcpRecord that = (DhcpRecord) obj;
+        return Objects.equals(locations, that.locations) &&
+                Objects.equals(macAddress, that.macAddress) &&
+                Objects.equals(vlanId, that.vlanId) &&
+                Objects.equals(ip4Address, that.ip4Address) &&
+                Objects.equals(ip4Status, that.ip4Status) &&
+                Objects.equals(nextHop, that.nextHop) &&
+                Objects.equals(ip6Address, that.ip6Address) &&
+                Objects.equals(ip6Status, that.ip6Status) &&
+                Objects.equals(lastSeen, that.lastSeen) &&
+                Objects.equals(directlyConnected, that.directlyConnected);
+    }
+
+    @Override
+    public String toString() {
+        return MoreObjects.toStringHelper(getClass())
+                .add("locations", locations)
+                .add("macAddress", macAddress)
+                .add("vlanId", vlanId)
+                .add("ip4Address", ip4Address)
+                .add("ip4State", ip4Status)
+                .add("nextHop", nextHop)
+                .add("ip6Address", ip6Address)
+                .add("ip6State", ip6Status)
+                .add("lastSeen", lastSeen)
+                .add("directlyConnected", directlyConnected)
+                .toString();
+    }
+}
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayStore.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayStore.java
new file mode 100644
index 0000000..30d6b71
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayStore.java
@@ -0,0 +1,61 @@
+/*
+ * 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.dhcprelay.store;
+
+import org.onosproject.net.HostId;
+import org.onosproject.store.Store;
+import org.onosproject.store.StoreDelegate;
+
+import java.util.Collection;
+import java.util.Optional;
+
+/**
+ * Stores DHCP records which relay-ed by DHCP relay application.
+ */
+public interface DhcpRelayStore extends Store<DhcpRelayStoreEvent, StoreDelegate<DhcpRelayStoreEvent>> {
+
+    /**
+     * Creates or updates DHCP record for specific host id (mac + vlan).
+     *
+     * @param hostId the id of host
+     * @param dhcpRecord the DHCP record to update
+     */
+    void updateDhcpRecord(HostId hostId, DhcpRecord dhcpRecord);
+
+    /**
+     * Gets DHCP record for specific host id (mac + vlan).
+     *
+     * @param hostId the id of host
+     * @return the DHCP record of the host; empty if record not exists
+     */
+    Optional<DhcpRecord> getDhcpRecord(HostId hostId);
+
+    /**
+     * Gets all DHCP records from store.
+     *
+     * @return all DHCP records from store
+     */
+    Collection<DhcpRecord> getDhcpRecords();
+
+    /**
+     * Removes record for specific host id (mac + vlan).
+     *
+     * @param hostId the id of host
+     * @return the DHCP record of the host; empty if record not exists
+     */
+    Optional<DhcpRecord> removeDhcpRecord(HostId hostId);
+}
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayStoreEvent.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayStoreEvent.java
new file mode 100644
index 0000000..bca3df3
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DhcpRelayStoreEvent.java
@@ -0,0 +1,51 @@
+/*
+ * 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.dhcprelay.store;
+
+
+import org.onosproject.event.AbstractEvent;
+
+/**
+ * Event class for DHCP relay store.
+ */
+public class DhcpRelayStoreEvent extends AbstractEvent<DhcpRelayStoreEvent.Type, DhcpRecord> {
+
+    /**
+     * Types of the event.
+     */
+    public enum Type {
+        /**
+         * A DHCP record has been created or updated.
+         */
+        UPDATED,
+
+        /**
+         * A DHCP record has been removed.
+         */
+        REMOVED
+    }
+
+    /**
+     * Creates a DHCP relay store event by given information.
+     *
+     * @param type the type of event
+     * @param subject the DHCP record of this event
+     */
+    protected DhcpRelayStoreEvent(Type type, DhcpRecord subject) {
+        super(type, subject);
+    }
+}
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
new file mode 100644
index 0000000..b5f2bf8
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/DistributedDhcpRelayStore.java
@@ -0,0 +1,143 @@
+/*
+ * 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.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.onlab.packet.DHCP;
+import org.onlab.packet.DHCP6;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.net.HostId;
+import org.onosproject.store.StoreDelegate;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.EventuallyConsistentMap;
+import org.onosproject.store.service.EventuallyConsistentMapEvent;
+import org.onosproject.store.service.EventuallyConsistentMapListener;
+import org.onosproject.store.service.StorageService;
+import org.onosproject.store.service.WallClockTimestamp;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Optional;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Distributed DHCP relay store.
+ */
+@Component
+public class DistributedDhcpRelayStore implements DhcpRelayStore {
+    private static final KryoNamespace APP_KRYO = KryoNamespace.newBuilder()
+            .register(KryoNamespaces.API)
+            .register(DhcpRecord.class)
+            .register(DHCP.MsgType.class)
+            .register(DHCP6.MsgType.class)
+            .build();
+
+    private Logger log = getLogger(getClass());
+    private StoreDelegate<DhcpRelayStoreEvent> delegate;
+    private EventuallyConsistentMap<HostId, DhcpRecord> dhcpRecords;
+    private EventuallyConsistentMapListener<HostId, DhcpRecord> listener;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected StorageService storageService;
+
+    @Activate
+    protected void activated() {
+        dhcpRecords = storageService.<HostId, DhcpRecord>eventuallyConsistentMapBuilder()
+                .withName("DHCP-Relay-Records")
+                .withTimestampProvider((hostId, record) -> new WallClockTimestamp(record.lastSeen()))
+                .withSerializer(APP_KRYO)
+                .build();
+        listener = new InternalMapListener();
+        dhcpRecords.addListener(listener);
+    }
+
+    @Deactivate
+    protected void deactivated() {
+        dhcpRecords.removeListener(listener);
+        dhcpRecords.destroy().join();
+    }
+
+    @Override
+    public void setDelegate(StoreDelegate<DhcpRelayStoreEvent> delegate) {
+        checkNotNull("Delegate can't be null", delegate);
+        this.delegate = delegate;
+    }
+
+    @Override
+    public void unsetDelegate(StoreDelegate<DhcpRelayStoreEvent> delegate) {
+        this.delegate = null;
+    }
+
+    @Override
+    public boolean hasDelegate() {
+        return delegate != null;
+    }
+
+    @Override
+    public void updateDhcpRecord(HostId hostId, DhcpRecord dhcpRecord) {
+        checkNotNull(hostId, "Host id can't be null");
+        checkNotNull(dhcpRecord, "DHCP record can't be null");
+        dhcpRecords.put(hostId, dhcpRecord);
+    }
+
+    @Override
+    public Optional<DhcpRecord> getDhcpRecord(HostId hostId) {
+        checkNotNull(hostId, "Host id can't be null");
+        return Optional.ofNullable(dhcpRecords.get(hostId));
+    }
+
+    @Override
+    public Collection<DhcpRecord> getDhcpRecords() {
+        return dhcpRecords.values();
+    }
+
+    @Override
+    public Optional<DhcpRecord> removeDhcpRecord(HostId hostId) {
+        checkNotNull(hostId, "Host id can't be null");
+        return Optional.ofNullable(dhcpRecords.remove(hostId));
+    }
+
+    /**
+     * Internal map listener for DHCP records map.
+     */
+    private class InternalMapListener implements EventuallyConsistentMapListener<HostId, DhcpRecord> {
+        @Override
+        public void event(EventuallyConsistentMapEvent<HostId, DhcpRecord> event) {
+            DhcpRelayStoreEvent.Type eventType;
+            switch (event.type()) {
+                case PUT:
+                    eventType = DhcpRelayStoreEvent.Type.UPDATED;
+                    break;
+                case REMOVE:
+                    eventType = DhcpRelayStoreEvent.Type.REMOVED;
+                    break;
+                default:
+                    log.warn("Unknown event type {}", event.type());
+                    return;
+            }
+            if (delegate != null) {
+                delegate.notify(new DhcpRelayStoreEvent(eventType, event.value()));
+            }
+        }
+    }
+}
diff --git a/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/package-info.java b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/package-info.java
new file mode 100644
index 0000000..9048977
--- /dev/null
+++ b/apps/dhcprelay/src/main/java/org/onosproject/dhcprelay/store/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * 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.
+ */
+
+/**
+ * Store of DHCP relay application.
+ */
+package org.onosproject.dhcprelay.store;
\ No newline at end of file