This is an automated email from the ASF dual-hosted git repository. wiener pushed a commit to branch edge-extensions in repository https://gitbox.apache.org/repos/asf/incubator-streampipes.git
commit 25a3c3cd8d97b3dd85534f88bfc2104d0ce327f4 Author: Patrick Wiener <[email protected]> AuthorDate: Sun Mar 14 09:31:55 2021 +0100 [WIP] initial work on pipeline element live reconfiguration --- docker-compose.yml | 19 -- .../streampipes/config/consul/ConsulSpConfig.java | 12 +- streampipes-connect/pom.xml | 6 + .../connect/adapter/GroundingService.java | 51 +++--- .../extensions/ExtensionsModelSubmitter.java | 32 ++-- .../streampipes/container/util/ConsulUtil.java | 24 ++- .../container/util/NodeControllerUtil.java | 76 ++++---- .../model/node/NodeInfoDescription.java | 8 + .../PipelineElementReconfigurationEntity.java | 105 +++++++++++ .../staticproperty/FreeTextStaticProperty.java | 12 ++ streampipes-node-controller-container/Dockerfile | 2 + .../aarch64.Dockerfile | 3 +- .../arm.Dockerfile | 3 +- .../controller/container/NodeControllerInit.java | 13 +- .../container/api/ContainerDeploymentResource.java | 19 +- .../container/api/InvocableEntityResource.java | 9 +- .../controller/container/config/ConfigKeys.java | 14 +- .../container/config/NodeControllerConfig.java | 157 ++++++++++++----- .../management/connect/ConnectManager.java | 18 +- .../container/management/node/NodeConstants.java | 5 +- .../container/management/node/NodeManager.java | 152 +++++++++++++--- .../orchestrator/ContainerDeploymentStatus.java | 72 ++++++++ .../orchestrator/ContainerOrchestrator.java | 4 +- .../orchestrator/docker/DockerConstants.java | 66 +++---- .../docker/DockerContainerManager.java | 117 +++++++------ .../docker/{ => model}/DockerInfo.java | 2 +- .../orchestrator/docker/utils/DockerUtils.java | 22 +-- .../management/pe/InvocableElementManager.java | 52 ++++-- .../http/ReconfigurationEndpointUrlGenerator.java | 47 +++++ .../execution/http/ReconfigurationSubmitter.java | 132 ++++++++++++++ .../PipelineElementReconfigurationExecutor.java | 41 +++++ .../manager/matching/ProtocolSelector.java | 40 +++-- .../migration/PipelineElementMigrationHandler.java | 10 +- .../manager/node/NodeClusterManager.java | 5 + .../streampipes/manager/operations/Operations.java | 5 + .../PipelineElementReconfigurationHandler.java | 191 +++++++++++++++++++++ .../org/apache/streampipes/rest/api/INode.java | 2 + .../org/apache/streampipes/rest/impl/Node.java | 12 ++ .../streampipes/rest/impl/PipelineResource.java | 22 +++ ...AbstractConfigurablePipelineElementBuilder.java | 21 +++ .../apache/streampipes/vocabulary/StreamPipes.java | 1 + .../node-configuration.component.html | 10 +- ui/src/app/core-model/gen/streampipes-model.ts | 6 +- .../static-property-util.service.ts | 1 + .../migrate-pipeline-processors.component.ts | 18 ++ .../components/edit/quickedit.component.html | 7 + .../components/edit/quickedit.component.ts | 9 + .../pipeline-details.component.html | 3 +- .../app/platform-services/apis/pipeline.service.ts | 8 + 49 files changed, 1318 insertions(+), 348 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 42c99f8..71c7419 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -51,24 +51,6 @@ services: networks: spnet: - connect-master: - build: - context: ./streampipes-connect-container-master - dockerfile: Dockerfile - args: - BASE_IMAGE: adoptopenjdk/openjdk8-openj9:alpine - image: incubator-streampipes_connect-master:release-validation - depends_on: - - consul - - couchdb - environment: - - EXECUTION_MODE=MASTER - - SP_CONNECT_CONTAINER_HOST=connect-master - - SP_CONNECT_CONTAINER_WORKER=connect-worker - logging: *default-logging - networks: - spnet: - ui: build: context: ./ui @@ -82,7 +64,6 @@ services: - couchdb - activemq - consul - - connect-master - backend logging: *default-logging networks: diff --git a/streampipes-config/src/main/java/org/apache/streampipes/config/consul/ConsulSpConfig.java b/streampipes-config/src/main/java/org/apache/streampipes/config/consul/ConsulSpConfig.java index e76a36d..2e92756 100644 --- a/streampipes-config/src/main/java/org/apache/streampipes/config/consul/ConsulSpConfig.java +++ b/streampipes-config/src/main/java/org/apache/streampipes/config/consul/ConsulSpConfig.java @@ -45,6 +45,7 @@ public class ConsulSpConfig extends SpConfig implements Runnable { private static final String CONSUL_ENV_LOCATION = "CONSUL_LOCATION"; private static final int CONSUL_DEFAULT_PORT = 8500; private static final String ENV_NODE_CONTROLLER_ID_KEY = "SP_NODE_CONTROLLER_ID"; + private static final String SP_URL = "SP_URL"; public static final String SERVICE_ROUTE_PREFIX = "sp/v1/"; public static final String BASE_PREFIX = "base"; @@ -82,7 +83,7 @@ public class ConsulSpConfig extends SpConfig implements Runnable { URL consulUrl = consulURL(); while (!connected) { - LOG.info("Trying to connect to Consul to register config items"); + LOG.info("Trying to connect to Consul to register config items: {}", consulUrl.toString()); connected = isReady(consulUrl.getHost(), consulUrl.getPort()); if (!connected) { @@ -102,7 +103,14 @@ public class ConsulSpConfig extends SpConfig implements Runnable { Map<String, String> env = System.getenv(); URL url = null; - if (env.containsKey(CONSUL_ENV_LOCATION)) { + if (env.containsKey(SP_URL)) { + try { + URL coreServerUrl = new URL(env.get(SP_URL)); + url = new URL("http", coreServerUrl.getHost(), CONSUL_DEFAULT_PORT, ""); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } else if (env.containsKey(CONSUL_ENV_LOCATION)) { try { url = new URL("http", env.get(CONSUL_ENV_LOCATION), CONSUL_DEFAULT_PORT, ""); } catch (MalformedURLException e) { diff --git a/streampipes-connect/pom.xml b/streampipes-connect/pom.xml index cf12739..d517948 100755 --- a/streampipes-connect/pom.xml +++ b/streampipes-connect/pom.xml @@ -167,5 +167,11 @@ <artifactId>powermock-api-mockito2</artifactId> <scope>test</scope> </dependency> + <dependency> + <groupId>org.apache.streampipes</groupId> + <artifactId>streampipes-storage-management</artifactId> + <version>0.68.0-SNAPSHOT</version> + <scope>compile</scope> + </dependency> </dependencies> </project> \ No newline at end of file diff --git a/streampipes-connect/src/main/java/org/apache/streampipes/connect/adapter/GroundingService.java b/streampipes-connect/src/main/java/org/apache/streampipes/connect/adapter/GroundingService.java index 50f0d3f..bc574e2 100644 --- a/streampipes-connect/src/main/java/org/apache/streampipes/connect/adapter/GroundingService.java +++ b/streampipes-connect/src/main/java/org/apache/streampipes/connect/adapter/GroundingService.java @@ -18,6 +18,7 @@ package org.apache.streampipes.connect.adapter; +import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.config.backend.BackendConfig; import org.apache.streampipes.config.backend.SpEdgeNodeProtocol; import org.apache.streampipes.config.backend.SpProtocol; @@ -33,8 +34,11 @@ import org.apache.streampipes.model.grounding.MqttTransportProtocol; import org.apache.streampipes.model.grounding.SimpleTopicDefinition; import org.apache.streampipes.model.grounding.TopicDefinition; import org.apache.streampipes.model.grounding.TransportProtocol; +import org.apache.streampipes.model.node.NodeInfoDescription; +import org.apache.streampipes.storage.management.StorageDispatcher; import java.util.Collections; +import java.util.Optional; import java.util.UUID; public class GroundingService { @@ -94,23 +98,24 @@ public class GroundingService { if (isEdgeProtocol(edgeNodeProtocol, MqttTransportProtocol.class)) { if (adapterDescription instanceof GenericAdapterDescription) { - String deploymentTargetNodeHostname = ((GenericAdapterDescription) adapterDescription) + + String nodeControllerId = ((GenericAdapterDescription) adapterDescription) .getProtocolDescription() - .getDeploymentTargetNodeHostname(); + .getDeploymentTargetNodeId(); + + MqttTransportProtocol brokerTransportProtocol = + (MqttTransportProtocol) getNodeBrokerTransportProtocol(nodeControllerId); + brokerTransportProtocol.setTopicDefinition(topicDefinition); - eventGrounding.setTransportProtocol( - makeMqttTransportProtocol( - getTargetNodeBrokerHost(deploymentTargetNodeHostname), - getTargetNodeBrokerPort(deploymentTargetNodeHostname), - topicDefinition)); + eventGrounding.setTransportProtocol(brokerTransportProtocol); } else { - String deploymentTargetNodeHostname = adapterDescription.getDeploymentTargetNodeHostname(); - eventGrounding.setTransportProtocol( - makeMqttTransportProtocol( - getTargetNodeBrokerHost(deploymentTargetNodeHostname), - getTargetNodeBrokerPort(deploymentTargetNodeHostname), - topicDefinition)); + String nodeControllerId = adapterDescription.getDeploymentTargetNodeId(); + MqttTransportProtocol brokerTransportProtocol = + (MqttTransportProtocol) getNodeBrokerTransportProtocol(nodeControllerId); + brokerTransportProtocol.setTopicDefinition(topicDefinition); + + eventGrounding.setTransportProtocol(brokerTransportProtocol); } } @@ -188,19 +193,15 @@ public class GroundingService { protocol.setTopicDefinition(topicDefinition); } - private static String getTargetNodeBrokerHost(String deploymentTargetNodeHostname) { - // TODO: no hardcoded route - only for testing - return ConsulUtil.getValueForRoute( - "sp/v1/node/org.apache.streampipes.node.controller/" - + deploymentTargetNodeHostname - + "/config/SP_NODE_BROKER_CONTAINER_HOST", String.class); + private static TransportProtocol getNodeBrokerTransportProtocol(String id) { + Optional<NodeInfoDescription> nodeInfoDescription = getNodeInfoDescriptionForId(id); + if (nodeInfoDescription.isPresent()) { + return nodeInfoDescription.get().getNodeBroker().getNodeTransportProtocol(); + } + throw new SpRuntimeException("Could not find node description for id: " + id); } - private static int getTargetNodeBrokerPort(String deploymentTargetNodeHostname) { - // TODO: no hardcoded route - only for testing - return ConsulUtil.getValueForRoute( - "sp/v1/node/org.apache.streampipes.node.controller/" - + deploymentTargetNodeHostname - + "/config/SP_NODE_BROKER_CONTAINER_PORT", Integer.class); + private static Optional<NodeInfoDescription> getNodeInfoDescriptionForId(String id){ + return StorageDispatcher.INSTANCE.getNoSqlStore().getNodeStorage().getNode(id); } } diff --git a/streampipes-container-extensions/src/main/java/org/apache/streampipes/container/extensions/ExtensionsModelSubmitter.java b/streampipes-container-extensions/src/main/java/org/apache/streampipes/container/extensions/ExtensionsModelSubmitter.java index 8d45a65..56a6004 100644 --- a/streampipes-container-extensions/src/main/java/org/apache/streampipes/container/extensions/ExtensionsModelSubmitter.java +++ b/streampipes-container-extensions/src/main/java/org/apache/streampipes/container/extensions/ExtensionsModelSubmitter.java @@ -17,7 +17,6 @@ */ package org.apache.streampipes.container.extensions; -import io.undertow.server.handlers.proxy.mod_cluster.NodeConfig; import org.apache.streampipes.connect.adapter.Adapter; import org.apache.streampipes.connect.adapter.model.generic.Protocol; import org.apache.streampipes.connect.container.worker.management.MasterRestClient; @@ -53,7 +52,6 @@ import org.springframework.context.annotation.Import; import javax.annotation.PreDestroy; import java.io.IOException; import java.util.*; -import java.util.stream.Collectors; @Configuration @EnableAutoConfiguration @@ -90,24 +88,24 @@ public abstract class ExtensionsModelSubmitter extends ModelSubmitter<EdgeExtens app.setDefaultProperties(Collections.singletonMap("server.port", conf.getPort())); app.run(); + LOG.info("Using StreamPipes Extensions Environment Variables"); + System.getenv().entrySet().stream() + .filter(e -> e.getKey().startsWith("SP_")) + .forEach(System.out::println); + // check wether pipeline element is managed by node controller if (System.getenv(NODE_CONTROLLER_ID) != null) { // secondary // register pipeline element service via node controller - NodeControllerUtil.register( - conf.getId(), - conf.getHost(), - conf.getPort(), - generateSupportedAppIds()); + NodeControllerUtil.register(conf, generateSupportedAppIds()); String nodeControllerUrl = PROTOCOL + conf.getNodeControllerHost() + COLON + conf.getNodeControllerPort(); boolean connected = false; while (!connected) { LOG.info("Trying to connect to the node controller: " + nodeControllerUrl); - connected = NodeControllerRestClient.register( - nodeControllerUrl, - getContainerDescription(conf.getHost(), conf.getPort(), true)); + connected = NodeControllerRestClient.register(nodeControllerUrl, + getContainerDescription(conf, true)); if (!connected) { LOG.info("Retrying in 5 seconds"); @@ -132,8 +130,8 @@ public abstract class ExtensionsModelSubmitter extends ModelSubmitter<EdgeExtens boolean connected = false; while (!connected) { LOG.info("Trying to connect to master in backend: " + backendUrl); - connected = MasterRestClient.register(backendUrl, getContainerDescription(conf.getHost(), - conf.getPort(), false)); + connected = MasterRestClient.register(backendUrl, + getContainerDescription(conf, false)); if (!connected) { LOG.info("Retrying in 5 seconds"); @@ -160,15 +158,17 @@ public abstract class ExtensionsModelSubmitter extends ModelSubmitter<EdgeExtens return supportedAppIds; } - private ConnectWorkerContainer getContainerDescription(String connectWorkerHost, int connectWorkerPort, - boolean runsOnEdgeNode) { + private ConnectWorkerContainer getContainerDescription(EdgeExtensionsConfig conf, boolean runsOnEdgeNode) { + + String connectWorkerHost = conf.getHost(); + int connectWorkerPort = conf.getPort(); String endpointUrl = PROTOCOL + connectWorkerHost + COLON + connectWorkerPort + SLASH; if (runsOnEdgeNode) { String deploymentTargetNodeId = System.getenv(NODE_CONTROLLER_ID); - String deploymentTargetNodeHostname = System.getenv(NODE_CONTROLLER_CONTAINER_HOST); - int deploymentTargetNodePort = Integer.parseInt(System.getenv(NODE_CONTROLLER_CONTAINER_PORT)); + String deploymentTargetNodeHostname = conf.getNodeControllerHost(); + int deploymentTargetNodePort = conf.getNodeControllerPort(); List<AdapterDescription> adapters = new ArrayList<>(); for (Adapter a : AdapterDeclarerSingleton.getInstance().getAllAdapters()) { diff --git a/streampipes-container/src/main/java/org/apache/streampipes/container/util/ConsulUtil.java b/streampipes-container/src/main/java/org/apache/streampipes/container/util/ConsulUtil.java index abe4094..e58e0b3 100644 --- a/streampipes-container/src/main/java/org/apache/streampipes/container/util/ConsulUtil.java +++ b/streampipes-container/src/main/java/org/apache/streampipes/container/util/ConsulUtil.java @@ -81,7 +81,7 @@ public class ConsulUtil { * @param port port of pipeline element service endpoint */ public static void registerPeService(String svcId, String host, int port) { - registerService(PE_SVC_TAG, makeUniqueSvcId(host, svcId), host, port, makeSvcTags()); + registerService(PE_SVC_TAG, makeUniqueSvcId(host, svcId), host, port, "", makeSvcTags()); } /** @@ -91,9 +91,11 @@ public class ConsulUtil { * @param svcId unique service id * @param host host address of node controller service endpoint * @param port port of node controller service endpoint + * @param healthCheckEndpoint endpoint to perform healthcheck */ - public static void registerNodeService(String svcId, String host, int port) { - registerService(NODE_SVC_TAG, makeUniqueSvcId(host, svcId), host, port, Collections.singletonList(NODE_SVC_TAG)); + public static void registerNodeService(String svcId, String host, int port, String healthCheckEndpoint) { + registerService(NODE_SVC_TAG, makeUniqueSvcId(host, svcId), host, port, healthCheckEndpoint, + Collections.singletonList(NODE_SVC_TAG)); } /** @@ -105,12 +107,14 @@ public class ConsulUtil { * @param port port of service endpoint * @param tags tags of service */ - public static void registerService(String svcGroup, String svcId, String host, int port, List<String> tags) { + public static void registerService(String svcGroup, String svcId, String host, int port, + String healthcheckRoute, List<String> tags) { boolean connected = false; while (!connected) { LOG.info("Trying to register service at Consul: " + svcId); - ConsulServiceRegistrationBody svcRegistration = createRegistrationBody(svcGroup, svcId, host, port, tags); + ConsulServiceRegistrationBody svcRegistration = createRegistrationBody(svcGroup, svcId, host, port, + healthcheckRoute, tags); connected = registerServiceHttpClient(svcRegistration); if (!connected) { @@ -355,7 +359,12 @@ public class ConsulUtil { } private static ConsulServiceRegistrationBody createRegistrationBody(String svcGroup, String id, String host, - int port, List<String> tags) { + int port, String healthcheckRoute, + List<String> tags) { + String endpoint = HTTP_PROTOCOL + host + COLON + port; + if (healthcheckRoute != null) { + endpoint = endpoint + healthcheckRoute; + } ConsulServiceRegistrationBody body = new ConsulServiceRegistrationBody(); body.setID(id); body.setName(svcGroup); @@ -363,8 +372,7 @@ public class ConsulUtil { body.setAddress(HTTP_PROTOCOL + host); body.setPort(port); body.setEnableTagOverride(true); - body.setCheck(new HealthCheckConfiguration("GET", - (HTTP_PROTOCOL + host + COLON + port), HEALTH_CHECK_INTERVAL)); + body.setCheck(new HealthCheckConfiguration("GET", endpoint, HEALTH_CHECK_INTERVAL)); return body; } diff --git a/streampipes-container/src/main/java/org/apache/streampipes/container/util/NodeControllerUtil.java b/streampipes-container/src/main/java/org/apache/streampipes/container/util/NodeControllerUtil.java index 497d537..4295c04 100644 --- a/streampipes-container/src/main/java/org/apache/streampipes/container/util/NodeControllerUtil.java +++ b/streampipes-container/src/main/java/org/apache/streampipes/container/util/NodeControllerUtil.java @@ -19,7 +19,7 @@ package org.apache.streampipes.container.util;/* import com.fasterxml.jackson.core.JsonProcessingException; import org.apache.http.client.fluent.Request; import org.apache.http.entity.ContentType; -import org.apache.streampipes.container.declarer.SemanticEventProcessingAgentDeclarer; +import org.apache.streampipes.container.model.EdgeExtensionsConfig; import org.apache.streampipes.container.model.node.InvocableRegistration; import org.apache.streampipes.container.model.consul.ConsulServiceRegistrationBody; import org.apache.streampipes.container.model.consul.HealthCheckConfiguration; @@ -28,6 +28,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; import java.util.*; public class NodeControllerUtil { @@ -41,22 +43,31 @@ public class NodeControllerUtil { private static final String SECONDARY_PE_IDENTIFIER_TAG = "secondary"; private static final String NODE_CONTROLLER_REGISTER_SVC_URL = "api/v2/node/element/register"; - private static final String NODE_CONTROLLER_CONTAINER_HOST = "SP_NODE_CONTROLLER_CONTAINER_HOST"; - private static final String NODE_CONTROLLER_CONTAINER_PORT = "SP_NODE_CONTROLLER_CONTAINER_PORT"; + // StandaloneModelSubmitter for pipeline-elements-all-jvm + public static void register(String id, String host, int port, List<String> supportedAppIds) { + String body = createSvcBody(PE_TAG, makeSvcId(host, id), host, + port, Arrays.asList(PE_TAG, SECONDARY_PE_IDENTIFIER_TAG), supportedAppIds); + String endpoint = generateNodeControllerEndpointFromEnv(); - public static void register(String serviceID, String host, int port, List<String> supportedAppIds) { - register(PE_TAG, makeSvcId(host, serviceID), host, port, - Arrays.asList(PE_TAG, SECONDARY_PE_IDENTIFIER_TAG), supportedAppIds); + registerService(endpoint, body); } - public static void register(String svcName, String svcId, String host, int port, List<String> tag, - List<String> supportedAppIds) { + // ExtensionsModelSubmitter for extensions-all + public static void register(EdgeExtensionsConfig conf, List<String> supportedAppIds) { + String body = createSvcBody(PE_TAG, makeSvcId(conf.getHost(), conf.getId()), conf.getHost(), + conf.getPort(), Arrays.asList(PE_TAG, SECONDARY_PE_IDENTIFIER_TAG), supportedAppIds); + String endpoint = generateNodeControllerEndpointFromConfig(conf); + + registerService(endpoint, body); + } + + + public static void registerService(String endpoint, String body) { boolean connected = false; while (!connected) { - LOG.info("Trying to register pipeline element container at node controller: " + makeRegistrationEndpoint()); - String body = createSvcBody(svcName, svcId, host, port, tag, supportedAppIds); - connected = registerSvcHttpClient(body); + + connected = registerSvcHttpClient(endpoint, body); if (!connected) { LOG.info("Retrying in 5 seconds"); @@ -67,20 +78,20 @@ public class NodeControllerUtil { } } } - LOG.info("Successfully registered pipeline element container: " + svcId); + LOG.info("Successfully registered pipeline element container at: {}", endpoint); } - private static boolean registerSvcHttpClient(String body) { - String endpoint = makeRegistrationEndpoint(); + private static boolean registerSvcHttpClient(String endpoint, String body) { + LOG.info("Trying to register pipeline element container at node controller: {}", endpoint); try { - Request.Post(makeRegistrationEndpoint()) + Request.Post(endpoint) .bodyString(body, ContentType.APPLICATION_JSON) .connectTimeout(1000) .socketTimeout(100000) .execute(); return true; } catch (IOException e) { - LOG.error("Could not register at " + endpoint); + LOG.error("Could not register at {}", endpoint); } return false; } @@ -109,22 +120,27 @@ public class NodeControllerUtil { throw new IllegalArgumentException("Failure"); } - private static String makeRegistrationEndpoint() { - if (System.getenv(NODE_CONTROLLER_CONTAINER_HOST) != null) { - return HTTP_PROTOCOL - + System.getenv(NODE_CONTROLLER_CONTAINER_HOST) - + COLON - + System.getenv(NODE_CONTROLLER_CONTAINER_PORT) - + SLASH - + NODE_CONTROLLER_REGISTER_SVC_URL; + private static String generateNodeControllerEndpointFromConfig(EdgeExtensionsConfig conf) { + return HTTP_PROTOCOL + + conf.getNodeControllerHost() + + COLON + + conf.getNodeControllerPort() + + SLASH + + NODE_CONTROLLER_REGISTER_SVC_URL; + } + + private static String generateNodeControllerEndpointFromEnv() { + String host = ""; + if ("true".equals(System.getenv("SP_DEBUG"))) { + try { + host = InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + throw new RuntimeException("Could not retrieve host IP", e); + } } else { - return HTTP_PROTOCOL - + "localhost" - + COLON - + "7077" - + SLASH - + NODE_CONTROLLER_REGISTER_SVC_URL; + host = "streampipes-node-controller"; } + return HTTP_PROTOCOL + host + COLON + 7077 + SLASH + NODE_CONTROLLER_REGISTER_SVC_URL; } private static String makeSvcId(String host, String serviceID) { diff --git a/streampipes-model/src/main/java/org/apache/streampipes/model/node/NodeInfoDescription.java b/streampipes-model/src/main/java/org/apache/streampipes/model/node/NodeInfoDescription.java index a41db8c..182abe6 100644 --- a/streampipes-model/src/main/java/org/apache/streampipes/model/node/NodeInfoDescription.java +++ b/streampipes-model/src/main/java/org/apache/streampipes/model/node/NodeInfoDescription.java @@ -146,6 +146,14 @@ public class NodeInfoDescription extends UnnamedStreamPipesEntity { this.registeredContainers = registeredContainers; } + public void addRegisteredContainer(DeploymentContainer registeredContainer) { + this.registeredContainers.add(registeredContainer); + } + + public void removeRegisteredContainer(DeploymentContainer registeredContainer) { + this.registeredContainers.remove(registeredContainer); + } + public String getNodeControllerId() { return nodeControllerId; } diff --git a/streampipes-model/src/main/java/org/apache/streampipes/model/pipeline/PipelineElementReconfigurationEntity.java b/streampipes-model/src/main/java/org/apache/streampipes/model/pipeline/PipelineElementReconfigurationEntity.java new file mode 100644 index 0000000..e6efba8 --- /dev/null +++ b/streampipes-model/src/main/java/org/apache/streampipes/model/pipeline/PipelineElementReconfigurationEntity.java @@ -0,0 +1,105 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.streampipes.model.pipeline; + +import org.apache.streampipes.model.staticproperty.StaticProperty; + +import java.util.ArrayList; +import java.util.List; + +public class PipelineElementReconfigurationEntity { + + private String deploymentRunningInstanceId; + private String pipelineElementName; + private String deploymentTargetNodeId; + private String deploymentTargetNodeHostname; + private Integer deploymentTargetNodePort; + private List<StaticProperty> reconfiguredStaticProperties; + + public PipelineElementReconfigurationEntity() { + this.reconfiguredStaticProperties = new ArrayList<>(); + } + + public PipelineElementReconfigurationEntity(String deploymentRunningInstanceId, + String pipelineElementName, String deploymentTargetNodeId, + String deploymentTargetNodeHostname, Integer deploymentTargetNodePort, + List<StaticProperty> reconfiguredStaticProperties) { + this.deploymentRunningInstanceId = deploymentRunningInstanceId; + this.pipelineElementName = pipelineElementName; + this.deploymentTargetNodeId = deploymentTargetNodeId; + this.deploymentTargetNodeHostname = deploymentTargetNodeHostname; + this.deploymentTargetNodePort = deploymentTargetNodePort; + this.reconfiguredStaticProperties = reconfiguredStaticProperties; + } + + public String getDeploymentRunningInstanceId() { + return deploymentRunningInstanceId; + } + + public void setDeploymentRunningInstanceId(String deploymentRunningInstanceId) { + this.deploymentRunningInstanceId = deploymentRunningInstanceId; + } + + public String getPipelineElementName() { + return pipelineElementName; + } + + public void setPipelineElementName(String pipelineElementName) { + this.pipelineElementName = pipelineElementName; + } + + public String getDeploymentTargetNodeId() { + return deploymentTargetNodeId; + } + + public void setDeploymentTargetNodeId(String deploymentTargetNodeId) { + this.deploymentTargetNodeId = deploymentTargetNodeId; + } + + public String getDeploymentTargetNodeHostname() { + return deploymentTargetNodeHostname; + } + + public void setDeploymentTargetNodeHostname(String deploymentTargetNodeHostname) { + this.deploymentTargetNodeHostname = deploymentTargetNodeHostname; + } + + public Integer getDeploymentTargetNodePort() { + return deploymentTargetNodePort; + } + + public void setDeploymentTargetNodePort(Integer deploymentTargetNodePort) { + this.deploymentTargetNodePort = deploymentTargetNodePort; + } + + public List<StaticProperty> getReconfiguredStaticProperties() { + return reconfiguredStaticProperties; + } + + public void setReconfiguredStaticProperties(List<StaticProperty> reconfiguredStaticProperties) { + this.reconfiguredStaticProperties = reconfiguredStaticProperties; + } + + public void addReconfiguredStaticProperties(StaticProperty reconfiguredStaticProperty) { + this.reconfiguredStaticProperties.add(reconfiguredStaticProperty); + } + + public void removeReconfiguredStaticProperties(StaticProperty reconfiguredStaticProperty){ + this.reconfiguredStaticProperties.remove(reconfiguredStaticProperty); + } +} diff --git a/streampipes-model/src/main/java/org/apache/streampipes/model/staticproperty/FreeTextStaticProperty.java b/streampipes-model/src/main/java/org/apache/streampipes/model/staticproperty/FreeTextStaticProperty.java index 000e635..4413ea9 100644 --- a/streampipes-model/src/main/java/org/apache/streampipes/model/staticproperty/FreeTextStaticProperty.java +++ b/streampipes-model/src/main/java/org/apache/streampipes/model/staticproperty/FreeTextStaticProperty.java @@ -59,6 +59,9 @@ public class FreeTextStaticProperty extends StaticProperty { @RdfProperty(StreamPipes.PLACEHOLDERS_SUPPORTED) private boolean placeholdersSupported; + @RdfProperty(StreamPipes.IS_RECONFIGURABLE) + private boolean reconfigurable; + @OneToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) @RdfProperty(StreamPipes.HAS_VALUE_SPECIFICATION) @@ -81,6 +84,7 @@ public class FreeTextStaticProperty extends StaticProperty { this.multiLine = other.isMultiLine(); this.placeholdersSupported = other.isPlaceholdersSupported(); this.mapsTo = other.getMapsTo(); + this.reconfigurable = other.isReconfigurable(); } public FreeTextStaticProperty(String internalName, String label, String description) { @@ -175,6 +179,14 @@ public class FreeTextStaticProperty extends StaticProperty { this.mapsTo = mapsTo; } + public boolean isReconfigurable() { + return reconfigurable; + } + + public void setReconfigurable(boolean reconfigurable) { + this.reconfigurable = reconfigurable; + } + @Override public void accept(StaticPropertyVisitor visitor) { visitor.visit(this); diff --git a/streampipes-node-controller-container/Dockerfile b/streampipes-node-controller-container/Dockerfile index 69a47fc..6b85e42 100644 --- a/streampipes-node-controller-container/Dockerfile +++ b/streampipes-node-controller-container/Dockerfile @@ -17,6 +17,8 @@ ARG BASE_IMAGE=adoptopenjdk/openjdk8-openj9:alpine-slim #ARG BASE_IMAGE=adoptopenjdk:8-jre-openj9 FROM $BASE_IMAGE +MAINTAINER [email protected] + EXPOSE 7077 ENV CONSUL_LOCATION consul diff --git a/streampipes-node-controller-container/aarch64.Dockerfile b/streampipes-node-controller-container/aarch64.Dockerfile index cd32813..49836fa 100644 --- a/streampipes-node-controller-container/aarch64.Dockerfile +++ b/streampipes-node-controller-container/aarch64.Dockerfile @@ -16,9 +16,10 @@ ARG BASE_IMAGE=arm64v8/openjdk:11-jre-slim FROM $BASE_IMAGE -ENV CONSUL_LOCATION consul +MAINTAINER [email protected] EXPOSE 7077 +ENV CONSUL_LOCATION consul COPY qemu-aarch64-static /usr/bin RUN set -ex; \ diff --git a/streampipes-node-controller-container/arm.Dockerfile b/streampipes-node-controller-container/arm.Dockerfile index 5a69a15..db71c93 100644 --- a/streampipes-node-controller-container/arm.Dockerfile +++ b/streampipes-node-controller-container/arm.Dockerfile @@ -16,9 +16,10 @@ ARG BASE_IMAGE=arm32v7/openjdk:11-jre-slim FROM $BASE_IMAGE -ENV CONSUL_LOCATION consul +MAINTAINER [email protected] EXPOSE 7077 +ENV CONSUL_LOCATION consul COPY qemu-arm-static /usr/bin RUN set -ex; \ diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/NodeControllerInit.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/NodeControllerInit.java index ca50136..2a3890f 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/NodeControllerInit.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/NodeControllerInit.java @@ -18,7 +18,6 @@ package org.apache.streampipes.node.controller.container; import org.apache.streampipes.commons.exceptions.SpRuntimeException; -import org.apache.streampipes.container.util.ConsulUtil; import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerContainerManager; import org.apache.streampipes.node.controller.container.api.NodeControllerResourceConfig; import org.apache.streampipes.node.controller.container.config.NodeControllerConfig; @@ -51,6 +50,11 @@ public class NodeControllerInit { app.setDefaultProperties(Collections.singletonMap("server.port", conf.getNodeControllerPort())); app.run(); + LOG.info("Configured environment variables"); + System.getenv().entrySet().stream() + .filter(e -> e.getKey().startsWith("SP_")) + .forEach(System.out::println); + LOG.info("Load node info description"); NodeManager.getInstance().init(); @@ -68,13 +72,6 @@ public class NodeControllerInit { LOG.info("Start janitor manager"); JanitorManager.getInstance().run(); } - - // registration with consul here - ConsulUtil.registerNodeService( - conf.getNodeServiceId(), - conf.getNodeHostName(), - conf.getNodeControllerPort() - ); } else throw new SpRuntimeException("Could not register node controller at backend"); } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/ContainerDeploymentResource.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/ContainerDeploymentResource.java index b6899df..69809e7 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/ContainerDeploymentResource.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/ContainerDeploymentResource.java @@ -18,6 +18,9 @@ package org.apache.streampipes.node.controller.container.api; import org.apache.streampipes.model.node.container.DockerContainer; +import org.apache.streampipes.node.controller.container.management.node.NodeManager; +import org.apache.streampipes.node.controller.container.management.orchestrator.ContainerDeploymentStatus; +import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerConstants; import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerContainerManager; import org.apache.streampipes.node.controller.container.management.pe.InvocableElementManager; @@ -37,14 +40,24 @@ public class ContainerDeploymentResource extends AbstractResource { @Path("/deploy") @Consumes(MediaType.APPLICATION_JSON) public javax.ws.rs.core.Response deployPipelineElementContainer(DockerContainer container) { - return ok(DockerContainerManager.getInstance().deploy(container)); + ContainerDeploymentStatus status = DockerContainerManager.getInstance().deploy(container); + + if (status.getStatus() == DockerConstants.ContainerStatus.DEPLOYED) { + NodeManager.getInstance().addToRegisteredContainers(status.getContainer()); + } + return ok(status); } @DELETE @Path("/remove") @Consumes(MediaType.APPLICATION_JSON) public javax.ws.rs.core.Response removePipelineElementContainer(DockerContainer container) { - InvocableElementManager.getInstance().unregister(); - return ok(DockerContainerManager.getInstance().remove(container)); + ContainerDeploymentStatus status = DockerContainerManager.getInstance().remove(container); + + if (status.getStatus() == DockerConstants.ContainerStatus.REMOVED) { + InvocableElementManager.getInstance().unregister(); + NodeManager.getInstance().removeFromRegisteredContainers(status.getContainer()); + } + return ok(status); } } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/InvocableEntityResource.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/InvocableEntityResource.java index 7ba5233..8397373 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/InvocableEntityResource.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/api/InvocableEntityResource.java @@ -69,18 +69,17 @@ public class InvocableEntityResource extends AbstractResource { if (elementResponse.isSuccess()) { RunningInvocableInstances.INSTANCE.add(graph.getDeploymentRunningInstanceId(), graph); } + return ok(elementResponse); - } - // Currently no data sinks are registered at node controller. If we, at some point, want to also run data - // sinks on edge nodes we need to register there Declarer at the node controller one startup. - else if (identifier.equals(DATA_SINK_PREFIX)) { + + } else if (identifier.equals(DATA_SINK_PREFIX)) { Response elementResponse = InvocableElementManager.getInstance().invoke(graph); if (elementResponse.isSuccess()) { RunningInvocableInstances.INSTANCE.add(graph.getDeploymentRunningInstanceId(), graph); } + return ok(elementResponse); } - return ok(); } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/ConfigKeys.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/ConfigKeys.java index 0c4e534..00d3091 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/ConfigKeys.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/ConfigKeys.java @@ -18,13 +18,25 @@ package org.apache.streampipes.node.controller.container.config; public class ConfigKeys { + // required + public static final String SP_URL = "SP_URL"; + public static final String SP_NODE_CONTROLLER_URL = "SP_NODE_CONTROLLER_URL"; + public static final String SP_API_KEY = "SP_API_KEY"; + public static final String NODE_TYPE = "SP_NODE_TYPE"; public static final String NODE_HOST = "SP_NODE_HOST"; + public static final String NODE_CONTROLLER_ID = "SP_NODE_CONTROLLER_ID"; public static final String NODE_CONTROLLER_CONTAINER_HOST = "SP_NODE_CONTROLLER_CONTAINER_HOST"; public static final String NODE_CONTROLLER_CONTAINER_PORT = "SP_NODE_CONTROLLER_CONTAINER_PORT"; + public static final String NODE_BROKER_CONTAINER_HOST = "SP_NODE_BROKER_CONTAINER_HOST"; public static final String NODE_BROKER_CONTAINER_PORT = "SP_NODE_BROKER_CONTAINER_PORT"; + + public static final String BACKEND_HOST = "SP_BACKEND_HOST"; + public static final String BACKEND_PORT = "SP_BACKEND_PORT"; + + // optional public static final String NODE_LOCATION = "SP_NODE_LOCATION"; public static final String NODE_HAS_GPU = "SP_NODE_HAS_GPU"; public static final String NODE_GPU_CUDA_CORES = "SP_NODE_GPU_CUDA_CORES"; @@ -35,6 +47,4 @@ public class ConfigKeys { public static final String RESOURCE_UPDATE_FREQ_SECS = "SP_NODE_RESOURCE_UPDATE_FREQ_SECS"; public static final String EVENT_BUFFER_SIZE = "SP_NODE_EVENT_BUFFER_SIZE"; public static final String SP_VERSION = "SP_VERSION"; - public static final String BACKEND_HOST = "SP_BACKEND_HOST"; - public static final String BACKEND_PORT = "SP_BACKEND_PORT"; } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/NodeControllerConfig.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/NodeControllerConfig.java index 9937254..9a9f6e8 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/NodeControllerConfig.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/config/NodeControllerConfig.java @@ -20,8 +20,10 @@ package org.apache.streampipes.node.controller.container.config; import org.apache.streampipes.config.SpConfig; import org.apache.streampipes.model.node.resources.fielddevice.FieldDeviceAccessResource; -import java.util.Arrays; +import java.net.MalformedURLException; +import java.net.URL; import java.util.List; +import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -31,34 +33,66 @@ public enum NodeControllerConfig { private SpConfig config; private static final String SLASH = "/"; + private static final String NODE_SERVICE_ID = "node/org.apache.streampipes.node.controller"; - private static final String DEFAULT_NODE_CONTROLLER_ID = "node-controller"; + + // Default hosts: accessible host (IP/DNS) for physical host, node controller, core + private static final String DEFAULT_NODE_HOST = "host.docker.internal"; + private static final String DEFAULT_NODE_CONTROLLER_HOST = "streampipes-node-controller"; + private static final String DEFAULT_NODE_BROKER_HOST = "streampipes-node-broker"; + private static final String DEFAULT_BACKEND_HOST = "host.docker.internal"; + + // Default ports: service endpoint ports private static final int DEFAULT_NODE_CONTROLLER_PORT = 7077; - private static final String DEFAULT_NODE_TYPE = "edge"; - private static final String DEFAULT_NODE_BROKER_HOST = "broker"; private static final int DEFAULT_NODE_BROKER_PORT = 1883; - private static final String DEFAULT_NODE_HOST_NAME = "host.docker.internal"; - private static final String DEFAULT_BACKEND_HOST = "host.docker.internal"; private static final int DEFAULT_BACKEND_PORT = 8030; - // Node controller configs + // Default configurations: Node controller configs private static final int DEFAULT_DOCKER_PRUNING_FREQ_SECS = 3600; private static final int DEFAULT_NODE_RESOURCE_UPDATE_FREQ_SECS = 30; private static final int DEFAULT_EVENT_BUFFER_SIZE = 1000; + private static final String DEFAULT_NODE_CONTROLLER_ID = "nodectlr"; + private static final String DEFAULT_NODE_TYPE = "edge"; NodeControllerConfig() { - config = SpConfig.getSpConfig(NODE_SERVICE_ID + SLASH + getNodeHostName()); - - config.register(ConfigKeys.NODE_HOST, DEFAULT_NODE_HOST_NAME, "node host name"); - config.register(ConfigKeys.NODE_TYPE, DEFAULT_NODE_TYPE, "node type"); - config.register(ConfigKeys.NODE_CONTROLLER_ID, DEFAULT_NODE_CONTROLLER_ID, "node controller id"); - config.register(ConfigKeys.NODE_CONTROLLER_CONTAINER_HOST, DEFAULT_NODE_CONTROLLER_ID, "node controller container host"); - config.register(ConfigKeys.NODE_CONTROLLER_CONTAINER_PORT, DEFAULT_NODE_CONTROLLER_PORT, "node controller port"); - config.register(ConfigKeys.NODE_BROKER_CONTAINER_HOST, DEFAULT_NODE_BROKER_HOST, "node broker host"); - config.register(ConfigKeys.NODE_BROKER_CONTAINER_PORT, DEFAULT_NODE_BROKER_PORT, "node broker port"); + config = SpConfig.getSpConfig(makeServiceId()); + + config.register(ConfigKeys.NODE_HOST, + checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_HOST, DEFAULT_NODE_HOST, String.class), + "node host name"); + config.register(ConfigKeys.NODE_TYPE, DEFAULT_NODE_TYPE, + "node type"); + config.register(ConfigKeys.NODE_CONTROLLER_ID, DEFAULT_NODE_CONTROLLER_ID, + "node controller id"); + config.register(ConfigKeys.NODE_CONTROLLER_CONTAINER_HOST, + checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_CONTROLLER_CONTAINER_HOST, DEFAULT_NODE_CONTROLLER_HOST, String.class), + "node controller container host"); + config.register(ConfigKeys.NODE_CONTROLLER_CONTAINER_PORT, + checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_CONTROLLER_CONTAINER_PORT, DEFAULT_NODE_CONTROLLER_PORT, Integer.class), + "node controller port"); + config.register(ConfigKeys.NODE_BROKER_CONTAINER_HOST, + checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_BROKER_CONTAINER_HOST, DEFAULT_NODE_BROKER_HOST, String.class), + "node broker host"); + config.register(ConfigKeys.NODE_BROKER_CONTAINER_PORT, + DEFAULT_NODE_BROKER_PORT, + "node broker port"); // currently used for connect adapter registration - config.register(ConfigKeys.BACKEND_HOST, DEFAULT_BACKEND_HOST, "backend host"); - config.register(ConfigKeys.BACKEND_PORT, DEFAULT_BACKEND_PORT, "backend port"); + config.register(ConfigKeys.BACKEND_HOST, + checkSpUrlOrElseDefault(ConfigKeys.BACKEND_HOST, DEFAULT_BACKEND_HOST, String.class), + "backend host"); + config.register(ConfigKeys.BACKEND_PORT, + checkSpUrlOrElseDefault(ConfigKeys.BACKEND_PORT, DEFAULT_BACKEND_PORT, Integer.class), + "backend port"); + } + + private String makeServiceId() { + return NODE_SERVICE_ID + SLASH + checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_CONTROLLER_CONTAINER_HOST, + DEFAULT_NODE_CONTROLLER_HOST, String.class); + } + + private String checkForNodeControllerIdPrefixOrUseDefault() { + String prefix = getEnvOrDefault(ConfigKeys.NODE_CONTROLLER_ID, DEFAULT_NODE_CONTROLLER_ID, String.class); + return prefix + "-" + generateSixDigitShortUUID(); } public String getNodeServiceId() { @@ -69,37 +103,30 @@ public enum NodeControllerConfig { return getEnvOrDefault(ConfigKeys.SP_VERSION, "", String.class); } - public String getNodeHostName(){ - return getEnvOrDefault(ConfigKeys.NODE_HOST, - DEFAULT_NODE_HOST_NAME, - String.class); + public String getNodeHost(){ + return checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_HOST, DEFAULT_NODE_HOST, String.class); } public String getNodeControllerId() { - return getEnvOrDefault(ConfigKeys.NODE_CONTROLLER_ID, - DEFAULT_NODE_CONTROLLER_ID, - String.class); + return getEnvOrDefault( + ConfigKeys.NODE_CONTROLLER_ID, + DEFAULT_NODE_CONTROLLER_ID, String.class); } public int getNodeControllerPort(){ - return getEnvOrDefault( - ConfigKeys.NODE_CONTROLLER_CONTAINER_PORT, - DEFAULT_NODE_CONTROLLER_PORT, - Integer.class); + return checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_CONTROLLER_CONTAINER_PORT, + DEFAULT_NODE_CONTROLLER_PORT, Integer.class); } public String getNodeBrokerHost() { - return getEnvOrDefault( - ConfigKeys.NODE_BROKER_CONTAINER_HOST, - DEFAULT_NODE_BROKER_HOST, + return checkSpNodeControllerUrlOrElseDefault(ConfigKeys.NODE_BROKER_CONTAINER_HOST, DEFAULT_NODE_BROKER_HOST, String.class); } public int getNodeBrokerPort() { return getEnvOrDefault( ConfigKeys.NODE_BROKER_CONTAINER_PORT, - DEFAULT_NODE_BROKER_PORT, - Integer.class); + DEFAULT_NODE_BROKER_PORT, Integer.class); } public List<String> getNodeLocations() { @@ -184,18 +211,57 @@ public enum NodeControllerConfig { String.class); } - public String getBackendHost() { - return getEnvOrDefault( - ConfigKeys.BACKEND_HOST, - DEFAULT_BACKEND_HOST, + public String getApiKey() { + String apiKey = getEnvOrDefault( + ConfigKeys.SP_API_KEY, + "", String.class); + if (!apiKey.isEmpty()) { + return apiKey; + } + throw new RuntimeException("StreamPipes API key not provided"); } - public int getBackendPort(){ - return getEnvOrDefault( - ConfigKeys.BACKEND_PORT, - DEFAULT_BACKEND_PORT, - Integer.class); + public String consulLocation() { + return checkSpUrlOrElseDefault("CONSUL_LOCATION", "consul", + String.class); + } + + public String backendLocation() { + return checkSpUrlOrElseDefault(ConfigKeys.BACKEND_HOST, DEFAULT_BACKEND_HOST, String.class); + } + + public int backendPort() { + return checkSpUrlOrElseDefault(ConfigKeys.BACKEND_PORT, DEFAULT_BACKEND_PORT, Integer.class); + } + + // Helpers + + public <T>T checkSpNodeControllerUrlOrElseDefault(String key, T defaultValue, Class<T> type) { + return checkEnvOrElseDefault(ConfigKeys.SP_NODE_CONTROLLER_URL, key, defaultValue, type); + } + + public <T>T checkSpUrlOrElseDefault(String key, T defaultValue, Class<T> type) { + return checkEnvOrElseDefault(ConfigKeys.SP_URL, key, defaultValue, type); + } + + private <T>T checkEnvOrElseDefault(String envUrl, String defaultKey, T defaultValue, Class<T> type) { + T result = null; + if (System.getenv(envUrl) != null) { + try { + URL url = new URL(System.getenv(envUrl)); + if (type.equals(String.class)) { + result = (T) url.getHost(); + } else if (type.equals(Integer.class)) { + result = (T) Integer.valueOf(url.getPort()); + } + } catch (MalformedURLException e) { + throw new RuntimeException("Could not parse provide URL:", e); + } + } else { + result = getEnvOrDefault(defaultKey, defaultValue, type); + } + return result; } private <T> T getEnvOrDefault(String k, T defaultValue, Class<T> type) { @@ -207,4 +273,9 @@ public enum NodeControllerConfig { return System.getenv(k) != null ? type.cast(System.getenv(k)) : defaultValue; } } + + private String generateSixDigitShortUUID() { + String uuid = UUID.randomUUID().toString(); + return uuid.substring(uuid.lastIndexOf('-') + 6); + } } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/connect/ConnectManager.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/connect/ConnectManager.java index 0756e1b..8063b13 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/connect/ConnectManager.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/connect/ConnectManager.java @@ -32,6 +32,7 @@ import org.apache.streampipes.model.connect.guess.GuessSchema; import org.apache.streampipes.model.connect.worker.ConnectWorkerContainer; import org.apache.streampipes.model.runtime.RuntimeOptionsRequest; import org.apache.streampipes.node.controller.container.config.NodeControllerConfig; +import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerConstants; import org.apache.streampipes.serializers.json.JacksonSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,15 +46,15 @@ public class ConnectManager { private static final String HTTP_PROTOCOL = "http://"; private static final String COLON = ":"; private static final String SLASH = "/"; - private static final String BACKEND_HOST = NodeControllerConfig.INSTANCE.getBackendHost(); - private static final int BACKEND_PORT = NodeControllerConfig.INSTANCE.getBackendPort(); + private static final String BACKEND_HOST = NodeControllerConfig.INSTANCE.backendLocation(); + private static final int BACKEND_PORT = NodeControllerConfig.INSTANCE.backendPort(); private static final String BACKEND_ADMINISTRATION_ROUTE = "/streampipes-backend/api/v2/connect/{username}/master" + "/administration"; // Connect adapter base route // TODO: get from registered extensions or connect adapater config - private static final String CONNECT_WORKER_HOST = "localhost"; - private static final int CONNECT_WORKER_PORT = 7024; + private static final String CONNECT_WORKER_HOST = DockerConstants.SP_CONTAINER_EXTENSIONS_NAME; + private static final int CONNECT_WORKER_PORT = 8090; private static final String CONNECT_WORKER_BASE_ROUTE = "/api/v1/{username}/worker"; private static final String STREAM_ROUTE = "/stream"; private static final String SET_ROUTE = "/set"; @@ -62,7 +63,7 @@ public class ConnectManager { private static final String GUESS_ROUTE = "/guess/schema"; private static final String RESOLVABLE_ROUTE = "/resolvable/{id}/configurations"; private static final String ADAPTER_ROUTE = "/adapters/{id}/assets"; - private static final String PROCOTOL_ROUTE = "/protocols/{id}/assets"; + private static final String PROTOCOL_ROUTE = "/protocols/{id}/assets"; private static final Integer CONNECT_TIMEOUT = 10000; private static final Integer SOCKET_TIMEOUT = 100000; @@ -145,9 +146,9 @@ public class ConnectManager { } } else if ("protocol".equals(assetType)) { if (subroute.isEmpty()) { - endpoint = endpointFromStringRoute(username, PROCOTOL_ROUTE.replace("{id}", appId)); + endpoint = endpointFromStringRoute(username, PROTOCOL_ROUTE.replace("{id}", appId)); } else { - endpoint = endpointFromStringRoute(username, (PROCOTOL_ROUTE.replace("{id}", appId) + subroute)); + endpoint = endpointFromStringRoute(username, (PROTOCOL_ROUTE.replace("{id}", appId) + subroute)); } } return get(endpoint); @@ -215,6 +216,9 @@ public class ConnectManager { } private String workerUrl() { + if("true".equals(System.getenv("SP_DEBUG"))) { + return HTTP_PROTOCOL + "localhost" + COLON + "7024"; + } return HTTP_PROTOCOL + CONNECT_WORKER_HOST + COLON + CONNECT_WORKER_PORT; } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeConstants.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeConstants.java index 98d4425..4c04463 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeConstants.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeConstants.java @@ -28,7 +28,7 @@ import org.apache.streampipes.model.node.resources.hardware.DISK; import org.apache.streampipes.model.node.resources.hardware.GPU; import org.apache.streampipes.model.node.resources.hardware.MEM; import org.apache.streampipes.node.controller.container.config.NodeControllerConfig; -import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerInfo; +import org.apache.streampipes.node.controller.container.management.orchestrator.docker.model.DockerInfo; import org.apache.streampipes.node.controller.container.management.orchestrator.docker.utils.DockerUtils; import oshi.SystemInfo; import oshi.hardware.ComputerSystem; @@ -54,7 +54,7 @@ public class NodeConstants { // accessible node constants public static final String NODE_CONTROLLER_ID = NodeControllerConfig.INSTANCE.getNodeControllerId(); - public static final String NODE_HOSTNAME = NodeControllerConfig.INSTANCE.getNodeHostName(); + public static final String NODE_HOSTNAME = NodeControllerConfig.INSTANCE.getNodeHost(); public static final int NODE_PORT = NodeControllerConfig.INSTANCE.getNodeControllerPort(); public static final String NODE_BROKER_HOST = NodeControllerConfig.INSTANCE.getNodeBrokerHost(); public static final int NODE_BROKER_PORT = NodeControllerConfig.INSTANCE.getNodeBrokerPort(); @@ -75,7 +75,6 @@ public class NodeConstants { public static final DISK NODE_DISK = getNodeDisk(); public static final GPU NODE_GPU = getNodeGpu(); - private static List<DeploymentContainer> getRegisteredDockerContainer() { List<DeploymentContainer> containers = new ArrayList<>(); DockerUtils.getInstance().getRunningStreamPipesContainer() diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeManager.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeManager.java index 0f01751..dac74c2 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeManager.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/node/NodeManager.java @@ -20,11 +20,13 @@ package org.apache.streampipes.node.controller.container.management.node; import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Response; import org.apache.http.entity.ContentType; +import org.apache.streampipes.model.client.version.VersionInfo; import org.apache.streampipes.model.message.Message; import org.apache.streampipes.model.message.NotificationType; import org.apache.streampipes.model.message.Notifications; import org.apache.streampipes.model.message.SuccessMessage; import org.apache.streampipes.model.node.*; +import org.apache.streampipes.model.node.container.DockerContainer; import org.apache.streampipes.model.node.meta.GeoLocation; import org.apache.streampipes.node.controller.container.config.NodeControllerConfig; import org.apache.streampipes.serializers.json.JacksonSerializer; @@ -40,7 +42,9 @@ public class NodeManager { private static final String SLASH = "/"; private static final String COLON = ":"; private static final String BACKEND_BASE_ROUTE = "/streampipes-backend"; + private static final String BACKEND_VERSION_ROUTE = "/api/v2/info/versions"; private static final String NODE_REGISTRATION_ROUTE = "/api/v2/users/[email protected]/nodes"; + private static final String NODE_SYNC_UPDATE_ROUTE = "/api/v2/users/[email protected]/nodes/sync"; private static final long RETRY_INTERVAL_MS = 5000; private static final int CONNECT_TIMEOUT_MS = 10000; @@ -94,13 +98,47 @@ public class NodeManager { add(nodeInfoDescription); } + public Message updateNodeInfoDescription(NodeInfoDescription desc) { + LOG.info("Update node description for node controller: {}", desc.getNodeControllerId()); + this.nodeInfo = desc; + return Notifications.success(NotificationType.OPERATION_SUCCESS); + } + + public Message activate() { + LOG.info("Activate node controller"); + this.nodeInfo.setActive(true); + return Notifications.success(NotificationType.OPERATION_SUCCESS); + } + + public Message deactivate() { + LOG.info("Deactivate node controller"); + this.nodeInfo.setActive(false); + return Notifications.success(NotificationType.OPERATION_SUCCESS); + } + + public void addToRegisteredContainers(DockerContainer container) { + if(!registered(container)) { + this.nodeInfo.addRegisteredContainer(container); + syncWithNodeClusterManager(); + } + } + + public void removeFromRegisteredContainers(DockerContainer container) { + if(registered(container)) { + this.nodeInfo.removeRegisteredContainer(container); + syncWithNodeClusterManager(); + } + } + + // Interactions with core + public boolean register() { boolean connected = false; try { String body = JacksonSerializer.getObjectMapper().writeValueAsString(this.nodeInfo); - String endpoint = generateEndpoint(); + String endpoint = generateRegistrationEndpoint(); - LOG.info("Trying to register node at backend: " + endpoint); + LOG.info("Trying to register node at node management: " + endpoint); while (!connected) { connected = post(endpoint, body); @@ -120,47 +158,115 @@ public class NodeManager { return connected; } - public Message updateNodeInfoDescription(NodeInfoDescription desc) { - LOG.info("Update node description for node controller: {}", desc.getNodeControllerId()); - this.nodeInfo = desc; - return Notifications.success(NotificationType.OPERATION_SUCCESS); + + private boolean syncWithNodeClusterManager() { + boolean connected = false; + try { + String body = JacksonSerializer.getObjectMapper().writeValueAsString(this.nodeInfo); + String endpoint = generateSyncronizationEndpoint(); + + LOG.info("Trying to sync node updates with node management: " + endpoint); + + while (!connected) { + connected = post(endpoint, body); + if (!connected) { + LOG.info("Retrying in {} seconds", (RETRY_INTERVAL_MS / 1000)); + try { + Thread.sleep(RETRY_INTERVAL_MS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + LOG.info("Successfully registered node at backend"); + } catch (IOException e) { + e.printStackTrace(); + } + return connected; } - public Message activate() { - LOG.info("Activate node controller"); - this.nodeInfo.setActive(true); - return Notifications.success(NotificationType.OPERATION_SUCCESS); + public String getStreamPipesVersion() { + boolean connected = false; + VersionInfo versionInfo = new VersionInfo(); + try { + String endpoint = generateVersionEndpoint(); + + LOG.info("Trying to fetch StreamPipes version from core: " + endpoint); + + while (!connected) { + Response response = get(endpoint); + versionInfo = deserialize(response, VersionInfo.class); + + if (versionInfo.getBackendVersion() != null) { + connected = true; + } + + if (!connected) { + LOG.info("Retrying in {} seconds", (RETRY_INTERVAL_MS / 1000)); + try { + Thread.sleep(RETRY_INTERVAL_MS); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + LOG.info("Successfully registered node at backend"); + } catch (IOException e) { + e.printStackTrace(); + } + return versionInfo.getBackendVersion(); } - public Message deactivate() { - LOG.info("Deactivate node controller"); - this.nodeInfo.setActive(false); - return Notifications.success(NotificationType.OPERATION_SUCCESS); + private Response get(String endpoint) throws IOException { + return Request.Get(endpoint) + .connectTimeout(CONNECT_TIMEOUT_MS) + .addHeader("Authorization", "Bearer " + NodeControllerConfig.INSTANCE.getApiKey()) + .execute(); } private boolean post(String endpoint, String body) throws IOException { Response response = Request.Post(endpoint) .bodyString(body, ContentType.APPLICATION_JSON) .connectTimeout(CONNECT_TIMEOUT_MS) + //.addHeader("Authorization", "Bearer " + NodeControllerConfig.INSTANCE.getApiKey()) .execute(); return handleResponse(response); } + // Helpers + + private boolean registered(DockerContainer container) { + return this.nodeInfo.getRegisteredContainers().contains(container); + } + private boolean handleResponse(Response response) throws IOException { - String resp = response.returnContent().asString(); - SuccessMessage message = JacksonSerializer - .getObjectMapper() - .readValue(resp, SuccessMessage.class); + SuccessMessage message = deserialize(response, SuccessMessage.class); LOG.info(message.getNotifications().get(0).getDescription()); return message.isSuccess(); } - private String generateEndpoint() { + private <T> T deserialize(Response response, Class<T> clazz) throws IOException { + String resp = response.returnContent().asString(); + return JacksonSerializer.getObjectMapper().readValue(resp, clazz); + } + + private String generateRegistrationEndpoint() { + return generateBaseEndpoint() + NODE_REGISTRATION_ROUTE; + } + + private String generateSyncronizationEndpoint() { + return generateBaseEndpoint() + NODE_SYNC_UPDATE_ROUTE; + } + + private String generateVersionEndpoint() { + return generateBaseEndpoint() + BACKEND_VERSION_ROUTE; + } + + private String generateBaseEndpoint() { return PROTOCOL - + NodeControllerConfig.INSTANCE.getBackendHost() + + NodeControllerConfig.INSTANCE.backendLocation() + COLON - + NodeControllerConfig.INSTANCE.getBackendPort() - + BACKEND_BASE_ROUTE - + NODE_REGISTRATION_ROUTE; + + NodeControllerConfig.INSTANCE.backendPort() + + BACKEND_BASE_ROUTE; } } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerDeploymentStatus.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerDeploymentStatus.java new file mode 100644 index 0000000..6e7ba29 --- /dev/null +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerDeploymentStatus.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.streampipes.node.controller.container.management.orchestrator; + +import org.apache.streampipes.model.node.container.DockerContainer; +import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerConstants; + +public class ContainerDeploymentStatus { + + private String containerId; + private DockerContainer container; + private long timestamp; + private DockerConstants.ContainerStatus status; + + public ContainerDeploymentStatus() { + } + + public ContainerDeploymentStatus(String containerId, DockerContainer container, long timestamp, + DockerConstants.ContainerStatus status) { + this.containerId = containerId; + this.container = container; + this.timestamp = timestamp; + this.status = status; + } + + public String getContainerId() { + return containerId; + } + + public void setContainerId(String containerId) { + this.containerId = containerId; + } + + public DockerContainer getContainer() { + return container; + } + + public void setContainer(DockerContainer container) { + this.container = container; + } + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public DockerConstants.ContainerStatus getStatus() { + return status; + } + + public void setStatus(DockerConstants.ContainerStatus status) { + this.status = status; + } +} diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerOrchestrator.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerOrchestrator.java index 0cb77a0..9fe151a 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerOrchestrator.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/ContainerOrchestrator.java @@ -23,9 +23,9 @@ public interface ContainerOrchestrator { void init(); - String deploy(DockerContainer p); + ContainerDeploymentStatus deploy(DockerContainer p); - String remove(DockerContainer p); + ContainerDeploymentStatus remove(DockerContainer p); String list(); diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerConstants.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerConstants.java index 3503069..6a54c93 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerConstants.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerConstants.java @@ -21,50 +21,54 @@ import org.apache.streampipes.model.node.container.DockerContainer; import org.apache.streampipes.model.node.container.DockerContainerBuilder; import org.apache.streampipes.node.controller.container.config.ConfigKeys; import org.apache.streampipes.node.controller.container.config.NodeControllerConfig; +import org.apache.streampipes.node.controller.container.management.node.NodeManager; import java.util.*; public class DockerConstants { - public static final String SP_DOCKER_CONTAINER_REPOSITORY = "apachestreampipes"; - public static final String SP_VERSION = NodeControllerConfig.INSTANCE.getSpVersion(); - public static final String SP_DOCKER_CONTAINER_NAME_PREFIX = "streampipes_"; - public static final String SP_DOCKER_NETWORK_NAME = "spnet"; + public static final String SP_VERSION = + !NodeControllerConfig.INSTANCE.getSpVersion().equals("") ? + NodeControllerConfig.INSTANCE.getSpVersion() : NodeManager.getInstance().getStreamPipesVersion(); + public static final String SP_CONTAINER_PREFIX = "streampipes-"; + public static final String SP_CONTAINER_NETWORK = "spnet"; // extensions container public static final String SP_EXTENSIONS_ID = "pe/org.apache.streampipes.extensions.all.jvm"; - public static final String SP_DOCKER_IMAGE_EXTENSIONS_NAME = "extensions-all-jvm"; - public static final String SP_DOCKER_CONTAINER_EXTENSIONS_IMG_TAG = SP_DOCKER_CONTAINER_REPOSITORY + - "/" + SP_DOCKER_IMAGE_EXTENSIONS_NAME + ":" + SP_VERSION; - public static final String SP_DOCKER_CONTAINER_EXTENSIONS_NAME = SP_DOCKER_CONTAINER_NAME_PREFIX + "extensions"; - public static final String[] SP_DOCKER_CONTAINER_EXTENSIONS_PORT = new String[]{"7025"}; + public static final String SP_IMG_EXTENSIONS = "apachestreampipes/extensions-all-jvm:" + SP_VERSION; + public static final String SP_CONTAINER_EXTENSIONS_NAME = SP_CONTAINER_PREFIX + "extensions"; + public static final String[] SP_CONTAINER_EXTENSIONS_PORT = new String[]{"8090"}; //broker container public static final String SP_BROKER_ID = "pe/org.apache.streampipes.node.broker"; - public static final String SP_DOCKER_IMAGE_BROKER_NAME = "eclipse-mosquitto"; - public static final String SP_DOCKER_IMAGE_BROKER_VERSION = "1.6.12"; - public static final String SP_DOCKER_CONTAINER_BROKER_IMG_TAG = - SP_DOCKER_IMAGE_BROKER_NAME + ":" + SP_DOCKER_IMAGE_BROKER_VERSION; - public static final String SP_DOCKER_CONTAINER_BROKER_NAME = SP_DOCKER_CONTAINER_NAME_PREFIX + "broker"; - public static final String[] SP_DOCKER_CONTAINER_BROKER_PORT = + public static final String SP_IMG_MOSQUITTO = "eclipse-mosquitto:1.6.12"; + public static final String SP_CONTAINER_BROKER_NAME = SP_CONTAINER_PREFIX + "node-broker"; + public static final String[] SP_CONTAINER_BROKER_PORT = System.getenv(ConfigKeys.NODE_BROKER_CONTAINER_PORT) != null ? new String[]{System.getenv(ConfigKeys.NODE_BROKER_CONTAINER_PORT)} : new String[]{"1883"}; - public static final List<String> SP_DOCKER_CONTAINER_ENV_VARIABLES = Arrays.asList( + // container env variables + public static final List<String> SP_CONTAINER_ENV_VARIABLES = Arrays.asList( ConfigKeys.NODE_CONTROLLER_ID + "=" + NodeControllerConfig.INSTANCE.getNodeControllerId(), - ConfigKeys.NODE_CONTROLLER_CONTAINER_HOST + "=" + NodeControllerConfig.INSTANCE.getNodeHostName(), + ConfigKeys.NODE_CONTROLLER_CONTAINER_HOST + "=" + NodeControllerConfig.INSTANCE.getNodeHost(), ConfigKeys.NODE_CONTROLLER_CONTAINER_PORT + "=" + NodeControllerConfig.INSTANCE.getNodeControllerPort(), ConfigKeys.NODE_BROKER_CONTAINER_HOST + "=" + NodeControllerConfig.INSTANCE.getNodeBrokerHost(), - ConfigKeys.NODE_BROKER_CONTAINER_PORT + "=" + NodeControllerConfig.INSTANCE.getNodeBrokerPort() + ConfigKeys.NODE_BROKER_CONTAINER_PORT + "=" + NodeControllerConfig.INSTANCE.getNodeBrokerPort(), + //TODO: remove once PE does not need it for KV registration + "CONSUL_LOCATION=" + NodeControllerConfig.INSTANCE.consulLocation(), + "SP_HOST=" + NodeControllerConfig.INSTANCE.getNodeHost(), + "SP_PORT=8090" ); - public static final Map<String, String> SP_DOCKER_CONTAINER_EXTENSIONS_LABELS = new HashMap<String, String>() {{ + // extension container labels + public static final Map<String, String> SP_CONTAINER_EXTENSIONS_LABELS = new HashMap<String, String>() {{ put("org.apache.streampipes.service.id", SP_EXTENSIONS_ID); put("org.apache.streampipes.node.type", NodeControllerConfig.INSTANCE.getNodeType()); put("org.apache.streampipes.container.type", "extensions"); }}; - public static final Map<String, String> SP_DOCKER_CONTAINER_BROKER_LABELS = new HashMap<String, String>() {{ + // mosquitto container labels + public static final Map<String, String> SP_CONTAINER_BROKER_LABELS = new HashMap<String, String>() {{ put("org.apache.streampipes.service.id", SP_BROKER_ID); put("org.apache.streampipes.node.type", NodeControllerConfig.INSTANCE.getNodeType()); put("org.apache.streampipes.container.type", "broker"); @@ -72,7 +76,7 @@ public class DockerConstants { public enum ContainerStatus { - DEPLOYED, RUNNING, STOPPED, REMOVED, UNKNOWN + DEPLOYED, RUNNING, STOPPED, REMOVED, UNKNOWN, FAILED } public enum ContainerType { @@ -87,20 +91,20 @@ public class DockerConstants { // Extensions container DockerContainer extensions = DockerContainerBuilder.create(SP_EXTENSIONS_ID) - .withImage(DockerConstants.SP_DOCKER_CONTAINER_EXTENSIONS_IMG_TAG) - .withName(DockerConstants.SP_DOCKER_CONTAINER_EXTENSIONS_NAME) - .withExposedPorts(DockerConstants.SP_DOCKER_CONTAINER_EXTENSIONS_PORT) - .withEnvironmentVariables(SP_DOCKER_CONTAINER_ENV_VARIABLES) - .withLabels(DockerConstants.SP_DOCKER_CONTAINER_EXTENSIONS_LABELS) + .withImage(DockerConstants.SP_IMG_EXTENSIONS) + .withName(DockerConstants.SP_CONTAINER_EXTENSIONS_NAME) + .withExposedPorts(DockerConstants.SP_CONTAINER_EXTENSIONS_PORT) + .withEnvironmentVariables(SP_CONTAINER_ENV_VARIABLES) + .withLabels(DockerConstants.SP_CONTAINER_EXTENSIONS_LABELS) .build(); // Node broker container DockerContainer nodeBroker = DockerContainerBuilder.create(SP_BROKER_ID) - .withImage(DockerConstants.SP_DOCKER_CONTAINER_BROKER_IMG_TAG) - .withName(DockerConstants.SP_DOCKER_CONTAINER_BROKER_NAME) - .withExposedPorts(DockerConstants.SP_DOCKER_CONTAINER_BROKER_PORT) - .withEnvironmentVariables(SP_DOCKER_CONTAINER_ENV_VARIABLES) - .withLabels(SP_DOCKER_CONTAINER_BROKER_LABELS) + .withImage(DockerConstants.SP_IMG_MOSQUITTO) + .withName(DockerConstants.SP_CONTAINER_BROKER_NAME) + .withExposedPorts(DockerConstants.SP_CONTAINER_BROKER_PORT) + .withEnvironmentVariables(SP_CONTAINER_ENV_VARIABLES) + .withLabels(SP_CONTAINER_BROKER_LABELS) .build(); nodeContainers.add(extensions); diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerContainerManager.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerContainerManager.java index bd64a4a..dea27b7 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerContainerManager.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerContainerManager.java @@ -17,7 +17,7 @@ */ package org.apache.streampipes.node.controller.container.management.orchestrator.docker; -import com.google.common.collect.ImmutableMap; +import com.fasterxml.jackson.core.JsonProcessingException; import com.google.gson.Gson; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.exceptions.NotFoundException; @@ -25,12 +25,14 @@ import com.spotify.docker.client.messages.Container; import org.apache.commons.lang.StringUtils; import org.apache.streampipes.container.util.ConsulUtil; import org.apache.streampipes.model.node.container.DockerContainer; +import org.apache.streampipes.node.controller.container.management.node.NodeManager; import org.apache.streampipes.node.controller.container.management.orchestrator.ContainerOrchestrator; +import org.apache.streampipes.node.controller.container.management.orchestrator.ContainerDeploymentStatus; import org.apache.streampipes.node.controller.container.management.orchestrator.docker.utils.DockerUtils; +import org.apache.streampipes.serializers.json.JacksonSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.Serializable; import java.util.*; public class DockerContainerManager implements ContainerOrchestrator { @@ -55,64 +57,55 @@ public class DockerContainerManager implements ContainerOrchestrator { @Override public void init() { - DockerConstants.NodeContainer.INSTANCE.getAllStreamPipesContainer().forEach(this::deploy); + DockerConstants.NodeContainer.INSTANCE.getAllStreamPipesContainer().forEach(container -> { + ContainerDeploymentStatus status = deploy(container); + + if (status.getStatus() == DockerConstants.ContainerStatus.DEPLOYED) { + NodeManager.getInstance().addToRegisteredContainers(status.getContainer()); + } + }); } @Override - public String deploy(DockerContainer p) { - LOG.info("Pull image and deploy pipeline element container {}", p.getImageUri()); + public ContainerDeploymentStatus deploy(DockerContainer container) { - Optional<Container> containerOptional = docker.getContainer(p.getContainerName()); + LOG.info("Pull image and deploy pipeline element container {}", container.getImageUri()); + Optional<Container> containerOptional = docker.getContainer(container.getContainerName()); if (!containerOptional.isPresent()) { - LOG.info("Deploy pipeline element container \"" + p.getImageUri() + "\""); + LOG.info("Deploy pipeline element container \"" + container.getImageUri() + "\""); String containerId = ""; try { - containerId = deployPipelineElementContainer(p); + containerId = deployPipelineElementContainer(container); } catch (Exception e) { LOG.error("Could not deploy pipeline element. {}", e.toString()); + return generateContainerStatus(containerId, container, DockerConstants.ContainerStatus.FAILED); } LOG.info("Finished pull image and deployed pipeline element container"); - ImmutableMap<String, ? extends Serializable> m = ImmutableMap.of( - "pipelineElementContainer", p.getContainerName(), - "containerId", containerId, - "status", DockerConstants.ContainerStatus.DEPLOYED - ); - return new Gson().toJson(m); + return generateContainerStatus(containerId, container, DockerConstants.ContainerStatus.DEPLOYED); } - LOG.info("Container already running {}", p.getContainerName()); - ImmutableMap<String, ? extends Serializable> m = ImmutableMap.of( - "message", "Pipeline element container already running", - "status", DockerConstants.ContainerStatus.RUNNING - ); - return new Gson().toJson(m); + LOG.info("Container already running {}", container.getContainerName()); + return generateContainerStatus(containerOptional.get().id(), container, DockerConstants.ContainerStatus.RUNNING); } @Override - public String remove(DockerContainer p) { - LOG.info("Remove pipeline element container: {}", p.getImageUri()); + public ContainerDeploymentStatus remove(DockerContainer container) { + LOG.info("Remove pipeline element container: {}", container.getImageUri()); - Optional<com.spotify.docker.client.messages.Container> containerOptional = docker.getContainer(p.getContainerName()); + Optional<com.spotify.docker.client.messages.Container> containerOptional = docker.getContainer(container.getContainerName()); if(containerOptional.isPresent()) { - docker.forceRemove(p.getContainerName()); + docker.forceRemove(container.getContainerName()); // deregister and delete kv pair in service in consul - ConsulUtil.deregisterService(p.getServiceId()); - ConsulUtil.deleteConfig(p.getServiceId()); - - ImmutableMap<String, ? extends Serializable> m = ImmutableMap.of( - "message", - "Pipeline element container removed", - "status", DockerConstants.ContainerStatus.REMOVED - ); - return new Gson().toJson(m); + ConsulUtil.deregisterService(container.getServiceId()); + ConsulUtil.deleteConfig(container.getServiceId()); + + return generateContainerStatus(containerOptional.get().id(), container, + DockerConstants.ContainerStatus.REMOVED); + } - ImmutableMap<String, ? extends Serializable> m = ImmutableMap.of( - "message", - "Pipeline element container does not exist", - "status", DockerConstants.ContainerStatus.UNKNOWN - ); - return new Gson().toJson(m); + return generateContainerStatus(containerOptional.get().id(), container, + DockerConstants.ContainerStatus.UNKNOWN); } @Override @@ -120,39 +113,55 @@ public class DockerContainerManager implements ContainerOrchestrator { LOG.info("List running pipeline element container"); List<Container> containerList = docker.getRunningStreamPipesContainer(); - HashMap<String, Object> m = new HashMap<>(); + HashMap<String, Object> containerJson = new HashMap<>(); if (containerList.size() > 0) { for (Container c: containerList) { - m.put("containerName", StringUtils.remove(c.names().get(0), "/")); - m.put("containerId", c.id()); - m.put("image", c.image()); - m.put("state", c.state()); - m.put("status", c.status()); - m.put("labels", c.labels()); + containerJson.put("containerName", StringUtils.remove(c.names().get(0), "/")); + containerJson.put("containerId", c.id()); + containerJson.put("image", c.image()); + containerJson.put("state", c.state()); + containerJson.put("status", c.status()); + containerJson.put("labels", c.labels()); } } - return new Gson().toJson(m); + try { + return JacksonSerializer.getObjectMapper().writeValueAsString(containerJson); + } catch (JsonProcessingException e) { + throw new RuntimeException("Could not serialize container list to JSON", e); + } } - private String deployPipelineElementContainer(DockerContainer p) throws Exception { - return deployPipelineElementContainer(p, true); + private String deployPipelineElementContainer(DockerContainer container) throws Exception { + return deployPipelineElementContainer(container, true); } - private String deployPipelineElementContainer(DockerContainer p, boolean pullImage) throws Exception { + private String deployPipelineElementContainer(DockerContainer container, boolean pullImage) throws Exception { if (pullImage) { try { - docker.pullImage(p.getImageUri(), false); + docker.pullImage(container.getImageUri(), false); } catch (DockerException | InterruptedException e) { LOG.error("unable to pull pipeline element container image {}", e.toString()); - deployPipelineElementContainer(p, false); + deployPipelineElementContainer(container, false); } } - if (!pullImage && !docker.findLocalImage(p.getImageUri())) { + if (!pullImage && !docker.findLocalImage(container.getImageUri())) { throw new NotFoundException("Image not found locally"); } - String containerId = docker.createContainer(p); + String containerId = docker.createContainer(container); docker.startContainer(containerId); return containerId; } + + private ContainerDeploymentStatus generateContainerStatus(String containerId, DockerContainer container, + DockerConstants.ContainerStatus containerStatus) { + ContainerDeploymentStatus status = new ContainerDeploymentStatus(); + + status.setTimestamp(System.currentTimeMillis()); + status.setContainerId(containerId); + status.setContainer(container); + status.setStatus(containerStatus); + + return status; + } } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerInfo.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/model/DockerInfo.java similarity index 99% rename from streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerInfo.java rename to streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/model/DockerInfo.java index 50b5cef..ee5939a 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/DockerInfo.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/model/DockerInfo.java @@ -15,7 +15,7 @@ * limitations under the License. * */ -package org.apache.streampipes.node.controller.container.management.orchestrator.docker; +package org.apache.streampipes.node.controller.container.management.orchestrator.docker.model; public class DockerInfo { diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/utils/DockerUtils.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/utils/DockerUtils.java index 4def964..4bad83f 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/utils/DockerUtils.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/orchestrator/docker/utils/DockerUtils.java @@ -27,7 +27,7 @@ import com.spotify.docker.client.messages.*; import com.spotify.docker.client.shaded.com.google.common.collect.ImmutableList; import org.apache.streampipes.model.node.container.DockerContainer; import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerConstants; -import org.apache.streampipes.node.controller.container.management.orchestrator.docker.DockerInfo; +import org.apache.streampipes.node.controller.container.management.orchestrator.docker.model.DockerInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -128,8 +128,8 @@ public class DockerUtils { } private String verifyContainerName(String containerName) { - return containerName.startsWith(DockerConstants.SP_DOCKER_CONTAINER_NAME_PREFIX) ? - containerName : DockerConstants.SP_DOCKER_CONTAINER_NAME_PREFIX + containerName; + return containerName.startsWith(DockerConstants.SP_CONTAINER_PREFIX) ? + containerName : DockerConstants.SP_CONTAINER_PREFIX + containerName; } private ContainerConfig getContainerConfig(DockerContainer p) { @@ -139,8 +139,8 @@ public class DockerUtils { .image(p.getImageUri()) .labels(p.getLabels()) .env(p.getEnvVars()) - .hostConfig(getHostConfig(DockerConstants.SP_DOCKER_NETWORK_NAME, p.getContainerPorts())) - .networkingConfig(getNetworkingConfig(DockerConstants.SP_DOCKER_NETWORK_NAME, p.getContainerName())) + .hostConfig(getHostConfig(DockerConstants.SP_CONTAINER_NETWORK, p.getContainerPorts())) + .networkingConfig(getNetworkingConfig(DockerConstants.SP_CONTAINER_NETWORK, p.getContainerName())) .build(); } @@ -182,6 +182,7 @@ public class DockerUtils { return HostConfig.builder() .portBindings(portBindings) .networkMode(network) + .restartPolicy(HostConfig.RestartPolicy.unlessStopped()) .build(); } @@ -279,17 +280,10 @@ public class DockerUtils { } public List<Container> getRunningStreamPipesContainer() { - - Map<String,String> allContainerLabels = new HashMap<>(); - allContainerLabels.putAll(DockerConstants.SP_DOCKER_CONTAINER_EXTENSIONS_LABELS); - allContainerLabels.putAll(DockerConstants.SP_DOCKER_CONTAINER_BROKER_LABELS); - return getContainerList() .stream() - .filter(c -> c.labels().values().stream() - .anyMatch(v -> allContainerLabels.values().stream() - .anyMatch(cl -> cl.equals(v)) - ) + .filter(container -> container.labels().keySet().stream() + .anyMatch(key -> key.startsWith("org.apache.streampipes")) ) .collect(Collectors.toList()); } diff --git a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/pe/InvocableElementManager.java b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/pe/InvocableElementManager.java index 8d0e99e..9d627c9 100644 --- a/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/pe/InvocableElementManager.java +++ b/streampipes-node-controller-container/src/main/java/org/apache/streampipes/node/controller/container/management/pe/InvocableElementManager.java @@ -43,9 +43,12 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; +import java.util.Map; public class InvocableElementManager implements PipelineElementLifeCycle { @@ -55,7 +58,10 @@ public class InvocableElementManager implements PipelineElementLifeCycle { private static final String HTTP_PROTOCOL = "http://"; private static final String COLON = ":"; private static final String SLASH = "/"; - private static final String ENV_CONSUL_LOCATION = "CONSUL_LOCATION"; + private static final String SP_URL = "SP_URL"; + private static final String CONSUL_LOCATION = "CONSUL_LOCATION"; + private static final String CONSUL_REGISTRATION_ROUTE = "v1/agent/service/register"; + private static final int CONSUL_DEFAULT_PORT = 8500; private static final Integer CONNECT_TIMEOUT = 10000; private static InvocableElementManager instance = null; @@ -182,9 +188,9 @@ public class InvocableElementManager implements PipelineElementLifeCycle { private String generateBackendEndpoint() { return HTTP_PROTOCOL - + NodeControllerConfig.INSTANCE.getBackendHost() + + NodeControllerConfig.INSTANCE.backendLocation() + COLON - + NodeControllerConfig.INSTANCE.getBackendPort() + + NodeControllerConfig.INSTANCE.backendPort() + SLASH + "streampipes-backend/api/v2/users/[email protected]/nodes" + SLASH @@ -193,7 +199,8 @@ public class InvocableElementManager implements PipelineElementLifeCycle { private void registerAtConsul(InvocableRegistration registration) { try { - Request.Put(makeConsulRegistrationEndpoint()) + String endpoint = consulURL().toString() + SLASH + CONSUL_REGISTRATION_ROUTE; + Request.Put(endpoint) .addHeader("accept", "application/json") .body(new StringEntity(toJson(registration.getConsulServiceRegistrationBody()))) .execute(); @@ -210,22 +217,31 @@ public class InvocableElementManager implements PipelineElementLifeCycle { .readValue(resp, Response.class); } - private String makeConsulRegistrationEndpoint() { - if (System.getenv(ENV_CONSUL_LOCATION) != null) { - return HTTP_PROTOCOL - + System.getenv(ENV_CONSUL_LOCATION) - + COLON - + "8500" - + SLASH - + "v1/agent/service/register"; + private static URL consulURL() { + Map<String, String> env = System.getenv(); + URL url = null; + + if (env.containsKey(SP_URL)) { + try { + URL coreServerUrl = new URL(env.get(SP_URL)); + url = new URL("http", coreServerUrl.getHost(), CONSUL_DEFAULT_PORT, ""); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } else if (env.containsKey(CONSUL_LOCATION)) { + try { + url = new URL("http", env.get(CONSUL_LOCATION), CONSUL_DEFAULT_PORT, ""); + } catch (MalformedURLException e) { + e.printStackTrace(); + } } else { - return HTTP_PROTOCOL - + "localhost" - + COLON - + "8500" - + SLASH - + "v1/agent/service/register"; + try { + url = new URL("http", "localhost", CONSUL_DEFAULT_PORT, ""); + } catch (MalformedURLException e) { + e.printStackTrace(); + } } + return url; } private <T> String toJson(T element) { diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/http/ReconfigurationEndpointUrlGenerator.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/http/ReconfigurationEndpointUrlGenerator.java new file mode 100644 index 0000000..0daa820 --- /dev/null +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/http/ReconfigurationEndpointUrlGenerator.java @@ -0,0 +1,47 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.streampipes.manager.execution.http; + +import org.apache.streampipes.model.pipeline.PipelineElementReconfigurationEntity; + +public class ReconfigurationEndpointUrlGenerator { + + protected static final String HTTP_PROTOCOL = "http://"; + protected static final String COLON = ":"; + protected static final String SLASH = "/"; + + private static final String BASE_ROUTE = "/api/v2/node/element"; + private static final String RECONFIGURE_ROUTE = "/adapt"; + + private final PipelineElementReconfigurationEntity reconfigurationEntity; + + public ReconfigurationEndpointUrlGenerator(PipelineElementReconfigurationEntity reconfigurationEntity) { + this.reconfigurationEntity = reconfigurationEntity; + } + + public String generateEndpoint() { + return HTTP_PROTOCOL + + reconfigurationEntity.getDeploymentTargetNodeHostname() + + COLON + + reconfigurationEntity.getDeploymentTargetNodePort() + + BASE_ROUTE + + RECONFIGURE_ROUTE; + + } + +} diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/http/ReconfigurationSubmitter.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/http/ReconfigurationSubmitter.java new file mode 100644 index 0000000..d4da1c2 --- /dev/null +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/http/ReconfigurationSubmitter.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.streampipes.manager.execution.http; + +import com.google.gson.JsonSyntaxException; +import org.apache.http.client.fluent.Request; +import org.apache.http.client.fluent.Response; +import org.apache.http.entity.ContentType; +import org.apache.streampipes.model.base.InvocableStreamPipesEntity; +import org.apache.streampipes.model.eventrelay.SpDataStreamRelayContainer; +import org.apache.streampipes.model.pipeline.Pipeline; +import org.apache.streampipes.model.pipeline.PipelineElementReconfigurationEntity; +import org.apache.streampipes.model.pipeline.PipelineElementStatus; +import org.apache.streampipes.model.pipeline.PipelineOperationStatus; +import org.apache.streampipes.serializers.json.JacksonSerializer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; + +public class ReconfigurationSubmitter { + protected final static Logger LOG = LoggerFactory.getLogger(ReconfigurationSubmitter.class); + + private static final Integer CONNECT_TIMEOUT = 10000; + + private final String pipelineId; + private final String pipelineName; + private final PipelineElementReconfigurationEntity reconfigurationEntity; + + public ReconfigurationSubmitter( String pipelineId, String pipelineName, + PipelineElementReconfigurationEntity reconfigurationEntity) { + this.pipelineId = pipelineId; + this.pipelineName = pipelineName; + this.reconfigurationEntity = reconfigurationEntity; + } + + public PipelineOperationStatus reconfigure() { + PipelineOperationStatus status = initPipelineOperationStatus(); + + reconfigurePipelineElements(status); + + return verifyPipelineOperationStatus( + status, + "Successfully reconfigured pipeline " + pipelineName, + "Could not reconfigure pipeline " + pipelineName, + true); + } + + private void reconfigurePipelineElements(PipelineOperationStatus status) { + status.addPipelineElementStatus(submit()); + } + + private PipelineElementStatus submit() { + String endpoint = new ReconfigurationEndpointUrlGenerator(reconfigurationEntity).generateEndpoint(); + LOG.info("Reconfigure pipeline element: " + endpoint); + try { + String json = toJson(); + Response httpResp = Request + .Post(endpoint) + .bodyString(json, ContentType.APPLICATION_JSON) + .connectTimeout(CONNECT_TIMEOUT) + .execute(); + return handleResponse(endpoint, httpResp); + } catch (Exception e) { + LOG.error(e.getMessage()); + return new PipelineElementStatus(endpoint, reconfigurationEntity.getPipelineElementName(), + false, e.getMessage()); + } + } + + private void rollback(PipelineOperationStatus status) { + //TODO: implement + } + + private PipelineElementStatus handleResponse(String endpoint, Response httpResp) throws JsonSyntaxException, + IOException { + String resp = httpResp.returnContent().asString(); + org.apache.streampipes.model.Response streamPipesResp = JacksonSerializer + .getObjectMapper() + .readValue(resp, org.apache.streampipes.model.Response.class); + + return new PipelineElementStatus(endpoint, + reconfigurationEntity.getPipelineElementName(), + streamPipesResp.isSuccess(), + streamPipesResp.getOptionalMessage()); + } + + + private PipelineOperationStatus verifyPipelineOperationStatus(PipelineOperationStatus status, String successMessage, + String errorMessage, boolean rollbackIfFailed) { + status.setSuccess(status.getElementStatus().stream() + .allMatch(PipelineElementStatus::isSuccess)); + + if (status.isSuccess()) { + status.setTitle(successMessage); + } else { + if (rollbackIfFailed) { + LOG.info("Could not reconfigure pipeline element, initializing rollback..."); + rollback(status); + } + status.setTitle(errorMessage); + } + return status; + } + + private PipelineOperationStatus initPipelineOperationStatus() { + PipelineOperationStatus status = new PipelineOperationStatus(); + status.setPipelineId(pipelineId); + status.setPipelineName(pipelineName); + status.setSuccess(true); + return status; + } + + private String toJson() throws Exception { + return JacksonSerializer.getObjectMapper().writeValueAsString(reconfigurationEntity); + } +} diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/pipeline/PipelineElementReconfigurationExecutor.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/pipeline/PipelineElementReconfigurationExecutor.java new file mode 100644 index 0000000..dc61206 --- /dev/null +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/execution/pipeline/PipelineElementReconfigurationExecutor.java @@ -0,0 +1,41 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.streampipes.manager.execution.pipeline; + +import org.apache.streampipes.manager.execution.http.ReconfigurationSubmitter; +import org.apache.streampipes.model.pipeline.Pipeline; +import org.apache.streampipes.model.pipeline.PipelineElementReconfigurationEntity; +import org.apache.streampipes.model.pipeline.PipelineOperationStatus; + +public class PipelineElementReconfigurationExecutor { + + private final Pipeline reconfiguredPipeline; + private final PipelineElementReconfigurationEntity reconfigurationEntity; + + public PipelineElementReconfigurationExecutor(Pipeline reconfiguredPipeline, + PipelineElementReconfigurationEntity reconfigurationEntity) { + this.reconfiguredPipeline = reconfiguredPipeline; + this.reconfigurationEntity = reconfigurationEntity; + } + + public PipelineOperationStatus reconfigurePipelineElement() { + return new ReconfigurationSubmitter(reconfiguredPipeline.getPipelineId(), reconfiguredPipeline.getName(), + reconfigurationEntity).reconfigure(); + } + +} diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/matching/ProtocolSelector.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/matching/ProtocolSelector.java index 117fbb8..a869e30 100644 --- a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/matching/ProtocolSelector.java +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/matching/ProtocolSelector.java @@ -18,6 +18,7 @@ package org.apache.streampipes.manager.matching; +import org.apache.streampipes.commons.exceptions.SpRuntimeException; import org.apache.streampipes.config.backend.BackendConfig; import org.apache.streampipes.config.backend.SpEdgeNodeProtocol; import org.apache.streampipes.config.backend.SpProtocol; @@ -27,12 +28,12 @@ import org.apache.streampipes.model.base.InvocableStreamPipesEntity; import org.apache.streampipes.model.base.NamedStreamPipesEntity; import org.apache.streampipes.model.SpDataStream; import org.apache.streampipes.model.graph.DataProcessorInvocation; -import org.apache.streampipes.model.grounding.JmsTransportProtocol; -import org.apache.streampipes.model.grounding.KafkaTransportProtocol; -import org.apache.streampipes.model.grounding.MqttTransportProtocol; -import org.apache.streampipes.model.grounding.TransportProtocol; +import org.apache.streampipes.model.grounding.*; +import org.apache.streampipes.model.node.NodeInfoDescription; +import org.apache.streampipes.storage.management.StorageDispatcher; import java.util.List; +import java.util.Optional; import java.util.Set; public class ProtocolSelector extends GroundingSelector { @@ -75,8 +76,14 @@ public class ProtocolSelector extends GroundingSelector { // use edge node protocol if (matches(edgeNodeProtocol, MqttTransportProtocol.class) && supportsProtocol(MqttTransportProtocol.class)) { if(matchesDeploymentTargets()) { - return new MqttTransportProtocol(getTargetNodeBrokerHost(), getTargetNodeBrokerPort(), - outputTopic); + // get node transport protocol + String nodeControllerId = ((InvocableStreamPipesEntity) source).getDeploymentTargetNodeId(); + + MqttTransportProtocol nodeTransportProtocol = (MqttTransportProtocol) + getNodeBrokerTransportProtocol(nodeControllerId); + nodeTransportProtocol.setTopicDefinition(new SimpleTopicDefinition(outputTopic)); + + return nodeTransportProtocol; } else { MqttTransportProtocol tp = (MqttTransportProtocol) ((InvocableStreamPipesEntity) source).getInputStreams().stream() @@ -168,20 +175,15 @@ public class ProtocolSelector extends GroundingSelector { return false; } - private String getTargetNodeBrokerHost() { - // TODO: no hardcoded route - only for testing - - return ConsulUtil.getValueForRoute( - "sp/v1/node/org.apache.streampipes.node.controller/" - + ((InvocableStreamPipesEntity) source).getDeploymentTargetNodeHostname() - + "/config/SP_NODE_BROKER_CONTAINER_HOST", String.class); + private static TransportProtocol getNodeBrokerTransportProtocol(String id) { + Optional<NodeInfoDescription> nodeInfoDescription = getNodeInfoDescriptionForId(id); + if (nodeInfoDescription.isPresent()) { + return nodeInfoDescription.get().getNodeBroker().getNodeTransportProtocol(); + } + throw new SpRuntimeException("Could not find node description for id: " + id); } - private int getTargetNodeBrokerPort() { - // TODO: no hardcoded route - only for testing - return ConsulUtil.getValueForRoute( - "sp/v1/node/org.apache.streampipes.node.controller/" - + ((InvocableStreamPipesEntity) source).getDeploymentTargetNodeHostname() - + "/config/SP_NODE_BROKER_CONTAINER_PORT", Integer.class); + private static Optional<NodeInfoDescription> getNodeInfoDescriptionForId(String id){ + return StorageDispatcher.INSTANCE.getNoSqlStore().getNodeStorage().getNode(id); } } diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/migration/PipelineElementMigrationHandler.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/migration/PipelineElementMigrationHandler.java index 4d3f6d5..e16e2fd 100644 --- a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/migration/PipelineElementMigrationHandler.java +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/migration/PipelineElementMigrationHandler.java @@ -63,7 +63,7 @@ public class PipelineElementMigrationHandler { } private void migratePipelineElementOrRollback() { - List<PipelineElementMigrationEntity> migrationEntityList = getPipelineDelta(desiredPipeline, migrationPipeline); + List<PipelineElementMigrationEntity> migrationEntityList = getPipelineDelta(); migrationEntityList.forEach(entity -> { swapPipelineElement(migrationPipeline, entity); @@ -106,12 +106,12 @@ public class PipelineElementMigrationHandler { return StorageDispatcher.INSTANCE.getNoSqlStore().getPipelineStorageAPI(); } - private List<PipelineElementMigrationEntity> getPipelineDelta(Pipeline pipelineX, Pipeline pipelineY){ + private List<PipelineElementMigrationEntity> getPipelineDelta(){ List<PipelineElementMigrationEntity> delta = new ArrayList<>(); - pipelineX.getSepas().forEach(iX -> { - if (pipelineY.getSepas().stream().filter(iY -> iY.getElementId().equals(iX.getElementId())) + desiredPipeline.getSepas().forEach(iX -> { + if (migrationPipeline.getSepas().stream().filter(iY -> iY.getElementId().equals(iX.getElementId())) .noneMatch(iY -> iY.getDeploymentTargetNodeId().equals(iX.getDeploymentTargetNodeId()))){ - Optional<DataProcessorInvocation> invocationY = pipelineY.getSepas().stream(). + Optional<DataProcessorInvocation> invocationY = migrationPipeline.getSepas().stream(). filter(iY -> iY.getDeploymentRunningInstanceId().equals(iX.getDeploymentRunningInstanceId())).findFirst(); invocationY.ifPresent(dataProcessorInvocation -> delta.add(new PipelineElementMigrationEntity(dataProcessorInvocation, iX))); } diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/node/NodeClusterManager.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/node/NodeClusterManager.java index 5b85135..4e8b8f6 100644 --- a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/node/NodeClusterManager.java +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/node/NodeClusterManager.java @@ -59,6 +59,11 @@ public class NodeClusterManager extends AbstractClusterManager { return Notifications.error("Could not update node"); } + public static Message syncRemoteNodeUpdateRequest(NodeInfoDescription desc) { + getNodeStorageApi().updateNode(desc); + return Notifications.success("Node updated"); + } + public static boolean deactivateNode(String nodeControllerId) { Optional<NodeInfoDescription> storedNode = getNodeStorageApi().getNode(nodeControllerId); boolean status = false; diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/operations/Operations.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/operations/Operations.java index 6047b1d..bf3383d 100644 --- a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/operations/Operations.java +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/operations/Operations.java @@ -28,6 +28,7 @@ import org.apache.streampipes.manager.matching.DataSetGroundingSelector; import org.apache.streampipes.manager.matching.PipelineVerificationHandler; import org.apache.streampipes.manager.migration.PipelineElementMigrationHandler; import org.apache.streampipes.manager.recommender.ElementRecommender; +import org.apache.streampipes.manager.reconfiguration.PipelineElementReconfigurationHandler; import org.apache.streampipes.manager.remote.ContainerProvidedOptionsHandler; import org.apache.streampipes.manager.runtime.PipelineElementRuntimeInfoFetcher; import org.apache.streampipes.manager.template.PipelineTemplateGenerator; @@ -192,4 +193,8 @@ public class Operations { return new PipelineElementMigrationHandler(desiredPipeline, visualize, storeStatus, monitor).handlePipelineMigration(); } + public static PipelineOperationStatus handlePipelineElementReconfiguration(Pipeline reconfiguredPipeline, + boolean storeStatus) { + return new PipelineElementReconfigurationHandler(reconfiguredPipeline, storeStatus).handleReconfiguration(); + } } diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/reconfiguration/PipelineElementReconfigurationHandler.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/reconfiguration/PipelineElementReconfigurationHandler.java new file mode 100644 index 0000000..223a85f --- /dev/null +++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/reconfiguration/PipelineElementReconfigurationHandler.java @@ -0,0 +1,191 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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.apache.streampipes.manager.reconfiguration; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.streampipes.commons.exceptions.SpRuntimeException; +import org.apache.streampipes.manager.execution.pipeline.PipelineElementReconfigurationExecutor; +import org.apache.streampipes.manager.operations.Operations; +import org.apache.streampipes.model.graph.DataProcessorInvocation; +import org.apache.streampipes.model.pipeline.*; +import org.apache.streampipes.model.staticproperty.FreeTextStaticProperty; +import org.apache.streampipes.model.staticproperty.StaticProperty; +import org.apache.streampipes.storage.api.IPipelineStorage; +import org.apache.streampipes.storage.management.StorageDispatcher; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +public class PipelineElementReconfigurationHandler { + + private final PipelineOperationStatus pipelineReconfigurationStatus; + private final Pipeline reconfiguredPipeline; + private Pipeline storedPipeline; + private final boolean storeStatus; + + public PipelineElementReconfigurationHandler(Pipeline reconfiguredPipeline, boolean storeStatus) { + this.pipelineReconfigurationStatus = new PipelineOperationStatus(); + this.reconfiguredPipeline = reconfiguredPipeline; + this.storedPipeline = getPipelineById(reconfiguredPipeline.getPipelineId()); + this.storeStatus = storeStatus; + } + + public PipelineOperationStatus handleReconfiguration() { + reconfigurePipelineElementOrRollback(); + return verifyPipelineReconfigurationStatus(pipelineReconfigurationStatus, + "Successfully reconfigured Pipeline Elements in Pipeline " + reconfiguredPipeline.getName(), + "Could not reconfigure all Pipeline Elements in Pipeline " + reconfiguredPipeline.getName()); + } + + private void reconfigurePipelineElementOrRollback() { + List<PipelineElementReconfigurationEntity> reconfiguredEntityList = comparePipelinesAndGetReconfiguration(); + + reconfiguredEntityList.forEach(entity -> { + PipelineOperationStatus entityStatus = reconfigurePipelineElement(entity); + + entityStatus.getElementStatus().forEach(pipelineReconfigurationStatus::addPipelineElementStatus); + + // TODO needed ? + if (entityStatus.isSuccess()) { + try { + storedPipeline = deepCopyPipeline(reconfiguredPipeline); + } catch (JsonProcessingException e) { + throw new SpRuntimeException("Could not deep copy pipeline for reconfiguration: " + e.getMessage(), + e); + } + } else { + //TODO: what to do when not successful? + } + }); + + if (storeStatus) { + Operations.overwritePipeline(reconfiguredPipeline); + } + } + + private PipelineOperationStatus reconfigurePipelineElement(PipelineElementReconfigurationEntity entity) { + return new PipelineElementReconfigurationExecutor(reconfiguredPipeline, entity).reconfigurePipelineElement(); + } + + private List<PipelineElementReconfigurationEntity> comparePipelinesAndGetReconfiguration() { + List<PipelineElementReconfigurationEntity> delta = new ArrayList<>(); + + List<DataProcessorInvocation> reconfiguredGraphs = filterReconfigurableFsp(reconfiguredPipeline); + List<DataProcessorInvocation> currentGraphs = filterReconfigurableFsp(storedPipeline); + + reconfiguredGraphs.forEach(reconfiguredProcessor -> currentGraphs.forEach(storedProcessor -> { + if (matchingElementIds(reconfiguredProcessor, storedProcessor)) { + List<StaticProperty> list = new ArrayList<>(); + getReconfigurableFsp(reconfiguredProcessor).forEach(reconfiguredFsp -> + getReconfigurableFsp(storedProcessor).forEach(storedFsp -> { + if (compareForChanges(reconfiguredFsp, storedFsp)) { + list.add(reconfiguredFsp); + } + })); + PipelineElementReconfigurationEntity entity = reconfigurationEntity(reconfiguredProcessor, list); + if (list.size() > 0 && !exists(delta, entity)) { + delta.add(entity); + } + } + })); + + return delta; + } + + private boolean exists(List<PipelineElementReconfigurationEntity> delta, + PipelineElementReconfigurationEntity entity) { + return delta.stream() + .anyMatch(e -> e.getDeploymentRunningInstanceId().equals(entity.getDeploymentRunningInstanceId())); + } + + private PipelineElementReconfigurationEntity reconfigurationEntity(DataProcessorInvocation graph, + List<StaticProperty> adaptedStaticProperty) { + PipelineElementReconfigurationEntity entity = new PipelineElementReconfigurationEntity(); + entity.setDeploymentRunningInstanceId(graph.getDeploymentRunningInstanceId()); + entity.setPipelineElementName(graph.getName()); + entity.setDeploymentTargetNodeId(graph.getDeploymentTargetNodeId()); + entity.setDeploymentTargetNodeHostname(graph.getDeploymentTargetNodeHostname()); + entity.setDeploymentTargetNodePort(graph.getDeploymentTargetNodePort()); + entity.setReconfiguredStaticProperties(adaptedStaticProperty); + return entity; + } + + private boolean compareForChanges(FreeTextStaticProperty one, FreeTextStaticProperty two) { + return one.getInternalName().equals(two.getInternalName()) && !one.getValue().equals(two.getValue()); + } + + private List<FreeTextStaticProperty> getReconfigurableFsp(DataProcessorInvocation graph) { + return graph.getStaticProperties().stream() + .filter(FreeTextStaticProperty.class::isInstance) + .map(FreeTextStaticProperty.class::cast) + .filter(FreeTextStaticProperty::isReconfigurable) + .collect(Collectors.toList()); + } + + private boolean matchingElementIds(DataProcessorInvocation one, DataProcessorInvocation two) { + return one.getElementId().equals(two.getElementId()); + } + + private List<DataProcessorInvocation> filterReconfigurableFsp(Pipeline pipeline) { + List<DataProcessorInvocation> filtered = new ArrayList<>(); + pipeline.getSepas().forEach(processor -> { + List<StaticProperty> fsp = new ArrayList<>(); + processor.getStaticProperties().forEach(sp -> { + if (sp instanceof FreeTextStaticProperty && ((FreeTextStaticProperty) sp).isReconfigurable()) { + fsp.add(sp); + } + }); + processor.setStaticProperties(fsp); + filtered.add(processor); + }); + + return filtered; + } + + + + // Helpers + + private PipelineOperationStatus verifyPipelineReconfigurationStatus(PipelineOperationStatus status, + String successMessage, + String errorMessage) { + status.setSuccess(status.getElementStatus().stream().allMatch(PipelineElementStatus::isSuccess)); + if (status.isSuccess()) { + status.setTitle(successMessage); + } else { + status.setTitle(errorMessage); + } + return status; + } + + private Pipeline getPipelineById(String pipelineId) { + return getPipelineStorageApi().getPipeline(pipelineId); + } + + private IPipelineStorage getPipelineStorageApi() { + return StorageDispatcher.INSTANCE.getNoSqlStore().getPipelineStorageAPI(); + } + + public static Pipeline deepCopyPipeline(Pipeline object) throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + return objectMapper.readValue(objectMapper.writeValueAsString(object), Pipeline.class); + } + +} diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/INode.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/INode.java index 484d084..18322d7 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/INode.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/api/INode.java @@ -27,6 +27,8 @@ public interface INode { Response updateNode(String username, String nodeControllerId, NodeInfoDescription desc); + Response syncRemoteUpdateFromNodeController(String username, NodeInfoDescription desc); + Response deleteNode(String username, String nodeControllerId); Response changeNodeState(String action, String username, String nodeControllerId); diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Node.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Node.java index e7db8e0..02c0b0a 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Node.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/Node.java @@ -17,6 +17,7 @@ */ package org.apache.streampipes.rest.impl; +import org.apache.streampipes.manager.info.VersionInfoProvider; import org.apache.streampipes.manager.node.NodeClusterManager; import org.apache.streampipes.model.message.NotificationType; import org.apache.streampipes.model.message.Notifications; @@ -57,6 +58,17 @@ public class Node extends AbstractRestResource implements INode { @POST @JacksonSerialized + @Path("/sync") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @Override + public Response syncRemoteUpdateFromNodeController(@PathParam("username") String username, + NodeInfoDescription desc) { + return statusMessage(NodeClusterManager.syncRemoteNodeUpdateRequest(desc)); + } + + @POST + @JacksonSerialized @Path("/{action}/{nodeControllerId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java index e8f005e..ee0559c 100644 --- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java +++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/PipelineResource.java @@ -264,6 +264,28 @@ public class PipelineResource extends AbstractAuthGuardedRestResource { return statusMessage(Notifications.success("Pipeline modified")); } + @PUT + @Path("/reconfigure/{pipelineId}") + @Produces(MediaType.APPLICATION_JSON) + @JacksonSerialized + @Operation(summary = "Live pipeline element reconfiguration of an existing pipeline", + tags = {"Pipeline"}) + public Response reconfigurePipelineElements(@PathParam("username") String username, + @PathParam("pipelineId") String pipelineId, + Pipeline reconfiguredPipeline) { + // check which elements got adapted (stored vs new pipeline) for which deployment target + // transform modified graphs (graphs = DataProcessorInvokation) to JSON payload (light): + // { "id" : "<runningInstanceId" + // POST /<runninginstanceid> with payload(JSON per modified graph) + // lookup(runninginstanceid) -> pub.connect(broker) -> pub.publish(event) + try { + return ok(Operations.handlePipelineElementReconfiguration(reconfiguredPipeline, true)); + } catch (Exception e) { + e.printStackTrace(); + return statusMessage(Notifications.error(NotificationType.UNKNOWN_ERROR)); + } + } + @POST @Path("/migrate/{pipelineId}") @Produces(MediaType.APPLICATION_JSON) diff --git a/streampipes-sdk/src/main/java/org/apache/streampipes/sdk/builder/AbstractConfigurablePipelineElementBuilder.java b/streampipes-sdk/src/main/java/org/apache/streampipes/sdk/builder/AbstractConfigurablePipelineElementBuilder.java index 624dcd4..3be4c1f 100644 --- a/streampipes-sdk/src/main/java/org/apache/streampipes/sdk/builder/AbstractConfigurablePipelineElementBuilder.java +++ b/streampipes-sdk/src/main/java/org/apache/streampipes/sdk/builder/AbstractConfigurablePipelineElementBuilder.java @@ -348,6 +348,13 @@ public abstract class AbstractConfigurablePipelineElementBuilder<BU extends return me(); } + public BU requiredReconfigurableIntegerParameter(Label label) { + FreeTextStaticProperty fsp = prepareFreeTextStaticProperty(label, XSD._integer.toString()); + fsp.setReconfigurable(true); + this.staticProperties.add(fsp); + return me(); + } + /** * @deprecated use {@link #requiredIntegerParameter(Label, String)} instead * @param internalId @@ -454,6 +461,20 @@ public abstract class AbstractConfigurablePipelineElementBuilder<BU extends } /** + * Assigns a new number-based configuration parameter (a float) which is required by the pipeline + * element. This parameter can be reconfigured by the user at pipeline run-time. + * @param label The {@link org.apache.streampipes.sdk.helpers.Label} that describes why this parameter is needed in a + * user-friendly manner. + * @return + */ + public BU requiredReconfigurableFloatParameter(Label label) { + FreeTextStaticProperty fsp = prepareFreeTextStaticProperty(label, XSD._double.toString()); + fsp.setReconfigurable(true); + this.staticProperties.add(fsp); + return me(); + } + + /** * Defines a number-based configuration parameter of type float provided by pipeline developers at pipeline * authoring time. The * value range of the parameter is restricted to the value specification of a selected input event property. diff --git a/streampipes-vocabulary/src/main/java/org/apache/streampipes/vocabulary/StreamPipes.java b/streampipes-vocabulary/src/main/java/org/apache/streampipes/vocabulary/StreamPipes.java index 5a78b2a..7570cf7 100644 --- a/streampipes-vocabulary/src/main/java/org/apache/streampipes/vocabulary/StreamPipes.java +++ b/streampipes-vocabulary/src/main/java/org/apache/streampipes/vocabulary/StreamPipes.java @@ -492,4 +492,5 @@ public class StreamPipes { public static final String HAS_REQUIRED_FILETYPES = NS + "hasRequiredFiletypes"; public static final String IS_INTERNALLY_MANAGED = NS + "isInternallyManaged"; public static final String HAS_CORRESPONDING_ADAPTER_ID = NS + "hasCorrespondingAdapterId"; + public static final String IS_RECONFIGURABLE = NS + "isReconfigurable"; } diff --git a/ui/src/app/configuration/node-configuration/node-configuration.component.html b/ui/src/app/configuration/node-configuration/node-configuration.component.html index 5104446..e339f40 100644 --- a/ui/src/app/configuration/node-configuration/node-configuration.component.html +++ b/ui/src/app/configuration/node-configuration/node-configuration.component.html @@ -82,9 +82,9 @@ </button> </div> <mat-card-title - style="font-size: 12pt">{{node.nodeControllerId}}</mat-card-title> + style="font-size: 12pt">{{node.hostname}}</mat-card-title> <mat-card-subtitle style="font-size: 10pt"> - {{node.hostname}} | <b>{{node.nodeResources.softwareResource.os}}</b> + {{node.nodeControllerId}} | <b>{{node.nodeResources.softwareResource.os}}</b> <div style="color: lightgrey;"> last contact: {{currentTimestamp}} </div> @@ -119,9 +119,9 @@ <b>{{nvidiaRuntime(node)}}</b></li> </ul> </div> - <div *ngFor="let container of node.registeredContainers"> - <span>{{container.containerName}}</span> - </div> +<!-- <div *ngFor="let container of node.registeredContainers">--> +<!-- <span>{{container.containerName}}</span>--> +<!-- </div>--> </mat-card-content> <mat-card-actions> </mat-card-actions> diff --git a/ui/src/app/core-model/gen/streampipes-model.ts b/ui/src/app/core-model/gen/streampipes-model.ts index 2587943..437271e 100644 --- a/ui/src/app/core-model/gen/streampipes-model.ts +++ b/ui/src/app/core-model/gen/streampipes-model.ts @@ -19,7 +19,7 @@ /* tslint:disable */ /* eslint-disable */ // @ts-nocheck -// Generated using typescript-generator version 2.27.744 on 2021-02-26 19:57:32. +// Generated using typescript-generator version 2.27.744 on 2021-03-13 13:56:44. export class AbstractStreamPipesEntity { "@class": "org.apache.streampipes.model.base.AbstractStreamPipesEntity" | "org.apache.streampipes.model.base.NamedStreamPipesEntity" | "org.apache.streampipes.model.connect.adapter.AdapterDescription" | "org.apache.streampipes.model.connect.adapter.AdapterSetDescription" | "org.apache.streampipes.model.connect.adapter.GenericAdapterSetDescription" | "org.apache.streampipes.model.connect.adapter.SpecificAdapterSetDescription" | "org.apache.streampipes.model.connect.adapter.AdapterStre [...] @@ -1749,6 +1749,7 @@ export class FreeTextStaticProperty extends StaticProperty { mapsTo: string; multiLine: boolean; placeholdersSupported: boolean; + reconfigurable: boolean; requiredDatatype: string; requiredDomainProperty: string; value: string; @@ -1768,6 +1769,7 @@ export class FreeTextStaticProperty extends StaticProperty { instance.htmlAllowed = data.htmlAllowed; instance.htmlFontFormat = data.htmlFontFormat; instance.placeholdersSupported = data.placeholdersSupported; + instance.reconfigurable = data.reconfigurable; instance.valueSpecification = PropertyValueSpecification.fromData(data.valueSpecification); return instance; } @@ -3460,4 +3462,4 @@ function __copyObject<T>(object: { [index: string]: T }, itemCopyFn: (item: T) = function __identity<T>(): (value: T) => T { return value => value; -} +} \ No newline at end of file diff --git a/ui/src/app/core-ui/static-properties/static-property-util.service.ts b/ui/src/app/core-ui/static-properties/static-property-util.service.ts index 5231fec..2666598 100644 --- a/ui/src/app/core-ui/static-properties/static-property-util.service.ts +++ b/ui/src/app/core-ui/static-properties/static-property-util.service.ts @@ -47,6 +47,7 @@ export class StaticPropertyUtilService{ clone.elementId = id; clone.value = val.value; clone.requiredDomainProperty = val.requiredDomainProperty; + clone.reconfigurable = val.reconfigurable; } else if (val instanceof FileStaticProperty) { clone = new FileStaticProperty(); diff --git a/ui/src/app/editor/dialog/migrate-pipeline-processors/migrate-pipeline-processors.component.ts b/ui/src/app/editor/dialog/migrate-pipeline-processors/migrate-pipeline-processors.component.ts index 8ea0f81..c94f7bb 100644 --- a/ui/src/app/editor/dialog/migrate-pipeline-processors/migrate-pipeline-processors.component.ts +++ b/ui/src/app/editor/dialog/migrate-pipeline-processors/migrate-pipeline-processors.component.ts @@ -1,3 +1,21 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + * + */ + import {Component, Input, OnInit} from '@angular/core'; import { DataProcessorInvocation, Message, diff --git a/ui/src/app/pipeline-details/components/edit/quickedit.component.html b/ui/src/app/pipeline-details/components/edit/quickedit.component.html index 01d1677..6155b29 100644 --- a/ui/src/app/pipeline-details/components/edit/quickedit.component.html +++ b/ui/src/app/pipeline-details/components/edit/quickedit.component.html @@ -28,6 +28,13 @@ <mat-icon>save</mat-icon> <span> Update pipeline</span> </button> + <button color="primary" mat-button mat-raised-button matTooltip="Save Pipeline" matTooltipPosition="above" + style="display:flex;align-items:center;" class="settings-bar-icon-button" + [disabled]="(!formValid || pipelineUpdating)" + (click)="reconfigurePipeline()"> + <mat-icon>save</mat-icon> + <span> Reconfigure pipeline</span> + </button> </div> </div> <div class="sp-blue-border"> diff --git a/ui/src/app/pipeline-details/components/edit/quickedit.component.ts b/ui/src/app/pipeline-details/components/edit/quickedit.component.ts index f20d33c..dee5d31 100644 --- a/ui/src/app/pipeline-details/components/edit/quickedit.component.ts +++ b/ui/src/app/pipeline-details/components/edit/quickedit.component.ts @@ -146,5 +146,14 @@ export class QuickEditComponent implements OnInit, AfterViewInit{ this.isInvocable = this._selectedElement instanceof DataProcessorInvocation || this._selectedElement instanceof DataSinkInvocation; } + + reconfigurePipeline() { + this.pipelineUpdating = true; + this.updatePipelineElement(); + this.pipelineService.reconfigurePipeline(this.pipeline).subscribe(data => { + this.reloadPipelineEmitter.emit(); + this.pipelineUpdating = false; + }); + } } diff --git a/ui/src/app/pipeline-details/pipeline-details.component.html b/ui/src/app/pipeline-details/pipeline-details.component.html index 799f9ae..bb7de38 100644 --- a/ui/src/app/pipeline-details/pipeline-details.component.html +++ b/ui/src/app/pipeline-details/pipeline-details.component.html @@ -24,7 +24,8 @@ <mat-tab label="Overview"></mat-tab> <mat-tab label="Monitoring"></mat-tab> <mat-tab label="Errors"></mat-tab> - <mat-tab label="Quick Edit" [disabled]="pipelineAvailable && pipeline.running"></mat-tab> +<!-- <mat-tab label="Quick Edit" [disabled]="pipelineAvailable && pipeline.running"></mat-tab>--> + <mat-tab label="Quick Edit"></mat-tab> </mat-tab-group> </div> </div> diff --git a/ui/src/app/platform-services/apis/pipeline.service.ts b/ui/src/app/platform-services/apis/pipeline.service.ts index 0abfc8a..fac5f2e 100644 --- a/ui/src/app/platform-services/apis/pipeline.service.ts +++ b/ui/src/app/platform-services/apis/pipeline.service.ts @@ -109,4 +109,12 @@ export class PipelineService { return (response as any[]).map(r => PipelineStatusMessage.fromData(r)); })); } + + reconfigurePipeline(pipeline: Pipeline): Observable<PipelineElementStatus> { + var pipelineId = pipeline._id; + return this.http.put(this.platformServicesCommons.authUserBasePath() + "/pipelines/reconfigure/" + pipelineId, pipeline) + .pipe(map(response => { + return PipelineElementStatus.fromData(response as PipelineElementStatus); + })); + } } \ No newline at end of file
