Import k8s client deps, support inject k8s API server config
Change-Id: Iaf246a06462b8a878e93ef3f98da399c3600b129
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/cli/K8sApiConfigListCommand.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/cli/K8sApiConfigListCommand.java
new file mode 100644
index 0000000..6ede6da
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/cli/K8sApiConfigListCommand.java
@@ -0,0 +1,68 @@
+/*
+ * 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.cli;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.google.common.collect.Lists;
+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.k8snode.api.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfigService;
+
+import java.util.Comparator;
+import java.util.List;
+
+import static org.onosproject.k8snode.util.K8sNodeUtil.prettyJson;
+
+/**
+ * Lists all kubernetes API server configs registered to the service.
+ */
+@Service
+@Command(scope = "onos", name = "k8s-api-configs",
+ description = "Lists all kubernetes API server configs registered to the service")
+public class K8sApiConfigListCommand extends AbstractShellCommand {
+
+ private static final String FORMAT = "%-10s%-25s%-10s";
+
+ @Override
+ protected void doExecute() {
+ K8sApiConfigService configService = get(K8sApiConfigService.class);
+ List<K8sApiConfig> configs = Lists.newArrayList(configService.apiConfigs());
+ configs.sort(Comparator.comparing(K8sApiConfig::ipAddress));
+
+ if (outputJson()) {
+ print("%s", json(configs));
+ } else {
+ print(FORMAT, "Scheme", "IpAddress", "Port");
+ for (K8sApiConfig config : configs) {
+ print(FORMAT, config.scheme().name(),
+ config.ipAddress().toString(), config.port());
+ }
+ print("Total %s API configs", configService.apiConfigs().size());
+ }
+ }
+
+ private String json(List<K8sApiConfig> configs) {
+ ObjectMapper mapper = new ObjectMapper();
+ ArrayNode result = mapper.createArrayNode();
+ for (K8sApiConfig config : configs) {
+ result.add(jsonForEntity(config, K8sApiConfig.class));
+ }
+ return prettyJson(mapper, result.toString());
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/codec/K8sApiConfigCodec.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/codec/K8sApiConfigCodec.java
new file mode 100644
index 0000000..5e0cb27
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/codec/K8sApiConfigCodec.java
@@ -0,0 +1,140 @@
+/*
+ * 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.DefaultK8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfig.Scheme;
+
+import static org.onlab.util.Tools.nullIsIllegal;
+import static org.onosproject.k8snode.api.K8sApiConfig.Scheme.HTTPS;
+
+/**
+ * Kubernetes API server config codec used for serializing and de-serializing JSON string.
+ */
+public final class K8sApiConfigCodec extends JsonCodec<K8sApiConfig> {
+
+ private static final String SCHEME = "scheme";
+ private static final String IP_ADDRESS = "ipAddress";
+ private static final String PORT = "port";
+ private static final String TOKEN = "token";
+ private static final String CA_CERT_DATA = "caCertData";
+ private static final String CLIENT_CERT_DATA = "clientCertData";
+ private static final String CLIENT_KEY_DATA = "clientKeyData";
+
+ private static final String MISSING_MESSAGE = " is required in K8sApiConfig";
+
+ @Override
+ public ObjectNode encode(K8sApiConfig entity, CodecContext context) {
+ ObjectNode node = context.mapper().createObjectNode()
+ .put(SCHEME, entity.scheme().name())
+ .put(IP_ADDRESS, entity.ipAddress().toString())
+ .put(PORT, entity.port());
+
+ if (entity.scheme() == HTTPS) {
+ node.put(TOKEN, entity.token())
+ .put(CA_CERT_DATA, entity.caCertData())
+ .put(CLIENT_CERT_DATA, entity.clientCertData())
+ .put(CLIENT_KEY_DATA, entity.clientKeyData());
+ } else {
+ if (entity.token() != null) {
+ node.put(TOKEN, entity.token());
+ }
+
+ if (entity.caCertData() != null) {
+ node.put(CA_CERT_DATA, entity.caCertData());
+ }
+
+ if (entity.clientCertData() != null) {
+ node.put(CLIENT_CERT_DATA, entity.clientCertData());
+ }
+
+ if (entity.clientKeyData() != null) {
+ node.put(CLIENT_KEY_DATA, entity.clientKeyData());
+ }
+ }
+
+ return node;
+ }
+
+ @Override
+ public K8sApiConfig decode(ObjectNode json, CodecContext context) {
+ if (json == null || !json.isObject()) {
+ return null;
+ }
+
+ Scheme scheme = Scheme.valueOf(nullIsIllegal(
+ json.get(SCHEME).asText(), SCHEME + MISSING_MESSAGE));
+ IpAddress ipAddress = IpAddress.valueOf(nullIsIllegal(
+ json.get(IP_ADDRESS).asText(), IP_ADDRESS + MISSING_MESSAGE));
+ int port = json.get(PORT).asInt();
+
+ K8sApiConfig.Builder builder = DefaultK8sApiConfig.builder()
+ .scheme(scheme)
+ .ipAddress(ipAddress)
+ .port(port);
+
+ JsonNode tokenJson = json.get(TOKEN);
+ JsonNode caCertDataJson = json.get(CA_CERT_DATA);
+ JsonNode clientCertDataJson = json.get(CLIENT_CERT_DATA);
+ JsonNode clientKeyDataJson = json.get(CLIENT_KEY_DATA);
+
+ String token = "";
+ String caCertData = "";
+ String clientCertData = "";
+ String clientKeyData = "";
+
+ if (scheme == HTTPS) {
+ token = nullIsIllegal(tokenJson.asText(),
+ TOKEN + MISSING_MESSAGE);
+ caCertData = nullIsIllegal(caCertDataJson.asText(),
+ CA_CERT_DATA + MISSING_MESSAGE);
+ clientCertData = nullIsIllegal(clientCertDataJson.asText(),
+ CLIENT_CERT_DATA + MISSING_MESSAGE);
+ clientKeyData = nullIsIllegal(clientKeyDataJson.asText(),
+ CLIENT_KEY_DATA + MISSING_MESSAGE);
+
+
+ } else {
+ if (tokenJson != null) {
+ token = tokenJson.asText();
+ }
+
+ if (caCertDataJson != null) {
+ caCertData = caCertDataJson.asText();
+ }
+
+ if (clientCertDataJson != null) {
+ clientCertData = clientCertDataJson.asText();
+ }
+
+ if (clientKeyDataJson != null) {
+ clientKeyData = clientKeyDataJson.asText();
+ }
+ }
+
+ return builder.token(token)
+ .caCertData(caCertData)
+ .clientCertData(clientCertData)
+ .clientKeyData(clientKeyData)
+ .build();
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/DistributedK8sApiConfigStore.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/DistributedK8sApiConfigStore.java
new file mode 100644
index 0000000..321aac0
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/DistributedK8sApiConfigStore.java
@@ -0,0 +1,198 @@
+/*
+ * 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.packet.IpAddress;
+import org.onlab.util.KryoNamespace;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.k8snode.api.DefaultK8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfigEvent;
+import org.onosproject.k8snode.api.K8sApiConfigStore;
+import org.onosproject.k8snode.api.K8sApiConfigStoreDelegate;
+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.K8sApiConfigEvent.Type.K8S_API_CONFIG_CREATED;
+import static org.onosproject.k8snode.api.K8sApiConfigEvent.Type.K8S_API_CONFIG_REMOVED;
+import static org.onosproject.k8snode.api.K8sApiConfigEvent.Type.K8S_API_CONFIG_UPDATED;
+import static org.onosproject.k8snode.util.K8sNodeUtil.endpoint;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Implementation of kubernetes API config store using consistent map.
+ */
+@Component(immediate = true, service = K8sApiConfigStore.class)
+public class DistributedK8sApiConfigStore
+ extends AbstractStore<K8sApiConfigEvent, K8sApiConfigStoreDelegate>
+ implements K8sApiConfigStore {
+
+ 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_API_CONFIG = KryoNamespace.newBuilder()
+ .register(KryoNamespaces.API)
+ .register(K8sApiConfig.class)
+ .register(DefaultK8sApiConfig.class)
+ .register(K8sApiConfig.Scheme.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, K8sApiConfig> apiConfigMapListener =
+ new K8sApiConfigMapListener();
+ private ConsistentMap<String, K8sApiConfig> apiConfigStore;
+
+ @Activate
+ protected void activate() {
+ ApplicationId appId = coreService.registerApplication(APP_ID);
+ apiConfigStore = storageService.<String, K8sApiConfig>consistentMapBuilder()
+ .withSerializer(Serializer.using(SERIALIZER_K8S_API_CONFIG))
+ .withName("k8s-apiconfig-store")
+ .withApplicationId(appId)
+ .build();
+ apiConfigStore.addListener(apiConfigMapListener);
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ apiConfigStore.removeListener(apiConfigMapListener);
+ eventExecutor.shutdown();
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createApiConfig(K8sApiConfig config) {
+ String key = endpoint(config);
+ apiConfigStore.compute(key, (endpoint, existing) -> {
+ final String error = key + ERR_DUPLICATE;
+ checkArgument(existing == null, error);
+ return config;
+ });
+ }
+
+ @Override
+ public void updateApiConfig(K8sApiConfig config) {
+ String key = endpoint(config);
+ apiConfigStore.compute(key, (endpoint, existing) -> {
+ final String error = key + ERR_NOT_FOUND;
+ checkArgument(existing != null, error);
+ return config;
+ });
+ }
+
+ @Override
+ public K8sApiConfig removeApiConfig(String endpoint) {
+ Versioned<K8sApiConfig> apiConfig = apiConfigStore.remove(endpoint);
+ if (apiConfig == null) {
+ final String error = endpoint + ERR_NOT_FOUND;
+ throw new IllegalArgumentException(error);
+ }
+ return apiConfig.value();
+ }
+
+ @Override
+ public K8sApiConfig removeApiConfig(K8sApiConfig.Scheme scheme,
+ IpAddress ipAddress, int port) {
+ String key = endpoint(scheme, ipAddress, port);
+ return removeApiConfig(key);
+ }
+
+ @Override
+ public Set<K8sApiConfig> apiConfigs() {
+ return ImmutableSet.copyOf(apiConfigStore.asJavaMap().values());
+ }
+
+ @Override
+ public K8sApiConfig apiConfig(String endpoint) {
+ return apiConfigStore.asJavaMap().get(endpoint);
+ }
+
+ @Override
+ public K8sApiConfig apiConfig(K8sApiConfig.Scheme scheme,
+ IpAddress ipAddress, int port) {
+ String key = endpoint(scheme, ipAddress, port);
+ return apiConfig(key);
+ }
+
+ private class K8sApiConfigMapListener
+ implements MapEventListener<String, K8sApiConfig> {
+
+ @Override
+ public void event(MapEvent<String, K8sApiConfig> event) {
+ switch (event.type()) {
+ case INSERT:
+ log.debug("Kubernetes API config created {}", event.newValue());
+ eventExecutor.execute(() ->
+ notifyDelegate(new K8sApiConfigEvent(
+ K8S_API_CONFIG_CREATED, event.newValue().value()
+ )));
+ break;
+ case UPDATE:
+ log.debug("Kubernetes API config updated {}", event.newValue());
+ eventExecutor.execute(() ->
+ notifyDelegate(new K8sApiConfigEvent(
+ K8S_API_CONFIG_UPDATED, event.newValue().value()
+ )));
+ break;
+ case REMOVE:
+ log.debug("Kubernetes API config removed {}", event.oldValue());
+ eventExecutor.execute(() ->
+ notifyDelegate(new K8sApiConfigEvent(
+ K8S_API_CONFIG_REMOVED, event.oldValue().value()
+ )));
+ break;
+ default:
+ // do nothing
+ break;
+ }
+ }
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/K8sApiConfigManager.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/K8sApiConfigManager.java
new file mode 100644
index 0000000..c7a5414
--- /dev/null
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/impl/K8sApiConfigManager.java
@@ -0,0 +1,167 @@
+/*
+ * 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 org.onlab.packet.IpAddress;
+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.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfig.Scheme;
+import org.onosproject.k8snode.api.K8sApiConfigAdminService;
+import org.onosproject.k8snode.api.K8sApiConfigEvent;
+import org.onosproject.k8snode.api.K8sApiConfigListener;
+import org.onosproject.k8snode.api.K8sApiConfigService;
+import org.onosproject.k8snode.api.K8sApiConfigStore;
+import org.onosproject.k8snode.api.K8sApiConfigStoreDelegate;
+import org.onosproject.store.service.StorageService;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.component.annotations.ReferenceCardinality;
+import org.slf4j.Logger;
+
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+
+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.util.K8sNodeUtil.endpoint;
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * Service administering the inventory of kubernetes API configs.
+ */
+@Component(
+ immediate = true,
+ service = { K8sApiConfigService.class, K8sApiConfigAdminService.class }
+)
+public class K8sApiConfigManager
+ extends ListenerRegistry<K8sApiConfigEvent, K8sApiConfigListener>
+ implements K8sApiConfigService, K8sApiConfigAdminService {
+
+ private final Logger log = getLogger(getClass());
+
+ private static final String MSG_CONFIG = "Kubernetes API config %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_CONFIG = "Kubernetes API config cannot be null";
+ private static final String ERR_NULL_ENDPOINT = "Kubernetes API endpoint cannot be null";
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY)
+ protected K8sApiConfigStore configStore;
+
+ @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;
+
+ private final ExecutorService eventExecutor = newSingleThreadExecutor(
+ groupedThreads(this.getClass().getSimpleName(), "event-handler", log));
+
+ private final K8sApiConfigStoreDelegate delegate = new InternalApiConfigStoreDelegate();
+
+ private ApplicationId appId;
+
+ @Activate
+ protected void activate() {
+ appId = coreService.registerApplication(APP_ID);
+ configStore.setDelegate(delegate);
+
+ leadershipService.runForLeadership(appId.name());
+
+ log.info("Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ configStore.unsetDelegate(delegate);
+
+ leadershipService.withdraw(appId.name());
+ eventExecutor.shutdown();
+
+ log.info("Stopped");
+ }
+
+ @Override
+ public void createApiConfig(K8sApiConfig config) {
+ checkNotNull(config, ERR_NULL_CONFIG);
+ configStore.createApiConfig(config);
+ log.info(String.format(MSG_CONFIG, endpoint(config), MSG_CREATED));
+ }
+
+ @Override
+ public void updateApiConfig(K8sApiConfig config) {
+ checkNotNull(config, ERR_NULL_CONFIG);
+ configStore.updateApiConfig(config);
+ log.info(String.format(MSG_CONFIG, endpoint(config), MSG_UPDATED));
+ }
+
+ @Override
+ public K8sApiConfig removeApiConfig(String endpoint) {
+ checkArgument(!Strings.isNullOrEmpty(endpoint), ERR_NULL_ENDPOINT);
+ K8sApiConfig config = configStore.removeApiConfig(endpoint);
+ log.info(String.format(MSG_CONFIG, endpoint, MSG_REMOVED));
+ return config;
+ }
+
+ @Override
+ public K8sApiConfig removeApiConfig(Scheme scheme,
+ IpAddress ipAddress, int port) {
+ return removeApiConfig(endpoint(scheme, ipAddress, port));
+ }
+
+ @Override
+ public Set<K8sApiConfig> apiConfigs() {
+ return configStore.apiConfigs();
+ }
+
+ @Override
+ public K8sApiConfig apiConfig(String endpoint) {
+ return configStore.apiConfig(endpoint);
+ }
+
+ @Override
+ public K8sApiConfig apiConfig(Scheme scheme, IpAddress ipAddress, int port) {
+ return apiConfig(endpoint(scheme, ipAddress, port));
+ }
+
+ private class InternalApiConfigStoreDelegate implements K8sApiConfigStoreDelegate {
+
+ @Override
+ public void notify(K8sApiConfigEvent event) {
+ if (event != null) {
+ log.trace("send kubernetes API config event {}", event);
+ process(event);
+ }
+ }
+ }
+}
diff --git a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/util/K8sNodeUtil.java b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/util/K8sNodeUtil.java
index c0a158e..7fea9cf 100644
--- a/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/util/K8sNodeUtil.java
+++ b/apps/k8s-node/app/src/main/java/org/onosproject/k8snode/util/K8sNodeUtil.java
@@ -17,6 +17,10 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
+import org.apache.commons.lang.StringUtils;
+import org.onlab.packet.IpAddress;
+import org.onosproject.k8snode.api.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfig.Scheme;
import org.onosproject.k8snode.api.K8sNode;
import org.onosproject.net.Device;
import org.onosproject.net.behaviour.BridgeConfig;
@@ -39,6 +43,9 @@
public final class K8sNodeUtil {
private static final Logger log = LoggerFactory.getLogger(K8sNodeUtil.class);
+ private static final String COLON_SLASH = "://";
+ private static final String COLON = ":";
+
/**
* Prevents object installation from external.
*/
@@ -146,4 +153,35 @@
}
return null;
}
+
+ /**
+ * Generates endpoint URL by referring to scheme, ipAddress and port.
+ *
+ * @param scheme scheme
+ * @param ipAddress IP address
+ * @param port port number
+ * @return generated endpoint URL
+ */
+ public static String endpoint(Scheme scheme, IpAddress ipAddress, int port) {
+ StringBuilder endpoint = new StringBuilder();
+ String protocol = StringUtils.lowerCase(scheme.name());
+
+ endpoint.append(protocol);
+ endpoint.append(COLON_SLASH);
+ endpoint.append(ipAddress.toString());
+ endpoint.append(COLON);
+ endpoint.append(port);
+
+ return endpoint.toString();
+ }
+
+ /**
+ * Generates endpoint URL by referring to scheme, ipAddress and port.
+ *
+ * @param apiConfig kubernetes API config
+ * @return generated endpoint URL
+ */
+ public static String endpoint(K8sApiConfig apiConfig) {
+ return endpoint(apiConfig.scheme(), apiConfig.ipAddress(), apiConfig.port());
+ }
}
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
index cb283f9..9138539 100644
--- 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
@@ -16,7 +16,9 @@
package org.onosproject.k8snode.web;
import org.onosproject.codec.CodecService;
+import org.onosproject.k8snode.api.K8sApiConfig;
import org.onosproject.k8snode.api.K8sNode;
+import org.onosproject.k8snode.codec.K8sApiConfigCodec;
import org.onosproject.k8snode.codec.K8sNodeCodec;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
@@ -42,6 +44,7 @@
protected void activate() {
codecService.registerCodec(K8sNode.class, new K8sNodeCodec());
+ codecService.registerCodec(K8sApiConfig.class, new K8sApiConfigCodec());
log.info("Started");
}
@@ -50,6 +53,7 @@
protected void deactivate() {
codecService.unregisterCodec(K8sNode.class);
+ codecService.unregisterCodec(K8sApiConfig.class);
log.info("Stopped");
}
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
index 0367e0f..590dc56 100644
--- 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
@@ -19,6 +19,8 @@
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.K8sApiConfig;
+import org.onosproject.k8snode.api.K8sApiConfigAdminService;
import org.onosproject.k8snode.api.K8sNode;
import org.onosproject.k8snode.api.K8sNodeAdminService;
import org.onosproject.rest.AbstractWebResource;
@@ -26,6 +28,7 @@
import org.slf4j.LoggerFactory;
import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
@@ -43,6 +46,7 @@
import static javax.ws.rs.core.Response.created;
import static org.onlab.util.Tools.nullIsIllegal;
import static org.onlab.util.Tools.readTreeFromStream;
+import static org.onosproject.k8snode.util.K8sNodeUtil.endpoint;
/**
* Handles REST API call of kubernetes node config.
@@ -55,15 +59,18 @@
private static final String MESSAGE_NODE = "Received node %s request";
private static final String NODES = "nodes";
+ private static final String API_CONFIGS = "apiConfigs";
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 REMOVE = "REMOVE";
private static final String HOST_NAME = "hostname";
+ private static final String ENDPOINT = "endpoint";
private static final String ERROR_MESSAGE = " cannot be null";
- private final K8sNodeAdminService adminService = get(K8sNodeAdminService.class);
+ private final K8sNodeAdminService nodeAdminService = get(K8sNodeAdminService.class);
+ private final K8sApiConfigAdminService configAdminService = get(K8sApiConfigAdminService.class);
@Context
private UriInfo uriInfo;
@@ -77,15 +84,16 @@
* @onos.rsModel K8sNode
*/
@POST
+ @Path("node")
@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());
+ K8sNode existing = nodeAdminService.node(node.hostname());
if (existing == null) {
- adminService.createNode(node);
+ nodeAdminService.createNode(node);
}
});
@@ -105,6 +113,7 @@
* @onos.rsModel K8sNode
*/
@PUT
+ @Path("node")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateNodes(InputStream input) {
@@ -112,12 +121,12 @@
Set<K8sNode> nodes = readNodeConfiguration(input);
for (K8sNode node: nodes) {
- K8sNode existing = adminService.node(node.hostname());
+ K8sNode 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)) {
- adminService.updateNode(node);
+ nodeAdminService.updateNode(node);
}
}
@@ -130,23 +139,22 @@
* @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
+ @DELETE
+ @Path("node/{hostname}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- @Path("{hostname}")
public Response deleteNodes(@PathParam("hostname") String hostname) {
- log.trace(String.format(MESSAGE_NODE, DELETE));
+ log.trace(String.format(MESSAGE_NODE, REMOVE));
K8sNode existing =
- adminService.node(nullIsIllegal(hostname, HOST_NAME + ERROR_MESSAGE));
+ 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 {
- adminService.removeNode(hostname);
+ nodeAdminService.removeNode(hostname);
}
return Response.noContent().build();
@@ -175,4 +183,111 @@
return nodeSet;
}
+
+ /**
+ * Creates a set of kubernetes API config from the JSON input stream.
+ *
+ * @param input kubernetes API configs JSON input stream
+ * @return 201 CREATED if the JSON is correct, 400 BAD_REQUEST if the JSON
+ * is malformed
+ * @onos.rsModel K8sApiConfig
+ */
+ @POST
+ @Path("api")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response createApiConfigs(InputStream input) {
+ log.trace(String.format(MESSAGE_NODE, CREATE));
+
+ readApiConfigConfiguration(input).forEach(config -> {
+ K8sApiConfig existing = configAdminService.apiConfig(endpoint(config));
+ if (existing == null) {
+ configAdminService.createApiConfig(config);
+ }
+ });
+
+ UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
+ .path(API_CONFIGS);
+
+ return created(locationBuilder.build()).build();
+ }
+
+ /**
+ * Updates a set of kubernetes API config from the JSON input stream.
+ *
+ * @param input kubernetes API configs JSON input stream
+ * @return 200 OK with the updated kubernetes API config, 400 BAD_REQUEST
+ * if the JSON is malformed, and 304 NOT_MODIFIED without the updated config
+ * @onos.rsModel K8sApiConfig
+ */
+ @PUT
+ @Path("api")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response updateApiConfigs(InputStream input) {
+ log.trace(String.format(MESSAGE_NODE, UPDATE));
+
+ Set<K8sApiConfig> configs = readApiConfigConfiguration(input);
+ for (K8sApiConfig config: configs) {
+ K8sApiConfig existing = configAdminService.apiConfig(endpoint(config));
+ if (existing == null) {
+ log.warn("There is no API configuration to update : {}", endpoint(config));
+ return Response.notModified().build();
+ } else if (!existing.equals(config)) {
+ configAdminService.updateApiConfig(config);
+ }
+ }
+
+ return Response.ok().build();
+ }
+
+ /**
+ * Removes a kubernetes API config.
+ *
+ * @param endpoint kubernetes API endpoint
+ * @return 204 NO_CONTENT, 400 BAD_REQUEST if the JSON is malformed
+ */
+ @DELETE
+ @Path("api/{endpoint : .+}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response deleteApiConfig(@PathParam("endpoint") String endpoint) {
+ log.trace(String.format(MESSAGE_NODE, REMOVE));
+
+ K8sApiConfig existing =
+ configAdminService.apiConfig(nullIsIllegal(endpoint, ENDPOINT + ERROR_MESSAGE));
+
+ if (existing == null) {
+ log.warn("There is no API configuration to delete : {}", endpoint);
+ return Response.notModified().build();
+ } else {
+ configAdminService.removeApiConfig(endpoint);
+ }
+
+ return Response.noContent().build();
+ }
+
+ private Set<K8sApiConfig> readApiConfigConfiguration(InputStream input) {
+ Set<K8sApiConfig> configSet = Sets.newHashSet();
+ try {
+ JsonNode jsonTree = readTreeFromStream(mapper().enable(INDENT_OUTPUT), input);
+ ArrayNode configs = (ArrayNode) jsonTree.path(API_CONFIGS);
+ configs.forEach(config -> {
+ try {
+ ObjectNode objectNode = config.deepCopy();
+ K8sApiConfig k8sApiConfig =
+ codec(K8sApiConfig.class).decode(objectNode, this);
+
+ configSet.add(k8sApiConfig);
+ } catch (Exception e) {
+ log.error("Exception occurred due to {}", e);
+ throw new IllegalArgumentException();
+ }
+ });
+ } catch (Exception e) {
+ throw new IllegalArgumentException(e);
+ }
+
+ return configSet;
+ }
}