Implement kubevirt node service, expose it through REST API and CLI

Change-Id: Ieebd2652af31344df3a7c91d3669a2ba150cb57f
diff --git a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/cli/KubevirtNodeListCommand.java b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/cli/KubevirtNodeListCommand.java
new file mode 100644
index 0000000..97c6eaf
--- /dev/null
+++ b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/cli/KubevirtNodeListCommand.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2020-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.kubevirtnode.cli;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import org.apache.commons.lang.StringUtils;
+import org.apache.karaf.shell.api.action.Command;
+import org.apache.karaf.shell.api.action.lifecycle.Service;
+import org.onosproject.cli.AbstractShellCommand;
+import org.onosproject.kubevirtnode.api.KubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNodeService;
+
+import java.util.Comparator;
+import java.util.List;
+
+import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.genFormatString;
+import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.prettyJson;
+
+
+/**
+ * Lists all nodes registered to the service.
+ */
+@Service
+@Command(scope = "onos", name = "kubevirt-nodes",
+        description = "Lists all nodes registered in KubeVirt node service")
+public class KubevirtNodeListCommand extends AbstractShellCommand {
+
+    private static final int HOSTNAME_LENGTH = 35;
+    private static final int TYPE_LENGTH = 15;
+    private static final int MANAGEMENT_IP_LENGTH = 25;
+    private static final int DATA_IP_LENGTH = 25;
+    private static final int STATUS = 15;
+    private static final int MARGIN_LENGTH = 2;
+
+    @Override
+    protected void doExecute() throws Exception {
+        KubevirtNodeService nodeService = get(KubevirtNodeService.class);
+        List<KubevirtNode> nodes = Lists.newArrayList(nodeService.nodes());
+        nodes.sort(Comparator.comparing(KubevirtNode::hostname));
+
+        String format = genFormatString(ImmutableList.of(HOSTNAME_LENGTH,
+                TYPE_LENGTH, MANAGEMENT_IP_LENGTH, DATA_IP_LENGTH, STATUS));
+
+        if (outputJson()) {
+            print("%s", json(nodes));
+        } else {
+            print(format, "Hostname", "Type", "Management IP", "Data IP", "State");
+            for (KubevirtNode node : nodes) {
+                print(format,
+                        StringUtils.substring(node.hostname(), 0,
+                                HOSTNAME_LENGTH - MARGIN_LENGTH),
+                        node.type(),
+                        StringUtils.substring(node.managementIp().toString(), 0,
+                                MANAGEMENT_IP_LENGTH - MARGIN_LENGTH),
+                        node.dataIp() != null ? StringUtils.substring(
+                                node.dataIp().toString(), 0,
+                                DATA_IP_LENGTH - MARGIN_LENGTH) : "",
+                        node.state());
+            }
+            print("Total %s nodes", nodeService.nodes().size());
+        }
+    }
+
+    private String json(List<KubevirtNode> nodes) {
+        ObjectMapper mapper = new ObjectMapper();
+        ArrayNode result = mapper.createArrayNode();
+        for (KubevirtNode node : nodes) {
+            result.add(jsonForEntity(node, KubevirtNode.class));
+        }
+        return prettyJson(mapper, result.toString());
+    }
+}
diff --git a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/DistributedKubevirtNodeStore.java b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/DistributedKubevirtNodeStore.java
new file mode 100644
index 0000000..ee488d4
--- /dev/null
+++ b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/DistributedKubevirtNodeStore.java
@@ -0,0 +1,204 @@
+/*
+ * Copyright 2020-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.kubevirtnode.impl;
+
+/**
+ * Implementation of kubevirt node store using consistent map.
+ */
+
+import com.google.common.collect.ImmutableSet;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.kubevirtnode.api.DefaultKubevirtNode;
+import org.onosproject.kubevirtnode.api.DefaultKubevirtPhyInterface;
+import org.onosproject.kubevirtnode.api.KubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNodeEvent;
+import org.onosproject.kubevirtnode.api.KubevirtNodeState;
+import org.onosproject.kubevirtnode.api.KubevirtNodeStore;
+import org.onosproject.kubevirtnode.api.KubevirtNodeStoreDelegate;
+import org.onosproject.kubevirtnode.api.KubevirtPhyInterface;
+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.kubevirtnode.api.KubevirtNodeEvent.Type.KUBEVIRT_NODE_COMPLETE;
+import static org.onosproject.kubevirtnode.api.KubevirtNodeEvent.Type.KUBEVIRT_NODE_CREATED;
+import static org.onosproject.kubevirtnode.api.KubevirtNodeEvent.Type.KUBEVIRT_NODE_INCOMPLETE;
+import static org.onosproject.kubevirtnode.api.KubevirtNodeEvent.Type.KUBEVIRT_NODE_REMOVED;
+import static org.onosproject.kubevirtnode.api.KubevirtNodeEvent.Type.KUBEVIRT_NODE_UPDATED;
+import static org.slf4j.LoggerFactory.getLogger;
+
+@Component(immediate = true, service = KubevirtNodeStore.class)
+public class DistributedKubevirtNodeStore
+        extends AbstractStore<KubevirtNodeEvent, KubevirtNodeStoreDelegate>
+        implements KubevirtNodeStore {
+
+    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.kubevirtnode";
+
+    private static final KryoNamespace
+            SERIALIZER_KUBEVIRT_NODE = KryoNamespace.newBuilder()
+            .register(KryoNamespaces.API)
+            .register(KubevirtNode.class)
+            .register(DefaultKubevirtNode.class)
+            .register(KubevirtPhyInterface.class)
+            .register(DefaultKubevirtPhyInterface.class)
+            .register(KubevirtNode.Type.class)
+            .register(KubevirtNodeState.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, KubevirtNode> nodeMapEventListener =
+            new KubevirtNodeMapListener();
+
+    private ConsistentMap<String, KubevirtNode> nodeStore;
+
+    @Activate
+    protected void activate() {
+        ApplicationId appId = coreService.registerApplication(APP_ID);
+        nodeStore = storageService.<String, KubevirtNode>consistentMapBuilder()
+                .withSerializer(Serializer.using(SERIALIZER_KUBEVIRT_NODE))
+                .withName("kubevirt-nodestore")
+                .withApplicationId(appId)
+                .build();
+        nodeStore.addListener(nodeMapEventListener);
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        nodeStore.removeListener(nodeMapEventListener);
+        eventExecutor.shutdown();
+        log.info("Stopped");
+    }
+
+    @Override
+    public void createNode(KubevirtNode node) {
+        nodeStore.compute(node.hostname(), (hostname, existing) -> {
+            final String error = node.hostname() + ERR_DUPLICATE;
+            checkArgument(existing == null, error);
+            return node;
+        });
+    }
+
+    @Override
+    public void updateNode(KubevirtNode node) {
+        nodeStore.compute(node.hostname(), (hostname, existing) -> {
+            final String error = node.hostname() + ERR_NOT_FOUND;
+            checkArgument(existing != null, error);
+            return node;
+        });
+    }
+
+    @Override
+    public KubevirtNode removeNode(String hostname) {
+        Versioned<KubevirtNode> node = nodeStore.remove(hostname);
+        if (node == null) {
+            final String error = hostname + ERR_NOT_FOUND;
+            throw new IllegalArgumentException(error);
+        }
+        return node.value();
+    }
+
+    @Override
+    public Set<KubevirtNode> nodes() {
+        return ImmutableSet.copyOf(nodeStore.asJavaMap().values());
+    }
+
+    @Override
+    public KubevirtNode node(String hostname) {
+        return nodeStore.asJavaMap().get(hostname);
+    }
+
+    private class KubevirtNodeMapListener
+            implements MapEventListener<String, KubevirtNode> {
+
+        @Override
+        public void event(MapEvent<String, KubevirtNode> event) {
+            switch (event.type()) {
+                case INSERT:
+                    log.debug("Kubevirt node created {}", event.newValue());
+                    eventExecutor.execute(() -> processNodeCreation(event));
+                    break;
+                case UPDATE:
+                    log.debug("Kubevirt node updated {}", event.newValue());
+                    eventExecutor.execute(() -> processNodeUpdate(event));
+                    break;
+                case REMOVE:
+                    log.debug("Kubevirt node removed {}", event.oldValue());
+                    eventExecutor.execute(() -> processNodeRemoval(event));
+                    break;
+                default:
+                    // do nothing
+                    break;
+            }
+        }
+
+        private void processNodeCreation(MapEvent<String, KubevirtNode> event) {
+            notifyDelegate(new KubevirtNodeEvent(
+                    KUBEVIRT_NODE_CREATED, event.newValue().value()));
+        }
+
+        private void processNodeUpdate(MapEvent<String, KubevirtNode> event) {
+            notifyDelegate(new KubevirtNodeEvent(
+                    KUBEVIRT_NODE_UPDATED, event.newValue().value()));
+
+            if (event.newValue().value().state() == KubevirtNodeState.COMPLETE) {
+                notifyDelegate(new KubevirtNodeEvent(
+                        KUBEVIRT_NODE_COMPLETE, event.newValue().value()));
+            } else if (event.newValue().value().state() == KubevirtNodeState.INCOMPLETE) {
+                notifyDelegate(new KubevirtNodeEvent(
+                        KUBEVIRT_NODE_INCOMPLETE, event.newValue().value()));
+            }
+        }
+
+        private void processNodeRemoval(MapEvent<String, KubevirtNode> event) {
+            notifyDelegate(new KubevirtNodeEvent(
+                    KUBEVIRT_NODE_REMOVED, event.oldValue().value()));
+        }
+    }
+}
diff --git a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/KubevirtNodeManager.java b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/KubevirtNodeManager.java
new file mode 100644
index 0000000..6578def
--- /dev/null
+++ b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/KubevirtNodeManager.java
@@ -0,0 +1,289 @@
+/*
+ * Copyright 2020-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.kubevirtnode.impl;
+
+/**
+ * Service administering the inventory of kubevirt nodes.
+ */
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableSet;
+import org.onlab.packet.IpAddress;
+import org.onlab.util.Tools;
+import org.onosproject.cluster.ClusterService;
+import org.onosproject.cluster.LeadershipService;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.ListenerRegistry;
+import org.onosproject.kubevirtnode.api.KubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNodeAdminService;
+import org.onosproject.kubevirtnode.api.KubevirtNodeEvent;
+import org.onosproject.kubevirtnode.api.KubevirtNodeListener;
+import org.onosproject.kubevirtnode.api.KubevirtNodeService;
+import org.onosproject.kubevirtnode.api.KubevirtNodeState;
+import org.onosproject.kubevirtnode.api.KubevirtNodeStore;
+import org.onosproject.kubevirtnode.api.KubevirtNodeStoreDelegate;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.ovsdb.controller.OvsdbController;
+import org.onosproject.store.service.AtomicCounter;
+import org.onosproject.store.service.StorageService;
+import org.osgi.service.component.ComponentContext;
+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.Modified;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Dictionary;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.stream.Collectors;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static java.util.concurrent.Executors.newSingleThreadExecutor;
+import static org.onlab.util.Tools.groupedThreads;
+import static org.onosproject.kubevirtnode.impl.OsgiPropertyConstants.OVSDB_PORT;
+import static org.onosproject.kubevirtnode.impl.OsgiPropertyConstants.OVSDB_PORT_NUM_DEFAULT;
+import static org.onosproject.kubevirtnode.util.KubevirtNodeUtil.genDpid;
+import static org.slf4j.LoggerFactory.getLogger;
+
+@Component(
+        immediate = true,
+        service = {KubevirtNodeService.class, KubevirtNodeAdminService.class},
+        property = {
+                OVSDB_PORT + ":Integer=" + OVSDB_PORT_NUM_DEFAULT
+        }
+)
+public class KubevirtNodeManager
+        extends ListenerRegistry<KubevirtNodeEvent, KubevirtNodeListener>
+        implements KubevirtNodeService, KubevirtNodeAdminService {
+
+    private final Logger log = getLogger(getClass());
+
+    private static final String MSG_NODE = "KubeVirt node %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 DEVICE_ID_COUNTER_NAME = "device-id-counter";
+
+    private static final String ERR_NULL_NODE = "KubeVirt node cannot be null";
+    private static final String ERR_NULL_HOSTNAME = "KubeVirt node hostname cannot be null";
+    private static final String ERR_NULL_DEVICE_ID = "KubeVirt node device ID cannot be null";
+
+    private static final String NOT_DUPLICATED_MSG = "% cannot be duplicated";
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected KubevirtNodeStore nodeStore;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected CoreService coreService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected ClusterService clusterService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected LeadershipService leadershipService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected StorageService storageService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected OvsdbController ovsdbController;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY)
+    protected DeviceService deviceService;
+
+    /**
+     * OVSDB server listen port.
+     */
+    private int ovsdbPortNum = OVSDB_PORT_NUM_DEFAULT;
+
+    private final ExecutorService eventExecutor = newSingleThreadExecutor(
+            groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
+
+    private final KubevirtNodeStoreDelegate delegate = new InternalNodeStoreDelegate();
+
+    private AtomicCounter deviceIdCounter;
+
+    private ApplicationId appId;
+
+    @Activate
+    protected void activate() {
+        appId = coreService.registerApplication(APP_ID);
+        nodeStore.setDelegate(delegate);
+
+        leadershipService.runForLeadership(appId.name());
+
+        deviceIdCounter = storageService.getAtomicCounter(DEVICE_ID_COUNTER_NAME);
+
+        log.info("Started");
+    }
+
+    @Deactivate
+    protected void deactivate() {
+        nodeStore.unsetDelegate(delegate);
+
+        leadershipService.withdraw(appId.name());
+        eventExecutor.shutdown();
+
+        log.info("Stopped");
+    }
+
+    @Modified
+    protected void modified(ComponentContext context) {
+        Dictionary<?, ?> properties = context.getProperties();
+        int updatedOvsdbPort = Tools.getIntegerProperty(properties, OVSDB_PORT);
+        if (!Objects.equals(updatedOvsdbPort, ovsdbPortNum)) {
+            ovsdbPortNum = updatedOvsdbPort;
+        }
+
+        log.info("Modified");
+    }
+
+    @Override
+    public void createNode(KubevirtNode node) {
+        checkNotNull(node, ERR_NULL_NODE);
+
+        KubevirtNode intNode;
+
+        if (node.intgBridge() == null) {
+            String deviceIdStr = genDpid(deviceIdCounter.incrementAndGet());
+            checkNotNull(deviceIdStr, ERR_NULL_DEVICE_ID);
+            intNode = node.updateIntgBridge(DeviceId.deviceId(deviceIdStr));
+            checkArgument(!hasIntgBridge(intNode.intgBridge(), intNode.hostname()),
+                    NOT_DUPLICATED_MSG, intNode.intgBridge());
+        } else {
+            intNode = node;
+            checkArgument(!hasIntgBridge(intNode.intgBridge(), intNode.hostname()),
+                    NOT_DUPLICATED_MSG, intNode.intgBridge());
+        }
+
+        nodeStore.createNode(intNode);
+
+        log.info(String.format(MSG_NODE, intNode.hostname(), MSG_CREATED));
+    }
+
+    @Override
+    public void updateNode(KubevirtNode node) {
+        checkNotNull(node, ERR_NULL_NODE);
+
+        KubevirtNode intNode;
+
+        KubevirtNode existingNode = nodeStore.node(node.hostname());
+        checkNotNull(existingNode, ERR_NULL_NODE);
+
+        DeviceId existIntgBridge = nodeStore.node(node.hostname()).intgBridge();
+
+        if (node.intgBridge() == null) {
+            intNode = node.updateIntgBridge(existIntgBridge);
+            checkArgument(!hasIntgBridge(intNode.intgBridge(), intNode.hostname()),
+                    NOT_DUPLICATED_MSG, intNode.intgBridge());
+        } else {
+            intNode = node;
+            checkArgument(!hasIntgBridge(intNode.intgBridge(), intNode.hostname()),
+                    NOT_DUPLICATED_MSG, intNode.intgBridge());
+        }
+
+        nodeStore.updateNode(intNode);
+
+        log.info(String.format(MSG_NODE, intNode.hostname(), MSG_UPDATED));
+    }
+
+    @Override
+    public KubevirtNode removeNode(String hostname) {
+        checkArgument(!Strings.isNullOrEmpty(hostname), ERR_NULL_HOSTNAME);
+        KubevirtNode node = nodeStore.removeNode(hostname);
+        log.info(String.format(MSG_NODE, hostname, MSG_REMOVED));
+        return node;
+    }
+
+    @Override
+    public Set<KubevirtNode> nodes() {
+        return nodeStore.nodes();
+    }
+
+    @Override
+    public Set<KubevirtNode> nodes(KubevirtNode.Type type) {
+        Set<KubevirtNode> nodes = nodeStore.nodes().stream()
+                .filter(node -> Objects.equals(node.type(), type))
+                .collect(Collectors.toSet());
+        return ImmutableSet.copyOf(nodes);
+    }
+
+    @Override
+    public Set<KubevirtNode> completeNodes() {
+        Set<KubevirtNode> nodes = nodeStore.nodes().stream()
+                .filter(node -> node.state() == KubevirtNodeState.COMPLETE)
+                .collect(Collectors.toSet());
+        return ImmutableSet.copyOf(nodes);
+    }
+
+    @Override
+    public Set<KubevirtNode> completeNodes(KubevirtNode.Type type) {
+        Set<KubevirtNode> nodes = nodeStore.nodes().stream()
+                .filter(node -> node.type() == type &&
+                        node.state() == KubevirtNodeState.COMPLETE)
+                .collect(Collectors.toSet());
+        return ImmutableSet.copyOf(nodes);
+    }
+
+    @Override
+    public KubevirtNode node(String hostname) {
+        return nodeStore.node(hostname);
+    }
+
+    @Override
+    public KubevirtNode node(DeviceId deviceId) {
+        return nodeStore.nodes().stream()
+                .filter(node -> Objects.equals(node.intgBridge(), deviceId) ||
+                        Objects.equals(node.ovsdb(), deviceId))
+                .findFirst().orElse(null);
+    }
+
+    @Override
+    public KubevirtNode node(IpAddress mgmtIp) {
+        return nodeStore.nodes().stream()
+                .filter(node -> Objects.equals(node.managementIp(), mgmtIp))
+                .findFirst().orElse(null);
+    }
+
+    private boolean hasIntgBridge(DeviceId deviceId, String hostname) {
+        Optional<KubevirtNode> existNode = nodeStore.nodes().stream()
+                .filter(n -> !n.hostname().equals(hostname))
+                .filter(n -> deviceId.equals(n.intgBridge()))
+                .findFirst();
+
+        return existNode.isPresent();
+    }
+
+    private class InternalNodeStoreDelegate implements KubevirtNodeStoreDelegate {
+
+        @Override
+        public void notify(KubevirtNodeEvent event) {
+            if (event != null) {
+                log.trace("send kubevirt node event {}", event);
+                process(event);
+            }
+        }
+    }
+}
diff --git a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/OsgiPropertyConstants.java b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/OsgiPropertyConstants.java
new file mode 100644
index 0000000..ae1b04c
--- /dev/null
+++ b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/impl/OsgiPropertyConstants.java
@@ -0,0 +1,31 @@
+/*
+ * 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.kubevirtnode.impl;
+
+/**
+ * Name/Value constants for properties.
+ */
+public final class OsgiPropertyConstants {
+    private OsgiPropertyConstants() {
+    }
+
+    static final String OVSDB_PORT = "ovsdbPortNum";
+    static final int OVSDB_PORT_NUM_DEFAULT = 6640;
+
+    static final String AUTO_RECOVERY = "autoRecovery";
+    static final boolean AUTO_RECOVERY_DEFAULT = true;
+}
diff --git a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/util/KubevirtNodeUtil.java b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/util/KubevirtNodeUtil.java
new file mode 100644
index 0000000..646965b
--- /dev/null
+++ b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/util/KubevirtNodeUtil.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2020-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.kubevirtnode.util;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * An utility that used in KubeVirt node app.
+ */
+public final class KubevirtNodeUtil {
+
+    private static final Logger log = LoggerFactory.getLogger(KubevirtNodeUtil.class);
+
+    private static final String COLON_SLASH = "://";
+    private static final String COLON = ":";
+
+    private static final int HEX_LENGTH = 16;
+    private static final String OF_PREFIX = "of:";
+    private static final String ZERO = "0";
+
+    /**
+     * Prevents object installation from external.
+     */
+    private KubevirtNodeUtil() {
+    }
+
+    /**
+     * Generates a DPID (of:0000000000000001) from an index value.
+     *
+     * @param index index value
+     * @return generated DPID
+     */
+    public static String genDpid(long index) {
+        if (index < 0) {
+            return null;
+        }
+
+        String hexStr = Long.toHexString(index);
+
+        StringBuilder zeroPadding = new StringBuilder();
+        for (int i = 0; i < HEX_LENGTH - hexStr.length(); i++) {
+            zeroPadding.append(ZERO);
+        }
+
+        return OF_PREFIX + zeroPadding.toString() + hexStr;
+    }
+
+    /**
+     * Generates string format based on the given string length list.
+     *
+     * @param stringLengths a list of string lengths
+     * @return string format (e.g., %-28s%-15s%-24s%-20s%-15s)
+     */
+    public static String genFormatString(List<Integer> stringLengths) {
+        StringBuilder fsb = new StringBuilder();
+        stringLengths.forEach(length -> {
+            fsb.append("%-");
+            fsb.append(length);
+            fsb.append("s");
+        });
+        return fsb.toString();
+    }
+
+    /**
+     * Prints out the JSON string in pretty format.
+     *
+     * @param mapper        Object mapper
+     * @param jsonString    JSON string
+     * @return pretty formatted JSON string
+     */
+    public static String prettyJson(ObjectMapper mapper, String jsonString) {
+        try {
+            Object jsonObject = mapper.readValue(jsonString, Object.class);
+            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject);
+        } catch (IOException e) {
+            log.debug("Json string parsing exception caused by {}", e);
+        }
+        return null;
+    }
+}
diff --git a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResource.java b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResource.java
index 65e5901..e3b18ba 100644
--- a/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResource.java
+++ b/apps/kubevirt-node/app/src/main/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResource.java
@@ -15,23 +15,66 @@
  */
 package org.onosproject.kubevirtnode.web;
 
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import com.google.common.collect.Sets;
+import org.onosproject.kubevirtnode.api.KubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNodeAdminService;
+import org.onosproject.kubevirtnode.api.KubevirtNodeState;
 import org.onosproject.rest.AbstractWebResource;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
 import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
 import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
 import java.io.InputStream;
