Implement kubevirt node service, expose it through REST API and CLI
Change-Id: Ieebd2652af31344df3a7c91d3669a2ba150cb57f
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/DefaultKubevirtNode.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/DefaultKubevirtNode.java
index cd653ce..3815ff3 100644
--- a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/DefaultKubevirtNode.java
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/DefaultKubevirtNode.java
@@ -125,6 +125,20 @@
}
@Override
+ public KubevirtNode updateIntgBridge(DeviceId deviceId) {
+ return new Builder()
+ .hostname(hostname)
+ .clusterName(clusterName)
+ .type(type)
+ .intgBridge(deviceId)
+ .managementIp(managementIp)
+ .dataIp(dataIp)
+ .state(state)
+ .phyIntfs(phyIntfs)
+ .build();
+ }
+
+ @Override
public Collection<KubevirtPhyInterface> phyIntfs() {
if (phyIntfs == null) {
return new ArrayList<>();
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNode.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNode.java
index 544c76b..402d0f9 100644
--- a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNode.java
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNode.java
@@ -100,11 +100,19 @@
* Returns new kubevirt node instance with given state.
*
* @param newState updated state
- * @return updated kubernetes node
+ * @return updated kubevirt node
*/
KubevirtNode updateState(KubevirtNodeState newState);
/**
+ * Returns new kubevirt node instance with given integration bridge.
+ *
+ * @param deviceId integration bridge device ID
+ * @return updated kubevirt node
+ */
+ KubevirtNode updateIntgBridge(DeviceId deviceId);
+
+ /**
* Returns a collection of physical interfaces.
*
* @return physical interfaces
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeAdminService.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeAdminService.java
new file mode 100644
index 0000000..424a422
--- /dev/null
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeAdminService.java
@@ -0,0 +1,44 @@
+/*
+ * 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.api;
+
+/**
+ * Service for administering inventory of {@link KubevirtNode}.
+ */
+public interface KubevirtNodeAdminService extends KubevirtNodeService {
+
+ /**
+ * Creates a new node.
+ *
+ * @param node kubevirt node
+ */
+ void createNode(KubevirtNode node);
+
+ /**
+ * Updates the node.
+ *
+ * @param node kubevirt node
+ */
+ void updateNode(KubevirtNode node);
+
+ /**
+ * Removes the node.
+ *
+ * @param hostname kubevirt node hostname
+ * @return removed node; null if the node does not exist
+ */
+ KubevirtNode removeNode(String hostname);
+}
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeEvent.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeEvent.java
new file mode 100644
index 0000000..742c0d7
--- /dev/null
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeEvent.java
@@ -0,0 +1,59 @@
+/*
+ * 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.api;
+
+import org.onosproject.event.AbstractEvent;
+
+/**
+ * Describes Kubevirt node init state event.
+ */
+public class KubevirtNodeEvent extends AbstractEvent<KubevirtNodeEvent.Type, KubevirtNode> {
+
+ /**
+ * List of kubevirt node event types.
+ */
+ public enum Type {
+
+ /**
+ * Signifies that new node is created.
+ */
+ KUBEVIRT_NODE_CREATED,
+
+ /**
+ * Signifies that the node state is updated.
+ */
+ KUBEVIRT_NODE_UPDATED,
+
+ /**
+ * Signifies that the node state is complete.
+ */
+ KUBEVIRT_NODE_COMPLETE,
+
+ /**
+ * Signifies that the node state is removed.
+ */
+ KUBEVIRT_NODE_REMOVED,
+
+ /**
+ * Signifies that the node state is changed to incomplete.
+ */
+ KUBEVIRT_NODE_INCOMPLETE
+ }
+
+ public KubevirtNodeEvent(Type type, KubevirtNode subject) {
+ super(type, subject);
+ }
+}
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeListener.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeListener.java
new file mode 100644
index 0000000..c5cff24
--- /dev/null
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeListener.java
@@ -0,0 +1,24 @@
+/*
+ * 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.api;
+
+import org.onosproject.event.EventListener;
+
+/**
+ * Listener for KubevirtNode event.
+ */
+public interface KubevirtNodeListener extends EventListener<KubevirtNodeEvent> {
+}
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeService.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeService.java
new file mode 100644
index 0000000..e032ba3
--- /dev/null
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeService.java
@@ -0,0 +1,85 @@
+/*
+ * 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.api;
+
+import org.onlab.packet.IpAddress;
+import org.onosproject.event.ListenerService;
+import org.onosproject.net.DeviceId;
+
+import java.util.Set;
+
+/**
+ * Service for interfacing with the inventory of {@link KubevirtNode}.
+ */
+public interface KubevirtNodeService extends ListenerService<KubevirtNodeEvent, KubevirtNodeListener> {
+
+ String APP_ID = "org.onosproject.kubevirtnode";
+
+ /**
+ * Returns all registered nodes.
+ *
+ * @return set of kubevirt nodes
+ */
+ Set<KubevirtNode> nodes();
+
+ /**
+ * Returns all nodes with the specified type.
+ *
+ * @param type node type
+ * @return set of kubevirt nodes
+ */
+ Set<KubevirtNode> nodes(KubevirtNode.Type type);
+
+ /**
+ * Returns all nodes with complete state.
+ *
+ * @return set of kubevirt nodes
+ */
+ Set<KubevirtNode> completeNodes();
+
+ /**
+ * Returns all nodes with complete state and the specified type.
+ *
+ * @param type node type
+ * @return set of kubevirt nodes
+ */
+ Set<KubevirtNode> completeNodes(KubevirtNode.Type type);
+
+ /**
+ * Returns the node with the specified hostname.
+ *
+ * @param hostname hostname
+ * @return kubevirt node
+ */
+ KubevirtNode node(String hostname);
+
+ /**
+ * Returns the node with the specified device ID.
+ * The device ID can be any one of integration bridge or ovsdb device.
+ *
+ * @param deviceId device id
+ * @return kubevirt node
+ */
+ KubevirtNode node(DeviceId deviceId);
+
+ /**
+ * Returns the node with the specified management IP address.
+ *
+ * @param mgmtIp management IP
+ * @return kubevirt node
+ */
+ KubevirtNode node(IpAddress mgmtIp);
+}
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeStore.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeStore.java
new file mode 100644
index 0000000..b6a9f03
--- /dev/null
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeStore.java
@@ -0,0 +1,63 @@
+/*
+ * 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.api;
+
+import org.onosproject.store.Store;
+
+import java.util.Set;
+
+/**
+ * Manages inventory of KubevirtNode; not intended for direct use.
+ */
+public interface KubevirtNodeStore extends Store<KubevirtNodeEvent, KubevirtNodeStoreDelegate> {
+
+ /**
+ * Creates a new node.
+ *
+ * @param node kubevirt node
+ */
+ void createNode(KubevirtNode node);
+
+ /**
+ * Updates the node.
+ *
+ * @param node kubevirt node
+ */
+ void updateNode(KubevirtNode node);
+
+ /**
+ * Removes the node.
+ *
+ * @param hostname kubevirt node hostname
+ * @return removed kubevirt node; null if no node mapped for the hostname
+ */
+ KubevirtNode removeNode(String hostname);
+
+ /**
+ * Returns all registered nodes.
+ *
+ * @return set of kubevirt nodes
+ */
+ Set<KubevirtNode> nodes();
+
+ /**
+ * Returns the node with the specified hostname.
+ *
+ * @param hostname hostname
+ * @return kubevirt node
+ */
+ KubevirtNode node(String hostname);
+}
diff --git a/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeStoreDelegate.java b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeStoreDelegate.java
new file mode 100644
index 0000000..5e87855
--- /dev/null
+++ b/apps/kubevirt-node/api/src/main/java/org/onosproject/kubevirtnode/api/KubevirtNodeStoreDelegate.java
@@ -0,0 +1,24 @@
+/*
+ * 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.api;
+
+import org.onosproject.store.StoreDelegate;
+
+/**
+ * KubevirtNode store delegate.
+ */
+public interface KubevirtNodeStoreDelegate extends StoreDelegate<KubevirtNodeEvent> {
+}
diff --git a/apps/kubevirt-node/app/BUILD b/apps/kubevirt-node/app/BUILD
index 601bc8a..372831d 100644
--- a/apps/kubevirt-node/app/BUILD
+++ b/apps/kubevirt-node/app/BUILD
@@ -14,6 +14,7 @@
]
TEST_DEPS = TEST_ADAPTERS + TEST_REST + [
+ "//apps/kubevirt-node/api:onos-apps-kubevirt-node-api-tests",
"//core/api:onos-api-tests",
"//core/common:onos-core-common-tests",
"//web/api:onos-rest-tests",
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;
+ }
}
diff --git a/apps/kubevirt-node/app/src/test/java/org/onosproject/kubevirtnode/impl/KubevirtNodeManagerTest.java b/apps/kubevirt-node/app/src/test/java/org/onosproject/kubevirtnode/impl/KubevirtNodeManagerTest.java
new file mode 100644
index 0000000..5bf6f21
--- /dev/null
+++ b/apps/kubevirt-node/app/src/test/java/org/onosproject/kubevirtnode/impl/KubevirtNodeManagerTest.java
@@ -0,0 +1,236 @@
+/*
+ * 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;
+
+import com.google.common.collect.Lists;
+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.cluster.ClusterServiceAdapter;
+import org.onosproject.cluster.LeadershipServiceAdapter;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.event.Event;
+import org.onosproject.kubevirtnode.api.DefaultKubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNodeEvent;
+import org.onosproject.kubevirtnode.api.KubevirtNodeListener;
+import org.onosproject.kubevirtnode.api.KubevirtNodeState;
+import org.onosproject.kubevirtnode.api.KubevirtNodeTest;
+import org.onosproject.net.Device;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.onosproject.kubevirtnode.api.KubevirtNode.Type.WORKER;
+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_REMOVED;
+import static org.onosproject.kubevirtnode.api.KubevirtNodeEvent.Type.KUBEVIRT_NODE_UPDATED;
+
+/**
+ * Unit tests for KubeVirt node manager.
+ */
+public class KubevirtNodeManagerTest extends KubevirtNodeTest {
+
+ private static final ApplicationId TEST_APP_ID = new DefaultApplicationId(1, "test");
+
+ private static final String ERR_SIZE = "Number of nodes did not match";
+ private static final String ERR_NOT_MATCH = "Node did not match";
+ private static final String ERR_NOT_FOUND = "Node did not exist";
+
+ private static final String WORKER_1_HOSTNAME = "worker_1";
+ private static final String WORKER_2_HOSTNAME = "worker_2";
+ private static final String WORKER_3_HOSTNAME = "worker_3";
+ private static final String WORKER_1_DUP_INT_HOSTNAME = "worker_1_dup_int";
+
+ private static final Device WORKER_1_INTG_DEVICE = createDevice(1);
+ private static final Device WORKER_2_INTG_DEVICE = createDevice(2);
+ private static final Device WORKER_3_INTG_DEVICE = createDevice(3);
+
+ private static final KubevirtNode WORKER_1 = createNode(
+ WORKER_1_HOSTNAME,
+ WORKER,
+ WORKER_1_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.1"),
+ KubevirtNodeState.INIT
+ );
+ private static final KubevirtNode WORKER_2 = createNode(
+ WORKER_2_HOSTNAME,
+ WORKER,
+ WORKER_2_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.2"),
+ KubevirtNodeState.INIT
+ );
+ private static final KubevirtNode WORKER_3 = createNode(
+ WORKER_3_HOSTNAME,
+ WORKER,
+ WORKER_3_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.3"),
+ KubevirtNodeState.COMPLETE
+ );
+ private static final KubevirtNode WORKER_DUP_INT = createNode(
+ WORKER_1_DUP_INT_HOSTNAME,
+ WORKER,
+ WORKER_3_INTG_DEVICE,
+ IpAddress.valueOf("10.100.0.2"),
+ KubevirtNodeState.COMPLETE
+ );
+
+ private final TestKubevirtNodeListener testListener = new TestKubevirtNodeListener();
+
+ private KubevirtNodeManager target;
+ private DistributedKubevirtNodeStore nodeStore;
+
+ @Before
+ public void setUp() {
+ nodeStore = new DistributedKubevirtNodeStore();
+ TestUtils.setField(nodeStore, "coreService", new TestCoreService());
+ TestUtils.setField(nodeStore, "storageService", new TestStorageService());
+ TestUtils.setField(nodeStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
+ nodeStore.activate();
+
+ nodeStore.createNode(WORKER_2);
+ nodeStore.createNode(WORKER_3);
+
+ target = new KubevirtNodeManager();
+ target.storageService = new TestStorageService();
+ target.coreService = new TestCoreService();
+ target.clusterService = new TestClusterService();
+ target.leadershipService = new TestLeadershipService();
+ target.nodeStore = nodeStore;
+ target.addListener(testListener);
+ target.activate();
+ testListener.events.clear();
+ }
+
+ @After
+ public void tearDown() {
+ target.removeListener(testListener);
+ target.deactivate();
+ nodeStore.deactivate();
+ nodeStore = null;
+ target = null;
+ }
+
+ private static class TestKubevirtNodeListener implements KubevirtNodeListener {
+ private List<KubevirtNodeEvent> events = Lists.newArrayList();
+
+ @Override
+ public void event(KubevirtNodeEvent event) {
+ events.add(event);
+ }
+ }
+
+ /**
+ * Checks if creating and removing a node work well with proper events.
+ */
+ @Test
+ public void testCreateAndRemoveNode() {
+ target.createNode(WORKER_1);
+ assertEquals(ERR_SIZE, 3, target.nodes().size());
+ assertTrue(target.node(WORKER_1_HOSTNAME) != null);
+
+ target.removeNode(WORKER_1_HOSTNAME);
+ assertEquals(ERR_SIZE, 2, target.nodes().size());
+ assertTrue(target.node(WORKER_1_HOSTNAME) == null);
+
+ validateEvents(KUBEVIRT_NODE_CREATED, KUBEVIRT_NODE_REMOVED);
+ }
+
+ /**
+ * Checks if creating null node fails with proper exception.
+ */
+ @Test(expected = NullPointerException.class)
+ public void testCreateNullNode() {
+ target.createNode(null);
+ }
+
+ /**
+ * Checks if creating a duplicated node fails with proper exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testCreateDuplicateNode() {
+ target.createNode(WORKER_1);
+ target.createNode(WORKER_1);
+ }
+
+ /**
+ * Checks if removing null node fails with proper exception.
+ */
+ @Test(expected = IllegalArgumentException.class)
+ public void testRemoveNullNode() {
+ target.removeNode(null);
+ }
+
+ /**
+ * Checks if updating a node works well with proper event.
+ */
+ @Test
+ public void testUpdateNode() {
+ KubevirtNode updated = DefaultKubevirtNode.from(WORKER_2)
+ .dataIp(IpAddress.valueOf("10.200.0.100"))
+ .build();
+ target.updateNode(updated);
+ assertEquals(ERR_NOT_MATCH, updated, target.node(WORKER_2_INTG_DEVICE.id()));
+ validateEvents(KUBEVIRT_NODE_UPDATED);
+ }
+
+ /**
+ * Checks if updating a node state to complete generates proper events.
+ */
+ @Test
+ public void testUpdateNodeStateComplete() {
+ KubevirtNode updated = DefaultKubevirtNode.from(WORKER_2)
+ .state(KubevirtNodeState.COMPLETE)
+ .build();
+ target.updateNode(updated);
+ assertEquals(ERR_NOT_MATCH, updated, target.node(WORKER_2_HOSTNAME));
+ validateEvents(KUBEVIRT_NODE_UPDATED, KUBEVIRT_NODE_COMPLETE);
+ }
+
+ 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();
+ }
+
+ private static class TestCoreService extends CoreServiceAdapter {
+
+ @Override
+ public ApplicationId registerApplication(String name) {
+ return TEST_APP_ID;
+ }
+ }
+
+ private class TestClusterService extends ClusterServiceAdapter {
+
+ }
+
+ private static class TestLeadershipService extends LeadershipServiceAdapter {
+
+ }
+}
diff --git a/apps/kubevirt-node/app/src/test/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResourceTest.java b/apps/kubevirt-node/app/src/test/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResourceTest.java
new file mode 100644
index 0000000..7d15e90
--- /dev/null
+++ b/apps/kubevirt-node/app/src/test/java/org/onosproject/kubevirtnode/web/KubevirtNodeWebResourceTest.java
@@ -0,0 +1,198 @@
+/*
+ * 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.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.kubevirtnode.api.DefaultKubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNode;
+import org.onosproject.kubevirtnode.api.KubevirtNodeAdminService;
+import org.onosproject.kubevirtnode.api.KubevirtNodeState;
+import org.onosproject.kubevirtnode.codec.KubevirtNodeCodec;
+import org.onosproject.net.DeviceId;
+import org.onosproject.rest.resources.ResourceTest;
+
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import java.io.InputStream;
+
+import static org.easymock.EasyMock.anyObject;
+import static org.easymock.EasyMock.anyString;
+import static org.easymock.EasyMock.createMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Unit test for KubeVirt node REST API.
+ */
+public class KubevirtNodeWebResourceTest extends ResourceTest {
+
+ final KubevirtNodeAdminService mockKubevirtNodeAdminService = createMock(KubevirtNodeAdminService.class);
+ private static final String NODE_PATH = "configure/node";
+
+ private KubevirtNode kubevirtNode;
+
+ /**
+ * Constructs a KubeVirt node resource test instance.
+ */
+ public KubevirtNodeWebResourceTest() {
+ super(ResourceConfig.forApplicationClass(KubevirtNodeWebApplication.class));
+ }
+
+ /**
+ * Sets up the global values for all the tests.
+ */
+ @Before
+ public void setUpTest() {
+ final CodecManager codecService = new CodecManager();
+ codecService.activate();
+ codecService.registerCodec(KubevirtNode.class, new KubevirtNodeCodec());
+ ServiceDirectory testDirectory =
+ new TestServiceDirectory()
+ .add(KubevirtNodeAdminService.class, mockKubevirtNodeAdminService)
+ .add(CodecService.class, codecService);
+ setServiceDirectory(testDirectory);
+
+ kubevirtNode = DefaultKubevirtNode.builder()
+ .hostname("worker-node")
+ .type(KubevirtNode.Type.WORKER)
+ .dataIp(IpAddress.valueOf("10.134.34.222"))
+ .managementIp(IpAddress.valueOf("10.134.231.30"))
+ .intgBridge(DeviceId.deviceId("of:00000000000000a1"))
+ .state(KubevirtNodeState.INIT)
+ .build();
+ }
+
+ /**
+ * Tests the results of the REST API POST method with creating new nodes operation.
+ */
+ @Test
+ public void testCreateNodesWithCreateOperation() {
+ expect(mockKubevirtNodeAdminService.node(anyString())).andReturn(null).once();
+ mockKubevirtNodeAdminService.createNode(anyObject());
+ replay(mockKubevirtNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = KubevirtNodeWebResourceTest.class
+ .getResourceAsStream("kubevirt-worker-node.json");
+
+ Response response = wt.path(NODE_PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .post(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(201));
+
+ verify(mockKubevirtNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API PUT method with modifying the nodes.
+ */
+ @Test
+ public void testUpdateNodesWithModifyOperation() {
+ expect(mockKubevirtNodeAdminService.node(anyString())).andReturn(kubevirtNode).once();
+ mockKubevirtNodeAdminService.updateNode(anyObject());
+ replay(mockKubevirtNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = KubevirtNodeWebResourceTest.class
+ .getResourceAsStream("kubevirt-worker-node.json");
+
+ Response response = wt.path(NODE_PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .put(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(200));
+
+ verify(mockKubevirtNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API PUT method without modifying the nodes.
+ */
+ @Test
+ public void testUpdateNodesWithoutModifyOperation() {
+ expect(mockKubevirtNodeAdminService.node(anyString())).andReturn(null).once();
+ replay(mockKubevirtNodeAdminService);
+
+ final WebTarget wt = target();
+ InputStream jsonStream = KubevirtNodeWebResourceTest.class
+ .getResourceAsStream("kubevirt-worker-node.json");
+
+ Response response = wt.path(NODE_PATH).request(MediaType.APPLICATION_JSON_TYPE)
+ .put(Entity.json(jsonStream));
+ final int status = response.getStatus();
+
+ assertThat(status, is(304));
+
+ verify(mockKubevirtNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API DELETE method with deleting the nodes.
+ */
+ @Test
+ public void testDeleteNodesWithDeletionOperation() {
+ expect(mockKubevirtNodeAdminService.node(anyString())).andReturn(kubevirtNode).once();
+ expect(mockKubevirtNodeAdminService.removeNode(anyString())).andReturn(kubevirtNode).once();
+ replay(mockKubevirtNodeAdminService);
+
+ String location = NODE_PATH + "/worker-node";
+
+ final WebTarget wt = target();
+ Response response = wt.path(location).request(
+ MediaType.APPLICATION_JSON_TYPE).delete();
+
+ final int status = response.getStatus();
+
+ assertThat(status, is(204));
+
+ verify(mockKubevirtNodeAdminService);
+ }
+
+ /**
+ * Tests the results of the REST API DELETE method without deleting the nodes.
+ */
+ @Test
+ public void testDeleteNodesWithoutDeletionOperation() {
+ expect(mockKubevirtNodeAdminService.node(anyString())).andReturn(null).once();
+ replay(mockKubevirtNodeAdminService);
+
+ String location = NODE_PATH + "/worker-node";
+
+ final WebTarget wt = target();
+ Response response = wt.path(location).request(
+ MediaType.APPLICATION_JSON_TYPE).delete();
+
+ final int status = response.getStatus();
+
+ assertThat(status, is(304));
+
+ verify(mockKubevirtNodeAdminService);
+ }
+}
diff --git a/apps/kubevirt-node/app/src/test/resources/org/onosproject/kubevirtnode/web/kubevirt-worker-node.json b/apps/kubevirt-node/app/src/test/resources/org/onosproject/kubevirtnode/web/kubevirt-worker-node.json
new file mode 100644
index 0000000..ddda185
--- /dev/null
+++ b/apps/kubevirt-node/app/src/test/resources/org/onosproject/kubevirtnode/web/kubevirt-worker-node.json
@@ -0,0 +1,12 @@
+{
+ "nodes" : [
+ {
+ "hostname" : "worker-node",
+ "type" : "WORKER",
+ "managementIp" : "10.134.231.32",
+ "dataIp" : "10.134.34.224",
+ "nodeIp" : "30.30.30.3",
+ "integrationBridge" : "of:00000000000000a2"
+ }
+ ]
+}
\ No newline at end of file