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

Change-Id: I32fd1fffb41ec728d0be092ac5a8f555179e7a9e
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);
+    }
+}