You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@streampipes.apache.org by oe...@apache.org on 2026/04/13 13:29:23 UTC
(streampipes) branch dev updated: fix(#3042): Automatic handling of data stream changes in python client (#4368)
This is an automated email from the ASF dual-hosted git repository.
oehler pushed a commit to branch dev
in repository https://gitbox.apache.org/repos/asf/streampipes.git
The following commit(s) were added to refs/heads/dev by this push:
new e4a2f1eeea fix(#3042): Automatic handling of data stream changes in python client (#4368)
e4a2f1eeea is described below
commit e4a2f1eeea745830087565914ba0af453491341e
Author: Sven Oehler <43...@users.noreply.github.com>
AuthorDate: Mon Apr 13 15:29:18 2026 +0200
fix(#3042): Automatic handling of data stream changes in python client (#4368)
---
.../streampipes/endpoint/endpoint.py | 28 ++
.../streampipes/functions/function_handler.py | 24 +-
.../tests/client/test_endpoint.py | 24 ++
.../tests/functions/test_function_handler.py | 71 +++++-
.../management/AdapterUpdateManagement.java | 146 +----------
.../update/DataStreamUpdateManagement.java | 47 ++++
.../pipeline/update/PipelineUpdateCoordinator.java | 191 +++++++-------
.../update/PipelineUpdateCoordinatorTest.java | 281 +++++++++++++++++++++
.../rest/impl/pe/DataStreamResource.java | 22 +-
9 files changed, 591 insertions(+), 243 deletions(-)
diff --git a/streampipes-client-python/streampipes/endpoint/endpoint.py b/streampipes-client-python/streampipes/endpoint/endpoint.py
index 2c491c6dd1..c1b52a7e9f 100644
--- a/streampipes-client-python/streampipes/endpoint/endpoint.py
+++ b/streampipes-client-python/streampipes/endpoint/endpoint.py
@@ -236,6 +236,34 @@ class APIEndpoint(Endpoint):
headers={"Content-type": "application/json"},
)
+ def put(self, resource: Resource, identifier: Optional[str] = None) -> None:
+ """Allows to update a resource in the StreamPipes API.
+
+ Parameters
+ ----------
+ resource: Resource
+ The resource to be updated.
+ identifier: Optional[str]
+ Optional resource identifier used in the endpoint path. If omitted,
+ the method tries to read `element_id` from the given resource.
+
+ Returns
+ -------
+ None
+ """
+
+ resource_identifier = identifier or getattr(resource, "element_id", None)
+
+ if not resource_identifier:
+ raise ValueError("Updating a resource requires an identifier or a resource with an element_id.")
+
+ self._make_request(
+ request_method=self._parent_client.request_session.put,
+ url=f"{self.build_url()}/{resource_identifier}",
+ data=json.dumps(resource.to_dict(use_source_names=True)),
+ headers={"Content-type": "application/json"},
+ )
+
class MessagingEndpoint(Endpoint):
"""Abstract implementation of a StreamPipes messaging endpoint.
diff --git a/streampipes-client-python/streampipes/functions/function_handler.py b/streampipes-client-python/streampipes/functions/function_handler.py
index 1a60bbb336..12361a3d13 100644
--- a/streampipes-client-python/streampipes/functions/function_handler.py
+++ b/streampipes-client-python/streampipes/functions/function_handler.py
@@ -70,17 +70,7 @@ class FunctionHandler:
for streampipes_function in self.registration.getFunctions():
# Create the output data streams for every function
for stream_id, output_stream in streampipes_function.function_definition.get_output_data_streams().items():
- try:
- self.client.dataStreamApi.post(output_stream)
- except HTTPError as e:
- logger.info("The data stream could not be created.")
- if e.response.status_code == HTTPStatus.BAD_REQUEST:
- logger.info(
- "This is due to the fact that this data stream already exists. "
- "Continuing with the existing data stream."
- )
- else:
- raise RuntimeError from e
+ self._create_or_update_output_stream(output_stream)
logger.info(
f"Using output data stream '{stream_id}' for function '{streampipes_function.getFunctionId().id}'"
)
@@ -107,6 +97,18 @@ class FunctionHandler:
else:
loop.create_task(self._function_loop())
+ def _create_or_update_output_stream(self, output_stream: DataStream) -> None:
+ """Creates a new output stream or updates it if it already exists."""
+ try:
+ self.client.dataStreamApi.get(output_stream.element_id)
+ except HTTPError as e:
+ if e.response.status_code == HTTPStatus.NOT_FOUND:
+ self.client.dataStreamApi.post(output_stream)
+ else:
+ raise RuntimeError from e
+ else:
+ self.client.dataStreamApi.put(output_stream)
+
async def _function_loop(self) -> None:
"""Loops through all messages and sends them to the functions until the function handler gets stopped.
diff --git a/streampipes-client-python/tests/client/test_endpoint.py b/streampipes-client-python/tests/client/test_endpoint.py
index 5b71d83531..1e7fba8915 100644
--- a/streampipes-client-python/tests/client/test_endpoint.py
+++ b/streampipes-client-python/tests/client/test_endpoint.py
@@ -232,6 +232,30 @@ class TestStreamPipesEndpoints(TestCase):
headers={"Content-type": "application/json"},
)
+ @patch("streampipes.client.client.Session", autospec=True)
+ @patch("streampipes.client.client.StreamPipesClient._get_server_version", autospec=True)
+ def test_endpoint_put(self, server_version: MagicMock, http_session: MagicMock):
+ http_session_mock = MagicMock()
+ http_session.return_value = http_session_mock
+
+ server_version.return_value = {"backendVersion": "0.x.y"}
+
+ client = StreamPipesClient(
+ client_config=StreamPipesClientConfig(
+ credential_provider=StreamPipesApiKeyCredentials(username="user", api_key="key"),
+ host_address="localhost",
+ )
+ )
+
+ client.dataStreamApi.put(DataStream(**self.data_stream_get))
+
+ http_session_mock.put.assert_called_with(
+ url="https://localhost:80/streampipes-backend/api/v2/streams/"
+ "urn:streampipes.apache.org:eventstream:uPDKLI",
+ data=json.dumps(self.data_stream_get),
+ headers={"Content-type": "application/json"},
+ )
+
@patch("streampipes.client.client.Session", autospec=True)
@patch("streampipes.client.client.StreamPipesClient._get_server_version", autospec=True)
def test_endpoint_data_stream_happy_path(self, server_version: MagicMock, http_session: MagicMock):
diff --git a/streampipes-client-python/tests/functions/test_function_handler.py b/streampipes-client-python/tests/functions/test_function_handler.py
index d7fa3348aa..c0a65e23f7 100644
--- a/streampipes-client-python/tests/functions/test_function_handler.py
+++ b/streampipes-client-python/tests/functions/test_function_handler.py
@@ -349,7 +349,7 @@ class TestFunctionHandler(TestCase):
pulish_event: MagicMock,
get_message: MagicMock,
time: MagicMock,
- *args: Tuple[AsyncMock]
+ *args: Tuple[AsyncMock],
):
http_session_mock = MagicMock()
http_session_mock.get.return_value.json.return_value = self.data_stream_nats
@@ -394,6 +394,75 @@ class TestFunctionHandler(TestCase):
self.assertListEqual(output_events, [{"number": i, "timestamp": 0} for i in range(len(self.test_stream_data1))])
+ @patch("streampipes.endpoint.api.data_stream.DataStreamEndpoint.put", autospec=True)
+ @patch("streampipes.endpoint.api.data_stream.DataStreamEndpoint.get", autospec=True)
+ @patch("streampipes.functions.broker.nats.nats_publisher.connect", autospec=True)
+ @patch("streampipes.functions.broker.nats.nats_consumer.connect", autospec=True)
+ @patch("streampipes.functions.streampipes_function.time", autospec=True)
+ @patch("streampipes.functions.broker.NatsConsumer.get_message", autospec=True)
+ @patch("streampipes.functions.broker.NatsPublisher.publish_event", autospec=True)
+ @patch("streampipes.client.client.Session", autospec=True)
+ @patch("streampipes.client.client.StreamPipesClient._get_server_version", autospec=True)
+ def test_function_output_stream_updates_existing_stream_nats(
+ self,
+ server_version: MagicMock,
+ http_session: MagicMock,
+ pulish_event: MagicMock,
+ get_message: MagicMock,
+ time: MagicMock,
+ _consumer_connect: AsyncMock,
+ _publisher_connect: AsyncMock,
+ get_data_stream: MagicMock,
+ put_data_stream: MagicMock,
+ ):
+ http_session_mock = MagicMock()
+ http_session_mock.headers = {}
+ http_session.return_value = http_session_mock
+
+ server_version.return_value = {"backendVersion": "0.x.y"}
+
+ output_events = []
+
+ def save_event(self, event: Dict[str, Any]):
+ output_events.append(event)
+
+ def get_stream(endpoint, stream_id):
+ if stream_id == "a1d":
+ existing_output_stream = create_data_stream(
+ "test", attributes={"number": RuntimeType.INTEGER.value}, stream_id="a1d"
+ )
+ return existing_output_stream
+ if stream_id == self.data_stream_nats["elementId"]:
+ return DataStream(**self.data_stream_nats)
+ raise AssertionError(f"Unexpected stream id requested: {stream_id}")
+
+ get_data_stream.side_effect = get_stream
+ pulish_event.side_effect = save_event
+ get_message.return_value = TestMessageIterator(self.test_stream_data1)
+ time.side_effect = lambda: 0
+
+ client = StreamPipesClient(
+ client_config=StreamPipesClientConfig(
+ credential_provider=StreamPipesApiKeyCredentials(username="user", api_key="key"),
+ host_address="localhost",
+ )
+ )
+
+ output_stream = create_data_stream("test", attributes={"number": RuntimeType.INTEGER.value}, stream_id="a1d")
+ test_function = TestFunctionOutput(
+ function_definition=FunctionDefinition(
+ consumed_streams=["urn:streampipes.apache.org:eventstream:uPDKLI"]
+ ).add_output_data_stream(output_stream)
+ )
+ registration = Registration()
+ registration.register(test_function)
+ function_handler = FunctionHandler(registration, client)
+ function_handler.initializeFunctions()
+
+ get_data_stream.assert_any_call(client.dataStreamApi, output_stream.element_id)
+ put_data_stream.assert_called_once_with(client.dataStreamApi, output_stream)
+ self.assertListEqual(output_events, [{"number": i, "timestamp": 0} for i in range(len(self.test_stream_data1))])
+
@patch("streampipes.functions.broker.kafka.kafka_publisher.Producer", autospec=True)
@patch("streampipes.functions.streampipes_function.time", autospec=True)
@patch("streampipes.functions.broker.kafka.kafka_consumer.KafkaConnection", autospec=True)
diff --git a/streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java b/streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java
index 8e38497457..9a68ba38e3 100644
--- a/streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java
+++ b/streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java
@@ -19,49 +19,30 @@
package org.apache.streampipes.connect.management.management;
import org.apache.streampipes.commons.exceptions.connect.AdapterException;
-import org.apache.streampipes.commons.prometheus.pipelines.PipelinesStats;
import org.apache.streampipes.manager.api.extensions.ExtensionServiceRequestManager;
-import org.apache.streampipes.manager.execution.PipelineExecutor;
-import org.apache.streampipes.manager.matching.PipelineVerificationHandlerV2;
-import org.apache.streampipes.manager.pipeline.PipelineManager;
+import org.apache.streampipes.manager.pipeline.update.PipelineUpdateCoordinator;
import org.apache.streampipes.model.SpDataStream;
-import org.apache.streampipes.model.base.NamedStreamPipesEntity;
import org.apache.streampipes.model.connect.adapter.AdapterDescription;
import org.apache.streampipes.model.connect.adapter.PipelineUpdateInfo;
-import org.apache.streampipes.model.message.PipelineModificationMessage;
-import org.apache.streampipes.model.pipeline.Pipeline;
-import org.apache.streampipes.model.pipeline.PipelineElementValidationInfo;
-import org.apache.streampipes.model.pipeline.PipelineHealthStatus;
import org.apache.streampipes.resource.management.AdapterResourceManager;
import org.apache.streampipes.resource.management.DataStreamResourceManager;
import org.apache.streampipes.resource.management.SpResourceManager;
-import org.apache.streampipes.storage.management.StorageDispatcher;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
-import java.util.stream.Stream;
public class AdapterUpdateManagement {
- private static final Logger LOG = LoggerFactory.getLogger(AdapterUpdateManagement.class);
-
private final AdapterMasterManagement adapterMasterManagement;
private final AdapterResourceManager adapterResourceManager;
private final DataStreamResourceManager dataStreamResourceManager;
- private final ExtensionServiceRequestManager requestManager;
- private static final PipelinesStats pipelinesStats = new PipelinesStats();
+ private final PipelineUpdateCoordinator pipelineUpdateCoordinator;
public AdapterUpdateManagement(AdapterMasterManagement adapterMasterManagement,
ExtensionServiceRequestManager requestManager) {
this.adapterMasterManagement = adapterMasterManagement;
this.adapterResourceManager = new SpResourceManager().manageAdapters();
this.dataStreamResourceManager = new SpResourceManager().manageDataStreams();
- this.requestManager = requestManager;
+ this.pipelineUpdateCoordinator = new PipelineUpdateCoordinator(requestManager);
}
public void updateAdapter(AdapterDescription ad)
@@ -77,36 +58,7 @@ public class AdapterUpdateManagement {
// update data source in database
this.updateDataSource(ad);
- // update pipelines
- var affectedPipelines = PipelineManager.getPipelinesContainingElements(ad.getCorrespondingDataStreamElementId());
-
- affectedPipelines.forEach(p -> {
- var shouldRestartPipeline = p.isRunning();
- if (shouldRestartPipeline) {
- new PipelineExecutor(p, requestManager).stopPipeline(true);
- }
- var storedPipeline = PipelineManager.getPipeline(p.getPipelineId());
- var pipeline = applyUpdatedDataStream(storedPipeline, ad);
- try {
- var modificationMessage = new PipelineVerificationHandlerV2(pipeline, requestManager).verifyPipeline();
- var updateInfo = makeUpdateInfo(modificationMessage, pipeline);
- var modifiedPipeline = new PipelineVerificationHandlerV2(pipeline, requestManager)
- .makeModifiedPipeline().pipeline();
- var canAutoMigrate = canAutoMigrate(modificationMessage);
- if (!canAutoMigrate) {
- modifiedPipeline.setHealthStatus(PipelineHealthStatus.REQUIRES_ATTENTION);
- pipelinesStats.updatePipelineHealthState(modifiedPipeline.getElementId(), modifiedPipeline.getName(),modifiedPipeline.getHealthStatus().toString());
- modifiedPipeline.setPipelineNotifications(toNotification(updateInfo));
- modifiedPipeline.setValid(false);
- }
- StorageDispatcher.INSTANCE.getNoSqlStore().getPipelineStorageAPI().updateElement(modifiedPipeline);
- if (shouldRestartPipeline && canAutoMigrate) {
- new PipelineExecutor(PipelineManager.getPipeline(p.getPipelineId()), requestManager).startPipeline();
- }
- } catch (Exception e) {
- LOG.error("Could not update pipeline {}", pipeline.getName(), e);
- }
- });
+ pipelineUpdateCoordinator.updatePipelines(ad);
if (shouldRestart) {
this.adapterMasterManagement.startStreamAdapter(ad.getElementId());
@@ -114,95 +66,7 @@ public class AdapterUpdateManagement {
}
public List<PipelineUpdateInfo> checkPipelineMigrations(AdapterDescription adapterDescription) {
- var affectedPipelines = PipelineManager
- .getPipelinesContainingElements(adapterDescription.getCorrespondingDataStreamElementId());
- var updateInfos = new ArrayList<PipelineUpdateInfo>();
-
- affectedPipelines.forEach(pipeline -> {
- var updatedPipeline = applyUpdatedDataStream(pipeline, adapterDescription);
- try {
- var modificationMessage = new PipelineVerificationHandlerV2(updatedPipeline, requestManager).verifyPipeline();
- var updateInfo = makeUpdateInfo(modificationMessage, updatedPipeline);
- updateInfos.add(updateInfo);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- });
-
- return updateInfos;
- }
-
- private PipelineUpdateInfo makeUpdateInfo(PipelineModificationMessage modificationMessage,
- Pipeline pipeline) {
- var updateInfo = new PipelineUpdateInfo();
- updateInfo.setPipelineId(pipeline.getPipelineId());
- updateInfo.setPipelineName(pipeline.getName());
- updateInfo.setCanAutoMigrate(canAutoMigrate(modificationMessage));
- updateInfo.setValidationInfos(extractModificationWarnings(pipeline, modificationMessage));
- return updateInfo;
- }
-
- private boolean canAutoMigrate(PipelineModificationMessage modificationMessage) {
- return modificationMessage
- .getPipelineModifications()
- .stream()
- .allMatch(m -> m.isPipelineElementValid() && m.getValidationInfos().isEmpty());
- }
-
- private List<String> toNotification(PipelineUpdateInfo updateInfo) {
- var notifications = new ArrayList<String>();
- updateInfo.getValidationInfos().keySet().forEach((k) -> {
- var msg = updateInfo
- .getValidationInfos()
- .get(k)
- .stream()
- .map(PipelineElementValidationInfo::getMessage)
- .toList()
- .toString();
- notifications.add(String.format("Adapter modification: %s: %s", k, msg));
- });
- return notifications;
- }
-
- private Map<String, List<PipelineElementValidationInfo>> extractModificationWarnings(
- Pipeline pipeline,
- PipelineModificationMessage modificationMessage) {
- var infos = new HashMap<String, List<PipelineElementValidationInfo>>();
- modificationMessage
- .getPipelineModifications()
- .stream()
- .filter(v -> !v.getValidationInfos().isEmpty())
- .forEach(m -> infos.put(getPipelineElementName(pipeline, m.getElementId()), m.getValidationInfos()));
-
- return infos;
- }
-
- private String getPipelineElementName(Pipeline pipeline,
- String elementId) {
- return Stream
- .concat(pipeline.getSepas().stream(), pipeline.getActions().stream())
- .filter(p -> p.getElementId().equals(elementId))
- .findFirst()
- .map(NamedStreamPipesEntity::getName)
- .orElse(elementId);
- }
-
- private Pipeline applyUpdatedDataStream(Pipeline originalPipeline,
- AdapterDescription updatedAdapter) {
- var updatedStreams = originalPipeline
- .getStreams()
- .stream()
- .peek(s -> {
- if (s.getElementId().equals(updatedAdapter.getCorrespondingDataStreamElementId())) {
- s.setEventSchema(updatedAdapter.getEventSchema());
- s.setName(updatedAdapter.getName());
- }
- })
- .toList();
-
- originalPipeline.setStreams(updatedStreams);
-
- return originalPipeline;
+ return pipelineUpdateCoordinator.checkPipelineMigrations(adapterDescription);
}
private void updateDataSource(AdapterDescription ad) {
diff --git a/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/pipeline/update/DataStreamUpdateManagement.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/pipeline/update/DataStreamUpdateManagement.java
new file mode 100644
index 0000000000..f4f51d2ee1
--- /dev/null
+++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/pipeline/update/DataStreamUpdateManagement.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.pipeline.update;
+
+import org.apache.streampipes.manager.api.extensions.ExtensionServiceRequestManager;
+import org.apache.streampipes.model.SpDataStream;
+import org.apache.streampipes.model.connect.adapter.PipelineUpdateInfo;
+import org.apache.streampipes.resource.management.DataStreamResourceManager;
+import org.apache.streampipes.resource.management.SpResourceManager;
+
+import java.util.List;
+
+public class DataStreamUpdateManagement {
+
+ private final DataStreamResourceManager dataStreamResourceManager;
+ private final PipelineUpdateCoordinator pipelineUpdateCoordinator;
+
+ public DataStreamUpdateManagement(ExtensionServiceRequestManager requestManager) {
+ this.dataStreamResourceManager = new SpResourceManager().manageDataStreams();
+ this.pipelineUpdateCoordinator = new PipelineUpdateCoordinator(requestManager);
+ }
+
+ public void updateDataStream(SpDataStream dataStream) {
+ dataStreamResourceManager.update(dataStream);
+ pipelineUpdateCoordinator.updatePipelines(dataStream);
+ }
+
+ public List<PipelineUpdateInfo> checkPipelineMigrations(SpDataStream dataStream) {
+ return pipelineUpdateCoordinator.checkPipelineMigrations(dataStream);
+ }
+}
diff --git a/streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/pipeline/update/PipelineUpdateCoordinator.java
similarity index 52%
copy from streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java
copy to streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/pipeline/update/PipelineUpdateCoordinator.java
index 8e38497457..6de0a17945 100644
--- a/streampipes-connect-management/src/main/java/org/apache/streampipes/connect/management/management/AdapterUpdateManagement.java
+++ b/streampipes-pipeline-management/src/main/java/org/apache/streampipes/manager/pipeline/update/PipelineUpdateCoordinator.java
@@ -16,9 +16,8 @@
*
*/
-package org.apache.streampipes.connect.management.management;
+package org.apache.streampipes.manager.pipeline.update;
-import org.apache.streampipes.commons.exceptions.connect.AdapterException;
import org.apache.streampipes.commons.prometheus.pipelines.PipelinesStats;
import org.apache.streampipes.manager.api.extensions.ExtensionServiceRequestManager;
import org.apache.streampipes.manager.execution.PipelineExecutor;
@@ -32,9 +31,7 @@ import org.apache.streampipes.model.message.PipelineModificationMessage;
import org.apache.streampipes.model.pipeline.Pipeline;
import org.apache.streampipes.model.pipeline.PipelineElementValidationInfo;
import org.apache.streampipes.model.pipeline.PipelineHealthStatus;
-import org.apache.streampipes.resource.management.AdapterResourceManager;
-import org.apache.streampipes.resource.management.DataStreamResourceManager;
-import org.apache.streampipes.resource.management.SpResourceManager;
+import org.apache.streampipes.model.schema.EventSchema;
import org.apache.streampipes.storage.management.StorageDispatcher;
import org.slf4j.Logger;
@@ -46,84 +43,106 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
-public class AdapterUpdateManagement {
+public class PipelineUpdateCoordinator {
- private static final Logger LOG = LoggerFactory.getLogger(AdapterUpdateManagement.class);
+ private static final Logger LOG = LoggerFactory.getLogger(PipelineUpdateCoordinator.class);
+ private static final PipelinesStats PIPELINES_STATS = new PipelinesStats();
- private final AdapterMasterManagement adapterMasterManagement;
- private final AdapterResourceManager adapterResourceManager;
- private final DataStreamResourceManager dataStreamResourceManager;
private final ExtensionServiceRequestManager requestManager;
- private static final PipelinesStats pipelinesStats = new PipelinesStats();
- public AdapterUpdateManagement(AdapterMasterManagement adapterMasterManagement,
- ExtensionServiceRequestManager requestManager) {
- this.adapterMasterManagement = adapterMasterManagement;
- this.adapterResourceManager = new SpResourceManager().manageAdapters();
- this.dataStreamResourceManager = new SpResourceManager().manageDataStreams();
+ public PipelineUpdateCoordinator(ExtensionServiceRequestManager requestManager) {
this.requestManager = requestManager;
}
- public void updateAdapter(AdapterDescription ad)
- throws AdapterException {
- // update adapter in database
- this.adapterResourceManager.encryptAndUpdate(ad);
- boolean shouldRestart = ad.isRunning();
+ public void updatePipelines(SpDataStream dataStream) {
+ updatePipelines(
+ dataStream.getElementId(),
+ dataStream.getName(),
+ dataStream.getEventSchema(),
+ "Data stream"
+ );
+ }
- if (ad.isRunning()) {
- this.adapterMasterManagement.stopStreamAdapter(ad.getElementId(), true);
- }
+ public void updatePipelines(AdapterDescription adapterDescription) {
+ updatePipelines(
+ adapterDescription.getCorrespondingDataStreamElementId(),
+ adapterDescription.getName(),
+ adapterDescription.getEventSchema(),
+ "Adapter"
+ );
+ }
- // update data source in database
- this.updateDataSource(ad);
+ public List<PipelineUpdateInfo> checkPipelineMigrations(SpDataStream dataStream) {
+ return checkPipelineMigrations(
+ dataStream.getElementId(),
+ dataStream.getName(),
+ dataStream.getEventSchema()
+ );
+ }
+
+ public List<PipelineUpdateInfo> checkPipelineMigrations(AdapterDescription adapterDescription) {
+ return checkPipelineMigrations(
+ adapterDescription.getCorrespondingDataStreamElementId(),
+ adapterDescription.getName(),
+ adapterDescription.getEventSchema()
+ );
+ }
- // update pipelines
- var affectedPipelines = PipelineManager.getPipelinesContainingElements(ad.getCorrespondingDataStreamElementId());
+ private void updatePipelines(String affectedElementId,
+ String updatedStreamName,
+ EventSchema updatedEventSchema,
+ String notificationType) {
+ var affectedPipelines = PipelineManager.getPipelinesContainingElements(affectedElementId);
- affectedPipelines.forEach(p -> {
- var shouldRestartPipeline = p.isRunning();
+ affectedPipelines.forEach(pipeline -> {
+ var shouldRestartPipeline = pipeline.isRunning();
if (shouldRestartPipeline) {
- new PipelineExecutor(p, requestManager).stopPipeline(true);
+ new PipelineExecutor(pipeline, requestManager).stopPipeline(true);
}
- var storedPipeline = PipelineManager.getPipeline(p.getPipelineId());
- var pipeline = applyUpdatedDataStream(storedPipeline, ad);
+
+ var storedPipeline = PipelineManager.getPipeline(pipeline.getPipelineId());
+ var updatedPipeline = updatePipeline(storedPipeline, affectedElementId, updatedStreamName, updatedEventSchema);
+
try {
- var modificationMessage = new PipelineVerificationHandlerV2(pipeline, requestManager).verifyPipeline();
- var updateInfo = makeUpdateInfo(modificationMessage, pipeline);
- var modifiedPipeline = new PipelineVerificationHandlerV2(pipeline, requestManager)
- .makeModifiedPipeline().pipeline();
+ var verificationHandler = new PipelineVerificationHandlerV2(updatedPipeline, requestManager);
+ var modificationMessage = verificationHandler.verifyPipeline();
+ var updateInfo = makeUpdateInfo(modificationMessage, updatedPipeline);
+ var modifiedPipeline = verificationHandler.makeModifiedPipeline().pipeline();
var canAutoMigrate = canAutoMigrate(modificationMessage);
+
if (!canAutoMigrate) {
modifiedPipeline.setHealthStatus(PipelineHealthStatus.REQUIRES_ATTENTION);
- pipelinesStats.updatePipelineHealthState(modifiedPipeline.getElementId(), modifiedPipeline.getName(),modifiedPipeline.getHealthStatus().toString());
- modifiedPipeline.setPipelineNotifications(toNotification(updateInfo));
+ PIPELINES_STATS.updatePipelineHealthState(
+ modifiedPipeline.getElementId(),
+ modifiedPipeline.getName(),
+ modifiedPipeline.getHealthStatus().toString()
+ );
+ modifiedPipeline.setPipelineNotifications(toNotification(updateInfo, notificationType));
modifiedPipeline.setValid(false);
}
+
StorageDispatcher.INSTANCE.getNoSqlStore().getPipelineStorageAPI().updateElement(modifiedPipeline);
+
if (shouldRestartPipeline && canAutoMigrate) {
- new PipelineExecutor(PipelineManager.getPipeline(p.getPipelineId()), requestManager).startPipeline();
+ new PipelineExecutor(PipelineManager.getPipeline(pipeline.getPipelineId()), requestManager).startPipeline();
}
} catch (Exception e) {
- LOG.error("Could not update pipeline {}", pipeline.getName(), e);
+ LOG.error("Could not update pipeline {}", updatedPipeline.getName(), e);
}
});
-
- if (shouldRestart) {
- this.adapterMasterManagement.startStreamAdapter(ad.getElementId());
- }
}
- public List<PipelineUpdateInfo> checkPipelineMigrations(AdapterDescription adapterDescription) {
- var affectedPipelines = PipelineManager
- .getPipelinesContainingElements(adapterDescription.getCorrespondingDataStreamElementId());
+ private List<PipelineUpdateInfo> checkPipelineMigrations(String affectedElementId,
+ String updatedStreamName,
+ EventSchema updatedEventSchema) {
+ var affectedPipelines = PipelineManager.getPipelinesContainingElements(affectedElementId);
var updateInfos = new ArrayList<PipelineUpdateInfo>();
affectedPipelines.forEach(pipeline -> {
- var updatedPipeline = applyUpdatedDataStream(pipeline, adapterDescription);
+ var updatedPipeline = updatePipeline(pipeline, affectedElementId, updatedStreamName, updatedEventSchema);
try {
var modificationMessage = new PipelineVerificationHandlerV2(updatedPipeline, requestManager).verifyPipeline();
- var updateInfo = makeUpdateInfo(modificationMessage, updatedPipeline);
- updateInfos.add(updateInfo);
+ updateInfos.add(makeUpdateInfo(modificationMessage, updatedPipeline));
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -132,6 +151,25 @@ public class AdapterUpdateManagement {
return updateInfos;
}
+ private Pipeline updatePipeline(Pipeline pipeline,
+ String affectedElementId,
+ String updatedStreamName,
+ EventSchema updatedEventSchema) {
+ var updatedStreams = pipeline
+ .getStreams()
+ .stream()
+ .peek(stream -> {
+ if (stream.getElementId().equals(affectedElementId)) {
+ stream.setEventSchema(updatedEventSchema);
+ stream.setName(updatedStreamName);
+ }
+ })
+ .toList();
+
+ pipeline.setStreams(updatedStreams);
+ return pipeline;
+ }
+
private PipelineUpdateInfo makeUpdateInfo(PipelineModificationMessage modificationMessage,
Pipeline pipeline) {
var updateInfo = new PipelineUpdateInfo();
@@ -146,20 +184,20 @@ public class AdapterUpdateManagement {
return modificationMessage
.getPipelineModifications()
.stream()
- .allMatch(m -> m.isPipelineElementValid() && m.getValidationInfos().isEmpty());
+ .allMatch(modification -> modification.isPipelineElementValid()
+ && modification.getValidationInfos().isEmpty());
}
- private List<String> toNotification(PipelineUpdateInfo updateInfo) {
+ private List<String> toNotification(PipelineUpdateInfo updateInfo,
+ String updateType) {
var notifications = new ArrayList<String>();
- updateInfo.getValidationInfos().keySet().forEach((k) -> {
- var msg = updateInfo
- .getValidationInfos()
- .get(k)
+ updateInfo.getValidationInfos().forEach((pipelineElementName, validationInfos) -> {
+ var message = validationInfos
.stream()
.map(PipelineElementValidationInfo::getMessage)
.toList()
.toString();
- notifications.add(String.format("Adapter modification: %s: %s", k, msg));
+ notifications.add(String.format("%s modification: %s: %s", updateType, pipelineElementName, message));
});
return notifications;
}
@@ -171,8 +209,11 @@ public class AdapterUpdateManagement {
modificationMessage
.getPipelineModifications()
.stream()
- .filter(v -> !v.getValidationInfos().isEmpty())
- .forEach(m -> infos.put(getPipelineElementName(pipeline, m.getElementId()), m.getValidationInfos()));
+ .filter(modification -> !modification.getValidationInfos().isEmpty())
+ .forEach(modification -> infos.put(
+ getPipelineElementName(pipeline, modification.getElementId()),
+ modification.getValidationInfos()
+ ));
return infos;
}
@@ -181,37 +222,9 @@ public class AdapterUpdateManagement {
String elementId) {
return Stream
.concat(pipeline.getSepas().stream(), pipeline.getActions().stream())
- .filter(p -> p.getElementId().equals(elementId))
+ .filter(pipelineElement -> pipelineElement.getElementId().equals(elementId))
.findFirst()
.map(NamedStreamPipesEntity::getName)
.orElse(elementId);
}
-
- private Pipeline applyUpdatedDataStream(Pipeline originalPipeline,
- AdapterDescription updatedAdapter) {
- var updatedStreams = originalPipeline
- .getStreams()
- .stream()
- .peek(s -> {
- if (s.getElementId().equals(updatedAdapter.getCorrespondingDataStreamElementId())) {
- s.setEventSchema(updatedAdapter.getEventSchema());
- s.setName(updatedAdapter.getName());
- }
- })
- .toList();
-
- originalPipeline.setStreams(updatedStreams);
-
- return originalPipeline;
- }
-
- private void updateDataSource(AdapterDescription ad) {
- // get data source
- SpDataStream dataStream = this.dataStreamResourceManager.find(ad.getCorrespondingDataStreamElementId());
-
- SourcesManagement.updateDataStream(ad, dataStream);
-
- // Update data source in database
- this.dataStreamResourceManager.update(dataStream);
- }
}
diff --git a/streampipes-pipeline-management/src/test/java/org/apache/streampipes/manager/pipeline/update/PipelineUpdateCoordinatorTest.java b/streampipes-pipeline-management/src/test/java/org/apache/streampipes/manager/pipeline/update/PipelineUpdateCoordinatorTest.java
new file mode 100644
index 0000000000..638a64fc24
--- /dev/null
+++ b/streampipes-pipeline-management/src/test/java/org/apache/streampipes/manager/pipeline/update/PipelineUpdateCoordinatorTest.java
@@ -0,0 +1,281 @@
+/*
+ * 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.pipeline.update;
+
+import org.apache.streampipes.manager.api.extensions.ExtensionServiceRequestManager;
+import org.apache.streampipes.manager.execution.PipelineExecutor;
+import org.apache.streampipes.manager.matching.PipelineVerificationHandlerV2;
+import org.apache.streampipes.manager.pipeline.PipelineManager;
+import org.apache.streampipes.model.SpDataStream;
+import org.apache.streampipes.model.connect.adapter.AdapterDescription;
+import org.apache.streampipes.model.connect.adapter.PipelineUpdateInfo;
+import org.apache.streampipes.model.graph.DataProcessorInvocation;
+import org.apache.streampipes.model.message.PipelineModificationMessage;
+import org.apache.streampipes.model.pipeline.Pipeline;
+import org.apache.streampipes.model.pipeline.PipelineElementValidationInfo;
+import org.apache.streampipes.model.pipeline.PipelineHealthStatus;
+import org.apache.streampipes.model.pipeline.PipelineModification;
+import org.apache.streampipes.model.pipeline.PipelineModificationResult;
+import org.apache.streampipes.model.schema.EventSchema;
+import org.apache.streampipes.storage.api.core.INoSqlStorage;
+import org.apache.streampipes.storage.api.pipeline.IPipelineStorage;
+import org.apache.streampipes.storage.couchdb.CouchDbStorageManager;
+
+import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.MockedConstruction;
+import org.mockito.MockedStatic;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockConstruction;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class PipelineUpdateCoordinatorTest {
+
+ @Test
+ void updatePipelines_ShouldRestartRunningPipelinesForDataStreamUpdates() {
+ var requestManager = mock(ExtensionServiceRequestManager.class);
+ var coordinator = new PipelineUpdateCoordinator(requestManager);
+ var dataStream = makeDataStream("stream-1", "Updated stream");
+ var affectedPipeline = makePipeline("pipeline-1", "Pipeline", true, "stream-1", "Old stream");
+ var storedPipeline = makePipeline("pipeline-1", "Pipeline", true, "stream-1", "Old stream");
+ var modifiedPipeline = makePipeline("pipeline-1", "Pipeline", true, "stream-1", "Updated stream");
+
+ var modificationMessage = new PipelineModificationMessage(List.of(validModification("sepa-1")));
+ var noSqlStorage = mock(INoSqlStorage.class);
+ var pipelineStorage = mock(IPipelineStorage.class);
+ var verifiedPipelines = new ArrayList<Pipeline>();
+ when(noSqlStorage.getPipelineStorageAPI()).thenReturn(pipelineStorage);
+
+ try (MockedStatic<PipelineManager> pipelineManager = mockStatic(PipelineManager.class);
+ MockedConstruction<PipelineVerificationHandlerV2> verificationHandlerConstruction =
+ mockConstruction(PipelineVerificationHandlerV2.class, (mock, context) -> {
+ verifiedPipelines.add((Pipeline) context.arguments().get(0));
+ when(mock.verifyPipeline()).thenReturn(modificationMessage);
+ when(mock.makeModifiedPipeline()).thenReturn(new PipelineModificationResult(modifiedPipeline, List.of()));
+ });
+ MockedConstruction<CouchDbStorageManager> storageManagerConstruction =
+ mockConstruction(CouchDbStorageManager.class, (mock, context) ->
+ when(mock.getPipelineStorageAPI()).thenReturn(pipelineStorage));
+ MockedConstruction<PipelineExecutor> executorConstruction =
+ mockConstruction(PipelineExecutor.class)) {
+
+ pipelineManager.when(() -> PipelineManager.getPipelinesContainingElements("stream-1"))
+ .thenReturn(List.of(affectedPipeline));
+ pipelineManager.when(() -> PipelineManager.getPipeline("pipeline-1"))
+ .thenReturn(storedPipeline, modifiedPipeline);
+
+ coordinator.updatePipelines(dataStream);
+
+ assertEquals(1, verificationHandlerConstruction.constructed().size());
+ var updatedPipeline = verifiedPipelines.get(0);
+ assertEquals("Updated stream", updatedPipeline.getStreams().get(0).getName());
+ assertSame(dataStream.getEventSchema(), updatedPipeline.getStreams().get(0).getEventSchema());
+
+ assertEquals(2, executorConstruction.constructed().size());
+ verify(executorConstruction.constructed().get(0)).stopPipeline(true);
+ verify(executorConstruction.constructed().get(1)).startPipeline();
+ assertEquals(1, storageManagerConstruction.constructed().size());
+ verify(pipelineStorage).updateElement(modifiedPipeline);
+ }
+ }
+
+ @Test
+ void updatePipelines_ShouldMarkPipelinesRequiringAttentionForAdapterUpdates() {
+ var requestManager = mock(ExtensionServiceRequestManager.class);
+ var coordinator = new PipelineUpdateCoordinator(requestManager);
+ var adapterDescription = makeAdapter("stream-1", "Updated adapter");
+ var storedPipeline = makePipeline("pipeline-1", "Pipeline", false, "stream-1", "Old stream");
+ var modifiedPipeline = makePipeline("pipeline-1", "Pipeline", false, "stream-1", "Updated adapter");
+ modifiedPipeline.setSepas(List.of(makeSepa("sepa-1", "Processor")));
+
+ var warning = PipelineElementValidationInfo.error("Schema mismatch");
+ var modificationMessage = new PipelineModificationMessage(List.of(invalidModification("sepa-1", warning)));
+ var noSqlStorage = mock(INoSqlStorage.class);
+ var pipelineStorage = mock(IPipelineStorage.class);
+ var verifiedPipelines = new ArrayList<Pipeline>();
+ when(noSqlStorage.getPipelineStorageAPI()).thenReturn(pipelineStorage);
+
+ try (MockedStatic<PipelineManager> pipelineManager = mockStatic(PipelineManager.class);
+ MockedConstruction<PipelineVerificationHandlerV2> verificationHandlerConstruction =
+ mockConstruction(PipelineVerificationHandlerV2.class, (mock, context) -> {
+ verifiedPipelines.add((Pipeline) context.arguments().get(0));
+ when(mock.verifyPipeline()).thenReturn(modificationMessage);
+ when(mock.makeModifiedPipeline()).thenReturn(new PipelineModificationResult(modifiedPipeline, List.of()));
+ });
+ MockedConstruction<CouchDbStorageManager> storageManagerConstruction =
+ mockConstruction(CouchDbStorageManager.class, (mock, context) ->
+ when(mock.getPipelineStorageAPI()).thenReturn(pipelineStorage));
+ MockedConstruction<PipelineExecutor> executorConstruction =
+ mockConstruction(PipelineExecutor.class)) {
+
+ pipelineManager.when(() -> PipelineManager.getPipelinesContainingElements("stream-1"))
+ .thenReturn(List.of(storedPipeline));
+ pipelineManager.when(() -> PipelineManager.getPipeline("pipeline-1"))
+ .thenReturn(storedPipeline);
+
+ coordinator.updatePipelines(adapterDescription);
+
+ assertEquals(1, verificationHandlerConstruction.constructed().size());
+ var updatedPipeline = verifiedPipelines.get(0);
+ assertEquals("Updated adapter", updatedPipeline.getStreams().get(0).getName());
+ assertSame(adapterDescription.getEventSchema(), updatedPipeline.getStreams().get(0).getEventSchema());
+
+ assertEquals(0, executorConstruction.constructed().size());
+ assertEquals(1, storageManagerConstruction.constructed().size());
+ var pipelineCaptor = ArgumentCaptor.forClass(Pipeline.class);
+ verify(pipelineStorage).updateElement(pipelineCaptor.capture());
+ assertEquals(PipelineHealthStatus.REQUIRES_ATTENTION, pipelineCaptor.getValue().getHealthStatus());
+ assertFalse(pipelineCaptor.getValue().isValid());
+ assertEquals(List.of("Adapter modification: Processor: [Schema mismatch]"),
+ pipelineCaptor.getValue().getPipelineNotifications());
+ }
+ }
+
+ @Test
+ void checkPipelineMigrations_ShouldUseUpdatedDataStreamValues() {
+ var requestManager = mock(ExtensionServiceRequestManager.class);
+ var coordinator = new PipelineUpdateCoordinator(requestManager);
+ var dataStream = makeDataStream("stream-1", "Updated stream");
+ var pipeline = makePipeline("pipeline-1", "Pipeline", false, "stream-1", "Old stream");
+ var modificationMessage = new PipelineModificationMessage(List.of(validModification("sepa-1")));
+ var verifiedPipelines = new ArrayList<Pipeline>();
+
+ try (MockedStatic<PipelineManager> pipelineManager = mockStatic(PipelineManager.class);
+ MockedConstruction<PipelineVerificationHandlerV2> verificationHandlerConstruction =
+ mockConstruction(PipelineVerificationHandlerV2.class, (mock, context) -> {
+ verifiedPipelines.add((Pipeline) context.arguments().get(0));
+ when(mock.verifyPipeline()).thenReturn(modificationMessage);
+ })) {
+
+ pipelineManager.when(() -> PipelineManager.getPipelinesContainingElements("stream-1"))
+ .thenReturn(List.of(pipeline));
+
+ var result = coordinator.checkPipelineMigrations(dataStream);
+
+ assertEquals(1, result.size());
+ assertEquals("pipeline-1", result.get(0).getPipelineId());
+ assertEquals("Pipeline", result.get(0).getPipelineName());
+ assertTrue(result.get(0).isCanAutoMigrate());
+
+ assertEquals(1, verificationHandlerConstruction.constructed().size());
+ var updatedPipeline = verifiedPipelines.get(0);
+ assertEquals("Updated stream", updatedPipeline.getStreams().get(0).getName());
+ assertSame(dataStream.getEventSchema(), updatedPipeline.getStreams().get(0).getEventSchema());
+ }
+ }
+
+ @Test
+ void checkPipelineMigrations_ShouldReportWarningsForAdapterUpdates() {
+ var requestManager = mock(ExtensionServiceRequestManager.class);
+ var coordinator = new PipelineUpdateCoordinator(requestManager);
+ var adapterDescription = makeAdapter("stream-1", "Updated adapter");
+ var pipeline = makePipeline("pipeline-1", "Pipeline", false, "stream-1", "Old stream");
+ pipeline.setSepas(List.of(makeSepa("sepa-1", "Processor")));
+ var warning = PipelineElementValidationInfo.error("Schema mismatch");
+ var modificationMessage = new PipelineModificationMessage(List.of(invalidModification("sepa-1", warning)));
+ var verifiedPipelines = new ArrayList<Pipeline>();
+
+ try (MockedStatic<PipelineManager> pipelineManager = mockStatic(PipelineManager.class);
+ MockedConstruction<PipelineVerificationHandlerV2> verificationHandlerConstruction =
+ mockConstruction(PipelineVerificationHandlerV2.class, (mock, context) -> {
+ verifiedPipelines.add((Pipeline) context.arguments().get(0));
+ when(mock.verifyPipeline()).thenReturn(modificationMessage);
+ })) {
+
+ pipelineManager.when(() -> PipelineManager.getPipelinesContainingElements("stream-1"))
+ .thenReturn(List.of(pipeline));
+
+ var result = coordinator.checkPipelineMigrations(adapterDescription);
+
+ assertEquals(1, result.size());
+ PipelineUpdateInfo updateInfo = result.get(0);
+ assertFalse(updateInfo.isCanAutoMigrate());
+ assertEquals(1, updateInfo.getValidationInfos().size());
+ assertEquals(List.of(warning), updateInfo.getValidationInfos().get("Processor"));
+
+ assertEquals(1, verificationHandlerConstruction.constructed().size());
+ var updatedPipeline = verifiedPipelines.get(0);
+ assertEquals("Updated adapter", updatedPipeline.getStreams().get(0).getName());
+ assertSame(adapterDescription.getEventSchema(), updatedPipeline.getStreams().get(0).getEventSchema());
+ }
+ }
+
+ private SpDataStream makeDataStream(String elementId, String name) {
+ var dataStream = new SpDataStream();
+ dataStream.setElementId(elementId);
+ dataStream.setName(name);
+ dataStream.setEventSchema(new EventSchema());
+ return dataStream;
+ }
+
+ private AdapterDescription makeAdapter(String correspondingDataStreamElementId, String name) {
+ var adapterDescription = new AdapterDescription();
+ adapterDescription.setCorrespondingDataStreamElementId(correspondingDataStreamElementId);
+ adapterDescription.setName(name);
+ adapterDescription.getDataStream().setEventSchema(new EventSchema());
+ return adapterDescription;
+ }
+
+ private Pipeline makePipeline(String pipelineId,
+ String name,
+ boolean running,
+ String streamElementId,
+ String streamName) {
+ var pipeline = new Pipeline();
+ pipeline.setPipelineId(pipelineId);
+ pipeline.setName(name);
+ pipeline.setRunning(running);
+ pipeline.setStreams(List.of(makeDataStream(streamElementId, streamName)));
+ pipeline.setSepas(List.of(makeSepa("sepa-1", "Processor")));
+ return pipeline;
+ }
+
+ private DataProcessorInvocation makeSepa(String elementId, String name) {
+ var sepa = new DataProcessorInvocation();
+ sepa.setElementId(elementId);
+ sepa.setName(name);
+ return sepa;
+ }
+
+ private PipelineModification validModification(String elementId) {
+ var modification = new PipelineModification();
+ modification.setElementId(elementId);
+ modification.setPipelineElementValid(true);
+ return modification;
+ }
+
+ private PipelineModification invalidModification(String elementId,
+ PipelineElementValidationInfo validationInfo) {
+ var modification = new PipelineModification();
+ modification.setElementId(elementId);
+ modification.setPipelineElementValid(false);
+ modification.setValidationInfos(List.of(validationInfo));
+ return modification;
+ }
+}
diff --git a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataStreamResource.java b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataStreamResource.java
index f087549c61..53ad620aff 100644
--- a/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataStreamResource.java
+++ b/streampipes-rest/src/main/java/org/apache/streampipes/rest/impl/pe/DataStreamResource.java
@@ -18,7 +18,10 @@
package org.apache.streampipes.rest.impl.pe;
+import org.apache.streampipes.manager.api.extensions.ExtensionServiceRequestManager;
+import org.apache.streampipes.manager.pipeline.update.DataStreamUpdateManagement;
import org.apache.streampipes.model.SpDataStream;
+import org.apache.streampipes.model.connect.adapter.PipelineUpdateInfo;
import org.apache.streampipes.model.message.Message;
import org.apache.streampipes.model.message.NotificationType;
import org.apache.streampipes.model.monitoring.SpLogMessage;
@@ -46,6 +49,12 @@ import java.util.List;
@RequestMapping("/api/v2/streams")
public class DataStreamResource extends AbstractAuthGuardedRestResource {
+ private final DataStreamUpdateManagement dataStreamUpdateManagement;
+
+ public DataStreamResource(ExtensionServiceRequestManager requestManager) {
+ this.dataStreamUpdateManagement = new DataStreamUpdateManagement(requestManager);
+ }
+
@GetMapping(path = "/available", produces = MediaType.APPLICATION_JSON_VALUE)
@PreAuthorize(AuthConstants.HAS_READ_PIPELINE_ELEMENT_PRIVILEGE)
@PostFilter("hasPermission(filterObject.elementId, 'READ')")
@@ -85,11 +94,22 @@ public class DataStreamResource extends AbstractAuthGuardedRestResource {
throw new HttpResponseException(400,
"Element ID in path variable does not match element ID in request body");
} else {
- getDataStreamResourceManager().update(updatedElement);
+ dataStreamUpdateManagement.updateDataStream(updatedElement);
return constructSuccessMessage(NotificationType.STORAGE_SUCCESS.uiNotification());
}
}
+ @PutMapping(
+ path = "/pipeline-migration-preflight",
+ produces = MediaType.APPLICATION_JSON_VALUE,
+ consumes = MediaType.APPLICATION_JSON_VALUE
+ )
+ @PreAuthorize(AuthConstants.HAS_WRITE_PIPELINE_ELEMENT_PRIVILEGE)
+ public ResponseEntity<List<PipelineUpdateInfo>> performPipelineMigrationPreflight(
+ @RequestBody SpDataStream updatedElement) {
+ return ok(dataStreamUpdateManagement.checkPipelineMigrations(updatedElement));
+ }
+
@PostMapping(
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE