[ONOS-7926] Implement IPAM service to allocate IP for Kubernetes POD

Change-Id: I32fd1fffb41ec728d0be092ac5a8f555179e7a9e
diff --git a/apps/k8s-networking/BUILD b/apps/k8s-networking/BUILD
index 866fca6..0794152a 100644
--- a/apps/k8s-networking/BUILD
+++ b/apps/k8s-networking/BUILD
@@ -1,6 +1,7 @@
 BUNDLES = [
     "//apps/k8s-networking/api:onos-apps-k8s-networking-api",
     "//apps/k8s-networking/app:onos-apps-k8s-networking-app",
+    "@commons_net//jar",
 ]
 
 onos_app(
diff --git a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/DefaultK8sIpam.java b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/DefaultK8sIpam.java
index cb488b3..605cdea 100644
--- a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/DefaultK8sIpam.java
+++ b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/DefaultK8sIpam.java
@@ -24,16 +24,23 @@
  */
 public final class DefaultK8sIpam implements K8sIpam {
 
+    private final String ipamId;
     private final IpAddress ipAddress;
     private final String networkId;
 
     // private constructor not intended for external invocation
-    public DefaultK8sIpam(IpAddress ipAddress, String networkId) {
+    public DefaultK8sIpam(String ipamId, IpAddress ipAddress, String networkId) {
+        this.ipamId = ipamId;
         this.ipAddress = ipAddress;
         this.networkId = networkId;
     }
 
     @Override
+    public String ipamId() {
+        return ipamId;
+    }
+
+    @Override
     public IpAddress ipAddress() {
         return ipAddress;
     }
@@ -52,18 +59,20 @@
             return false;
         }
         DefaultK8sIpam that = (DefaultK8sIpam) o;
-        return Objects.equal(ipAddress, that.ipAddress) &&
+        return Objects.equal(ipamId, that.ipamId) &&
+                Objects.equal(ipAddress, that.ipAddress) &&
                 Objects.equal(networkId, that.networkId);
     }
 
     @Override
     public int hashCode() {
-        return Objects.hashCode(ipAddress, networkId);
+        return Objects.hashCode(ipamId, ipAddress, networkId);
     }
 
     @Override
     public String toString() {
         return MoreObjects.toStringHelper(this)
+                .add("ipamId", ipamId)
                 .add("ipAddress", ipAddress)
                 .add("networkId", networkId)
                 .toString();
diff --git a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpam.java b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpam.java
index 9969f30..cc57058 100644
--- a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpam.java
+++ b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpam.java
@@ -23,6 +23,13 @@
 public interface K8sIpam {
 
     /**
+     * Returns the IPAM identifier.
+     *
+     * @return IPAM identifier
+     */
+    String ipamId();
+
+    /**
      * Returns the IP address.
      *
      * @return IP address
diff --git a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamAdminService.java b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamAdminService.java
index f34421a..d8752f8 100644
--- a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamAdminService.java
+++ b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamAdminService.java
@@ -17,6 +17,8 @@
 
 import org.onlab.packet.IpAddress;
 
+import java.util.Set;
+
 /**
  * IP Address Management admin service for kubernetes network.
  */
@@ -31,10 +33,26 @@
     IpAddress allocateIp(String networkId);
 
     /**
-     * Leases the IP address from the given network.
+     * Releases the IP address from the given network.
      *
      * @param networkId network identifier
-     * @return leased IP address
+     * @param ipAddress IP address
+     * @return true if the given IP was successfully released, false otherwise
      */
-    IpAddress leaseIp(String networkId);
+    boolean releaseIp(String networkId, IpAddress ipAddress);
+
+    /**
+     * Initializes IP address pool.
+     *
+     * @param networkId network identifier
+     * @param ipAddresses a set of IP addresses contained in this IP pool
+     */
+    void initializeIpPool(String networkId, Set<IpAddress> ipAddresses);
+
+    /**
+     * Purges the existing IP address pool of the given network identifier.
+     *
+     * @param networkId network identifier
+     */
+    void purgeIpPool(String networkId);
 }
diff --git a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamStore.java b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamStore.java
index bcd1d1f..5a88756 100644
--- a/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamStore.java
+++ b/apps/k8s-networking/api/src/main/java/org/onosproject/k8snetworking/api/K8sIpamStore.java
@@ -15,7 +15,6 @@
  */
 package org.onosproject.k8snetworking.api;
 
-import org.onlab.packet.IpAddress;
 import org.onosproject.store.Store;
 
 import java.util.Set;
@@ -26,48 +25,88 @@
 public interface K8sIpamStore extends Store<K8sIpamEvent, K8sIpamStoreDelegate> {
 
     /**
-     * Allocates a new IP address.
+     * Creates a new allocated IP address.
      *
-     * @param networkId network identifier
-     * @return newly allocated IP address
+     * @param ipam IPAM instance
      */
-    IpAddress allocateIp(String networkId);
+    void createAllocatedIp(K8sIpam ipam);
 
     /**
-     * Leases the existing IP address.
+     * Updates the existing allocated IP address.
      *
-     * @param networkId network identifier
-     * @return leased IP address
+     * @param ipam IPAM instance
      */
-    IpAddress leaseIp(String networkId);
+    void updateAllocatedIp(K8sIpam ipam);
 
     /**
-     * Initializes a new IP pool with the given network.
+     * Removes the existing allocated IP address.
      *
-     * @param networkId network identifier
+     * @param ipamId IPAM identifier
+     * @return removed IPAM instance; null if failed
      */
-    void initializeIpPool(String networkId);
+    K8sIpam removeAllocatedIp(String ipamId);
 
     /**
-     * Purges an existing IP pool associated with the given network.
+     * Returns the IPAM with the given IPAM identifier.
      *
-     * @param networkId network identifier
+     * @param ipamId IPAM identifier
+     * @return IPAM; null it not found
      */
-    void purgeIpPool(String networkId);
+    K8sIpam allocatedIp(String ipamId);
 
     /**
-     * Returns the already allocated IP addresses.
+     * Returns all allocated IPAM instances.
      *
-     * @param networkId network identifier
-     * @return allocated IP addresses
+     * @return set of IPAM instances
      */
-    Set<IpAddress> allocatedIps(String networkId);
+    Set<K8sIpam> allocatedIps();
 
     /**
-     * Returns the available IP addresses.
+     * Creates a new available IP address.
+     *
+     * @param ipam IPAM instance
+     */
+    void createAvailableIp(K8sIpam ipam);
+
+    /**
+     * Updates the existing available IP address.
+     *
+     * @param ipam IPAM instance
+     */
+    void updateAvailableIp(K8sIpam ipam);
+
+    /**
+     * Removes the existing available IP address.
+     *
+     * @param ipamId IPAM identifier
+     * @return remved IPAM instance; null if failed
+     */
+    K8sIpam removeAvailableIp(String ipamId);
+
+    /**
+     * Returns the IPAM with the given IPAM identifier.
+     *
+     * @param ipamId IPAM identifier
+     * @return IPAM; null it not found
+     */
+    K8sIpam availableIp(String ipamId);
+
+    /**
+     * Returns all available IPAM instances.
+     *
+     * @return set of IPAM instances
+     */
+    Set<K8sIpam> availableIps();
+
+    /**
+     * Clears all allocated and available IP addresses.
+     */
+    void clear();
+
+    /**
+     * Clears allocated and available IP addresses associated with the given network.
      *
      * @param networkId network identifier
-     * @return available IP addresses
      */
-    Set<IpAddress> availableIps(String networkId);
+    void clear(String networkId);
 }
diff --git a/apps/k8s-networking/api/src/test/java/org/onosproject/k8snetworking/api/DefaultK8sIpamTest.java b/apps/k8s-networking/api/src/test/java/org/onosproject/k8snetworking/api/DefaultK8sIpamTest.java
index bfb5670..243d64d 100644
--- a/apps/k8s-networking/api/src/test/java/org/onosproject/k8snetworking/api/DefaultK8sIpamTest.java
+++ b/apps/k8s-networking/api/src/test/java/org/onosproject/k8snetworking/api/DefaultK8sIpamTest.java
@@ -32,6 +32,8 @@
     private static final IpAddress IP_ADDRESS_2 = IpAddress.valueOf("20.20.20.20");
     private static final String NETWORK_ID_1 = "network-1";
     private static final String NETWORK_ID_2 = "network-2";
+    private static final String IPAM_ID_1 = NETWORK_ID_1 + "-" + IP_ADDRESS_1.toString();
+    private static final String IPAM_ID_2 = NETWORK_ID_2 + "-" + IP_ADDRESS_2.toString();
 
     private K8sIpam ipam1;
     private K8sIpam sameAsIpam1;
@@ -50,9 +52,9 @@
      */
     @Before
     public void setUp() {
-        ipam1 = new DefaultK8sIpam(IP_ADDRESS_1, NETWORK_ID_1);
-        sameAsIpam1 = new DefaultK8sIpam(IP_ADDRESS_1, NETWORK_ID_1);
-        ipam2 = new DefaultK8sIpam(IP_ADDRESS_2, NETWORK_ID_2);
+        ipam1 = new DefaultK8sIpam(IPAM_ID_1, IP_ADDRESS_1, NETWORK_ID_1);
+        sameAsIpam1 = new DefaultK8sIpam(IPAM_ID_1, IP_ADDRESS_1, NETWORK_ID_1);
+        ipam2 = new DefaultK8sIpam(IPAM_ID_2, IP_ADDRESS_2, NETWORK_ID_2);
     }
 
     /**
@@ -72,6 +74,7 @@
     public void testConstruction() {
         K8sIpam ipam = ipam1;
 
+        assertEquals(IPAM_ID_1, ipam.ipamId());
         assertEquals(IP_ADDRESS_1, ipam.ipAddress());
         assertEquals(NETWORK_ID_1, ipam.networkId());
     }
diff --git a/apps/k8s-networking/app/BUILD b/apps/k8s-networking/app/BUILD
index 0a9af85..eb29430 100644
--- a/apps/k8s-networking/app/BUILD
+++ b/apps/k8s-networking/app/BUILD
@@ -4,7 +4,7 @@
     "//protocols/ovsdb/rfc:onos-protocols-ovsdb-rfc",
     "//apps/k8s-node/api:onos-apps-k8s-node-api",
     "//apps/k8s-networking/api:onos-apps-k8s-networking-api",
-    "@commons_codec//jar",
+    "@commons_net//jar",
 ]
 
 TEST_DEPS = TEST_ADAPTERS + TEST_REST + [
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/codec/K8sIpamCodec.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/codec/K8sIpamCodec.java
index 695156c..8785906 100644
--- a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/codec/K8sIpamCodec.java
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/codec/K8sIpamCodec.java
@@ -34,6 +34,7 @@
 
     private final Logger log = getLogger(getClass());
 
+    private static final String IPAM_ID = "ipamId";
     private static final String IP_ADDRESS = "ipAddress";
     private static final String NETWORK_ID = "networkId";
 
@@ -44,6 +45,7 @@
         checkNotNull(ipam, "Kubernetes IPAM cannot be null");
 
         return context.mapper().createObjectNode()
+                .put(IPAM_ID, ipam.ipamId())
                 .put(IP_ADDRESS, ipam.ipAddress().toString())
                 .put(NETWORK_ID, ipam.networkId());
     }
@@ -54,11 +56,13 @@
             return null;
         }
 
+        String ipamId = nullIsIllegal(json.get(IPAM_ID).asText(),
+                IPAM_ID + MISSING_MESSAGE);
         String ipAddress = nullIsIllegal(json.get(IP_ADDRESS).asText(),
                 IP_ADDRESS + MISSING_MESSAGE);
         String networkId = nullIsIllegal(json.get(NETWORK_ID).asText(),
                 NETWORK_ID + MISSING_MESSAGE);
 
-        return new DefaultK8sIpam(IpAddress.valueOf(ipAddress), networkId);
+        return new DefaultK8sIpam(ipamId, IpAddress.valueOf(ipAddress), networkId);
     }
 }
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sIpamStore.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sIpamStore.java
new file mode 100644
index 0000000..9142e24
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sIpamStore.java
@@ -0,0 +1,195 @@
+/*
+ * Copyright 2019-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.k8snetworking.impl;
+
+import com.google.common.collect.ImmutableSet;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snetworking.api.DefaultK8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpamEvent;
+import org.onosproject.k8snetworking.api.K8sIpamStore;
+import org.onosproject.k8snetworking.api.K8sIpamStoreDelegate;
+import org.onosproject.store.AbstractStore;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.Serializer;
+import org.onosproject.store.service.StorageService;
+import org.onosproject.store.service.Versioned;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Collection;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubernetes IP address management store using consistent map.
+ */
+@Component(immediate = true, service = K8sIpamStore.class)
+public class DistributedK8sIpamStore
+        extends AbstractStore<K8sIpamEvent, K8sIpamStoreDelegate>
+        implements K8sIpamStore {
+
+    private final Logger log = getLogger(getClass());
+
+    private static final String ERR_NOT_FOUND = " does not exist";
+    private static final String ERR_DUPLICATE = " already exists";
+    private static final String APP_ID = "org.onosproject.k8snetwork";
+
+    private static final KryoNamespace
+            SERIALIZER_K8S_IPAM = KryoNamespace.newBuilder()
+            .register(KryoNamespaces.API)
+            .register(K8sIpam.class)
+            .register(DefaultK8sIpam.class)
+            .register(Collection.class)
+            .build();
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected StorageService storageService;
+
+    private final ExecutorService eventExecutor = newSingleThreadExecutor(
+            groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
+
+    private ConsistentMap<String, K8sIpam> allocatedStore;
+    private ConsistentMap<String, K8sIpam> availableStore;
+
+    @Activate
+    protected void activate() {
+        ApplicationId appId = coreService.registerApplication(APP_ID);
+        allocatedStore = storageService.<String, K8sIpam>consistentMapBuilder()
+                .withSerializer(Serializer.using(SERIALIZER_K8S_IPAM))
+                .withName("k8s-ipam-allocated-store")
+                .withApplicationId(appId)
+                .build();
+        availableStore = storageService.<String, K8sIpam>consistentMapBuilder()
+                .withSerializer(Serializer.using(SERIALIZER_K8S_IPAM))
+                .withName("k8s-ipam-available-store")
+                .withApplicationId(appId)
+                .build();
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        eventExecutor.shutdown();
+        log.info("Stopped");
+    }
+
+    @Override
+    public void createAllocatedIp(K8sIpam ipam) {
+        allocatedStore.compute(ipam.ipamId(), (ipamId, existing) -> {
+            final String error = ipam.ipamId() + ERR_DUPLICATE;
+            checkArgument(existing == null, error);
+            return ipam;
+        });
+    }
+
+    @Override
+    public void updateAllocatedIp(K8sIpam ipam) {
+        allocatedStore.compute(ipam.ipamId(), (ipamId, existing) -> {
+            final String error = ipam.ipamId() + ERR_NOT_FOUND;
+            checkArgument(existing != null, error);
+            return ipam;
+        });
+    }
+
+    @Override
+    public K8sIpam removeAllocatedIp(String ipamId) {
+        Versioned<K8sIpam> ipam = allocatedStore.remove(ipamId);
+        if (ipam == null) {
+            final String error = ipamId + ERR_NOT_FOUND;
+            throw new IllegalArgumentException(error);
+        }
+        return ipam.value();
+    }
+
+    @Override
+    public K8sIpam allocatedIp(String ipamId) {
+        return allocatedStore.asJavaMap().get(ipamId);
+    }
+
+    @Override
+    public Set<K8sIpam> allocatedIps() {
+        return ImmutableSet.copyOf(allocatedStore.asJavaMap().values());
+    }
+
+    @Override
+    public void createAvailableIp(K8sIpam ipam) {
+        availableStore.compute(ipam.ipamId(), (ipamId, existing) -> {
+            final String error = ipam.ipamId() + ERR_DUPLICATE;
+            checkArgument(existing == null, error);
+            return ipam;
+        });
+    }
+
+    @Override
+    public void updateAvailableIp(K8sIpam ipam) {
+        availableStore.compute(ipam.ipamId(), (ipamId, existing) -> {
+            final String error = ipam.ipamId() + ERR_NOT_FOUND;
+            checkArgument(existing != null, error);
+            return ipam;
+        });
+    }
+
+    @Override
+    public K8sIpam removeAvailableIp(String ipamId) {
+        Versioned<K8sIpam> ipam = availableStore.remove(ipamId);
+        if (ipam == null) {
+            final String error = ipamId + ERR_NOT_FOUND;
+            throw new IllegalArgumentException(error);
+        }
+        return ipam.value();
+    }
+
+    @Override
+    public K8sIpam availableIp(String ipamId) {
+        return availableStore.asJavaMap().get(ipamId);
+    }
+
+    @Override
+    public Set<K8sIpam> availableIps() {
+        return ImmutableSet.copyOf(availableStore.asJavaMap().values());
+    }
+
+    @Override
+    public void clear() {
+        allocatedStore.clear();
+        availableStore.clear();
+    }
+
+    @Override
+    public void clear(String networkId) {
+        Set<K8sIpam> ipams = allocatedStore.asJavaMap().values().stream()
+                            .filter(i -> i.networkId().equals(networkId))
+                            .collect(Collectors.toSet());
+        ipams.forEach(i -> allocatedStore.remove(i.ipamId()));
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sIpamHandler.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sIpamHandler.java
new file mode 100644
index 0000000..5591d2e
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sIpamHandler.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2019-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.k8snetworking.impl;
+
+import org.onlab.packet.IpAddress;
+import org.onosproject.cluster.ClusterService;
+import org.onosproject.cluster.LeadershipService;
+import org.onosproject.cluster.NodeId;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snetworking.api.K8sIpamAdminService;
+import org.onosproject.k8snetworking.api.K8sNetworkEvent;
+import org.onosproject.k8snetworking.api.K8sNetworkListener;
+import org.onosproject.k8snetworking.api.K8sNetworkService;
+import org.onosproject.mastership.MastershipService;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
+import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.getSubnetIps;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Initializes and purges the kubernetes IPAM.
+ */
+@Component(immediate = true)
+public class K8sIpamHandler {
+
+    private final Logger log = getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected MastershipService mastershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected ClusterService clusterService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected LeadershipService leadershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sNetworkService k8sNetworkService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sIpamAdminService k8sIpamAdminService;
+
+    private final ExecutorService eventExecutor = newSingleThreadExecutor(
+            groupedThreads(this.getClass().getSimpleName(), "event-handler"));
+    private final InternalK8sNetworkListener k8sNetworkListener =
+            new InternalK8sNetworkListener();
+
+    private ApplicationId appId;
+    private NodeId localNodeId;
+
+    @Activate
+    protected void activate() {
+        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
+        localNodeId = clusterService.getLocalNode().id();
+        leadershipService.runForLeadership(appId.name());
+        k8sNetworkService.addListener(k8sNetworkListener);
+
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        k8sNetworkService.removeListener(k8sNetworkListener);
+        leadershipService.withdraw(appId.name());
+        eventExecutor.shutdown();
+
+        log.info("Stopped");
+    }
+
+    private class InternalK8sNetworkListener implements K8sNetworkListener {
+
+        private boolean isRelevantHelper() {
+            return Objects.equals(localNodeId, leadershipService.getLeader(appId.name()));
+        }
+
+        @Override
+        public void event(K8sNetworkEvent event) {
+            switch (event.type()) {
+                case K8S_NETWORK_CREATED:
+                    eventExecutor.execute(() -> processNetworkAddition(event));
+                    break;
+                case K8S_NETWORK_REMOVED:
+                    eventExecutor.execute(() -> processNetworkRemoval(event));
+                    break;
+                default:
+                    break;
+            }
+        }
+
+        private void processNetworkAddition(K8sNetworkEvent event) {
+            if (!isRelevantHelper()) {
+                return;
+            }
+
+            Set<IpAddress> ips = getSubnetIps(event.subject().cidr());
+            k8sIpamAdminService.initializeIpPool(event.subject().networkId(), ips);
+        }
+
+        private void processNetworkRemoval(K8sNetworkEvent event) {
+            if (!isRelevantHelper()) {
+                return;
+            }
+
+            k8sIpamAdminService.purgeIpPool(event.subject().networkId());
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sIpamManager.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sIpamManager.java
new file mode 100644
index 0000000..5501971
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sIpamManager.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2019-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.k8snetworking.impl;
+
+import org.onlab.packet.IpAddress;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.ListenerRegistry;
+import org.onosproject.k8snetworking.api.DefaultK8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpamAdminService;
+import org.onosproject.k8snetworking.api.K8sIpamEvent;
+import org.onosproject.k8snetworking.api.K8sIpamListener;
+import org.onosproject.k8snetworking.api.K8sIpamService;
+import org.onosproject.k8snetworking.api.K8sIpamStore;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Provides implementation of administering and interfacing kubernetes IPAM.
+ */
+@Component(
+        immediate = true,
+        service = {K8sIpamAdminService.class, K8sIpamService.class}
+)
+public class K8sIpamManager
+        extends ListenerRegistry<K8sIpamEvent, K8sIpamListener>
+        implements K8sIpamAdminService, K8sIpamService {
+
+    protected final Logger log = getLogger(getClass());
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sIpamStore k8sIpamStore;
+
+    private ApplicationId appId;
+
+    @Activate
+    protected void activate() {
+        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
+
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        log.info("Stopped");
+    }
+
+    @Override
+    public IpAddress allocateIp(String networkId) {
+        IpAddress availableIp = availableIps(networkId).stream()
+                .findFirst().orElse(null);
+        if (availableIp != null) {
+            String ipamId = networkId + "-" + availableIp.toString();
+            k8sIpamStore.removeAvailableIp(ipamId);
+            k8sIpamStore.createAllocatedIp(
+                    new DefaultK8sIpam(ipamId, availableIp, networkId));
+
+            log.info("Allocate a new IP {}", availableIp.toString());
+
+            return availableIp;
+        } else {
+            log.warn("No IPs are available for allocating.");
+        }
+        return null;
+    }
+
+    @Override
+    public boolean releaseIp(String networkId, IpAddress ipAddress) {
+        IpAddress releasedIp = allocatedIps(networkId).stream()
+                .filter(ip -> ip.equals(ipAddress))
+                .findFirst().orElse(null);
+        if (releasedIp != null) {
+            String ipamId = networkId + "-" + releasedIp.toString();
+            k8sIpamStore.removeAllocatedIp(ipamId);
+            k8sIpamStore.createAvailableIp(
+                    new DefaultK8sIpam(ipamId, releasedIp, networkId));
+
+            log.info("Release the IP {}", releasedIp.toString());
+
+            return true;
+        } else {
+            log.warn("Failed to find requested IP {} for releasing...", ipAddress.toString());
+        }
+
+        return false;
+    }
+
+    @Override
+    public void initializeIpPool(String networkId, Set<IpAddress> ipAddresses) {
+        ipAddresses.forEach(ip -> {
+            String ipamId = networkId + "-" + ip;
+            K8sIpam ipam = new DefaultK8sIpam(ipamId, ip, networkId);
+            k8sIpamStore.createAvailableIp(ipam);
+        });
+    }
+
+    @Override
+    public void purgeIpPool(String networkId) {
+        k8sIpamStore.clear(networkId);
+    }
+
+    @Override
+    public Set<IpAddress> allocatedIps(String networkId) {
+        return k8sIpamStore.allocatedIps().stream()
+                .filter(i -> i.networkId().equals(networkId))
+                .map(K8sIpam::ipAddress).collect(Collectors.toSet());
+    }
+
+    @Override
+    public Set<IpAddress> availableIps(String networkId) {
+        return k8sIpamStore.availableIps().stream()
+                .filter(i -> i.networkId().equals(networkId))
+                .map(K8sIpam::ipAddress).collect(Collectors.toSet());
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/util/K8sNetworkingUtil.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/util/K8sNetworkingUtil.java
index f6fd629..68a8d50 100644
--- a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/util/K8sNetworkingUtil.java
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/util/K8sNetworkingUtil.java
@@ -19,6 +19,8 @@
 import com.fasterxml.jackson.core.JsonProcessingException;
 import com.fasterxml.jackson.databind.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.net.util.SubnetUtils;
+import org.onlab.packet.IpAddress;
 import org.onosproject.cfg.ConfigProperty;
 import org.onosproject.k8snetworking.api.K8sNetwork;
 import org.onosproject.k8snetworking.api.K8sNetworkService;
@@ -28,8 +30,11 @@
 import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
 import java.util.Optional;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import static org.onosproject.k8snetworking.api.Constants.PORT_NAME_PREFIX_CONTAINER;
 
@@ -130,4 +135,26 @@
         }
         return null;
     }
+
+    /**
+     * Obtains valid IP addresses of the given subnet.
+     *
+     * @param cidr CIDR
+     * @return set of IP addresses
+     */
+    public static Set<IpAddress> getSubnetIps(String cidr) {
+        SubnetUtils utils = new SubnetUtils(cidr);
+        utils.setInclusiveHostCount(true);
+        SubnetUtils.SubnetInfo info = utils.getInfo();
+        Set<String> allAddresses =
+                new HashSet<>(Arrays.asList(info.getAllAddresses()));
+
+        if (allAddresses.size() > 2) {
+            allAddresses.remove(info.getBroadcastAddress());
+            allAddresses.remove(info.getNetworkAddress());
+        }
+
+        return allAddresses.stream()
+                .map(IpAddress::valueOf).collect(Collectors.toSet());
+    }
 }
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sIpamWebResource.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sIpamWebResource.java
new file mode 100644
index 0000000..888dfe7
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sIpamWebResource.java
@@ -0,0 +1,102 @@
+/*
+ * 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.onosproject.k8snetworking.web;
+
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onlab.packet.IpAddress;
+import org.onosproject.k8snetworking.api.DefaultK8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpamAdminService;
+import org.onosproject.k8snetworking.api.K8sNetwork;
+import org.onosproject.k8snetworking.api.K8sNetworkService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import static org.onlab.util.Tools.nullIsNotFound;
+
+/**
+ * Handles IPAM related REST API call from CNI plugin.
+ */
+@Path("ipam")
+public class K8sIpamWebResource extends AbstractWebResource {
+
+    protected final Logger log = LoggerFactory.getLogger(getClass());
+
+    private static final String NETWORK_ID_NOT_FOUND = "Network Id is not found";
+    private static final String IP_NOT_ALLOCATED = "IP address cannot be allocated";
+
+    private static final String IPAM = "ipam";
+
+    private final K8sNetworkService networkService = get(K8sNetworkService.class);
+    private final K8sIpamAdminService ipamService = get(K8sIpamAdminService.class);
+
+    /**
+     * Requests for allocating a unique IP address of the given network ID.
+     *
+     * @param netId     network identifier
+     * @return 200 OK with the serialized IPAM JSON string
+     * @onos.rsModel K8sIpam
+     */
+    @GET
+    @Path("{netId}")
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response allocateIp(@PathParam("netId") String netId) {
+        log.trace("Received IP allocation request of network " + netId);
+
+        K8sNetwork network =
+                nullIsNotFound(networkService.network(netId), NETWORK_ID_NOT_FOUND);
+
+        IpAddress ip =
+                nullIsNotFound(ipamService.allocateIp(network.networkId()), IP_NOT_ALLOCATED);
+
+        ObjectNode root = mapper().createObjectNode();
+        String ipamId = network.networkId() + "-" + ip.toString();
+        K8sIpam ipam = new DefaultK8sIpam(ipamId, ip, network.networkId());
+        root.set(IPAM, codec(K8sIpam.class).encode(ipam, this));
+
+        return ok(root).build();
+    }
+
+    /**
+     * Requests for releasing the given IP address.
+     *
+     * @param netId     network identifier
+     * @param ip        IP address
+     * @return 204 NO CONTENT
+     */
+    @DELETE
+    @Path("{netId}/{ip}")
+    public Response releaseIp(@PathParam("netId") String netId,
+                              @PathParam("ip") String ip) {
+        log.trace("Received IP release request of network " + netId);
+
+        K8sNetwork network =
+                nullIsNotFound(networkService.network(netId), NETWORK_ID_NOT_FOUND);
+
+        ipamService.releaseIp(network.networkId(), IpAddress.valueOf(ip));
+
+        return Response.noContent().build();
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sNetworkingWebApplication.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sNetworkingWebApplication.java
index ff268d8..228d371 100644
--- a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sNetworkingWebApplication.java
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/web/K8sNetworkingWebApplication.java
@@ -27,7 +27,8 @@
     public Set<Class<?>> getClasses() {
         return getClasses(
                 K8sNetworkWebResource.class,
-                K8sPortWebResource.class
+                K8sPortWebResource.class,
+                K8sIpamWebResource.class
         );
     }
 }
diff --git a/apps/k8s-networking/app/src/main/resources/definitions/K8sIpam.json b/apps/k8s-networking/app/src/main/resources/definitions/K8sIpam.json
new file mode 100644
index 0000000..b233a68
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/resources/definitions/K8sIpam.json
@@ -0,0 +1,26 @@
+{
+  "type": "object",
+  "description": "An IPAM object.",
+  "required": [
+    "ipamId",
+    "networkId",
+    "ipAddress"
+  ],
+  "properties": {
+    "ipamId": {
+      "type": "string",
+      "example": "sona-network-10.10.10.2",
+      "description": "The ID of the IPAM."
+    },
+    "networkId": {
+      "type": "string",
+      "example": "sona-network",
+      "description": "The ID of the attached network."
+    },
+    "ipAddress": {
+      "type": "string",
+      "example": "10.10.10.2",
+      "description": "The IP address of IPAM."
+    }
+  }
+}
\ No newline at end of file
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamCodecTest.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamCodecTest.java
index 8335867..95914eb 100644
--- a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamCodecTest.java
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamCodecTest.java
@@ -76,7 +76,7 @@
      */
     @Test
     public void testK8sIpamEncode() {
-        K8sIpam ipam = new DefaultK8sIpam(
+        K8sIpam ipam = new DefaultK8sIpam("network-1-10.10.10.10",
                 IpAddress.valueOf("10.10.10.10"), "network-1");
 
         ObjectNode nodeJson = k8sIpamCodec.encode(ipam, context);
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamJsonMatcher.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamJsonMatcher.java
index 81bbf10..3934ea9 100644
--- a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamJsonMatcher.java
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/codec/K8sIpamJsonMatcher.java
@@ -27,6 +27,7 @@
 
     private final K8sIpam ipam;
 
+    private static final String IPAM_ID = "ipamId";
     private static final String IP_ADDRESS = "ipAddress";
     private static final String NETWORK_ID = "networkId";
 
@@ -37,6 +38,14 @@
     @Override
     protected boolean matchesSafely(JsonNode jsonNode, Description description) {
 
+        // check IPAM ID
+        String jsonIpamId = jsonNode.get(IPAM_ID).asText();
+        String ipamId = ipam.ipamId();
+        if (!jsonIpamId.equals(ipamId)) {
+            description.appendText("IPAM ID was " + jsonIpamId);
+            return false;
+        }
+
         // check IP address
         String jsonIpAddress = jsonNode.get(IP_ADDRESS).asText();
         String ipAddress = ipam.ipAddress().toString();
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sIpamManagerTest.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sIpamManagerTest.java
new file mode 100644
index 0000000..887cca5
--- /dev/null
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sIpamManagerTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2019-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.k8snetworking.impl;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.MoreExecutors;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onlab.packet.IpAddress;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Unit tests for kubernetes IPAM manager.
+ */
+public class K8sIpamManagerTest {
+
+    private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+    private static final String NETWORK_ID = "sona-network";
+    private static final IpAddress IP_ADDRESS_1 = IpAddress.valueOf("10.10.10.2");
+    private static final IpAddress IP_ADDRESS_2 = IpAddress.valueOf("10.10.10.3");
+    private static final Set<IpAddress> IP_ADDRESSES = ImmutableSet.of(IP_ADDRESS_1, IP_ADDRESS_2);
+
+    private K8sIpamManager target;
+    private DistributedK8sIpamStore k8sIpamStore;
+
+    @Before
+    public void setUp() throws Exception {
+        k8sIpamStore = new DistributedK8sIpamStore();
+        TestUtils.setField(k8sIpamStore, "coreService", new TestCoreService());
+        TestUtils.setField(k8sIpamStore, "storageService", new TestStorageService());
+        TestUtils.setField(k8sIpamStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+        k8sIpamStore.activate();
+
+        target = new K8sIpamManager();
+        TestUtils.setField(target, "coreService", new TestCoreService());
+        target.k8sIpamStore = k8sIpamStore;
+        target.activate();
+    }
+
+    @After
+    public void tearDown() {
+        k8sIpamStore.deactivate();
+        target.deactivate();
+        k8sIpamStore = null;
+        target = null;
+    }
+
+    /**
+     * Tests if allocating IP address works correctly.
+     */
+    @Test
+    public void testAllocateIp() {
+        createBasicIpPool();
+
+        assertEquals("Number of allocated IPs did not match", 0,
+                target.allocatedIps(NETWORK_ID).size());
+        assertEquals("Number of available IPs did not match", 2,
+                target.availableIps(NETWORK_ID).size());
+
+        IpAddress allocatedIp = target.allocateIp(NETWORK_ID);
+        assertEquals("Number of allocated IPs did not match", 1,
+                target.allocatedIps(NETWORK_ID).size());
+        assertEquals("Number of available IPs did not match", 1,
+                target.availableIps(NETWORK_ID).size());
+        assertTrue("Allocated IP did not match",
+                IP_ADDRESSES.contains(allocatedIp));
+    }
+
+    /**
+     * Tests if releasing IP address works correctly.
+     */
+    @Test
+    public void testReleaseIp() {
+        createBasicIpPool();
+
+        IpAddress allocatedIp1 = target.allocateIp(NETWORK_ID);
+        IpAddress allocatedIp2 = target.allocateIp(NETWORK_ID);
+
+        assertEquals("Number of allocated IPs did not match", 2,
+                target.allocatedIps(NETWORK_ID).size());
+        assertEquals("Number of available IPs did not match", 0,
+                target.availableIps(NETWORK_ID).size());
+
+        target.releaseIp(NETWORK_ID, allocatedIp1);
+
+        assertEquals("Number of allocated IPs did not match", 1,
+                target.allocatedIps(NETWORK_ID).size());
+        assertEquals("Number of available IPs did not match", 1,
+                target.availableIps(NETWORK_ID).size());
+
+        target.releaseIp(NETWORK_ID, allocatedIp2);
+
+        assertEquals("Number of allocated IPs did not match", 0,
+                target.allocatedIps(NETWORK_ID).size());
+        assertEquals("Number of available IPs did not match", 2,
+                target.availableIps(NETWORK_ID).size());
+    }
+
+    private void createBasicIpPool() {
+        target.initializeIpPool(NETWORK_ID, IP_ADDRESSES);
+    }
+
+    private static class TestCoreService extends CoreServiceAdapter {
+
+        @Override
+        public ApplicationId registerApplication(String name) {
+            return TEST_APP_ID;
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/util/K8sNetworkUtilTest.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/util/K8sNetworkUtilTest.java
new file mode 100644
index 0000000..810c6f0
--- /dev/null
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/util/K8sNetworkUtilTest.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2019-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.k8snetworking.util;
+
+import org.junit.Test;
+import org.onlab.packet.IpAddress;
+
+import java.util.Set;
+
+import static junit.framework.TestCase.assertEquals;
+import static org.onosproject.k8snetworking.util.K8sNetworkingUtil.getSubnetIps;
+
+/**
+ * Unit tests for kubernetes networking utils.
+ */
+public final class K8sNetworkUtilTest {
+
+    /**
+     * Tests the getSubnetIps method.
+     */
+    @Test
+    public void testGetSubnetIps() {
+        String bClassCidr = "10.10.0.0/16";
+        Set<IpAddress> bClassIps = getSubnetIps(bClassCidr);
+        assertEquals(((Double) Math.pow(2, 16)).intValue() - 2, bClassIps.size());
+
+        String cClassCidr = "10.10.10.0/24";
+        Set<IpAddress> cClassIps = getSubnetIps(cClassCidr);
+        assertEquals(((Double) Math.pow(2, 8)).intValue() - 2, cClassIps.size());
+
+        String dClassCidr = "10.10.10.10/32";
+        Set<IpAddress> dClassIps = getSubnetIps(dClassCidr);
+        assertEquals(1, dClassIps.size());
+    }
+}
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/web/K8sIpamWebResourceTest.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/web/K8sIpamWebResourceTest.java
new file mode 100644
index 0000000..ad6e52b
--- /dev/null
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/web/K8sIpamWebResourceTest.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2019-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.k8snetworking.web;
+
+import org.glassfish.jersey.server.ResourceConfig;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.osgi.TestServiceDirectory;
+import org.onlab.packet.IpAddress;
+import org.onosproject.codec.CodecService;
+import org.onosproject.codec.impl.CodecManager;
+import org.onosproject.k8snetworking.api.DefaultK8sNetwork;
+import org.onosproject.k8snetworking.api.K8sIpam;
+import org.onosproject.k8snetworking.api.K8sIpamAdminService;
+import org.onosproject.k8snetworking.api.K8sNetwork;
+import org.onosproject.k8snetworking.api.K8sNetworkService;
+import org.onosproject.k8snetworking.codec.K8sIpamCodec;
+import org.onosproject.rest.resources.ResourceTest;
+
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.Response;
+
+import static junit.framework.TestCase.assertEquals;
+import static org.easymock.EasyMock.anyObject;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+
+/**
+ * Unit test for kubernetes IPAM REST API.
+ */
+public class K8sIpamWebResourceTest extends ResourceTest {
+
+    final K8sNetworkService mockNetworkService = createMock(K8sNetworkService.class);
+    final K8sIpamAdminService mockIpamService = createMock(K8sIpamAdminService.class);
+
+    private static final String IPAM = "ipam";
+
+    private K8sNetwork k8sNetwork;
+
+    /**
+     * Constructs a kubernetes networking resource test instance.
+     */
+    public K8sIpamWebResourceTest() {
+        super(ResourceConfig.forApplicationClass(K8sNetworkingWebApplication.class));
+    }
+
+    /**
+     * Sets up the global values for all the tests.
+     */
+    @Before
+    public void setUpTest() {
+        final CodecManager codecService = new CodecManager();
+        codecService.activate();
+        codecService.registerCodec(K8sIpam.class, new K8sIpamCodec());
+        ServiceDirectory testDirectory =
+                new TestServiceDirectory()
+                        .add(K8sNetworkService.class, mockNetworkService)
+                        .add(K8sIpamAdminService.class, mockIpamService)
+                        .add(CodecService.class, codecService);
+        setServiceDirectory(testDirectory);
+
+        k8sNetwork = DefaultK8sNetwork.builder()
+                .networkId("sona-network")
+                .name("sona-network")
+                .segmentId("1")
+                .cidr("10.10.10.0/24")
+                .gatewayIp(IpAddress.valueOf("10.10.10.1"))
+                .type(K8sNetwork.Type.VXLAN)
+                .mtu(1500)
+                .build();
+    }
+
+    /**
+     * Tests the IP allocation with incorrect network ID.
+     */
+    @Test
+    public void testAllocateIpWithIncorrectNetId() {
+        expect(mockNetworkService.network(anyObject())).andReturn(null);
+
+        replay(mockNetworkService);
+
+        final WebTarget wt = target();
+        Response response = wt.path(IPAM + "/sona-network").request().get();
+        final int status = response.getStatus();
+
+        assertEquals(404, status);
+
+        verify(mockNetworkService);
+    }
+
+    /**
+     * Tests the IP allocation with null IP address returned.
+     */
+    @Test
+    public void testAllocateIpWithNullIp() {
+        expect(mockNetworkService.network(anyObject())).andReturn(k8sNetwork);
+        expect(mockIpamService.allocateIp(anyObject())).andReturn(null);
+
+        replay(mockNetworkService);
+        replay(mockIpamService);
+
+        final WebTarget wt = target();
+        Response response = wt.path(IPAM + "/sona-network").request().get();
+        final int status = response.getStatus();
+
+        assertEquals(404, status);
+
+        verify(mockNetworkService);
+        verify(mockIpamService);
+    }
+
+    /**
+     * Tests the IP allocation with correct IP address returned.
+     */
+    @Test
+    public void testAllocateIp() {
+        expect(mockNetworkService.network(anyObject())).andReturn(k8sNetwork);
+        expect(mockIpamService.allocateIp(anyObject()))
+                .andReturn(IpAddress.valueOf("10.10.10.2"));
+
+        replay(mockNetworkService);
+        replay(mockIpamService);
+
+        final WebTarget wt = target();
+        Response response = wt.path(IPAM + "/sona-network").request().get();
+        final int status = response.getStatus();
+
+        assertEquals(200, status);
+
+        verify(mockNetworkService);
+        verify(mockIpamService);
+    }
+
+    /**
+     * Tests the IP allocation with incorrect network ID.
+     */
+    @Test
+    public void testReleaseIpWithIncorrectNetIdAndIp() {
+        expect(mockNetworkService.network(anyObject())).andReturn(null);
+
+        replay(mockNetworkService);
+
+        final WebTarget wt = target();
+        Response response = wt.path(IPAM + "/sona-network/10.10.10.2").request().delete();
+        final int status = response.getStatus();
+
+        assertEquals(404, status);
+
+        verify(mockNetworkService);
+    }
+
+    /**
+     * Tests the IP allocation with correct network ID and IP address.
+     */
+    @Test
+    public void testReleaseIpWithCorrectNetIdAndIp() {
+        expect(mockNetworkService.network(anyObject())).andReturn(k8sNetwork);
+        expect(mockIpamService.releaseIp(anyObject(), anyObject())).andReturn(true);
+
+        replay(mockNetworkService);
+        replay(mockIpamService);
+
+        final WebTarget wt = target();
+        Response response = wt.path(IPAM + "/sona-network/10.10.10.2").request().delete();
+        final int status = response.getStatus();
+
+        assertEquals(204, status);
+
+        verify(mockNetworkService);
+        verify(mockIpamService);
+    }
+}
diff --git a/apps/k8s-networking/app/src/test/resources/org/onosproject/k8snetworking/codec/K8sIpam.json b/apps/k8s-networking/app/src/test/resources/org/onosproject/k8snetworking/codec/K8sIpam.json
index 22e1c19..4e5294e2 100644
--- a/apps/k8s-networking/app/src/test/resources/org/onosproject/k8snetworking/codec/K8sIpam.json
+++ b/apps/k8s-networking/app/src/test/resources/org/onosproject/k8snetworking/codec/K8sIpam.json
@@ -1,4 +1,5 @@
 {
+  "ipamId": "network-1-10.10.10.2",
   "ipAddress": "10.10.10.2",
   "networkId": "network-1"
 }
\ No newline at end of file