[ONOS-7902] Add default implementation of k8s node with unit tests
Change-Id: I283967ae14dc7f38e749d7407e4bec698536c18b
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/codec/K8sNodeCodec.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/codec/K8sNodeCodec.java
new file mode 100644
index 0000000..e07ad6c
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/codec/K8sNodeCodec.java
@@ -0,0 +1,102 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snode.codec;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onlab.packet.IpAddress;
+import org.onosproject.codec.CodecContext;
+import org.onosproject.codec.JsonCodec;
+import org.onosproject.k8snode.api.DefaultK8sNode;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeState;
+import org.onosproject.net.DeviceId;
+import org.slf4j.Logger;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.util.Tools.nullIsIllegal;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Kubernetes node codec used for serializing and de-serializing JSON string.
+ */
+public final class K8sNodeCodec extends JsonCodec<K8sNode> {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String HOSTNAME = "hostname";
+ private static final String TYPE = "type";
+ private static final String MANAGEMENT_IP = "managementIp";
+ private static final String DATA_IP = "dataIp";
+ private static final String INTEGRATION_BRIDGE = "integrationBridge";
+ private static final String STATE = "state";
+
+ private static final String MISSING_MESSAGE = " is required in K8sNode";
+
+ @Override
+ public ObjectNode encode(K8sNode node, CodecContext context) {
+ checkNotNull(node, "Kubernetes node cannot be null");
+
+ ObjectNode result = context.mapper().createObjectNode()
+ .put(HOSTNAME, node.hostname())
+ .put(TYPE, node.type().name())
+ .put(STATE, node.state().name())
+ .put(MANAGEMENT_IP, node.managementIp().toString());
+
+ if (node.intgBridge() != null) {
+ result.put(INTEGRATION_BRIDGE, node.intgBridge().toString());
+ }
+
+ if (node.dataIp() != null) {
+ result.put(DATA_IP, node.dataIp().toString());
+ }
+
+ return result;
+ }
+
+ @Override
+ public K8sNode decode(ObjectNode json, CodecContext context) {
+ if (json == null || !json.isObject()) {
+ return null;
+ }
+
+ String hostname = nullIsIllegal(json.get(HOSTNAME).asText(),
+ HOSTNAME + MISSING_MESSAGE);
+ String type = nullIsIllegal(json.get(TYPE).asText(),
+ TYPE + MISSING_MESSAGE);
+ String mIp = nullIsIllegal(json.get(MANAGEMENT_IP).asText(),
+ MANAGEMENT_IP + MISSING_MESSAGE);
+
+ DefaultK8sNode.Builder nodeBuilder = DefaultK8sNode.builder()
+ .hostname(hostname)
+ .type(K8sNode.Type.valueOf(type))
+ .state(K8sNodeState.INIT)
+ .managementIp(IpAddress.valueOf(mIp));
+
+ if (json.get(DATA_IP) != null) {
+ nodeBuilder.dataIp(IpAddress.valueOf(json.get(DATA_IP).asText()));
+ }
+
+ JsonNode intBridgeJson = json.get(INTEGRATION_BRIDGE);
+ if (intBridgeJson != null) {
+ nodeBuilder.intgBridge(DeviceId.deviceId(intBridgeJson.asText()));
+ }
+
+ log.trace("node is {}", nodeBuilder.build().toString());
+
+ return nodeBuilder.build();
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/DistributedK8sNodeStore.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/DistributedK8sNodeStore.java
new file mode 100644
index 0000000..15d2697
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/DistributedK8sNodeStore.java
@@ -0,0 +1,201 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snode.impl;
+
+import com.google.common.collect.ImmutableSet;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snode.api.DefaultK8sNode;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeEvent;
+import org.onosproject.k8snode.api.K8sNodeState;
+import org.onosproject.k8snode.api.K8sNodeStore;
+import org.onosproject.k8snode.api.K8sNodeStoreDelegate;
+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.k8snode.api.K8sNodeEvent.Type.K8S_NODE_COMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_CREATED;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_INCOMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_REMOVED;
+import static org.onosproject.k8snode.api.K8sNodeEvent.Type.K8S_NODE_UPDATED;
+import static org.onosproject.k8snode.api.K8sNodeState.COMPLETE;
+import static org.onosproject.k8snode.api.K8sNodeState.INCOMPLETE;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubernetes node store using consistent map.
+ */
+@Component(immediate = true, service = K8sNodeStore.class)
+public class DistributedK8sNodeStore
+ extends AbstractStore<K8sNodeEvent, K8sNodeStoreDelegate>
+ implements K8sNodeStore {
+
+ 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.k8snode";
+
+ private static final KryoNamespace
+ SERIALIZER_K8S_NODE = KryoNamespace.newBuilder()
+ .register(KryoNamespaces.API)
+ .register(K8sNode.class)
+ .register(DefaultK8sNode.class)
+ .register(K8sNode.Type.class)
+ .register(K8sNodeState.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, K8sNode> nodeMapListener =
+ new K8sNodeMapListener();
+ private ConsistentMap<String, K8sNode> nodeStore;
+
+ @Activate
+ protected void activate() {
+ ApplicationId appId = coreService.registerApplication(APP_ID);
+ nodeStore = storageService.<String, K8sNode>consistentMapBuilder()
+ .withSerializer(Serializer.using(SERIALIZER_K8S_NODE))
+ .withName("k8s-nodestore")
+ .withApplicationId(appId)
+ .build();
+ nodeStore.addListener(nodeMapListener);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ nodeStore.removeListener(nodeMapListener);
+ eventExecutor.shutdown();
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createNode(K8sNode node) {
+ nodeStore.compute(node.hostname(), (hostname, existing) -> {
+ final String error = node.hostname() + ERR_DUPLICATE;
+ checkArgument(existing == null, error);
+ return node;
+ });
+ }
+
+ @Override
+ public void updateNode(K8sNode node) {
+ nodeStore.compute(node.hostname(), (hostname, existing) -> {
+ final String error = node.hostname() + ERR_NOT_FOUND;
+ checkArgument(existing != null, error);
+ return node;
+ });
+ }
+
+ @Override
+ public K8sNode removeNode(String hostname) {
+ Versioned<K8sNode> node = nodeStore.remove(hostname);
+ if (node == null) {
+ final String error = hostname + ERR_NOT_FOUND;
+ throw new IllegalArgumentException(error);
+ }
+ return node.value();
+ }
+
+ @Override
+ public Set<K8sNode> nodes() {
+ return ImmutableSet.copyOf(nodeStore.asJavaMap().values());
+ }
+
+ @Override
+ public K8sNode node(String hostname) {
+ return nodeStore.asJavaMap().get(hostname);
+ }
+
+ private class K8sNodeMapListener
+ implements MapEventListener<String, K8sNode> {
+
+ @Override
+ public void event(MapEvent<String, K8sNode> event) {
+
+ switch (event.type()) {
+ case INSERT:
+ log.debug("Kubernetes node created {}", event.newValue());
+ eventExecutor.execute(() ->
+ notifyDelegate(new K8sNodeEvent(
+ K8S_NODE_CREATED, event.newValue().value()
+ )));
+ break;
+ case UPDATE:
+ log.debug("Kubernetes node updated {}", event.newValue());
+ eventExecutor.execute(() -> {
+ notifyDelegate(new K8sNodeEvent(
+ K8S_NODE_UPDATED,
+ event.newValue().value()
+ ));
+
+ if (event.newValue().value().state() == COMPLETE) {
+ notifyDelegate(new K8sNodeEvent(
+ K8S_NODE_COMPLETE,
+ event.newValue().value()
+ ));
+ } else if (event.newValue().value().state() == INCOMPLETE) {
+ notifyDelegate(new K8sNodeEvent(
+ K8S_NODE_INCOMPLETE,
+ event.newValue().value()
+ ));
+ }
+ });
+ break;
+ case REMOVE:
+ log.debug("Kubernetes node removed {}", event.oldValue());
+ eventExecutor.execute(() ->
+ notifyDelegate(new K8sNodeEvent(
+ K8S_NODE_REMOVED, event.oldValue().value()
+ )));
+ break;
+ default:
+ // do nothing
+ break;
+ }
+ }
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/K8sNodeManager.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/K8sNodeManager.java
new file mode 100644
index 0000000..d80ef21
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/K8sNodeManager.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snode.impl;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableSet;
+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.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNode.Type;
+import org.onosproject.k8snode.api.K8sNodeAdminService;
+import org.onosproject.k8snode.api.K8sNodeEvent;
+import org.onosproject.k8snode.api.K8sNodeListener;
+import org.onosproject.k8snode.api.K8sNodeService;
+import org.onosproject.k8snode.api.K8sNodeStore;
+import org.onosproject.k8snode.api.K8sNodeStoreDelegate;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.device.DeviceService;
+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.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.k8snode.api.K8sNodeState.COMPLETE;
+import static org.onosproject.k8snode.impl.OsgiPropertyConstants.OVSDB_PORT;
+import static org.onosproject.k8snode.impl.OsgiPropertyConstants.OVSDB_PORT_NUM_DEFAULT;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Service administering the inventory of kubernetes nodes.
+ */
+@Component(
+ immediate = true,
+ service = { K8sNodeService.class, K8sNodeAdminService.class },
+ property = {
+ OVSDB_PORT + ":Integer=" + OVSDB_PORT_NUM_DEFAULT
+ }
+)
+public class K8sNodeManager
+ extends ListenerRegistry<K8sNodeEvent, K8sNodeListener>
+ implements K8sNodeService, K8sNodeAdminService {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String MSG_NODE = "Kubernetes 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 ERR_NULL_NODE = "Kubernetes node cannot be null";
+ private static final String ERR_NULL_HOSTNAME = "Kubernetes node hostname cannot be null";
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected K8sNodeStore 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 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 K8sNodeStoreDelegate delegate = new K8sNodeManager.InternalNodeStoreDelegate();
+
+ private ApplicationId appId;
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(APP_ID);
+ nodeStore.setDelegate(delegate);
+
+ leadershipService.runForLeadership(appId.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(K8sNode node) {
+ checkNotNull(node, ERR_NULL_NODE);
+ nodeStore.createNode(node);
+ log.info(String.format(MSG_NODE, node.hostname(), MSG_CREATED));
+ }
+
+ @Override
+ public void updateNode(K8sNode node) {
+ checkNotNull(node, ERR_NULL_NODE);
+ nodeStore.updateNode(node);
+ log.info(String.format(MSG_NODE, node.hostname(), MSG_UPDATED));
+ }
+
+ @Override
+ public K8sNode removeNode(String hostname) {
+ checkArgument(!Strings.isNullOrEmpty(hostname), ERR_NULL_HOSTNAME);
+ K8sNode node = nodeStore.removeNode(hostname);
+ log.info(String.format(MSG_NODE, hostname, MSG_REMOVED));
+ return node;
+ }
+
+ @Override
+ public Set<K8sNode> nodes() {
+ return nodeStore.nodes();
+ }
+
+ @Override
+ public Set<K8sNode> nodes(Type type) {
+ Set<K8sNode> nodes = nodeStore.nodes().stream()
+ .filter(node -> Objects.equals(node.type(), type))
+ .collect(Collectors.toSet());
+ return ImmutableSet.copyOf(nodes);
+ }
+
+ @Override
+ public Set<K8sNode> completeNodes() {
+ Set<K8sNode> nodes = nodeStore.nodes().stream()
+ .filter(node -> node.state() == COMPLETE)
+ .collect(Collectors.toSet());
+ return ImmutableSet.copyOf(nodes);
+ }
+
+ @Override
+ public Set<K8sNode> completeNodes(Type type) {
+ Set<K8sNode> nodes = nodeStore.nodes().stream()
+ .filter(node -> node.type() == type &&
+ node.state() == COMPLETE)
+ .collect(Collectors.toSet());
+ return ImmutableSet.copyOf(nodes);
+ }
+
+ @Override
+ public K8sNode node(String hostname) {
+ return nodeStore.node(hostname);
+ }
+
+ @Override
+ public K8sNode node(DeviceId deviceId) {
+ return nodeStore.nodes().stream()
+ .filter(node -> Objects.equals(node.intgBridge(), deviceId) ||
+ Objects.equals(node.ovsdb(), deviceId))
+ .findFirst().orElse(null);
+ }
+
+ private class InternalNodeStoreDelegate implements K8sNodeStoreDelegate {
+
+ @Override
+ public void notify(K8sNodeEvent event) {
+ if (event != null) {
+ log.trace("send kubernetes node event {}", event);
+ process(event);
+ }
+ }
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/OsgiPropertyConstants.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/OsgiPropertyConstants.java
new file mode 100644
index 0000000..eed9d93
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/OsgiPropertyConstants.java
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.k8snode.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/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeCodecRegister.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeCodecRegister.java
new file mode 100644
index 0000000..cb283f9
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeCodecRegister.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snode.web;
+
+import org.onosproject.codec.CodecService;
+import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.codec.K8sNodeCodec;
+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 static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of the JSON codec brokering service for K8sNode.
+ */
+@Component(immediate = true)
+public class K8sNodeCodecRegister {
+
+ private final Logger log = getLogger(getClass());
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected CodecService codecService;
+
+ @Activate
+ protected void activate() {
+
+ codecService.registerCodec(K8sNode.class, new K8sNodeCodec());
+
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+
+ codecService.unregisterCodec(K8sNode.class);
+
+ log.info("Stopped");
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeWebApplication.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeWebApplication.java
new file mode 100644
index 0000000..7b13666
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeWebApplication.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snode.web;
+
+import org.onlab.rest.AbstractWebApplication;
+
+import java.util.Set;
+
+/**
+ * Kubernetes node REST APIs web application.
+ */
+public class K8sNodeWebApplication extends AbstractWebApplication {
+ @Override
+ public Set<Class<?>> getClasses() {
+ return getClasses(K8sNodeWebResource.class);
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeWebResource.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeWebResource.java
new file mode 100644
index 0000000..0367e0f
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/web/K8sNodeWebResource.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2019-present Open Networking Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.onosproject.k8snode.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.k8snode.api.K8sNode;
+import org.onosproject.k8snode.api.K8sNodeAdminService;
+import org.onosproject.rest.AbstractWebResource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.Consumes;
+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 kubernetes node config.
+ */
+
+@Path("configure")
+public class K8sNodeWebResource 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 DELETE = "DELETE";
+
+ private static final String HOST_NAME = "hostname";
+ private static final String ERROR_MESSAGE = " cannot be null";
+
+ private final K8sNodeAdminService adminService = get(K8sNodeAdminService.class);
+
+ @Context
+ private UriInfo uriInfo;
+
+ /**
+ * Creates a set of kubernetes nodes' config from the JSON input stream.
+ *
+ * @param input kubernetes nodes JSON input stream
+ * @return 201 CREATED if the JSON is correct, 400 BAD_REQUEST if the JSON
+ * is malformed
+ * @onos.rsModel K8sNode
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response createNodes(InputStream input) {
+ log.trace(String.format(MESSAGE_NODE, CREATE));
+
+ readNodeConfiguration(input).forEach(node -> {
+ K8sNode existing = adminService.node(node.hostname());
+ if (existing == null) {
+ adminService.createNode(node);
+ }
+ });
+
+ UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
+ .path(NODES)
+ .path(NODE_ID);
+
+ return created(locationBuilder.build()).build();
+ }
+
+ /**
+ * Updates a set of kubernetes nodes' config from the JSON input stream.
+ *
+ * @param input kubernetes nodes JSON input stream
+ * @return 200 OK with the updated kubernetes node's config, 400 BAD_REQUEST
+ * if the JSON is malformed, and 304 NOT_MODIFIED without the updated config
+ * @onos.rsModel K8sNode
+ */
+ @PUT
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response updateNodes(InputStream input) {
+ log.trace(String.format(MESSAGE_NODE, UPDATE));
+
+ Set<K8sNode> nodes = readNodeConfiguration(input);
+ for (K8sNode node: nodes) {
+ K8sNode existing = adminService.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)) {
+ adminService.updateNode(node);
+ }
+ }
+
+ return Response.ok().build();
+ }
+
+ /**
+ * Removes a set of kubernetes nodes' config from the JSON input stream.
+ *
+ * @param hostname host name contained in kubernetes nodes configuration
+ * @return 204 NO_CONTENT, 400 BAD_REQUEST if the JSON is malformed, and
+ * 304 NOT_MODIFIED without the updated config
+ * @onos.rsModel K8sNode
+ */
+ @javax.ws.rs.DELETE
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ @Path("{hostname}")
+ public Response deleteNodes(@PathParam("hostname") String hostname) {
+ log.trace(String.format(MESSAGE_NODE, DELETE));
+
+ K8sNode existing =
+ adminService.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 {
+ adminService.removeNode(hostname);
+ }
+
+ return Response.noContent().build();
+ }
+
+ private Set<K8sNode> readNodeConfiguration(InputStream input) {
+ Set<K8sNode> 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();
+ K8sNode k8sNode =
+ codec(K8sNode.class).decode(objectNode, this);
+
+ nodeSet.add(k8sNode);
+ } catch (Exception e) {
+ log.error("Exception occurred due to {}", e);
+ throw new IllegalArgumentException();
+ }
+ });
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+
+ return nodeSet;
+ }
+}