[ONOS-7933] Add k8s service store and manager with unit tests

Change-Id: I18ffd491dc4cf979a350acd50d3c7b1599fc229a
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sServiceStore.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sServiceStore.java
new file mode 100644
index 0000000..116f535
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/DistributedK8sServiceStore.java
@@ -0,0 +1,187 @@
+/*
+ * 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 io.fabric8.kubernetes.api.model.ObjectMeta;
+import io.fabric8.kubernetes.api.model.Service;
+import io.fabric8.kubernetes.api.model.ServiceSpec;
+import io.fabric8.kubernetes.api.model.ServiceStatus;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snetworking.api.K8sServiceEvent;
+import org.onosproject.k8snetworking.api.K8sServiceStore;
+import org.onosproject.k8snetworking.api.K8sServiceStoreDelegate;
+import org.onosproject.store.AbstractStore;
+import org.onosproject.store.serializers.KryoNamespaces;
+import org.onosproject.store.service.ConsistentMap;
+import org.onosproject.store.service.MapEvent;
+import org.onosproject.store.service.MapEventListener;
+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 static com.google.common.base.Preconditions.checkArgument;
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.k8snetworking.api.K8sServiceEvent.Type.K8S_SERVICE_CREATED;
+import static org.onosproject.k8snetworking.api.K8sServiceEvent.Type.K8S_SERVICE_REMOVED;
+import static org.onosproject.k8snetworking.api.K8sServiceEvent.Type.K8S_SERVICE_UPDATED;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubernetes service store using consistent map.
+ */
+@Component(immediate = true, service = K8sServiceStore.class)
+public class DistributedK8sServiceStore
+        extends AbstractStore<K8sServiceEvent, K8sServiceStoreDelegate>
+        implements K8sServiceStore {
+
+    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_SERVICE = KryoNamespace.newBuilder()
+            .register(KryoNamespaces.API)
+            .register(Service.class)
+            .register(ObjectMeta.class)
+            .register(ServiceSpec.class)
+            .register(ServiceStatus.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 final MapEventListener<String, Service> serviceMapListener =
+            new K8sServiceMapListener();
+
+    private ConsistentMap<String, Service> serviceStore;
+
+    @Activate
+    protected void activate() {
+        ApplicationId appId = coreService.registerApplication(APP_ID);
+        serviceStore = storageService.<String, Service>consistentMapBuilder()
+                .withSerializer(Serializer.using(SERIALIZER_K8S_SERVICE))
+                .withName("k8s-service-store")
+                .withApplicationId(appId)
+                .build();
+
+        serviceStore.addListener(serviceMapListener);
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        serviceStore.removeListener(serviceMapListener);
+        eventExecutor.shutdown();
+        log.info("Stopped");
+    }
+
+    @Override
+    public void createService(Service service) {
+        serviceStore.compute(service.getMetadata().getUid(), (uid, existing) -> {
+            final String error = service.getMetadata().getUid() + ERR_DUPLICATE;
+            checkArgument(existing == null, error);
+            return service;
+        });
+    }
+
+    @Override
+    public void updateService(Service service) {
+        serviceStore.compute(service.getMetadata().getUid(), (uid, existing) -> {
+            final String error = service.getMetadata().getUid() + ERR_NOT_FOUND;
+            checkArgument(existing != null, error);
+            return service;
+        });
+    }
+
+    @Override
+    public Service removeService(String uid) {
+        Versioned<Service> service = serviceStore.remove(uid);
+        if (service == null) {
+            final String error = uid + ERR_NOT_FOUND;
+            throw new IllegalArgumentException(error);
+        }
+        return service.value();
+    }
+
+    @Override
+    public Service service(String uid) {
+        return serviceStore.asJavaMap().get(uid);
+    }
+
+    @Override
+    public Set<Service> services() {
+        return ImmutableSet.copyOf(serviceStore.asJavaMap().values());
+    }
+
+    @Override
+    public void clear() {
+        serviceStore.clear();
+    }
+
+    private class K8sServiceMapListener implements MapEventListener<String, Service> {
+
+        @Override
+        public void event(MapEvent<String, Service> event) {
+
+            switch (event.type()) {
+                case INSERT:
+                    log.debug("Kubernetes service created {}", event.newValue());
+                    eventExecutor.execute(() ->
+                            notifyDelegate(new K8sServiceEvent(
+                                K8S_SERVICE_CREATED, event.newValue().value())));
+                    break;
+                case UPDATE:
+                    log.debug("Kubernetes service updated {}", event.newValue());
+                    eventExecutor.execute(() ->
+                            notifyDelegate(new K8sServiceEvent(
+                                    K8S_SERVICE_UPDATED, event.newValue().value())));
+                    break;
+                case REMOVE:
+                    log.debug("Kubernetes service removed {}", event.oldValue());
+                    eventExecutor.execute(() ->
+                            notifyDelegate(new K8sServiceEvent(
+                                    K8S_SERVICE_REMOVED, event.oldValue().value())));
+                    break;
+                default:
+                    // do nothing
+                    break;
+            }
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sServiceManager.java b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sServiceManager.java
new file mode 100644
index 0000000..fd18c7e
--- /dev/null
+++ b/apps/k8s-networking/app/src/main/java/org/onosproject/k8snetworking/impl/K8sServiceManager.java
@@ -0,0 +1,163 @@
+/*
+ * 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.base.Strings;
+import com.google.common.collect.ImmutableSet;
+import io.fabric8.kubernetes.api.model.Service;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.ListenerRegistry;
+import org.onosproject.k8snetworking.api.K8sServiceAdminService;
+import org.onosproject.k8snetworking.api.K8sServiceEvent;
+import org.onosproject.k8snetworking.api.K8sServiceListener;
+import org.onosproject.k8snetworking.api.K8sServiceService;
+import org.onosproject.k8snetworking.api.K8sServiceStore;
+import org.onosproject.k8snetworking.api.K8sServiceStoreDelegate;
+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 static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onosproject.k8snetworking.api.Constants.K8S_NETWORKING_APP_ID;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Provides implementation of administering and interfacing kubernetes service.
+ */
+@Component(
+        immediate = true,
+        service = {K8sServiceAdminService.class, K8sServiceService.class}
+)
+public class K8sServiceManager
+        extends ListenerRegistry<K8sServiceEvent, K8sServiceListener>
+        implements K8sServiceAdminService, K8sServiceService {
+
+    protected final Logger log = getLogger(getClass());
+
+    private static final String MSG_SERVICE  = "Kubernetes service %s %s";
+    private static final String MSG_CREATED = "created";
+    private static final String MSG_UPDATED = "updated";
+    private static final String MSG_REMOVED = "removed";
+
+    private static final String ERR_NULL_SERVICE  = "Kubernetes service cannot be null";
+    private static final String ERR_NULL_SERVICE_UID  = "Kubernetes service UID cannot be null";
+
+    private static final String ERR_IN_USE = " still in use";
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected K8sServiceStore k8sServiceStore;
+
+    private final K8sServiceStoreDelegate
+            delegate = new InternalServiceStorageDelegate();
+
+    private ApplicationId appId;
+
+    @Activate
+    protected void activate() {
+        appId = coreService.registerApplication(K8S_NETWORKING_APP_ID);
+
+        k8sServiceStore.setDelegate(delegate);
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        k8sServiceStore.unsetDelegate(delegate);
+        log.info("Stopped");
+    }
+
+    @Override
+    public void createService(Service service) {
+        checkNotNull(service, ERR_NULL_SERVICE);
+        checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()),
+                ERR_NULL_SERVICE_UID);
+
+        k8sServiceStore.createService(service);
+
+        log.info(String.format(MSG_SERVICE, service.getMetadata().getName(), MSG_CREATED));
+    }
+
+    @Override
+    public void updateService(Service service) {
+        checkNotNull(service, ERR_NULL_SERVICE);
+        checkArgument(!Strings.isNullOrEmpty(service.getMetadata().getUid()),
+                ERR_NULL_SERVICE_UID);
+
+        k8sServiceStore.updateService(service);
+
+        log.info(String.format(MSG_SERVICE, service.getMetadata().getName(), MSG_UPDATED));
+    }
+
+    @Override
+    public void removeService(String uid) {
+        checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_SERVICE_UID);
+
+        synchronized (this) {
+            if (isServiceInUse(uid)) {
+                final String error = String.format(MSG_SERVICE, uid, ERR_IN_USE);
+                throw new IllegalStateException(error);
+            }
+
+            Service service = k8sServiceStore.removeService(uid);
+
+            if (service != null) {
+                log.info(String.format(MSG_SERVICE,
+                        service.getMetadata().getName(), MSG_REMOVED));
+            }
+        }
+    }
+
+    @Override
+    public void clear() {
+        k8sServiceStore.clear();
+    }
+
+    @Override
+    public Service service(String uid) {
+        checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_SERVICE_UID);
+        return k8sServiceStore.service(uid);
+    }
+
+    @Override
+    public Set<Service> services() {
+        return ImmutableSet.copyOf(k8sServiceStore.services());
+    }
+
+    private boolean isServiceInUse(String uid) {
+        return false;
+    }
+
+    private class InternalServiceStorageDelegate implements K8sServiceStoreDelegate {
+
+        @Override
+        public void notify(K8sServiceEvent event) {
+            if (event != null) {
+                log.trace("send kubernetes service event {}", event);
+                process(event);
+            }
+        }
+    }
+}
diff --git a/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sServiceManagerTest.java b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sServiceManagerTest.java
new file mode 100644
index 0000000..a78f514
--- /dev/null
+++ b/apps/k8s-networking/app/src/test/java/org/onosproject/k8snetworking/impl/K8sServiceManagerTest.java
@@ -0,0 +1,220 @@
+/*
+ * 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.Lists;
+import com.google.common.util.concurrent.MoreExecutors;
+import io.fabric8.kubernetes.api.model.ObjectMeta;
+import io.fabric8.kubernetes.api.model.Service;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.k8snetworking.api.K8sServiceEvent;
+import org.onosproject.k8snetworking.api.K8sServiceListener;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.onosproject.k8snetworking.api.K8sServiceEvent.Type.K8S_SERVICE_CREATED;
+import static org.onosproject.k8snetworking.api.K8sServiceEvent.Type.K8S_SERVICE_REMOVED;
+import static org.onosproject.k8snetworking.api.K8sServiceEvent.Type.K8S_SERVICE_UPDATED;
+
+/**
+ * Unit tests for kubernetes service manager.
+ */
+public class K8sServiceManagerTest {
+
+    private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+    private static final String UNKNOWN_UID = "unknown_uid";
+    private static final String UPDATED_UID = "updated_uid";
+    private static final String UPDATED_NAME = "updated_name";
+
+    private static final String SERVICE_UID = "service_uid";
+    private static final String SERVICE_NAME = "service_name_1";
+
+    private static final Service SERVICE = createK8sService(SERVICE_UID, SERVICE_NAME);
+    private static final Service SERVICE_UPDATED =
+            createK8sService(SERVICE_UID, UPDATED_NAME);
+
+
+    private final TestK8sServiceListener testListener = new TestK8sServiceListener();
+
+    private K8sServiceManager target;
+    private DistributedK8sServiceStore k8sServiceStore;
+
+    @Before
+    public void setUp() throws Exception {
+        k8sServiceStore = new DistributedK8sServiceStore();
+        TestUtils.setField(k8sServiceStore, "coreService", new TestCoreService());
+        TestUtils.setField(k8sServiceStore, "storageService", new TestStorageService());
+        TestUtils.setField(k8sServiceStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+        k8sServiceStore.activate();
+
+        target = new K8sServiceManager();
+        TestUtils.setField(target, "coreService", new TestCoreService());
+        target.k8sServiceStore = k8sServiceStore;
+        target.addListener(testListener);
+        target.activate();
+    }
+
+    @After
+    public void tearDown() {
+        target.removeListener(testListener);
+        k8sServiceStore.deactivate();
+        target.deactivate();
+        k8sServiceStore = null;
+        target = null;
+    }
+
+    /**
+     * Tests if getting all services return correct set of services.
+     */
+    @Test
+    public void testGetServices() {
+        createBasicServices();
+        assertEquals("Number of service did not match", 1, target.services().size());
+    }
+
+    /**
+     * Tests if getting a service with UID returns the correct service.
+     */
+    @Test
+    public void testGetServiceByUid() {
+        createBasicServices();
+        assertNotNull("Service did not match", target.service(SERVICE_UID));
+        assertNull("Service did not match", target.service(UNKNOWN_UID));
+    }
+
+    /**
+     * Tests creating and removing a service, and checks if it triggers proper events.
+     */
+    @Test
+    public void testCreateAndRemoveService() {
+        target.createService(SERVICE);
+        assertEquals("Number of services did not match", 1, target.services().size());
+        assertNotNull("Service was not created", target.service(SERVICE_UID));
+
+        target.removeService(SERVICE_UID);
+        assertEquals("Number of services did not match", 0, target.services().size());
+        assertNull("Service was not removed", target.service(SERVICE_UID));
+
+        validateEvents(K8S_SERVICE_CREATED, K8S_SERVICE_REMOVED);
+    }
+
+    /**
+     * Tests updating a service, and checks if it triggers proper events.
+     */
+    @Test
+    public void testCreateAndUpdateService() {
+        target.createService(SERVICE);
+        assertEquals("Number of services did not match", 1, target.services().size());
+        assertEquals("Service did not match", SERVICE_NAME,
+                target.service(SERVICE_UID).getMetadata().getName());
+
+        target.updateService(SERVICE_UPDATED);
+
+        assertEquals("Number of services did not match", 1, target.services().size());
+        assertEquals("Service did not match", UPDATED_NAME,
+                target.service(SERVICE_UID).getMetadata().getName());
+        validateEvents(K8S_SERVICE_CREATED, K8S_SERVICE_UPDATED);
+    }
+
+    /**
+     * Tests if creating a null service fails with an exception.
+     */
+    @Test(expected = NullPointerException.class)
+    public void testCreateNullService() {
+        target.createService(null);
+    }
+
+    /**
+     * Tests if creating a duplicate service fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testCreateDuplicateService() {
+        target.createService(SERVICE);
+        target.createService(SERVICE);
+    }
+
+    /**
+     * Tests if removing service with null ID fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testRemoveServiceWithNull() {
+        target.removeService(null);
+    }
+
+    /**
+     * Tests if updating an unregistered service fails with an exception.
+     */
+    @Test(expected = IllegalArgumentException.class)
+    public void testUpdateUnregisteredService() {
+        target.updateService(SERVICE);
+    }
+
+    private void createBasicServices() {
+        target.createService(SERVICE);
+    }
+
+    private static Service createK8sService(String uid, String name) {
+        ObjectMeta meta = new ObjectMeta();
+        meta.setUid(uid);
+        meta.setName(name);
+
+        Service service = new Service();
+        service.setApiVersion("v1");
+        service.setKind("service");
+        service.setMetadata(meta);
+
+        return service;
+    }
+
+    private static class TestCoreService extends CoreServiceAdapter {
+
+        @Override
+        public ApplicationId registerApplication(String name) {
+            return TEST_APP_ID;
+        }
+    }
+
+    private static class TestK8sServiceListener implements K8sServiceListener {
+        private List<K8sServiceEvent> events = Lists.newArrayList();
+
+        @Override
+        public void event(K8sServiceEvent event) {
+            events.add(event);
+        }
+    }
+
+    private void validateEvents(Enum... types) {
+        int i = 0;
+        assertEquals("Number of events did not match", types.length, testListener.events.size());
+        for (Event event : testListener.events) {
+            assertEquals("Incorrect event received", types[i], event.type());
+            i++;
+        }
+        testListener.events.clear();
+    }
+}