+import java.util.Set;
 
+import static com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT;
+import static javax.ws.rs.core.Response.created;
+import static org.onlab.util.Tools.nullIsIllegal;
+import static org.onlab.util.Tools.readTreeFromStream;
+
+/**
+ * Handles REST API call of KubeVirt node config.
+ */
 @Path("configure")
 public class KubevirtNodeWebResource extends AbstractWebResource {
 
     private final Logger log = LoggerFactory.getLogger(getClass());
 
+    private static final String MESSAGE_NODE = "Received node %s request";
+    private static final String NODES = "nodes";
+    private static final String CREATE = "CREATE";
+    private static final String UPDATE = "UPDATE";
+    private static final String NODE_ID = "NODE_ID";
+    private static final String REMOVE = "REMOVE";
+    private static final String QUERY = "QUERY";
+    private static final String INIT = "INIT";
+    private static final String NOT_EXIST = "Not exist";
+    private static final String STATE = "State";
+    private static final String RESULT = "Result";
+
+    private static final String HOST_NAME = "hostname";
+    private static final String ERROR_MESSAGE = " cannot be null";
+
+    private final KubevirtNodeAdminService nodeAdminService = get(KubevirtNodeAdminService.class);
+
+    @Context
+    private UriInfo uriInfo;
+
     /**
      * Creates a set of KubeVirt nodes' config from the JSON input stream.
      *
@@ -44,7 +87,180 @@
     @Path("node")
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
-    public Response dummy(InputStream input) {
+    public Response createNodes(InputStream input) {
+        log.trace(String.format(MESSAGE_NODE, CREATE));
+
+        readNodeConfiguration(input).forEach(node -> {
+            KubevirtNode existing = nodeAdminService.node(node.hostname());
+            if (existing == null) {
+                nodeAdminService.createNode(node);
+            }
+        });
+
+        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
+                .path(NODES)
+                .path(NODE_ID);
+
+        return created(locationBuilder.build()).build();
+    }
+
+    /**
+     * Updates a set of KubeVirt nodes' config from the JSON input stream.
+     *
+     * @param input KubeVirt nodes JSON input stream
+     * @return 200 OK with the updated KubeVirt node's config, 400 BAD_REQUEST
+     * if the JSON is malformed, and 304 NOT_MODIFIED without the updated config
+     * @onos.rsModel KubevirtNode
+     */
+    @PUT
+    @Path("node")
+    @Consumes(MediaType.APPLICATION_JSON)
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response updateNodes(InputStream input) {
+        log.trace(String.format(MESSAGE_NODE, UPDATE));
+
+        Set<KubevirtNode> nodes = readNodeConfiguration(input);
+        for (KubevirtNode node: nodes) {
+            KubevirtNode existing = nodeAdminService.node(node.hostname());
+            if (existing == null) {
+                log.warn("There is no node configuration to update : {}", node.hostname());
+                return Response.notModified().build();
+            } else if (!existing.equals(node)) {
+                nodeAdminService.updateNode(node);
+            }
+        }
+
         return Response.ok().build();
     }
+
+    /**
+     * Removes a set of KubeVirt nodes' config from the JSON input stream.
+     *
+     * @param hostname host name contained in KubeVirt nodes configuration
+     * @return 204 NO_CONTENT, 400 BAD_REQUEST if the JSON is malformed, and
+     * 304 NOT_MODIFIED without the updated config
+     */
+    @DELETE
+    @Path("node/{hostname}")
+    @Consumes(MediaType.APPLICATION_JSON)
+    @Produces(MediaType.APPLICATION_JSON)
+    public Response deleteNode(@PathParam("hostname") String hostname) {
+        log.trace(String.format(MESSAGE_NODE, REMOVE));
+
+        KubevirtNode existing = nodeAdminService.node(
+                nullIsIllegal(hostname, HOST_NAME + ERROR_MESSAGE));
+
+        if (existing == null) {
+            log.warn("There is no node configuration to delete : {}", hostname);
+            return Response.notModified().build();
+        } else {
+            nodeAdminService.removeNode(hostname);
+        }
+
+        return Response.noContent().build();
+    }
+
+    /**
+     * Obtains the state of the KubeVirt node.
+     *
+     * @param hostname hostname of the KubeVirt
+     * @return the state of the KubeVirt node in Json
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("state/{hostname}")
+    public Response stateOfNode(@PathParam("hostname") String hostname) {
+        log.trace(String.format(MESSAGE_NODE, QUERY));
+
+        KubevirtNode node = nodeAdminService.node(hostname);
+        String nodeState = node != null ? node.state().toString() : NOT_EXIST;
+
+        return ok(mapper().createObjectNode().put(STATE, nodeState)).build();
+    }
+
+    /**
+     * Initializes KubeVirt node.
+     *
+     * @param hostname hostname of KubeVirt node
+     * @return 200 OK with init result, 404 not found, 500 server error
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("init/node/{hostname}")
+    public Response initNode(@PathParam("hostname") String hostname) {
+        log.trace(String.format(MESSAGE_NODE, QUERY));
+
+        KubevirtNode node = nodeAdminService.node(hostname);
+        if (node == null) {
+            log.error("Given node {} does not exist", hostname);
+            return Response.serverError().build();
+        }
+        KubevirtNode updated = node.updateState(KubevirtNodeState.INIT);
+        nodeAdminService.updateNode(updated);
+        return ok(mapper().createObjectNode()).build();
+    }
+
+    /**
+     * Initializes all KubeVirt nodes.
+     *
+     * @return 200 OK with init result, 500 server error
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("init/all")
+    public Response initAllNodes() {
+        log.trace(String.format(MESSAGE_NODE, QUERY));
+
+        nodeAdminService.nodes()
+                .forEach(n -> {
+                    KubevirtNode updated = n.updateState(KubevirtNodeState.INIT);
+                    nodeAdminService.updateNode(updated);
+                });
+
+        return ok(mapper().createObjectNode()).build();
+    }
+
+    /**
+     * Initializes KubeVirt nodes which are in the stats other than COMPLETE.
+     *
+     * @return 200 OK with init result, 500 server error
+     */
+    @GET
+    @Produces(MediaType.APPLICATION_JSON)
+    @Path("init/incomplete")
+    public Response initIncompleteNodes() {
+        log.trace(String.format(MESSAGE_NODE, QUERY));
+
+        nodeAdminService.nodes().stream()
+                .filter(n -> n.state() != KubevirtNodeState.COMPLETE)
+                .forEach(n -> {
+                    KubevirtNode updated = n.updateState(KubevirtNodeState.INIT);
+                    nodeAdminService.updateNode(updated);
+                });
+
+        return ok(mapper().createObjectNode()).build();
+    }
+
+    private Set<KubevirtNode> readNodeConfiguration(InputStream input) {
+        Set<KubevirtNode> nodeSet = Sets.newHashSet();
+        try {
+            JsonNode jsonTree = readTreeFromStream(mapper().enable(INDENT_OUTPUT), input);
+            ArrayNode nodes = (ArrayNode) jsonTree.path(NODES);
+            nodes.forEach(node -> {
+                try {
+                    ObjectNode objectNode = node.deepCopy();
+                    KubevirtNode kubevirtNode =
+                            codec(KubevirtNode.class).decode(objectNode, this);
+                    nodeSet.add(kubevirtNode);
+                } catch (Exception e) {
+                    log.error("Exception occurred due to {}", e);
+                    throw new IllegalArgumentException();
+                }
+            });
+        } catch (Exception e) {
+            throw new IllegalArgumentException(e);
+        }
+
+        return nodeSet;
+    }
 }