Merge master and fix Pipe startup review findings
diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/utils/TestUtils.java b/integration-test/src/test/java/org/apache/iotdb/db/it/utils/TestUtils.java index 6ca881c..2ab3100 100644 --- a/integration-test/src/test/java/org/apache/iotdb/db/it/utils/TestUtils.java +++ b/integration-test/src/test/java/org/apache/iotdb/db/it/utils/TestUtils.java
@@ -35,6 +35,7 @@ import org.apache.iotdb.it.env.cluster.env.AbstractEnv; import org.apache.iotdb.it.env.cluster.node.DataNodeWrapper; import org.apache.iotdb.itbase.env.BaseEnv; +import org.apache.iotdb.itbase.exception.InconsistentDataException; import org.apache.iotdb.itbase.runtime.ClusterTestConnection; import org.apache.iotdb.itbase.runtime.ClusterTestResultSet; import org.apache.iotdb.rpc.IoTDBConnectionException; @@ -248,6 +249,8 @@ .atMost(60, TimeUnit.SECONDS) .pollInSameThread() .pollInterval(20, TimeUnit.MILLISECONDS) + // DESCRIBE may disagree across DataNodes while the asynchronous column drop propagates. + .ignoreException(InconsistentDataException.class) .until( () -> { try (final ResultSet result =
diff --git a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java index c68553c..ad88497 100644 --- a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java +++ b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/IoTDBRpcDataSetFragmentTest.java
@@ -52,7 +52,7 @@ @Test public void testAssembleOneOversizedTsBlockAcrossResponses() throws Exception { - byte[] bytes = serializeInt64Block(); + byte[] bytes = serializeInt64Block(10L); int totalLength = bytes.length; int split = totalLength / 2; @@ -78,8 +78,8 @@ @Test public void testCompleteBlocksAndTrailingFragmentInOneResponse() throws Exception { - byte[] first = serializeInt64Block(); - byte[] second = serializeInt64Block(); + byte[] first = serializeInt64Block(10L); + byte[] second = serializeInt64Block(10L); int split = second.length / 2; IClientRPCService.Iface client = mockClient(); @@ -106,8 +106,84 @@ } @Test + public void testCompleteFragmentWithFollowingBlocksAndTrailingFragmentInOneResponse() + throws Exception { + byte[] first = serializeInt64Block(10L); + byte[] second = serializeInt64Block(30L); + byte[] third = serializeInt64Block(50L); + int firstSplit = first.length / 2; + // a different split point, so that reusing the previous offset is caught + int thirdSplit = third.length / 3; + assertTrue(firstSplit != thirdSplit); + + IClientRPCService.Iface client = mockClient(); + when(client.fetchResultsV2(any(TSFetchResultsReq.class))) + .thenReturn( + fragmentResponse(ByteBuffer.wrap(first, 0, firstSplit), firstSplit, first.length, true), + response( + List.of( + ByteBuffer.wrap(first, firstSplit, first.length - firstSplit), + ByteBuffer.wrap(second), + ByteBuffer.wrap(third, 0, thirdSplit)), + thirdSplit, + third.length, + true), + fragmentResponse( + ByteBuffer.wrap(third, thirdSplit, third.length - thirdSplit), -1, -1, false)); + + IoTDBRpcDataSet dataSet = newDataSet(client); + + // the response that completes the first fragment also carries the next block, and one + // response can end with a new fragment again + long[] expected = {10L, 20L, 30L, 40L, 50L, 60L}; + for (long value : expected) { + assertTrue(dataSet.next()); + assertEquals(value, dataSet.getLong(COLUMN)); + } + assertFalse(dataSet.next()); + + ArgumentCaptor<TSFetchResultsReq> captor = ArgumentCaptor.forClass(TSFetchResultsReq.class); + verify(client, times(3)).fetchResultsV2(captor.capture()); + assertEquals(0, captor.getAllValues().get(0).getOffset()); + assertEquals(firstSplit, captor.getAllValues().get(1).getOffset()); + assertEquals(thirdSplit, captor.getAllValues().get(2).getOffset()); + } + + @Test + public void testFragmentTailThenWholeBlockInNextResponse() throws Exception { + byte[] first = serializeInt64Block(10L); + byte[] second = serializeInt64Block(30L); + int split = first.length / 2; + + IClientRPCService.Iface client = mockClient(); + when(client.fetchResultsV2(any(TSFetchResultsReq.class))) + .thenReturn( + fragmentResponse(ByteBuffer.wrap(first, 0, split), split, first.length, true), + // the tail completes the fragment without starting a new one: the server held the + // following block back for the next response + response(List.of(ByteBuffer.wrap(first, split, first.length - split)), -1, -1, true), + response(List.of(ByteBuffer.wrap(second)), -1, -1, false)); + + IoTDBRpcDataSet dataSet = newDataSet(client); + + long[] expected = {10L, 20L, 30L, 40L}; + for (long value : expected) { + assertTrue(dataSet.next()); + assertEquals(value, dataSet.getLong(COLUMN)); + } + assertFalse(dataSet.next()); + + // nothing is pending on the client after the tail, so the third request starts from offset 0 + ArgumentCaptor<TSFetchResultsReq> captor = ArgumentCaptor.forClass(TSFetchResultsReq.class); + verify(client, times(3)).fetchResultsV2(captor.capture()); + assertEquals(0, captor.getAllValues().get(0).getOffset()); + assertEquals(split, captor.getAllValues().get(1).getOffset()); + assertEquals(0, captor.getAllValues().get(2).getOffset()); + } + + @Test public void testLegacyResponseWithoutOffset() throws Exception { - byte[] bytes = serializeInt64Block(); + byte[] bytes = serializeInt64Block(10L); IClientRPCService.Iface client = mockClient(); when(client.fetchResultsV2(any(TSFetchResultsReq.class))) .thenReturn(response(List.of(ByteBuffer.wrap(bytes)), -1, -1, false)); @@ -123,7 +199,7 @@ @Test public void testBlocksInExecuteResponseAreConsumedBeforeFetching() throws Exception { - byte[] bytes = serializeInt64Block(); + byte[] bytes = serializeInt64Block(10L); IClientRPCService.Iface client = mockClient(); IoTDBRpcDataSet dataSet = new IoTDBRpcDataSet( @@ -156,7 +232,7 @@ @Test(expected = IllegalArgumentException.class) public void testRejectMissingTotalLengthForFirstFragment() throws Exception { - byte[] bytes = serializeInt64Block(); + byte[] bytes = serializeInt64Block(10L); IClientRPCService.Iface client = mockClient(); when(client.fetchResultsV2(any(TSFetchResultsReq.class))) .thenReturn( @@ -169,7 +245,7 @@ @Test(expected = IllegalArgumentException.class) public void testRejectNonIncreasingFragmentOffset() throws Exception { - byte[] bytes = serializeInt64Block(); + byte[] bytes = serializeInt64Block(10L); int split = bytes.length / 2; IClientRPCService.Iface client = mockClient(); // the offset must equal the accumulated length, otherwise the dataset must refuse to continue @@ -230,14 +306,14 @@ return resp; } - /** [time=1, s1=10], [time=2, s1=20] as an INT64 column. */ - private static byte[] serializeInt64Block() throws Exception { + /** [time=1, s1=valueBase], [time=2, s1=valueBase+10] as an INT64 column. */ + private static byte[] serializeInt64Block(long valueBase) throws Exception { TsBlockBuilder builder = new TsBlockBuilder(Collections.singletonList(TSDataType.INT64)); builder.getTimeColumnBuilder().writeLong(1L); - builder.getColumnBuilder(0).writeLong(10L); + builder.getColumnBuilder(0).writeLong(valueBase); builder.declarePosition(); builder.getTimeColumnBuilder().writeLong(2L); - builder.getColumnBuilder(0).writeLong(20L); + builder.getColumnBuilder(0).writeLong(valueBase + 10L); builder.declarePosition(); TsBlock tsBlock = builder.build();
diff --git a/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicConfig.java b/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicConfig.java index 17c32c1..51b5f3c 100644 --- a/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicConfig.java +++ b/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicConfig.java
@@ -33,7 +33,6 @@ import java.util.HashSet; import java.util.Locale; import java.util.Map; -import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; @@ -73,7 +72,7 @@ } public TopicConfig(final Map<String, String> attributes) { - super(attributes); + super(TopicProperty.normalizeAttributes(attributes)); } public TopicConfig(final TopicConfig config) { @@ -444,7 +443,7 @@ final Map<String, String> attributesWithProcessorPrefix = new HashMap<>(); attributes.forEach( (key, value) -> { - if (key.toLowerCase().startsWith("sink")) { + if (key != null && key.trim().toLowerCase(Locale.ROOT).startsWith("sink")) { attributesWithProcessorPrefix.put(key, value); } }); @@ -452,15 +451,10 @@ } private boolean containsKeyIgnoreCase(final String expectedKey) { - return attributes.keySet().stream().anyMatch(key -> expectedKey.equalsIgnoreCase(key)); + return TopicProperty.containsAttribute(attributes, expectedKey); } private String getStringIgnoreCase(final String expectedKey, final String defaultValue) { - return attributes.entrySet().stream() - .filter(entry -> expectedKey.equalsIgnoreCase(entry.getKey())) - .map(Map.Entry::getValue) - .filter(Objects::nonNull) - .findFirst() - .orElse(defaultValue); + return TopicProperty.getAttributeValue(attributes, expectedKey, defaultValue); } }
diff --git a/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicProperty.java b/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicProperty.java index 73b93c1..9faba7a 100644 --- a/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicProperty.java +++ b/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicProperty.java
@@ -83,9 +83,58 @@ return key == null ? null : PROPERTIES_BY_KEY.get(key.trim().toLowerCase(Locale.ROOT)); } - /** Canonicalize built-in keys while preserving extension keys and all values verbatim. */ + public static Map<String, String> normalizeAttributes(final Map<String, String> attributes) { + final Map<String, String> normalizedAttributes = new HashMap<>(); + if (attributes == null) { + return normalizedAttributes; + } + attributes.forEach( + (key, value) -> { + final TopicProperty property = fromKey(key); + normalizedAttributes.put( + property == null ? key : property.key, property == null ? value : trim(value)); + }); + return normalizedAttributes; + } + + public static void replaceNowTimeValues( + final Map<String, String> attributes, final String currentTime) { + attributes.replaceAll( + (key, value) -> { + final TopicProperty property = fromKey(key); + return value != null + && TopicConstant.NOW_TIME_VALUE.equalsIgnoreCase(value.trim()) + && (property == START_TIME || property == END_TIME) + ? currentTime + : value; + }); + } + + public static boolean containsAttribute( + final Map<String, String> attributes, final String expectedKey) { + return attributes.keySet().stream() + .filter(key -> key != null) + .anyMatch(key -> expectedKey.equalsIgnoreCase(key.trim())); + } + + public static String getAttributeValue( + final Map<String, String> attributes, final String expectedKey, final String defaultValue) { + return attributes.entrySet().stream() + .filter(entry -> entry.getKey() != null) + .filter(entry -> expectedKey.equalsIgnoreCase(entry.getKey().trim())) + .map(Map.Entry::getValue) + .filter(value -> value != null) + .map(String::trim) + .findFirst() + .orElse(defaultValue); + } + public static String canonicalizeKey(final String key) { final TopicProperty property = fromKey(key); return property == null ? key : property.getKey(); } + + private static String trim(final String value) { + return value == null ? null : value.trim(); + } }
diff --git a/iotdb-client/subscription/src/test/java/org/apache/iotdb/rpc/subscription/config/TopicConfigTest.java b/iotdb-client/subscription/src/test/java/org/apache/iotdb/rpc/subscription/config/TopicConfigTest.java index 4242c0d..773f732 100644 --- a/iotdb-client/subscription/src/test/java/org/apache/iotdb/rpc/subscription/config/TopicConfigTest.java +++ b/iotdb-client/subscription/src/test/java/org/apache/iotdb/rpc/subscription/config/TopicConfigTest.java
@@ -104,6 +104,8 @@ Assert.assertTrue(topicConfigWithMode(" INITIAL ").isInitialMode()); Assert.assertTrue(topicConfigWithMode(" INCREMENTAL ").isIncrementalMode()); + Assert.assertTrue( + new TopicConfig(Collections.singletonMap(" MODE ", " SNAPSHOT ")).isSnapshotMode()); } @Test @@ -284,6 +286,28 @@ .isProgressRetainedAfterUnsubscribe()); } + @Test + public void testNowTimeValuesUseNormalizedBuiltinKeysAndValues() { + final Map<String, String> attributes = new HashMap<>(); + attributes.put(" START-TIME ", " NoW "); + attributes.put("eNd-TiMe", "nOw"); + attributes.put("extension.end-time", " now "); + + TopicProperty.replaceNowTimeValues(attributes, "123"); + + Assert.assertEquals("123", attributes.get(" START-TIME ")); + Assert.assertEquals("123", attributes.get("eNd-TiMe")); + Assert.assertEquals(" now ", attributes.get("extension.end-time")); + } + + @Test + public void testSinkAttributesWithPaddedPrefixAreIncluded() { + final TopicConfig topicConfig = new TopicConfig(Map.of(" SINK.Topic ", " MixedTopic ")); + + Assert.assertEquals( + Map.of(" SINK.Topic ", " MixedTopic "), topicConfig.getAttributesWithSinkPrefix()); + } + private static TopicConfig topicConfigWithMode(final String mode) { return new TopicConfig(Collections.singletonMap(TopicConstant.MODE_KEY, mode)); }
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/agent/task/PipeConfigNodeSubtask.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/agent/task/PipeConfigNodeSubtask.java index 9162c79..723a22a 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/agent/task/PipeConfigNodeSubtask.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/agent/task/PipeConfigNodeSubtask.java
@@ -20,6 +20,7 @@ package org.apache.iotdb.confignode.manager.pipe.agent.task; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeException; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta; import org.apache.iotdb.commons.pipe.agent.task.progress.PipeEventCommitManager; @@ -89,7 +90,8 @@ } private void initSource(final Map<String, String> sourceAttributes) throws Exception { - final PipeParameters sourceParameters = new PipeParameters(sourceAttributes); + final PipeParameters sourceParameters = + PipePluginAgent.normalizeSourceParameters(new PipeParameters(sourceAttributes)); // 1. Construct extractor source = PipeConfigNodeAgent.plugin().reflectSource(sourceParameters); @@ -118,7 +120,8 @@ } private void initProcessor(final Map<String, String> processorAttributes) { - final PipeParameters processorParameters = new PipeParameters(processorAttributes); + final PipeParameters processorParameters = + PipePluginAgent.normalizeProcessorParameters(new PipeParameters(processorAttributes)); final PipeTaskRuntimeConfiguration runtimeConfiguration = new PipeTaskRuntimeConfiguration( @@ -136,7 +139,8 @@ } private void initSink(final Map<String, String> sinkAttributes) throws Exception { - final PipeParameters sinkParameters = new PipeParameters(sinkAttributes); + final PipeParameters sinkParameters = + PipePluginAgent.normalizeSinkParameters(new PipeParameters(sinkAttributes)); // 1. Construct connector outputPipeSink = PipeConfigNodeAgent.plugin().reflectSink(sinkParameters);
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/coordinator/task/PipeTaskCoordinator.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/coordinator/task/PipeTaskCoordinator.java index d32c2f1..ec0c114 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/coordinator/task/PipeTaskCoordinator.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/manager/pipe/coordinator/task/PipeTaskCoordinator.java
@@ -186,11 +186,7 @@ } private TSStatus validateDoubleLivingPipeParameters(final PipeParameters sourceParameters) { - final Boolean isForwardingPipeRequests = - sourceParameters.getBooleanByKeys( - PipeSourceConstant.EXTRACTOR_FORWARDING_PIPE_REQUESTS_KEY, - PipeSourceConstant.SOURCE_FORWARDING_PIPE_REQUESTS_KEY); - return Boolean.TRUE.equals(isForwardingPipeRequests) + return PipeSourceConstant.isForwardingPipeRequestsEnabled(sourceParameters) ? RpcUtils.getStatus( TSStatusCode.PIPE_ERROR, PipeMessages
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/pipe/PipeTaskInfo.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/pipe/PipeTaskInfo.java index 9d038c1..1864c1f 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/pipe/PipeTaskInfo.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/pipe/PipeTaskInfo.java
@@ -26,6 +26,7 @@ import org.apache.iotdb.commons.exception.pipe.PipeRuntimeCriticalException; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeException; import org.apache.iotdb.commons.i18n.PipeMessages; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.task.PipeTaskAgent; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMeta; @@ -272,11 +273,14 @@ alterPipeRequest.setExtractorAttributes( copiedPipeStaticMetaFromCoordinator.getSourceParameters().getAttribute()); } else { + final PipeParameters existingSourceParameters = + copiedPipeStaticMetaFromCoordinator.getSourceParameters(); alterPipeRequest.setExtractorAttributes( - copiedPipeStaticMetaFromCoordinator - .getSourceParameters() + existingSourceParameters .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeRequest.getExtractorAttributes())) + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(alterPipeRequest.getExtractorAttributes()), + existingSourceParameters)) .getAttribute()); } } @@ -288,11 +292,14 @@ alterPipeRequest.setProcessorAttributes( copiedPipeStaticMetaFromCoordinator.getProcessorParameters().getAttribute()); } else { + final PipeParameters existingProcessorParameters = + copiedPipeStaticMetaFromCoordinator.getProcessorParameters(); alterPipeRequest.setProcessorAttributes( - copiedPipeStaticMetaFromCoordinator - .getProcessorParameters() + existingProcessorParameters .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeRequest.getProcessorAttributes())) + PipePluginAgent.normalizeProcessorParametersForUpdate( + new PipeParameters(alterPipeRequest.getProcessorAttributes()), + existingProcessorParameters)) .getAttribute()); } } @@ -302,11 +309,14 @@ alterPipeRequest.setConnectorAttributes( copiedPipeStaticMetaFromCoordinator.getSinkParameters().getAttribute()); } else { + final PipeParameters existingSinkParameters = + copiedPipeStaticMetaFromCoordinator.getSinkParameters(); alterPipeRequest.setConnectorAttributes( - copiedPipeStaticMetaFromCoordinator - .getSinkParameters() + existingSinkParameters .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeRequest.getConnectorAttributes())) + PipePluginAgent.normalizeSinkParametersForUpdate( + new PipeParameters(alterPipeRequest.getConnectorAttributes()), + existingSinkParameters)) .getAttribute()); } }
diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfo.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfo.java index de692d1..1d9bf6a 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfo.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfo.java
@@ -241,8 +241,8 @@ throws SubscriptionException { final Map<String, String> topicAttributes = new HashMap<>(safeTopicAttributes(createTopicReq.getTopicAttributes())); + validateDuplicateTopicAttributes(topicAttributes); final TopicConfig topicConfig = new TopicConfig(topicAttributes); - validateDuplicateTopicAttributes(topicConfig); canonicalizeTopicAttributes(topicAttributes); createTopicReq.setTopicAttributes(topicAttributes); validateTopicConfig(topicConfig); @@ -352,7 +352,7 @@ public void validateUpdatedTopicAttributes(final Map<String, String> updatedAttributes) throws SubscriptionException { - validateDuplicateTopicAttributes(new TopicConfig(safeTopicAttributes(updatedAttributes))); + validateDuplicateTopicAttributes(safeTopicAttributes(updatedAttributes)); } private void checkBeforeAlteringTopicInternal( @@ -393,7 +393,7 @@ } private void validateTopicConfig(final TopicConfig topicConfig) throws SubscriptionException { - validateDuplicateTopicAttributes(topicConfig); + validateDuplicateTopicAttributes(topicConfig.getAttribute()); validateTopicDoesNotOnlySelectAuditDatabase(topicConfig); final String mode = topicConfig.getMode(); @@ -628,10 +628,10 @@ throw new SubscriptionException(exceptionMessage); } - private void validateDuplicateTopicAttributes(final TopicConfig topicConfig) + private void validateDuplicateTopicAttributes(final Map<String, String> attributes) throws SubscriptionException { final Set<String> seenKeys = new HashSet<>(); - for (final String key : topicConfig.getAttribute().keySet()) { + for (final String key : attributes.keySet()) { if (Objects.isNull(key)) { continue; }
diff --git a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/consensus/response/pipe/PipeTableRespTest.java b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/consensus/response/pipe/PipeTableRespTest.java index 66bc79f..9c342a9 100644 --- a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/consensus/response/pipe/PipeTableRespTest.java +++ b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/consensus/response/pipe/PipeTableRespTest.java
@@ -171,6 +171,37 @@ } @Test + public void testConvertToTShowPipeRespDisplaysNormalizedParameters() { + final PipeStaticMeta staticMeta = + new PipeStaticMeta( + "normalizedPipe", + 1L, + Map.of(" SOURCE ", " IOTDB-EXTRACTOR ", " Source.Path ", " ROOT.SG.** "), + Map.of(" PROCESSOR ", " DO-NOTHING-PROCESSOR ", " Processor.Mode ", " ON "), + Map.of( + " CONNECTOR ", " IOTDB-THRIFT-CONNECTOR ", + " Connector.User ", " ROOT ", + " Connector.Node-URLs ", " https://NODEA:6667,NodeB:6667 ")); + final ConcurrentMap<Integer, PipeTaskMeta> pipeTasks = new ConcurrentHashMap<>(); + pipeTasks.put(1, new PipeTaskMeta(MinimumProgressIndex.INSTANCE, 1)); + final PipeMeta pipeMeta = new PipeMeta(staticMeta, new PipeRuntimeMeta(pipeTasks)); + final PipeTableResp response = + new PipeTableResp( + new TSStatus(TSStatusCode.SUCCESS_STATUS.getStatusCode()), List.of(pipeMeta)); + + final TShowPipeInfo pipeInfo = response.convertToTShowPipeResp().getPipeInfoList().get(0); + + Assert.assertTrue(pipeInfo.getPipeExtractor().contains("source.path= ROOT.SG.** ")); + Assert.assertFalse(pipeInfo.getPipeExtractor().contains("source.path=root.sg.**")); + Assert.assertTrue(pipeInfo.getPipeProcessor().contains("processor.mode=on")); + Assert.assertTrue(pipeInfo.getPipeConnector().contains("connector.user= ROOT ")); + Assert.assertTrue( + pipeInfo + .getPipeConnector() + .contains("connector.node-urls= https://NODEA:6667,NodeB:6667 ")); + } + + @Test public void testConvertToTShowPipeRespAggregatesRecentFailures() { final PipeTableResp pipeTableResp = constructPipeTableResp(); final PipeTemporaryMetaInCoordinator temporaryMeta =
diff --git a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfoTopicValidationTest.java b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfoTopicValidationTest.java index 89b2d3a..c2e6ff5 100644 --- a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfoTopicValidationTest.java +++ b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfoTopicValidationTest.java
@@ -245,12 +245,27 @@ public void testRejectDuplicateTopicConfigKeys() { final SubscriptionInfo subscriptionInfo = new SubscriptionInfo(); final Map<String, String> attributes = newInitialTableTopicAttributes(); - attributes.put("Mode", TopicConstant.MODE_SNAPSHOT_VALUE); + attributes.put(" MODE ", TopicConstant.MODE_SNAPSHOT_VALUE); assertCreateRejected(subscriptionInfo, attributes, "duplicate mode"); } @Test + public void testRejectDuplicateTopicConfigKeysOnAlter() { + final SubscriptionInfo subscriptionInfo = new SubscriptionInfo(); + final Map<String, String> updatedAttributes = new HashMap<>(); + updatedAttributes.put(TopicConstant.MODE_KEY, TopicConstant.MODE_INITIAL_VALUE); + updatedAttributes.put(" MODE ", TopicConstant.MODE_SNAPSHOT_VALUE); + + try { + subscriptionInfo.validateUpdatedTopicAttributes(updatedAttributes); + Assert.fail("Expected duplicate topic attributes to be rejected"); + } catch (final SubscriptionException e) { + Assert.assertTrue(e.getMessage().contains("duplicate mode")); + } + } + + @Test public void testAcceptColumnFilterOnInitialTsFileTableTopic() throws Exception { final SubscriptionInfo subscriptionInfo = new SubscriptionInfo(); final Map<String, String> attributes = newInitialTableTopicAttributes();
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/plugin/dataregion/PipeDataRegionPluginAgent.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/plugin/dataregion/PipeDataRegionPluginAgent.java index fd03582..34a518b 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/plugin/dataregion/PipeDataRegionPluginAgent.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/plugin/dataregion/PipeDataRegionPluginAgent.java
@@ -75,7 +75,8 @@ // validate visibility // TODO: validate visibility for schema region and config region final Visibility pipeVisibility = - VisibilityUtils.calculateFromExtractorParameters(new PipeParameters(sourceAttributes)); + VisibilityUtils.calculateFromExtractorParameters( + normalizeSourceParameters(new PipeParameters(sourceAttributes))); final Visibility sourceVisibility = VisibilityUtils.calculateFromPluginClass(temporaryExtractor.getClass()); final Visibility processorVisibility =
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java index 4206015..2f94b05 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/PipeDataNodeTask.java
@@ -58,10 +58,9 @@ this.processorStage = processorStage; this.sinkStage = sinkStage; - if (sourceStage instanceof PipeTaskSourceStage - && processorStage instanceof PipeTaskProcessorStage) { - ((PipeTaskSourceStage) sourceStage) - .setSourceStartedCallback(((PipeTaskProcessorStage) processorStage)::wakeUpWorker); + if (sourceStage instanceof PipeTaskSourceStage pipeTaskSourceStage + && processorStage instanceof PipeTaskProcessorStage pipeTaskProcessorStage) { + pipeTaskSourceStage.setSourceStartedCallback(pipeTaskProcessorStage::wakeUpWorker); } }
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java index bb17a6a..47413e0 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskProcessorStage.java
@@ -21,6 +21,7 @@ import org.apache.iotdb.commons.audit.UserEntity; import org.apache.iotdb.commons.consensus.DataRegionId; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.task.connection.EventSupplier; import org.apache.iotdb.commons.pipe.agent.task.connection.UnboundedBlockingPendingQueue; @@ -80,25 +81,21 @@ new PipeTaskRuntimeConfiguration( new PipeTaskProcessorRuntimeEnvironment( pipeName, creationTime, regionId, pipeTaskMeta, sourceUserEntity, sourcePassword)); - final PipeProcessor pipeProcessor = + final boolean isDataRegionSource = StorageEngine.getInstance().getAllDataRegionIds().contains(new DataRegionId(regionId)) - || PipeRuntimeMeta.isSourceExternal(regionId) - ? PipeDataNodeAgent.plugin() - .dataRegion() - .getConfiguredProcessor( - pipeProcessorParameters.getStringOrDefault( - PipeProcessorConstant.PROCESSOR_KEY, - BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName()), - pipeProcessorParameters, - runtimeConfiguration) - : PipeDataNodeAgent.plugin() - .schemaRegion() - .getConfiguredProcessor( - pipeProcessorParameters.getStringOrDefault( - PipeProcessorConstant.PROCESSOR_KEY, - BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName()), - pipeProcessorParameters, - runtimeConfiguration); + || PipeRuntimeMeta.isSourceExternal(regionId); + final PipeParameters normalizedProcessorParameters = + PipePluginAgent.normalizeProcessorParameters(pipeProcessorParameters); + final PipeProcessor pipeProcessor = + (isDataRegionSource + ? PipeDataNodeAgent.plugin().dataRegion() + : PipeDataNodeAgent.plugin().schemaRegion()) + .getConfiguredProcessor( + normalizedProcessorParameters.getStringOrDefault( + PipeProcessorConstant.PROCESSOR_KEY, + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName()), + normalizedProcessorParameters, + runtimeConfiguration); // Should add creation time in taskID, because subtasks are stored in the hashmap // PipeProcessorSubtaskWorker.subtasks, and deleted subtasks will be removed by
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java index 1532ef6..5a9b379 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSinkStage.java
@@ -19,6 +19,7 @@ package org.apache.iotdb.db.pipe.agent.task.stage; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.task.connection.UnboundedBlockingPendingQueue; import org.apache.iotdb.commons.pipe.agent.task.stage.PipeTaskStage; import org.apache.iotdb.commons.pipe.config.plugin.env.PipeTaskSinkRuntimeEnvironment; @@ -48,7 +49,7 @@ Supplier<? extends PipeSinkSubtaskExecutor> executor) { this.pipeName = pipeName; this.creationTime = creationTime; - this.pipeSinkParameters = pipeSinkParameters; + this.pipeSinkParameters = PipePluginAgent.normalizeSinkParameters(pipeSinkParameters); this.regionId = regionId; this.executor = executor;
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java index 20e65fc..0ce4ada 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStage.java
@@ -20,6 +20,7 @@ package org.apache.iotdb.db.pipe.agent.task.stage; import org.apache.iotdb.commons.consensus.DataRegionId; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.task.connection.EventSupplier; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMeta; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeTaskMeta; @@ -39,15 +40,17 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.atomic.AtomicReference; + public class PipeTaskSourceStage extends PipeTaskStage { private static final Logger LOGGER = LoggerFactory.getLogger(PipeTaskSourceStage.class); private final PipeExtractor pipeExtractor; private volatile boolean isStarted; - private volatile boolean isClosed; - private volatile Throwable startFailure; - private volatile Runnable sourceStartedCallback; + private boolean isClosed; + private final AtomicReference<Throwable> startFailure = new AtomicReference<>(); + private final AtomicReference<Runnable> sourceStartedCallback = new AtomicReference<>(); PipeTaskSourceStage(final PipeExtractor pipeExtractor) { this.pipeExtractor = pipeExtractor; @@ -59,23 +62,27 @@ PipeParameters sourceParameters, int regionId, PipeTaskMeta pipeTaskMeta) { - pipeExtractor = + final boolean isDataRegionSource = StorageEngine.getInstance().getAllDataRegionIds().contains(new DataRegionId(regionId)) - || PipeRuntimeMeta.isSourceExternal(regionId) - ? PipeDataNodeAgent.plugin().dataRegion().reflectSource(sourceParameters) - : PipeDataNodeAgent.plugin().schemaRegion().reflectSource(sourceParameters); + || PipeRuntimeMeta.isSourceExternal(regionId); + final PipeParameters normalizedSourceParameters = + PipePluginAgent.normalizeSourceParameters(sourceParameters); + pipeExtractor = + isDataRegionSource + ? PipeDataNodeAgent.plugin().dataRegion().reflectSource(normalizedSourceParameters) + : PipeDataNodeAgent.plugin().schemaRegion().reflectSource(normalizedSourceParameters); // Validate and customize should be called before createSubtask. this allows source exposing // exceptions in advance. try { // 1. Validate source parameters - pipeExtractor.validate(new PipeParameterValidator(sourceParameters)); + pipeExtractor.validate(new PipeParameterValidator(normalizedSourceParameters)); // 2. Customize source final PipeTaskRuntimeConfiguration runtimeConfiguration = new PipeTaskRuntimeConfiguration( new PipeTaskSourceRuntimeEnvironment(pipeName, creationTime, regionId, pipeTaskMeta)); - pipeExtractor.customize(sourceParameters, runtimeConfiguration); + pipeExtractor.customize(normalizedSourceParameters, runtimeConfiguration); } catch (Exception | Error e) { try { pipeExtractor.close(); @@ -99,17 +106,17 @@ @Override public void startSubtask() throws PipeException { - final Throwable previousStartFailure = startFailure; + final Throwable previousStartFailure = startFailure.get(); if (previousStartFailure != null) { - if (previousStartFailure instanceof Error) { - throw (Error) previousStartFailure; + if (previousStartFailure instanceof Error error) { + throw error; } throw (PipeException) previousStartFailure; } try { pipeExtractor.start(); isStarted = true; - final Runnable callback = sourceStartedCallback; + final Runnable callback = sourceStartedCallback.get(); if (callback != null) { callback.run(); } @@ -122,12 +129,13 @@ e.addSuppressed(closeException); } } - if (e instanceof Error) { - startFailure = e; - throw (Error) e; + if (e instanceof Error error) { + startFailure.set(error); + throw error; } - startFailure = new PipeException(e.getMessage(), e); - throw (PipeException) startFailure; + final PipeException pipeException = new PipeException(e.getMessage(), e); + startFailure.set(pipeException); + throw pipeException; } } @@ -145,16 +153,16 @@ } } - private void closeExtractor() throws Exception { + private synchronized void closeExtractor() throws Exception { isStarted = false; if (!isClosed) { - isClosed = true; pipeExtractor.close(); + isClosed = true; } } public void setSourceStartedCallback(final Runnable sourceStartedCallback) { - this.sourceStartedCallback = sourceStartedCallback; + this.sourceStartedCallback.set(sourceStartedCallback); } public EventSupplier getEventSupplier() {
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java index cd12d66..8d0e45f 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskLifeCycle.java
@@ -29,6 +29,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.concurrent.TimeUnit; + public class PipeSinkSubtaskLifeCycle implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(PipeSinkSubtaskLifeCycle.class); @@ -145,6 +147,11 @@ subtask.awaitFirstExecution(); } + public void awaitFirstExecution(final long timeout, final TimeUnit timeUnit) + throws InterruptedException { + subtask.awaitFirstExecution(timeout, timeUnit); + } + public synchronized void stop() { if (runningTaskCount <= 0) { throw new IllegalStateException(DataNodePipeMessages.RUNNINGTASKCOUNT_0_1);
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java index 8e3b4a0..2ffa097 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/pipe/agent/task/subtask/sink/PipeSinkSubtaskManager.java
@@ -25,6 +25,7 @@ import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMeta; import org.apache.iotdb.commons.pipe.agent.task.progress.CommitterKey; import org.apache.iotdb.commons.pipe.agent.task.progress.PipeEventCommitManager; +import org.apache.iotdb.commons.pipe.agent.task.subtask.PipeSubtask; import org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant; import org.apache.iotdb.commons.pipe.config.constant.SystemConstant; import org.apache.iotdb.commons.pipe.config.plugin.configuraion.PipeTaskRuntimeConfiguration; @@ -53,6 +54,7 @@ import java.util.Map; import java.util.Objects; import java.util.TreeMap; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; @@ -264,8 +266,12 @@ private void awaitFirstExecution(final List<PipeSinkSubtaskLifeCycle> lifeCycles) { try { + final long deadlineNanos = + System.nanoTime() + + TimeUnit.MILLISECONDS.toNanos(PipeSubtask.getFirstExecutionTimeoutInMs()); for (final PipeSinkSubtaskLifeCycle lifeCycle : lifeCycles) { - lifeCycle.awaitFirstExecution(); + lifeCycle.awaitFirstExecution( + Math.max(0L, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS); } } catch (final InterruptedException e) { Thread.currentThread().interrupt();
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java index c848b7b..381af85 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/IQueryExecution.java
@@ -45,6 +45,14 @@ Optional<ByteBuffer> getByteBufferBatchResult() throws IoTDBException; + /** + * Returns whether {@link #getByteBufferBatchResult()} can provide a batch without waiting for the + * producer. Executions whose results are already materialized never block, hence the default. + */ + default boolean isResultAvailable() { + return true; + } + /** Returns the pending fragment holder, or null if this execution does not fragment results. */ default PendingResultFragment getPendingResultFragment() { return null;
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java index 8004095..a91be35 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragment.java
@@ -24,7 +24,13 @@ /** * The tail of a serialized TsBlock that did not fit into the previous RPC response and is waiting * to be sent in the following response(s). The block is already serialized and removed from the - * result handle, so this fragment only holds a reference to it and never copies the payload. + * result handle, so this fragment only holds a reference to it and never copies the payload. The + * block's row count is recorded so that the response completing the fragment can keep packing new + * blocks into the same response while respecting the fetch size. + * + * <p>The fragment also holds a block that has not been sent at all ({@code nextOffset} 0) when the + * response that completed another fragment had no room left for it: such a block is delivered whole + * by the next response from a fresh payload instead of being fragmented. * * <p>The memory of the pending block is reserved from the query memory pool through an {@link * Account} owned by the query, and released when the fragment is {@link #clear() cleared}. The @@ -53,13 +59,17 @@ private ByteBuffer block; private int nextOffset; + private int rowCount; public PendingResultFragment(Account account) { this.account = account; } - /** Records that {@code block} has been sent up to {@code nextOffset} bytes. */ - public void reset(ByteBuffer block, int nextOffset) { + /** + * Records that {@code block}, with {@code rowCount} rows, has been sent up to {@code nextOffset} + * bytes. + */ + public void reset(ByteBuffer block, int nextOffset, int rowCount) { boolean newBlock; boolean hadPending; synchronized (this) { @@ -67,6 +77,7 @@ newBlock = block != this.block; this.block = block; this.nextOffset = nextOffset; + this.rowCount = rowCount; } if (!newBlock || account == null) { return; @@ -94,6 +105,14 @@ } /** + * Returns the row count of the pending block, so that the response completing it can account for + * its rows when packing more blocks into the same response. + */ + public synchronized int getRowCount() { + return rowCount; + } + + /** * Discards the pending fragment and releases the memory of the pending block, cancelling a * reservation that is still waiting. It is also called right after a complete block has been * added to a response, when nothing is pending. Calling it repeatedly is a no-op. @@ -102,6 +121,7 @@ synchronized (this) { block = null; nextOffset = 0; + rowCount = 0; } if (account != null) { account.release();
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java index 97c8d25..956570a 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/QueryExecution.java
@@ -737,6 +737,19 @@ return pendingResultFragment; } + /** + * Mirrors the waiting conditions of {@link #getResult}: a batch can be obtained without waiting + * once the result handle is finished or aborted, or once the future returned by {@link + * ISourceHandle#isBlocked()} completes, since the request thread is the only consumer. + */ + @Override + public boolean isResultAvailable() { + return resultHandle == null + || resultHandle.isFinished() + || resultHandle.isAborted() + || resultHandle.isBlocked().isDone(); + } + private ByteBuffer getSerializedTsBlock() throws IoTDBException { return resultHandle.getSerializedTsBlock(); }
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java index d2aef58..aa83ae4 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/executor/ClusterConfigTaskExecutor.java
@@ -64,6 +64,7 @@ import org.apache.iotdb.commons.path.MeasurementPath; import org.apache.iotdb.commons.path.PartialPath; import org.apache.iotdb.commons.path.PathPatternTree; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.plugin.service.PipePluginClassLoader; import org.apache.iotdb.commons.pipe.agent.plugin.service.PipePluginExecutableManager; @@ -359,7 +360,7 @@ import org.apache.iotdb.rpc.RpcUtils; import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.rpc.TSStatusCode; -import org.apache.iotdb.rpc.subscription.config.TopicConstant; +import org.apache.iotdb.rpc.subscription.config.TopicProperty; import org.apache.iotdb.service.rpc.thrift.TPipeTransferReq; import org.apache.iotdb.service.rpc.thrift.TPipeTransferResp; import org.apache.iotdb.trigger.api.Trigger; @@ -2332,7 +2333,8 @@ } final PipeParameters sourcePipeParameters = - new PipeParameters(createPipeStatement.getSourceAttributes()); + PipePluginAgent.normalizeSourceParameters( + new PipeParameters(createPipeStatement.getSourceAttributes())); final PipeParameters sinkPipeParameters = new PipeParameters(createPipeStatement.getSinkAttributes()); @@ -2408,11 +2410,7 @@ } private void validateDoubleLivingPipeParameters(final PipeParameters sourcePipeParameters) { - final Boolean isForwardingPipeRequests = - sourcePipeParameters.getBooleanByKeys( - PipeSourceConstant.EXTRACTOR_FORWARDING_PIPE_REQUESTS_KEY, - PipeSourceConstant.SOURCE_FORWARDING_PIPE_REQUESTS_KEY); - if (Boolean.TRUE.equals(isForwardingPipeRequests)) { + if (PipeSourceConstant.isForwardingPipeRequestsEnabled(sourcePipeParameters)) { throw new PipeParameterNotValidException( PipeMessages .EXCEPTION_FORWARDING_PIPE_REQUESTS_CAN_NOT_SPECIFIED_TRUE_DOUBLE_LIVING_ENABLED_B000E8A1); @@ -2699,24 +2697,27 @@ final Map<String, String> sinkAttributes; try { if (!alterPipeStatement.getSourceAttributes().isEmpty()) { + final PipeParameters existingSourceParameters = + pipeMetaFromCoordinator.getStaticMeta().getSourceParameters(); + final PipeParameters updatedSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(alterPipeStatement.getSourceAttributes()), + existingSourceParameters, + alterPipeStatement.isReplaceAllSourceAttributes()); // We don't allow changing the extractor plugin type - if (alterPipeStatement.getSourceAttributes().containsKey(PipeSourceConstant.EXTRACTOR_KEY) - || alterPipeStatement.getSourceAttributes().containsKey(PipeSourceConstant.SOURCE_KEY) + if (updatedSourceParameters.hasAnyAttributes( + PipeSourceConstant.EXTRACTOR_KEY, PipeSourceConstant.SOURCE_KEY) || alterPipeStatement.isReplaceAllSourceAttributes()) { - checkIfSourcePluginChanged( - pipeMetaFromCoordinator.getStaticMeta().getSourceParameters(), - new PipeParameters(alterPipeStatement.getSourceAttributes())); + checkIfSourcePluginChanged(existingSourceParameters, updatedSourceParameters); } if (alterPipeStatement.isReplaceAllSourceAttributes()) { - sourceAttributes = alterPipeStatement.getSourceAttributes(); + sourceAttributes = updatedSourceParameters.getAttribute(); } else { - final boolean onlyContainsUser = - onlyContainsUser(alterPipeStatement.getSourceAttributes()); + final boolean onlyContainsUser = onlyContainsUser(updatedSourceParameters.getAttribute()); pipeMetaFromCoordinator .getStaticMeta() .getSourceParameters() - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getSourceAttributes())); + .addOrReplaceEquivalentAttributes(updatedSourceParameters); sourceAttributes = pipeMetaFromCoordinator.getStaticMeta().getSourceParameters().getAttribute(); if (onlyContainsUser) { @@ -2725,21 +2726,26 @@ } hasSourcePassword = !checkSourceType(sourceAttributes) - || containsPassword(alterPipeStatement.getSourceAttributes()); + || containsPassword(updatedSourceParameters.getAttribute()); } else { sourceAttributes = pipeMetaFromCoordinator.getStaticMeta().getSourceParameters().getAttribute(); } if (!alterPipeStatement.getProcessorAttributes().isEmpty()) { + final PipeParameters existingProcessorParameters = + pipeMetaFromCoordinator.getStaticMeta().getProcessorParameters(); + final PipeParameters updatedProcessorParameters = + PipePluginAgent.normalizeProcessorParametersForUpdate( + new PipeParameters(alterPipeStatement.getProcessorAttributes()), + existingProcessorParameters); if (alterPipeStatement.isReplaceAllProcessorAttributes()) { - processorAttributes = alterPipeStatement.getProcessorAttributes(); + processorAttributes = updatedProcessorParameters.getAttribute(); } else { pipeMetaFromCoordinator .getStaticMeta() .getProcessorParameters() - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getProcessorAttributes())); + .addOrReplaceEquivalentAttributes(updatedProcessorParameters); processorAttributes = pipeMetaFromCoordinator.getStaticMeta().getProcessorParameters().getAttribute(); } @@ -2749,16 +2755,20 @@ } if (!alterPipeStatement.getSinkAttributes().isEmpty()) { + final PipeParameters existingSinkParameters = + pipeMetaFromCoordinator.getStaticMeta().getSinkParameters(); + final PipeParameters updatedSinkParameters = + PipePluginAgent.normalizeSinkParametersForUpdate( + new PipeParameters(alterPipeStatement.getSinkAttributes()), existingSinkParameters); // Do not remove for handshake if (alterPipeStatement.isReplaceAllSinkAttributes()) { - sinkAttributes = alterPipeStatement.getSinkAttributes(); + sinkAttributes = updatedSinkParameters.getAttribute(); } else { - final boolean onlyContainsUser = onlyContainsUser(alterPipeStatement.getSinkAttributes()); + final boolean onlyContainsUser = onlyContainsUser(updatedSinkParameters.getAttribute()); pipeMetaFromCoordinator .getStaticMeta() .getSinkParameters() - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getSinkAttributes())); + .addOrReplaceEquivalentAttributes(updatedSinkParameters); sinkAttributes = pipeMetaFromCoordinator.getStaticMeta().getSinkParameters().getAttribute(); if (onlyContainsUser) { @@ -2767,7 +2777,7 @@ } hasSinkPassword = !checkSinkType(sinkAttributes) - || containsPassword(alterPipeStatement.getSinkAttributes()); + || containsPassword(updatedSinkParameters.getAttribute()); } else { sinkAttributes = pipeMetaFromCoordinator.getStaticMeta().getSinkParameters().getAttribute(); } @@ -2849,14 +2859,18 @@ private static void checkIfSourcePluginChanged( final PipeParameters oldPipeParameters, final PipeParameters newPipeParameters) { + final PipeParameters normalizedOldParameters = + PipePluginAgent.normalizeSourceParameters(oldPipeParameters); + final PipeParameters normalizedNewParameters = + PipePluginAgent.normalizeSourceParameters(newPipeParameters); final String oldPluginName = - oldPipeParameters + normalizedOldParameters .getStringOrDefault( Arrays.asList(PipeSourceConstant.EXTRACTOR_KEY, PipeSourceConstant.SOURCE_KEY), BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName()) .toLowerCase(); final String newPluginName = - newPipeParameters + normalizedNewParameters .getStringOrDefault( Arrays.asList(PipeSourceConstant.EXTRACTOR_KEY, PipeSourceConstant.SOURCE_KEY), BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName()) @@ -2883,7 +2897,8 @@ } private static boolean checkSourceType(final Map<String, String> replacedSourceAttributes) { - final PipeParameters sourceParameters = new PipeParameters(replacedSourceAttributes); + final PipeParameters sourceParameters = + PipePluginAgent.normalizeSourceParameters(new PipeParameters(replacedSourceAttributes)); final String pluginName = sourceParameters .getStringOrDefault( @@ -2925,7 +2940,8 @@ } private static boolean checkSinkType(final Map<String, String> sinkAttributes) { - final PipeParameters sinkParameters = new PipeParameters(sinkAttributes); + final PipeParameters sinkParameters = + PipePluginAgent.normalizeSinkParameters(new PipeParameters(sinkAttributes)); final String pluginName = sinkParameters .getStringOrDefault( @@ -3225,22 +3241,7 @@ CommonDateTimeUtils.convertMilliTimeWithPrecision( System.currentTimeMillis(), CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); - topicAttributes.computeIfPresent( - TopicConstant.START_TIME_KEY, - (k, v) -> { - if (TopicConstant.NOW_TIME_VALUE.equals(v)) { - return String.valueOf(currentTime); - } - return v; - }); - topicAttributes.computeIfPresent( - TopicConstant.END_TIME_KEY, - (k, v) -> { - if (TopicConstant.NOW_TIME_VALUE.equals(v)) { - return String.valueOf(currentTime); - } - return v; - }); + TopicProperty.replaceNowTimeValues(topicAttributes, String.valueOf(currentTime)); // Validate topic config final TopicMeta temporaryTopicMeta =
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/task/subtask/SubscriptionSinkSubtaskManager.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/task/subtask/SubscriptionSinkSubtaskManager.java index 48c42d9..363db7c 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/task/subtask/SubscriptionSinkSubtaskManager.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/subscription/task/subtask/SubscriptionSinkSubtaskManager.java
@@ -19,6 +19,7 @@ package org.apache.iotdb.db.subscription.task.subtask; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.task.connection.UnboundedBlockingPendingQueue; import org.apache.iotdb.commons.pipe.agent.task.progress.CommitterKey; @@ -68,8 +69,9 @@ public synchronized String register( final PipeSinkSubtaskExecutor executor, - final PipeParameters pipeSinkParameters, + PipeParameters pipeSinkParameters, final PipeTaskSinkRuntimeEnvironment environment) { + pipeSinkParameters = PipePluginAgent.normalizeSinkParameters(pipeSinkParameters); final String connectorKey = pipeSinkParameters .getStringOrDefault(
diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java index dc6e755..9c96409 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/QueryDataSetUtils.java
@@ -272,7 +272,15 @@ * Fetches query results with a bounded payload size. A serialized TsBlock larger than {@code * maxPayloadSize} is cut into fragments: the response only carries the bytes that fit into the * payload, and the remaining bytes are kept in {@link PendingResultFragment} on the query - * execution, to be sent by the following request carrying the returned offset. + * execution, to be sent by the following request carrying the returned offset. The response that + * completes a pending fragment keeps packing subsequent TsBlocks that are already available while + * the payload and the fetch size still have room, so a fragmented block does not cost an extra + * round trip; a block that does not fit into the remaining space is left whole for the next + * response instead of being fragmented. + * + * <p>{@code fetchSize} is a soft bound, like {@link #convertQueryResultByFetchSize( + * IQueryExecution, int)}: it is checked before pulling each block, so one response can exceed it + * by up to the rows of the last block it carries. */ public static ResultChunk convertQueryResultByFetchSize( IQueryExecution queryExecution, int fetchSize, int requestOffset, int maxPayloadSize) @@ -298,8 +306,14 @@ return ResultChunk.complete(pair.left, pair.right); } ByteBuffer pendingBlock = pendingFragment.getBlock(); + // whether this response continues a pending fragment; such a response is not delayed by + // blocks that are still being produced, and it keeps a whole block that does not fit into the + // remaining payload for the next response instead of fragmenting it + boolean continuation = false; if (pendingBlock != null) { + continuation = true; int nextOffset = pendingFragment.getNextOffset(); + int pendingRowCount = pendingFragment.getRowCount(); if (requestOffset != nextOffset) { throw new IllegalArgumentException( String.format( @@ -310,15 +324,22 @@ } int fragmentSize = Math.min(remainingPayloadSize, pendingBlock.limit() - nextOffset); res.add(slice(pendingBlock, nextOffset, fragmentSize)); - if (nextOffset + fragmentSize == pendingBlock.limit()) { - pendingFragment.clear(); - // Do not fetch new blocks in the same response, otherwise the response would carry the - // tail of the big block plus up to fetchSize new rows, whose row count is not accounted - // for. One response either continues a fragmented block or delivers new blocks. - return ResultChunk.complete(res, !queryExecution.hasNextResult()); + if (nextOffset + fragmentSize < pendingBlock.limit()) { + pendingFragment.reset(pendingBlock, nextOffset + fragmentSize, pendingRowCount); + // A block held whole starts its fragment in this response, and the client has no + // reassembly buffer for it yet, so it needs the total length; when a fragment is + // continued, the client already holds the total length of the response that started it. + return ResultChunk.fragment( + res, nextOffset + fragmentSize, nextOffset == 0 ? pendingBlock.limit() : -1, false); } - pendingFragment.reset(pendingBlock, nextOffset + fragmentSize); - return ResultChunk.fragment(res, nextOffset + fragmentSize, -1, false); + // The tail completes the fragmented block, but it usually leaves room in this response. + // The rows of the completed block count against fetchSize, then the response continues with + // new blocks instead of ending here, so an ordinary block that got fragmented does not cost + // an extra round trip. + rowCount = pendingRowCount; + pendingFragment.clear(); + remainingPayloadSize -= fragmentSize; + memorySize += fragmentSize; } else if (requestOffset != 0) { throw new IllegalArgumentException( String.format( @@ -328,6 +349,12 @@ } while (rowCount < fetchSize && memorySize < MAX_RETURN_SIZE && remainingPayloadSize > 0) { + // A continuation already carries the tail the client waits for; blocking here on a block + // that is still being produced would delay that response, so end it and let the following + // request wait for the block instead. + if (continuation && !queryExecution.isResultAvailable()) { + break; + } Optional<ByteBuffer> optionalByteBuffer = queryExecution.getByteBufferBatchResult(); if (!optionalByteBuffer.isPresent()) { break; @@ -346,9 +373,16 @@ remainingPayloadSize -= blockSize; memorySize += blockSize; pendingFragment.clear(); + } else if (continuation) { + // The block does not fit into what is left of this response. Keep it whole for the next + // response instead of fragmenting it: fragmenting it here would leave the next response + // the same leftover space, and so fragment every following block again. A block larger + // than a whole payload is fragmented by the next response as usual. + pendingFragment.reset(byteBuffer, 0, positionCount); + return ResultChunk.complete(res, false); } else { res.add(slice(byteBuffer, 0, remainingPayloadSize)); - pendingFragment.reset(byteBuffer, remainingPayloadSize); + pendingFragment.reset(byteBuffer, remainingPayloadSize, positionCount); return ResultChunk.fragment(res, remainingPayloadSize, blockSize, false); } }
diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/plugin/PipeDataNodePluginAgentTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/plugin/PipeDataNodePluginAgentTest.java index 7b065a0..b8c4e29 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/plugin/PipeDataNodePluginAgentTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/plugin/PipeDataNodePluginAgentTest.java
@@ -19,11 +19,15 @@ package org.apache.iotdb.db.pipe.agent.plugin; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.plugin.meta.DataNodePipePluginMetaKeeper; import org.apache.iotdb.commons.pipe.agent.plugin.meta.PipePluginMeta; import org.apache.iotdb.commons.pipe.agent.plugin.service.PipePluginClassLoaderManager; import org.apache.iotdb.commons.pipe.agent.plugin.service.PipePluginExecutableManager; +import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMeta; +import org.apache.iotdb.commons.pipe.agent.task.meta.PipeRuntimeMeta; +import org.apache.iotdb.commons.pipe.agent.task.meta.PipeStaticMeta; import org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant; import org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant; import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant; @@ -33,6 +37,7 @@ import org.apache.iotdb.db.pipe.sink.protocol.thrift.async.IoTDBDataRegionAsyncSink; import org.apache.iotdb.db.pipe.sink.protocol.thrift.sync.IoTDBDataRegionSyncSink; import org.apache.iotdb.db.pipe.source.dataregion.IoTDBDataRegionSource; +import org.apache.iotdb.db.queryengine.plan.execution.config.metadata.relational.ShowCreatePipeTask; import org.apache.iotdb.db.utils.EnvironmentUtils; import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters; @@ -46,6 +51,7 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; +import java.util.Map; public class PipeDataNodePluginAgentTest { private static final String TMP_LIB_ROOT_DIR = "PipePluginAgentTest_libroot"; @@ -185,6 +191,191 @@ } @Test + public void testBuiltInAndCustomParametersAreNormalized() { + final PipeDataNodePluginAgent agent = new PipeDataNodePluginAgent(); + final PipeParameters builtInParameters = + new PipeParameters( + Map.of( + " SOURCE ", " IOTDB-EXTRACTOR ", + " Source.Path ", " ROOT.SG.** ", + " Source.Mode ", " QUERY ", + " Source.Custom.Option ", " Mixed Value ")); + final PipeParameters normalizedParameters = + PipePluginAgent.normalizeSourceParameters(builtInParameters); + + Assert.assertNotSame(builtInParameters, normalizedParameters); + Assert.assertEquals("iotdb-extractor", normalizedParameters.getString("source")); + Assert.assertEquals(" ROOT.SG.** ", normalizedParameters.getString("source.path")); + Assert.assertEquals("query", normalizedParameters.getString("source.mode")); + Assert.assertEquals("mixed value", normalizedParameters.getString("source.custom.option")); + Assert.assertEquals("iotdb-extractor", normalizedParameters.getAttribute().get("source")); + + final PipeParameters customParameters = + new PipeParameters( + Map.of(" SOURCE ", " CUSTOM-PLUGIN ", " Custom.Option ", " Mixed Value ")); + final PipeParameters normalizedCustomParameters = + PipePluginAgent.normalizeSourceParameters(customParameters); + Assert.assertEquals(" CUSTOM-PLUGIN ", normalizedCustomParameters.getString("source")); + Assert.assertEquals( + " Mixed Value ", normalizedCustomParameters.getAttribute().get(" Custom.Option ")); + final PipeParameters renormalizedCustomParameters = + PipePluginAgent.normalizeSourceParameters(normalizedCustomParameters); + Assert.assertEquals( + normalizedCustomParameters.getAttribute(), renormalizedCustomParameters.getAttribute()); + final PipeParameters existingBuiltInSourceParameters = + new PipeParameters(Map.of("source", "iotdb-extractor")); + final PipeParameters updatedBuiltInSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(Map.of(" SOURCE.PATH ", " root.sg.** ", " SOURCE.MODE ", " QUERY ")), + existingBuiltInSourceParameters); + Assert.assertEquals(" root.sg.** ", updatedBuiltInSourceParameters.getString("source.path")); + Assert.assertEquals("query", updatedBuiltInSourceParameters.getString("source.mode")); + final PipeParameters existingCustomSourceParameters = + new PipeParameters(Map.of("source", "custom-plugin")); + final PipeParameters updatedCustomSourceParameters = + new PipeParameters(Map.of(" Custom.Option ", " Mixed Value ")); + final PipeParameters normalizedUpdatedCustomSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + updatedCustomSourceParameters, existingCustomSourceParameters); + Assert.assertNotSame(updatedCustomSourceParameters, normalizedUpdatedCustomSourceParameters); + Assert.assertEquals( + " Mixed Value ", + normalizedUpdatedCustomSourceParameters.getAttribute().get(" Custom.Option ")); + Assert.assertEquals( + "IOTDB-THRIFT-CONNECTOR", + PipeSinkConstant.getConnectorOrSinkNameWithDefault( + new PipeParameters(Map.of(" CONNECTOR ", " IOTDB-THRIFT-CONNECTOR ")))); + Assert.assertEquals( + BuiltinPipePlugin.IOTDB_THRIFT_CONNECTOR.getPipePluginName(), + PipeSinkConstant.getConnectorOrSinkNameWithDefault( + new PipeParameters(Map.of(" CONNECTOR ", " ")))); + final PipeParameters replacementSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(Map.of(" SOURCE.MODE ", " QUERY ")), + existingCustomSourceParameters, + true); + Assert.assertEquals("query", replacementSourceParameters.getString("source.mode")); + final PipeParameters modifiedCustomSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(Map.of(" SOURCE.MODE ", " QUERY ")), existingCustomSourceParameters); + Assert.assertEquals( + " QUERY ", modifiedCustomSourceParameters.getAttribute().get(" SOURCE.MODE ")); + Assert.assertTrue( + PipeSinkConstant.isSerializeByRegionEnabled( + new PipeParameters(Map.of(" CONNECTOR.SERIALIZE-BY-REGION ", " TRUE ")))); + Assert.assertTrue( + PipeSinkConstant.isSerializeByRegionEnabled( + new PipeParameters(Map.of(" SERIALIZE-BY-REGION ", " TRUE ")))); + final PipeParameters normalizedProcessorParameters = + PipePluginAgent.normalizeProcessorParameters( + new PipeParameters( + Map.of( + " PROCESSOR ", + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName().toUpperCase(), + " Processor.Mode ", + " ON "))); + Assert.assertEquals( + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName(), + normalizedProcessorParameters.getString("processor")); + Assert.assertEquals("on", normalizedProcessorParameters.getString("processor.mode")); + Assert.assertEquals( + "Count", + PipePluginAgent.normalizeProcessorParameters( + new PipeParameters( + Map.of("PROCESSOR", "AGGREGATE-PROCESSOR", "PROCESSOR.OPERATORS", "Count"))) + .getString(PipeProcessorConstant.PROCESSOR_OPERATORS_KEY)); + final PipeParameters normalizedSinkParameters = + PipePluginAgent.normalizeSinkParameters( + new PipeParameters( + Map.of( + " CONNECTOR ", + " IOTDB-THRIFT-CONNECTOR ", + " Connector.User ", + " ROOT ", + " Connector.Node-URLs ", + " https://NODEA:6667,NodeB:6667 ", + " Connector.Host ", + " HOST.EXAMPLE.COM ", + " Connector.IP ", + " 2001:DB8::1 ", + " Connector.Password ", + " P@SSword ", + " Connector.Ssl.Trust-Store-Path ", + " C:\\CERTS\\STORE.JKS ", + " Connector.Ssl.Enable ", + " TRUE "))); + Assert.assertEquals( + BuiltinPipePlugin.IOTDB_THRIFT_CONNECTOR.getPipePluginName(), + normalizedSinkParameters.getString("connector")); + Assert.assertEquals(" ROOT ", normalizedSinkParameters.getString("connector.user")); + Assert.assertEquals( + " https://NODEA:6667,NodeB:6667 ", + normalizedSinkParameters.getString(PipeSinkConstant.CONNECTOR_IOTDB_NODE_URLS_KEY)); + Assert.assertEquals(" HOST.EXAMPLE.COM ", normalizedSinkParameters.getString("connector.host")); + Assert.assertEquals(" 2001:DB8::1 ", normalizedSinkParameters.getString("connector.ip")); + Assert.assertEquals(" P@SSword ", normalizedSinkParameters.getString("connector.password")); + Assert.assertEquals( + " C:\\CERTS\\STORE.JKS ", + normalizedSinkParameters.getString( + PipeSinkConstant.CONNECTOR_IOTDB_SSL_TRUST_STORE_PATH_KEY)); + Assert.assertEquals("true", normalizedSinkParameters.getString("connector.ssl.enable")); + Assert.assertEquals( + "No-Privileges", + PipePluginAgent.normalizeSinkParameters( + new PipeParameters( + Map.of( + "CONNECTOR", + "IOTDB-THRIFT-CONNECTOR", + PipeSinkConstant.CONNECTOR_SKIP_IF_KEY, + "No-Privileges"))) + .getString(PipeSinkConstant.CONNECTOR_SKIP_IF_KEY)); + + final PipeParameters normalizedSubscriptionSinkParameters = + PipePluginAgent.normalizeSinkParameters( + new PipeParameters( + Map.of( + " CONNECTOR ", " SUBSCRIPTION-SINK ", + " Sink.Topic ", " MixedTopic ", + " Sink.Consumer-Group ", " MixedGroup "))); + Assert.assertEquals( + " MixedTopic ", normalizedSubscriptionSinkParameters.getString("sink.topic")); + Assert.assertEquals( + " MixedGroup ", normalizedSubscriptionSinkParameters.getString("sink.consumer-group")); + } + + @Test + public void testShowCreatePipeDisplaysNormalizedParameters() { + final PipeMeta pipeMeta = + new PipeMeta( + new PipeStaticMeta( + "normalizedPipe", + 1L, + Map.of( + " SOURCE ", " IOTDB-EXTRACTOR ", + " Source.Path ", " ROOT.SG.** ", + " Source.Mode ", " QUERY ", + " Source.Custom.Option ", " Mixed Value "), + Map.of( + " PROCESSOR ", " DO-NOTHING-PROCESSOR ", + " Processor.Mode ", " ON "), + Map.of( + " CONNECTOR ", " IOTDB-THRIFT-CONNECTOR ", + " Connector.Custom.Option ", " Mixed Value ", + " Connector.Node-URLs ", " https://NODEA:6667,NodeB:6667 ")), + new PipeRuntimeMeta()); + + final String showCreate = ShowCreatePipeTask.getShowCreatePipeSQL(pipeMeta); + + Assert.assertTrue(showCreate.contains("'source.path'=' ROOT.SG.** '")); + Assert.assertTrue(showCreate.contains("'source.mode'='query'")); + Assert.assertTrue(showCreate.contains("'source.custom.option'='mixed value'")); + Assert.assertTrue(showCreate.contains("'processor.mode'='on'")); + Assert.assertTrue(showCreate.contains("'connector.custom.option'='mixed value'")); + Assert.assertTrue( + showCreate.contains("'connector.node-urls'=' https://NODEA:6667,NodeB:6667 '")); + } + + @Test public void testPluginLoadFailureIsRecordedForShowPipePlugins() throws Exception { final PipeDataNodePluginAgent agent = new PipeDataNodePluginAgent(); final PipePluginMeta plugin =
diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java index 43825f6..f4e6805 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/pipe/agent/task/stage/PipeTaskSourceStageTest.java
@@ -121,7 +121,7 @@ } @Test - public void testSourceStartErrorRemainsPrimaryWhenCloseAlsoFails() throws Exception { + public void testSourceStartErrorRemainsPrimaryAndDropRetriesFailedClose() throws Exception { final AssertionError startError = new AssertionError("start failed"); final AssertionError closeError = new AssertionError("close failed"); final TestExtractor extractor = new TestExtractor(startError, closeError); @@ -134,7 +134,7 @@ Assert.assertNull(stage.getEventSupplier().supply()); stage.drop(); - Assert.assertEquals(1, extractor.closeCount); + Assert.assertEquals(2, extractor.closeCount); } @Test @@ -228,7 +228,7 @@ @Override public void close() { closeCount++; - if (closeError != null) { + if (closeError != null && closeCount == 1) { throw closeError; } }
diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java index e1118399..817f6a8 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/PendingResultFragmentTest.java
@@ -41,19 +41,21 @@ PendingResultFragment fragment = new PendingResultFragment(account); ByteBuffer block = ByteBuffer.allocate(100); - fragment.reset(block, 30); + fragment.reset(block, 30, 2); assertEquals(List.of(100L), account.reserved); assertEquals(0, account.releases); // continuing the same block must not reserve again - fragment.reset(block, 60); + fragment.reset(block, 60, 2); assertEquals(List.of(100L), account.reserved); assertSame(block, fragment.getBlock()); assertEquals(60, fragment.getNextOffset()); + assertEquals(2, fragment.getRowCount()); fragment.clear(); assertEquals(1, account.releases); assertNull(fragment.getBlock()); + assertEquals(0, fragment.getRowCount()); } @Test @@ -61,19 +63,20 @@ RecordingAccount account = new RecordingAccount(); PendingResultFragment fragment = new PendingResultFragment(account); - fragment.reset(ByteBuffer.allocate(100), 30); - fragment.reset(ByteBuffer.allocate(50), 10); + fragment.reset(ByteBuffer.allocate(100), 30, 1); + fragment.reset(ByteBuffer.allocate(50), 10, 3); // the previous reservation is released before the new one is taken assertEquals(List.of(100L, 50L), account.reserved); assertEquals(1, account.releases); assertEquals(50L, account.accounted); + assertEquals(3, fragment.getRowCount()); } @Test public void testNullAccountDisablesAccounting() { PendingResultFragment fragment = new PendingResultFragment(null); - fragment.reset(ByteBuffer.allocate(100), 30); + fragment.reset(ByteBuffer.allocate(100), 30, 1); fragment.clear(); assertNull(fragment.getBlock()); } @@ -88,7 +91,7 @@ new Thread( () -> { try { - fragment.reset(ByteBuffer.allocate(100), 30); + fragment.reset(ByteBuffer.allocate(100), 30, 1); } catch (IllegalStateException expected) { // the reservation was cancelled by the cleanup failure.set(expected);
diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java index febb701..bed8791 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/QueryDataSetUtilsTest.java
@@ -41,6 +41,7 @@ import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -48,6 +49,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class QueryDataSetUtilsTest { @@ -299,6 +302,7 @@ Mockito.when(queryExecution.getByteBufferBatchResult()) .thenReturn(Optional.of(serialized.duplicate()), Optional.empty()); Mockito.when(queryExecution.hasNextResult()).thenReturn(false); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); QueryDataSetUtils.ResultChunk firstChunk = QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); @@ -341,6 +345,7 @@ Mockito.when(queryExecution.getByteBufferBatchResult()) .thenReturn(Optional.of(smallBlock), Optional.of(serialized.duplicate()), Optional.empty()); Mockito.when(queryExecution.hasNextResult()).thenReturn(false); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); QueryDataSetUtils.ResultChunk firstChunk = QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); @@ -364,7 +369,261 @@ } @Test - public void testContinuationCompletionDoesNotFetchNewBlocks() throws IoTDBException, IOException { + public void testContinuationCompletesFragmentAndDeliversFollowingBlocks() + throws IoTDBException, IOException { + TsBlock tsBlock = buildTsBlock(); + ByteBuffer serialized = new TsBlockSerde().serialize(tsBlock); + int blockSize = serialized.remaining(); + int payloadSize = blockSize / 2; + + IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class); + PendingResultFragment pendingFragment = new PendingResultFragment(null); + Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment); + Mockito.when(queryExecution.getByteBufferBatchResult()) + .thenReturn( + Optional.of(serialized.duplicate()), + Optional.of(serialized.duplicate()), + Optional.empty()); + Mockito.when(queryExecution.hasNextResult()).thenReturn(false); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); + + QueryDataSetUtils.ResultChunk firstChunk = + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); + assertFalse(firstChunk.isFinished()); + assertEquals(payloadSize, firstChunk.getNextOffset()); + assertEquals(tsBlock.getPositionCount(), pendingFragment.getRowCount()); + + // The response that completes the fragmented block continues with the following blocks while + // the payload and the fetch size still have room, instead of ending here and costing an extra + // round trip. + QueryDataSetUtils.ResultChunk continuationChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, 10, firstChunk.getNextOffset(), 2 * blockSize); + assertTrue(continuationChunk.isFinished()); + assertFalse(continuationChunk.hasNextOffset()); + assertEquals(2, continuationChunk.getQueryResult().size()); + // the tail of the fragmented block comes first + assertEquals(blockSize - payloadSize, continuationChunk.getQueryResult().get(0).remaining()); + // then the following block, delivered by the same response + assertEquals(blockSize, continuationChunk.getQueryResult().get(1).remaining()); + assertNull(pendingFragment.getBlock()); + } + + @Test + public void testContinuationCountsPendingRowsAgainstFetchSize() + throws IoTDBException, IOException { + TsBlock tsBlock = buildTsBlock(); + ByteBuffer serialized = new TsBlockSerde().serialize(tsBlock); + int blockSize = serialized.remaining(); + int payloadSize = blockSize / 2; + + IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class); + PendingResultFragment pendingFragment = new PendingResultFragment(null); + Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment); + Mockito.when(queryExecution.getByteBufferBatchResult()) + .thenReturn( + Optional.of(serialized.duplicate()), + Optional.of(serialized.duplicate()), + Optional.empty()); + Mockito.when(queryExecution.hasNextResult()).thenReturn(true, false); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); + + // fetchSize equals the rows of one block + QueryDataSetUtils.ResultChunk firstChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, tsBlock.getPositionCount(), 0, payloadSize); + assertFalse(firstChunk.isFinished()); + assertEquals(tsBlock.getPositionCount(), pendingFragment.getRowCount()); + + // The rows of the completed block already fill the fetch size, so the continuation response + // stops after the tail even though the payload still has room. + QueryDataSetUtils.ResultChunk continuationChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, tsBlock.getPositionCount(), firstChunk.getNextOffset(), 2 * blockSize); + assertFalse(continuationChunk.isFinished()); + assertFalse(continuationChunk.hasNextOffset()); + assertEquals(1, continuationChunk.getQueryResult().size()); + assertEquals(blockSize - payloadSize, continuationChunk.getQueryResult().get(0).remaining()); + assertNull(pendingFragment.getBlock()); + + // The following block is delivered by the next request. + QueryDataSetUtils.ResultChunk nextChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, tsBlock.getPositionCount(), 0, 2 * blockSize); + assertTrue(nextChunk.isFinished()); + assertFalse(nextChunk.hasNextOffset()); + assertEquals(1, nextChunk.getQueryResult().size()); + assertEquals(blockSize, nextChunk.getQueryResult().get(0).remaining()); + } + + @Test + public void testContinuationHoldsWholeBlockThatFitsFreshResponse() + throws IoTDBException, IOException { + ByteBuffer first = serializeTextBlock(64 * 1024); + ByteBuffer second = serializeTextBlock(64 * 1024); + ByteBuffer third = serializeTextBlock(64 * 1024); + int blockSize = first.remaining(); + // 1.2 blocks: the first block fits with 0.2 left, so the second one is fragmented at 0.2; + // the continuation completes it with 0.8 left, and the third block (1.0) fits into a fresh + // payload but not into the remaining space + int payloadSize = blockSize + blockSize / 5; + + IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class); + PendingResultFragment pendingFragment = new PendingResultFragment(null); + Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment); + Mockito.when(queryExecution.getByteBufferBatchResult()) + .thenReturn( + Optional.of(first.duplicate()), + Optional.of(second.duplicate()), + Optional.of(third.duplicate()), + Optional.empty()); + Mockito.when(queryExecution.hasNextResult()).thenReturn(false); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); + + QueryDataSetUtils.ResultChunk firstChunk = + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); + assertFalse(firstChunk.isFinished()); + assertTrue(firstChunk.hasNextOffset()); + assertEquals(payloadSize - blockSize, firstChunk.getNextOffset()); + assertEquals(blockSize, firstChunk.getTotalLength()); + + // The continuation must not fragment the third block at the remaining space: it keeps it whole + // for the next response, which sees a fresh payload. + QueryDataSetUtils.ResultChunk continuationChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, 10, firstChunk.getNextOffset(), payloadSize); + assertFalse(continuationChunk.isFinished()); + assertFalse(continuationChunk.hasNextOffset()); + assertEquals(1, continuationChunk.getQueryResult().size()); + assertEquals( + blockSize - (payloadSize - blockSize), + continuationChunk.getQueryResult().get(0).remaining()); + assertNotNull(pendingFragment.getBlock()); + assertEquals(0, pendingFragment.getNextOffset()); + assertEquals(1, pendingFragment.getRowCount()); + + // The next request delivers the held block whole. + QueryDataSetUtils.ResultChunk nextChunk = + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); + assertTrue(nextChunk.isFinished()); + assertFalse(nextChunk.hasNextOffset()); + assertEquals(1, nextChunk.getQueryResult().size()); + assertEquals(blockSize, nextChunk.getQueryResult().get(0).remaining()); + assertNull(pendingFragment.getBlock()); + } + + @Test + public void testResumingHeldBlockLargerThanPayloadStartsFragmentWithTotalLength() + throws IoTDBException, IOException { + ByteBuffer first = serializeTextBlock(96 * 1024); + ByteBuffer second = serializeTextBlock(96 * 1024); + int blockSize = first.remaining(); + // the payload is smaller than a block, so the second block held by the continuation starts + // a fragment of its own in the response that resumes it; the extra bytes leave room for the + // odd serialized size, so that the continuation does complete the first tail + int payloadSize = blockSize / 2 + 16; + + IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class); + PendingResultFragment pendingFragment = new PendingResultFragment(null); + Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment); + Mockito.when(queryExecution.getByteBufferBatchResult()) + .thenReturn( + Optional.of(first.duplicate()), Optional.of(second.duplicate()), Optional.empty()); + Mockito.when(queryExecution.hasNextResult()).thenReturn(false); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); + + QueryDataSetUtils.ResultChunk firstChunk = + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); + assertFalse(firstChunk.isFinished()); + assertEquals(payloadSize, firstChunk.getNextOffset()); + assertEquals(blockSize, firstChunk.getTotalLength()); + + // the continuation completes the first block and holds the second one whole + QueryDataSetUtils.ResultChunk continuationChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, 10, firstChunk.getNextOffset(), payloadSize); + assertFalse(continuationChunk.isFinished()); + assertFalse(continuationChunk.hasNextOffset()); + assertNotNull(pendingFragment.getBlock()); + assertEquals(0, pendingFragment.getNextOffset()); + + // Resuming the held block: it does not fit into the payload either, so this response starts + // its fragment. The client has no reassembly buffer for it, so the total length is required. + QueryDataSetUtils.ResultChunk resumedChunk = + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, payloadSize); + assertFalse(resumedChunk.isFinished()); + assertTrue(resumedChunk.hasNextOffset()); + assertEquals(payloadSize, resumedChunk.getNextOffset()); + assertTrue(resumedChunk.hasTotalLength()); + assertEquals(blockSize, resumedChunk.getTotalLength()); + assertEquals(1, resumedChunk.getQueryResult().size()); + assertEquals(payloadSize, resumedChunk.getQueryResult().get(0).remaining()); + + // the following continuation completes the block without repeating the total length + QueryDataSetUtils.ResultChunk tailChunk = + QueryDataSetUtils.convertQueryResultByFetchSize( + queryExecution, 10, resumedChunk.getNextOffset(), payloadSize); + assertTrue(tailChunk.isFinished()); + assertFalse(tailChunk.hasNextOffset()); + assertEquals(blockSize - payloadSize, tailChunk.getQueryResult().get(0).remaining()); + assertNull(pendingFragment.getBlock()); + } + + @Test + public void testOrdinaryBlocksAreNotRepeatedlySplit() throws IoTDBException, IOException { + // the scenario from the review: two smaller blocks followed by six blocks of exactly one + // payload, which must not make every following block a fragment + List<ByteBuffer> blocks = new ArrayList<>(); + blocks.add(serializeTextBlock(96 * 1024)); + blocks.add(serializeTextBlock(96 * 1024)); + for (int i = 0; i < 6; i++) { + blocks.add(serializeTextBlock(128 * 1024)); + } + int payloadSize = blocks.get(2).remaining(); + assertTrue(blocks.get(0).remaining() < payloadSize); + + IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class); + PendingResultFragment pendingFragment = new PendingResultFragment(null); + Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment); + Mockito.when(queryExecution.getByteBufferBatchResult()) + .thenAnswer( + invocation -> + blocks.isEmpty() ? Optional.empty() : Optional.of(blocks.remove(0).duplicate())); + Mockito.when(queryExecution.hasNextResult()) + .thenAnswer(invocation -> !blocks.isEmpty() || pendingFragment.getBlock() != null); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); + + List<QueryDataSetUtils.ResultChunk> chunks = new ArrayList<>(); + int offset = 0; + while (true) { + QueryDataSetUtils.ResultChunk chunk = + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, offset, payloadSize); + chunks.add(chunk); + for (ByteBuffer block : chunk.getQueryResult()) { + assertTrue(block.remaining() <= payloadSize); + } + if (chunk.isFinished()) { + break; + } + offset = chunk.hasNextOffset() ? chunk.getNextOffset() : 0; + } + + // one response per block, and only the second block (which landed near the end of the first + // response) is split, so the client reassembles exactly one block + assertEquals(8, chunks.size()); + assertEquals(1, chunks.stream().filter(QueryDataSetUtils.ResultChunk::hasNextOffset).count()); + // the response that completes the split block does not start another one + assertEquals(2, chunks.get(0).getQueryResult().size()); + assertEquals(1, chunks.get(1).getQueryResult().size()); + for (int i = 2; i < chunks.size(); i++) { + assertEquals(1, chunks.get(i).getQueryResult().size()); + assertEquals(payloadSize, chunks.get(i).getQueryResult().get(0).remaining()); + } + } + + @Test + public void testContinuationReturnsWithoutWaitingForUnavailableBlocks() + throws IoTDBException, IOException { TsBlock tsBlock = buildTsBlock(); ByteBuffer serialized = new TsBlockSerde().serialize(tsBlock); int blockSize = serialized.remaining(); @@ -385,26 +644,37 @@ assertFalse(firstChunk.isFinished()); assertEquals(payloadSize, firstChunk.getNextOffset()); - // The response that completes the fragmented block must not fetch new blocks, otherwise its - // row count would exceed fetchSize (the tail of the big block is not accounted). + // The next block is still being produced: the continuation must return the tail immediately + // instead of waiting for it. + Mockito.when(queryExecution.isResultAvailable()).thenReturn(false); QueryDataSetUtils.ResultChunk continuationChunk = QueryDataSetUtils.convertQueryResultByFetchSize( - queryExecution, 10, firstChunk.getNextOffset(), blockSize); + queryExecution, 10, firstChunk.getNextOffset(), 2 * blockSize); assertFalse(continuationChunk.isFinished()); assertFalse(continuationChunk.hasNextOffset()); assertEquals(1, continuationChunk.getQueryResult().size()); assertEquals(blockSize - payloadSize, continuationChunk.getQueryResult().get(0).remaining()); - assertTrue(pendingFragment.getBlock() == null); + Mockito.verify(queryExecution, Mockito.times(1)).getByteBufferBatchResult(); - // New blocks are delivered by the following request only + // The following request waits for the block and delivers it. + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); QueryDataSetUtils.ResultChunk nextChunk = - QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, blockSize); + QueryDataSetUtils.convertQueryResultByFetchSize(queryExecution, 10, 0, 2 * blockSize); assertTrue(nextChunk.isFinished()); - assertFalse(nextChunk.hasNextOffset()); assertEquals(1, nextChunk.getQueryResult().size()); assertEquals(blockSize, nextChunk.getQueryResult().get(0).remaining()); } + private ByteBuffer serializeTextBlock(int valueSize) throws IOException { + byte[] value = new byte[valueSize]; + Arrays.fill(value, (byte) 'x'); + TsBlockBuilder builder = new TsBlockBuilder(Collections.singletonList(TSDataType.TEXT)); + builder.getTimeColumnBuilder().writeLong(1L); + builder.getColumnBuilder(0).writeBinary(new Binary(value)); + builder.declarePosition(); + return new TsBlockSerde().serialize(builder.build()); + } + @Test public void testEmptyBlockReleasesItsMemory() throws IoTDBException, IOException { TsBlock emptyTsBlock = new TsBlockBuilder(Collections.singletonList(TSDataType.INT64)).build(); @@ -430,7 +700,7 @@ @Test(expected = IllegalArgumentException.class) public void testConvertQueryResultByFetchSizeRejectsMismatchedOffset() throws IoTDBException { PendingResultFragment pendingFragment = new PendingResultFragment(null); - pendingFragment.reset(ByteBuffer.wrap(new byte[10]), 5); + pendingFragment.reset(ByteBuffer.wrap(new byte[10]), 5, 0); IQueryExecution queryExecution = Mockito.mock(IQueryExecution.class); Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment);
diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java index 525cb4b..3f11952 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/ResultChunkingEndToEndTest.java
@@ -126,6 +126,66 @@ } @Test(timeout = 60_000) + public void testHeldBlockLargerThanPayloadRoundTrip() throws Exception { + // the continuation holds the second block, which is larger than a whole payload, and the + // response resuming it has to start its fragment with a total length for the client + int[] textSizes = {300 * 1024, 400 * 1024, 8}; + char[] fills = {'a', 'b', 'c'}; + List<ByteBuffer> blocks = new ArrayList<>(); + for (int i = 0; i < textSizes.length; i++) { + blocks.add( + new TsBlockSerde() + .serialize(buildTsBlockWithText(1_000L * (i + 1), fills[i], textSizes[i]))); + } + + ServerSideSimulation server = new ServerSideSimulation(blocks, 100); + + IClientRPCService.Iface client = mock(IClientRPCService.Iface.class); + when(client.closeOperation(any(TSCloseOperationReq.class))) + .thenReturn(RpcUtils.getStatus(TSStatusCode.SUCCESS_STATUS)); + when(client.fetchResultsV2(any(TSFetchResultsReq.class))) + .thenAnswer(invocation -> server.handleFetchResults(invocation.getArgument(0))); + + IoTDBRpcDataSet dataSet = + new IoTDBRpcDataSet( + "", + List.of(COLUMN, TEXT_COLUMN), + List.of(TSDataType.INT64.name(), TSDataType.TEXT.name()), + null, + true, + true, + 1L, + 2L, + client, + 3L, + null, + 100, + 0, + ZoneId.systemDefault(), + RpcUtils.DEFAULT_TIME_FORMAT, + 1_000_000, + true, + new ArrayList<>(Arrays.asList(0, 1))); + + for (int i = 0; i < textSizes.length; i++) { + assertTrue(dataSet.next()); + String value = dataSet.getString(TEXT_COLUMN); + assertEquals(textSizes[i], value.length()); + assertEquals(fills[i], value.charAt(0)); + } + assertFalse(dataSet.next()); + + assertEquals("the held block must cost no extra response", 4, server.rpcCount.get()); + for (int payload : server.payloadSizes) { + assertTrue( + String.format("one response payload %d exceeds the bound %d", payload, MAX_PAYLOAD_SIZE), + payload <= MAX_PAYLOAD_SIZE); + } + assertTrue(server.releaseCount.get() > 0); + assertEquals("the pending fragment must be cleared in the end", null, server.getPendingBlock()); + } + + @Test(timeout = 60_000) public void testSmallResultUsesOneResponseWithoutFragment() throws Exception { TsBlockBuilder builder = new TsBlockBuilder(List.of(TSDataType.INT64)); builder.getTimeColumnBuilder().writeLong(1L); @@ -197,12 +257,17 @@ private ServerSideSimulation(ByteBuffer serialized, int positionCount, int totalLength) throws Exception { - this.serialized = serialized; - this.positionCount = positionCount; - this.totalLength = totalLength; - this.remainingBlocks.add(serialized); + this(List.of(serialized), positionCount); + } + + private ServerSideSimulation(List<ByteBuffer> blocks, int fetchSize) throws Exception { + this.serialized = null; + this.positionCount = fetchSize; + this.totalLength = -1; + this.remainingBlocks.addAll(blocks); this.queryExecution = Mockito.mock(IQueryExecution.class); Mockito.when(queryExecution.getPendingResultFragment()).thenReturn(pendingFragment); + Mockito.when(queryExecution.isResultAvailable()).thenReturn(true); Mockito.when(queryExecution.getByteBufferBatchResult()) .thenAnswer( invocation -> @@ -247,6 +312,18 @@ } } + /** [time=time, v=time/1000, text=textSize bytes of {@code fill}]. */ + private static TsBlock buildTsBlockWithText(long time, char fill, int textSize) { + byte[] value = new byte[textSize]; + Arrays.fill(value, (byte) fill); + TsBlockBuilder builder = new TsBlockBuilder(Arrays.asList(TSDataType.INT64, TSDataType.TEXT)); + builder.getTimeColumnBuilder().writeLong(time); + builder.getColumnBuilder(0).writeLong(time / 1000); + builder.getColumnBuilder(1).writeBinary(new Binary(value)); + builder.declarePosition(); + return builder.build(); + } + /** [time=1, v=10, text="small"], [time=2, v=20, text=<LARGE_VALUE_SIZE bytes>]. */ private static TsBlock buildTsBlockWithLargeValue() { byte[] largeValue = new byte[LARGE_VALUE_SIZE];
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgent.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgent.java index c0c8a19..d71f00c 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgent.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgent.java
@@ -20,11 +20,14 @@ package org.apache.iotdb.commons.pipe.agent.plugin; import org.apache.iotdb.commons.i18n.PipeMessages; +import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.agent.plugin.constructor.PipeProcessorConstructor; import org.apache.iotdb.commons.pipe.agent.plugin.constructor.PipeSinkConstructor; import org.apache.iotdb.commons.pipe.agent.plugin.constructor.PipeSourceConstructor; import org.apache.iotdb.commons.pipe.agent.plugin.meta.PipePluginMetaKeeper; import org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant; +import org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant; +import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant; import org.apache.iotdb.commons.pipe.config.plugin.configuraion.PipeTaskRuntimeConfiguration; import org.apache.iotdb.commons.pipe.config.plugin.env.PipeTaskTemporaryRuntimeEnvironment; import org.apache.iotdb.pipe.api.PipeConnector; @@ -38,10 +41,14 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.stream.Collectors; import java.util.stream.StreamSupport; @@ -54,6 +61,43 @@ private final PipeProcessorConstructor pipeProcessorConstructor; private final PipeSinkConstructor pipeSinkConstructor; + private static final Set<String> PARAMETER_VALUE_PRESERVATION_KEYS = + Set.of( + "path", + "path.inclusion", + "path.exclusion", + "operators", + "skipif", + "pattern", + "pattern.inclusion", + "pattern.exclusion", + "database-name", + "table-name", + "database", + "table", + "user", + "topic", + "consumer-group", + "username", + "password", + "scp.password", + "cli-hostname", + "ip", + "host", + "node-urls", + "ssl.trust-store-path", + "ssl.trust-store-pwd", + "ssl.key-store-path", + "ssl.key-store-pwd", + "output.database", + "output.measurements", + "output.series", + "output-series", + "new-db-name", + "opcda.clsid", + "opcda.progid", + "consensus.pipe-name"); + protected PipePluginAgent(final PipePluginMetaKeeper pipePluginMetaKeeper) { this.pipePluginMetaKeeper = pipePluginMetaKeeper; pipeExtractorConstructor = createPipeSourceConstructor(pipePluginMetaKeeper); @@ -82,6 +126,169 @@ return pipeSinkConstructor.reflectPlugin(sinkParameters); } + public static PipeParameters normalizeSourceParameters(final PipeParameters parameters) { + return normalizeSourceParameters(parameters, null); + } + + public static PipeParameters normalizeSourceParametersForUpdate( + final PipeParameters parameters, final PipeParameters existingParameters) { + return normalizeSourceParametersForUpdate(parameters, existingParameters, false); + } + + public static PipeParameters normalizeSourceParametersForUpdate( + final PipeParameters parameters, + final PipeParameters existingParameters, + final boolean replaceAll) { + return normalizeSourceParameters(parameters, replaceAll ? null : existingParameters); + } + + private static PipeParameters normalizeSourceParameters( + final PipeParameters parameters, final PipeParameters existingParameters) { + return normalizePluginParameters( + parameters, + existingParameters, + Arrays.asList(PipeSourceConstant.EXTRACTOR_KEY, PipeSourceConstant.SOURCE_KEY), + null, + BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName(), + PipeExtractor.class); + } + + public static PipeParameters normalizeProcessorParameters(final PipeParameters parameters) { + return normalizeProcessorParameters(parameters, null, null); + } + + public static PipeParameters normalizeProcessorParametersForUpdate( + final PipeParameters parameters, final PipeParameters existingParameters) { + return normalizeProcessorParameters(parameters, existingParameters, null); + } + + private static PipeParameters normalizeProcessorParameters( + final PipeParameters parameters, + final PipeParameters existingParameters, + final String selectedPluginName) { + return normalizePluginParameters( + parameters, + existingParameters, + Collections.singletonList(PipeProcessorConstant.PROCESSOR_KEY), + selectedPluginName, + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName(), + PipeProcessor.class); + } + + public static PipeParameters normalizeSinkParameters(final PipeParameters parameters) { + return normalizeSinkParameters(parameters, null); + } + + public static PipeParameters normalizeSinkParametersForUpdate( + final PipeParameters parameters, final PipeParameters existingParameters) { + return normalizeSinkParameters(parameters, existingParameters); + } + + private static PipeParameters normalizeSinkParameters( + final PipeParameters parameters, final PipeParameters existingParameters) { + final PipeParameters defaultParameters = + existingParameters == null ? parameters : existingParameters; + return normalizePluginParameters( + parameters, + existingParameters, + Arrays.asList(PipeSinkConstant.CONNECTOR_KEY, PipeSinkConstant.SINK_KEY), + null, + PipeSinkConstant.getConnectorOrSinkNameWithDefault(defaultParameters), + PipeConnector.class); + } + + private static PipeParameters normalizePluginParameters( + final PipeParameters parameters, + final PipeParameters existingParameters, + final List<String> pluginNameKeys, + final String selectedPluginName, + final String defaultPluginName, + final Class<?> pluginClass) { + String pluginName = selectedPluginName; + if (pluginName == null) { + pluginName = getPluginName(parameters, pluginNameKeys); + } + if (pluginName == null && existingParameters != null) { + pluginName = getPluginName(existingParameters, pluginNameKeys); + } + if (pluginName == null) { + pluginName = defaultPluginName; + } + final boolean builtinPlugin = isBuiltinPlugin(pluginName, pluginClass); + final Map<String, String> normalizedAttributes = new HashMap<>(); + parameters + .getAttribute() + .forEach( + (key, value) -> { + if (key == null) { + normalizedAttributes.put(null, value); + return; + } + + final String trimmedKey = key.trim(); + final String normalizedKey = trimmedKey.toLowerCase(Locale.ROOT); + if (isPluginNameKey(trimmedKey, pluginNameKeys)) { + normalizedAttributes.put( + normalizedKey, + value == null || !builtinPlugin + ? value + : value.trim().toLowerCase(Locale.ROOT)); + } else if (builtinPlugin) { + normalizedAttributes.put( + normalizedKey, + value == null || shouldPreserveParameterValue(normalizedKey) + ? value + : value.trim().toLowerCase(Locale.ROOT)); + } else { + normalizedAttributes.put(key, value); + } + }); + return new PipeParameters(normalizedAttributes); + } + + private static String getPluginName( + final PipeParameters parameters, final List<String> pluginNameKeys) { + if (parameters == null) { + return null; + } + for (final String pluginNameKey : pluginNameKeys) { + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && pluginNameKey.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null) { + return entry.getValue(); + } + } + } + return null; + } + + private static boolean isPluginNameKey(final String key, final List<String> pluginNameKeys) { + for (final String pluginNameKey : pluginNameKeys) { + if (pluginNameKey.equalsIgnoreCase(key)) { + return true; + } + } + return false; + } + + private static boolean isBuiltinPlugin(final String pluginName, final Class<?> pluginClass) { + if (pluginName == null) { + return false; + } + final String normalizedPluginName = pluginName.trim().toLowerCase(Locale.ROOT); + return Arrays.stream(BuiltinPipePlugin.values()) + .anyMatch( + builtinPipePlugin -> + pluginClass.isAssignableFrom(builtinPipePlugin.getPipePluginClass()) + && normalizedPluginName.equals(builtinPipePlugin.getPipePluginName())); + } + + private static boolean shouldPreserveParameterValue(final String normalizedKey) { + return PARAMETER_VALUE_PRESERVATION_KEYS.contains( + PipeParameters.KeyReducer.reduce(normalizedKey).toLowerCase(Locale.ROOT)); + } + public void validate( final String pipeName, final Map<String, String> sourceAttributes, @@ -95,7 +302,8 @@ protected PipeExtractor validateSource( final String pipeName, final Map<String, String> sourceAttributes) throws Exception { - final PipeParameters sourceParameters = new PipeParameters(sourceAttributes); + final PipeParameters sourceParameters = + normalizeSourceParameters(new PipeParameters(sourceAttributes)); final PipeExtractor temporarySource = reflectSource(sourceParameters); try { temporarySource.validate(new PipeParameterValidator(sourceParameters)); @@ -114,7 +322,8 @@ protected PipeProcessor validateProcessor(final Map<String, String> processorAttributes) throws Exception { - final PipeParameters processorParameters = new PipeParameters(processorAttributes); + final PipeParameters processorParameters = + normalizeProcessorParameters(new PipeParameters(processorAttributes)); final PipeProcessor temporaryProcessor = reflectProcessor(processorParameters); try { temporaryProcessor.validate(new PipeParameterValidator(processorParameters)); @@ -130,7 +339,8 @@ protected PipeConnector validateSink( final String pipeName, final Map<String, String> sinkAttributes) throws Exception { - final PipeParameters sinkParameters = new PipeParameters(sinkAttributes); + final PipeParameters sinkParameters = + normalizeSinkParameters(new PipeParameters(sinkAttributes)); final PipeConnector temporarySink = reflectSink(sinkParameters); try { temporarySink.validate(new PipeParameterValidator(sinkParameters)); @@ -189,13 +399,16 @@ String pipeProcessorName, PipeParameters processorParameters, PipeProcessorRuntimeConfiguration runtimeConfigurations) { + final PipeParameters normalizedParameters = + normalizeProcessorParameters(processorParameters, null, pipeProcessorName); final HashMap<String, String> processorKeyMap = new HashMap<>(); if (Objects.nonNull(pipeProcessorName)) { processorKeyMap.put(PipeProcessorConstant.PROCESSOR_KEY, pipeProcessorName); } - final PipeParameters replacedParameters = - processorParameters.addOrReplaceEquivalentAttributesWithClone( + final PipeParameters mergedParameters = + normalizedParameters.addOrReplaceEquivalentAttributesWithClone( new PipeParameters(processorKeyMap)); + final PipeParameters replacedParameters = normalizeProcessorParameters(mergedParameters); final PipeProcessor processor = reflectProcessor(replacedParameters); // Validate and customize should be called to expose exceptions in advance // and configure the processor.
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java index 2b1844b..25da4a2 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/PipeTaskAgent.java
@@ -1050,8 +1050,8 @@ // task meta so that the meta sync creates and starts the task again instead of keeping it // "RUNNING" but dead until the node restarts. rollbackPipeTask(consensusGroupId, pipeStaticMeta, e); - if (e instanceof Error) { - throw (Error) e; + if (e instanceof Error error) { + throw error; } return; }
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/meta/PipeStaticMeta.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/meta/PipeStaticMeta.java index da215ae..601ad96 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/meta/PipeStaticMeta.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/meta/PipeStaticMeta.java
@@ -20,6 +20,7 @@ package org.apache.iotdb.commons.pipe.agent.task.meta; import org.apache.iotdb.commons.conf.IoTDBConstant; +import org.apache.iotdb.commons.pipe.agent.plugin.PipePluginAgent; import org.apache.iotdb.commons.pipe.agent.plugin.builtin.BuiltinPipePlugin; import org.apache.iotdb.commons.pipe.config.constant.PipeProcessorConstant; import org.apache.iotdb.commons.pipe.config.constant.PipeSinkConstant; @@ -66,9 +67,12 @@ final Map<String, String> connectorAttributes) { this.pipeName = pipeName; this.creationTime = creationTime; - sourceParameters = new PipeParameters(extractorAttributes); - processorParameters = new PipeParameters(processorAttributes); - sinkParameters = new PipeParameters(connectorAttributes); + sourceParameters = + PipePluginAgent.normalizeSourceParameters(new PipeParameters(extractorAttributes)); + processorParameters = + PipePluginAgent.normalizeProcessorParameters(new PipeParameters(processorAttributes)); + sinkParameters = + PipePluginAgent.normalizeSinkParameters(new PipeParameters(connectorAttributes)); updateCompletionSupport(); } @@ -177,6 +181,7 @@ .put(PipeSourceConstant.SOURCE_IOTDB_USER_ID, String.valueOf(IoTDBConstant.SUPER_USER_ID)); sourceParameters.getAttribute().put(PipeSourceConstant.SOURCE_IOTDB_USERNAME_KEY, rootUserName); sourceParameters.getAttribute().put(PipeSourceConstant.SOURCE_IOTDB_PASSWORD_KEY, password); + sourceParameters = PipePluginAgent.normalizeSourceParameters(sourceParameters); } public void enrichWriteBackSinkWithRootUserForCompatibility( @@ -186,6 +191,7 @@ .put(PipeSinkConstant.SINK_IOTDB_USER_ID, String.valueOf(IoTDBConstant.SUPER_USER_ID)); sinkParameters.getAttribute().put(PipeSinkConstant.SINK_IOTDB_USERNAME_KEY, rootUserName); sinkParameters.getAttribute().put(PipeSinkConstant.SINK_IOTDB_PASSWORD_KEY, password); + sinkParameters = PipePluginAgent.normalizeSinkParameters(sinkParameters); } public ByteBuffer serialize() throws IOException { @@ -245,6 +251,7 @@ pipeStaticMeta.sinkParameters.getAttribute().put(key, value); } + pipeStaticMeta.normalizePluginParameters(); pipeStaticMeta.updateCompletionSupport(); return pipeStaticMeta; } @@ -278,10 +285,17 @@ pipeStaticMeta.sinkParameters.getAttribute().put(key, value); } + pipeStaticMeta.normalizePluginParameters(); pipeStaticMeta.updateCompletionSupport(); return pipeStaticMeta; } + private void normalizePluginParameters() { + sourceParameters = PipePluginAgent.normalizeSourceParameters(sourceParameters); + processorParameters = PipePluginAgent.normalizeProcessorParameters(processorParameters); + sinkParameters = PipePluginAgent.normalizeSinkParameters(sinkParameters); + } + @Override public boolean equals(final Object obj) { if (this == obj) {
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java index 1c0fb3b..2d9cdb3 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtask.java
@@ -19,6 +19,7 @@ package org.apache.iotdb.commons.pipe.agent.task.subtask; +import org.apache.iotdb.commons.conf.CommonDescriptor; import org.apache.iotdb.commons.i18n.PipeMessages; import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler; import org.apache.iotdb.commons.pipe.event.EnrichedEvent; @@ -38,13 +39,14 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; public abstract class PipeSubtask implements FutureCallback<Boolean>, Callable<Boolean>, AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(PipeSubtask.class); - private static final long FIRST_EXECUTION_TIMEOUT_IN_MS = TimeUnit.MINUTES.toMillis(1); + private static final long MAX_FIRST_EXECUTION_TIMEOUT_IN_MS = TimeUnit.MINUTES.toMillis(1); // Used for identifying the subtask protected final String taskID; @@ -60,7 +62,8 @@ protected final AtomicBoolean shouldStopSubmittingSelf = new AtomicBoolean(true); protected final AtomicBoolean isClosed = new AtomicBoolean(false); protected PipeSubtaskScheduler subtaskScheduler; - private volatile CountDownLatch firstExecutionLatch = new CountDownLatch(0); + private final AtomicReference<CountDownLatch> firstExecutionLatch = + new AtomicReference<>(new CountDownLatch(0)); // For fail-over public static final int MAX_RETRY_TIMES = 5; @@ -81,7 +84,7 @@ @Override public Boolean call() throws Exception { - final CountDownLatch currentFirstExecutionLatch = firstExecutionLatch; + final CountDownLatch currentFirstExecutionLatch = firstExecutionLatch.get(); boolean hasAtLeastOneEventProcessed = false; try { @@ -113,16 +116,16 @@ protected void onExecutionStart() {} public final void prepareForStart() { - firstExecutionLatch = new CountDownLatch(1); + firstExecutionLatch.set(new CountDownLatch(1)); } public final void awaitFirstExecution() throws InterruptedException { - awaitFirstExecution(FIRST_EXECUTION_TIMEOUT_IN_MS, TimeUnit.MILLISECONDS); + awaitFirstExecution(getFirstExecutionTimeoutInMs(), TimeUnit.MILLISECONDS); } public final void awaitFirstExecution(final long timeout, final TimeUnit timeUnit) throws InterruptedException { - if (!firstExecutionLatch.await(timeout, timeUnit)) { + if (!firstExecutionLatch.get().await(timeout, timeUnit)) { throw new PipeException( String.format( PipeMessages @@ -133,6 +136,12 @@ } } + public static long getFirstExecutionTimeoutInMs() { + return Math.min( + MAX_FIRST_EXECUTION_TIMEOUT_IN_MS, + Math.max(1L, CommonDescriptor.getInstance().getConfig().getDnConnectionTimeoutInMS() / 6L)); + } + /** Should be synchronized with {@link PipeSubtask#decreaseReferenceCountAndReleaseLastEvent} */ protected synchronized void setLastEvent(final Event event) { lastEvent = event;
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSinkConstant.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSinkConstant.java index 98dffc5..51c0156 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSinkConstant.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSinkConstant.java
@@ -29,6 +29,9 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; import java.util.Set; import static org.apache.iotdb.commons.conf.IoTDBConstant.MB; @@ -80,14 +83,42 @@ public static final boolean CONNECTOR_SERIALIZE_BY_REGION_DEFAULT_VALUE = false; public static boolean isSerializeByRegionEnabled(final PipeParameters parameters) { - return parameters.getBooleanOrDefault( - Arrays.asList(CONNECTOR_SERIALIZE_BY_REGION_KEY, SINK_SERIALIZE_BY_REGION_KEY), - CONNECTOR_SERIALIZE_BY_REGION_DEFAULT_VALUE); + return Boolean.parseBoolean( + getStringOrDefaultIgnoreCase( + parameters, + Arrays.asList(CONNECTOR_SERIALIZE_BY_REGION_KEY, SINK_SERIALIZE_BY_REGION_KEY), + Boolean.toString(CONNECTOR_SERIALIZE_BY_REGION_DEFAULT_VALUE))); } public static String getConnectorOrSinkNameWithDefault(final PipeParameters parameters) { - return parameters.getStringOrDefault( - Arrays.asList(CONNECTOR_KEY, SINK_KEY), getDefaultConnectorOrSinkName(parameters)); + return getStringOrDefaultIgnoreCase( + parameters, + Arrays.asList(CONNECTOR_KEY, SINK_KEY), + getDefaultConnectorOrSinkName(parameters)); + } + + private static String getStringOrDefaultIgnoreCase( + final PipeParameters parameters, final List<String> keys, final String defaultValue) { + for (final String key : keys) { + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && key.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue().trim(); + } + } + final String reducedKey = PipeParameters.KeyReducer.reduce(key.toLowerCase(Locale.ROOT)); + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && reducedKey.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue().trim(); + } + } + } + return defaultValue; } private static String getDefaultConnectorOrSinkName(final PipeParameters parameters) {
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java index 70d452a..a7a3e1c 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSourceConstant.java
@@ -26,6 +26,7 @@ import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; @@ -227,8 +228,46 @@ "extractor.consensus.receiver-dn-id"; public static boolean isDoubleLiving(final PipeParameters sourceParameters) { - return sourceParameters.getBooleanOrDefault( - DOUBLE_LIVING_KEYS, EXTRACTOR_MODE_DOUBLE_LIVING_DEFAULT_VALUE); + for (final String key : DOUBLE_LIVING_KEYS) { + final String value = getStringIgnoreCase(sourceParameters, key); + if (value != null) { + return Boolean.parseBoolean(value); + } + } + return EXTRACTOR_MODE_DOUBLE_LIVING_DEFAULT_VALUE; + } + + private static String getStringIgnoreCase( + final PipeParameters parameters, final String expectedKey) { + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && expectedKey.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue().trim(); + } + } + final String reducedKey = + PipeParameters.KeyReducer.reduce(expectedKey.toLowerCase(Locale.ROOT)); + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && reducedKey.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue().trim(); + } + } + return null; + } + + public static boolean isForwardingPipeRequestsEnabled(final PipeParameters parameters) { + for (final String key : FORWARDING_PIPE_REQUESTS_KEYS) { + final String value = getStringIgnoreCase(parameters, key); + if (value != null) { + return Boolean.parseBoolean(value); + } + } + return false; } public static void removeDoubleLivingAttributes(final Map<String, String> sourceAttributes) { @@ -244,11 +283,15 @@ final Map<String, String> sourceAttributes, final List<String> equivalentKeys) { final Set<String> reducedKeys = equivalentKeys.stream() - .map(PipeParameters.KeyReducer::reduce) + .map(key -> PipeParameters.KeyReducer.reduce(key.toLowerCase(Locale.ROOT).trim())) .collect(java.util.stream.Collectors.toSet()); sourceAttributes .keySet() - .removeIf(key -> reducedKeys.contains(PipeParameters.KeyReducer.reduce(key))); + .removeIf( + key -> + key != null + && reducedKeys.contains( + PipeParameters.KeyReducer.reduce(key.toLowerCase(Locale.ROOT).trim()))); } private PipeSourceConstant() {
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptions.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptions.java index 7f3dae5..de29b99 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptions.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptions.java
@@ -32,6 +32,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -218,17 +219,43 @@ } public static String getInclusionString(final PipeParameters parameters) { - return parameters.getStringOrDefault( + return getStringIgnoreCase( + parameters, Arrays.asList(EXTRACTOR_INCLUSION_KEY, SOURCE_INCLUSION_KEY), EXTRACTOR_INCLUSION_DEFAULT_VALUE); } public static String getExclusionString(final PipeParameters parameters) { - return parameters.getStringOrDefault( + return getStringIgnoreCase( + parameters, Arrays.asList(EXTRACTOR_EXCLUSION_KEY, SOURCE_EXCLUSION_KEY), EXTRACTOR_EXCLUSION_DEFAULT_VALUE); } + private static String getStringIgnoreCase( + final PipeParameters parameters, final List<String> keys, final String defaultValue) { + for (final String key : keys) { + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && key.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue().trim(); + } + } + final String reducedKey = PipeParameters.KeyReducer.reduce(key.toLowerCase(Locale.ROOT)); + for (final Map.Entry<String, String> entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && reducedKey.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue().trim(); + } + } + } + return defaultValue; + } + public static Set<PartialPath> parseOptions(final String optionsString) throws IllegalPathException { if (optionsString.isEmpty()) {
diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/subscription/meta/topic/TopicMeta.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/subscription/meta/topic/TopicMeta.java index 086976d..06a211d 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/subscription/meta/topic/TopicMeta.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/subscription/meta/topic/TopicMeta.java
@@ -410,13 +410,7 @@ // both "Tag-Filter" and "tag-filter" with different values. Extension keys remain unchanged. private static Map<String, String> canonicalizeTopicAttributes( final Map<String, String> topicAttributes) { - final Map<String, String> canonicalAttributes = new HashMap<>(); - if (Objects.isNull(topicAttributes)) { - return canonicalAttributes; - } - topicAttributes.forEach( - (key, value) -> canonicalAttributes.put(canonicalizeTopicAttributeKey(key), value)); - return canonicalAttributes; + return TopicProperty.normalizeAttributes(topicAttributes); } private static void canonicalizeTopicAttributesInPlace(final Map<String, String> attributes) {
diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java index 94acc0e..15353a6 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/task/subtask/PipeSubtaskTest.java
@@ -18,6 +18,7 @@ package org.apache.iotdb.commons.pipe.agent.task.subtask; +import org.apache.iotdb.commons.conf.CommonDescriptor; import org.apache.iotdb.commons.pipe.agent.task.execution.PipeSubtaskScheduler; import org.apache.iotdb.pipe.api.exception.PipeException; @@ -38,6 +39,18 @@ public class PipeSubtaskTest { @Test + public void testFirstExecutionTimeoutTracksDataNodeConnectionTimeout() { + final int previousTimeout = + CommonDescriptor.getInstance().getConfig().getDnConnectionTimeoutInMS(); + try { + CommonDescriptor.getInstance().getConfig().setDnConnectionTimeoutInMS(12_000); + Assert.assertEquals(2_000L, PipeSubtask.getFirstExecutionTimeoutInMs()); + } finally { + CommonDescriptor.getInstance().getConfig().setDnConnectionTimeoutInMS(previousTimeout); + } + } + + @Test public void testFirstExecutionSignalIsResetForEachStart() throws Exception { final TestSubtask subtask = new TestSubtask(); final ExecutorService workerExecutor = Executors.newSingleThreadExecutor();
diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptionsTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptionsTest.java index 7251a39..774794f 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptionsTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/options/PipeInclusionOptionsTest.java
@@ -86,4 +86,27 @@ "source.inclusion", "all", "source.inclusion.exclusion", "data.insert.extra")))); } + + @Test + public void testInclusionAttributeIsCaseInsensitiveAndTrimmed() throws Exception { + Assert.assertTrue( + PipeInclusionOptions.isDataInsertionIncluded( + new PipeParameters(Map.of(" EXTRACTOR.INCLUSION ", " data.insert ")))); + Assert.assertEquals( + "data.insert", + PipeInclusionOptions.getInclusionString( + new PipeParameters(Map.of(" Extractor.Inclusion ", " data.insert ")))); + Assert.assertEquals( + "data.insert", + PipeInclusionOptions.getInclusionString( + new PipeParameters(Map.of(" INCLUSION ", " data.insert ")))); + } + + @Test + public void testBlankInclusionAttributeUsesDefault() { + Assert.assertEquals( + "data.insert", + PipeInclusionOptions.getInclusionString( + new PipeParameters(Map.of("extractor.inclusion", " ")))); + } }
diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/visibility/VisibilityUtilsTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/visibility/VisibilityUtilsTest.java index 6802eb7..3ea5b0e 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/visibility/VisibilityUtilsTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/datastructure/visibility/VisibilityUtilsTest.java
@@ -128,6 +128,40 @@ PipeSourceConstant.EXTRACTOR_FORWARDING_PIPE_REQUESTS_DEFAULT_VALUE)); } + @Test + public void testDoubleLivingAttributeIsCaseInsensitiveAndTrimmed() { + Assert.assertTrue( + PipeSourceConstant.isDoubleLiving( + new PipeParameters(Map.of(" EXTRACTOR.MODE.DOUBLE-LIVING ", " TRUE ")))); + Assert.assertTrue( + PipeSourceConstant.isDoubleLiving(new PipeParameters(Map.of(" DOUBLE-LIVING ", " TRUE ")))); + Assert.assertFalse( + PipeSourceConstant.isDoubleLiving( + new PipeParameters( + Map.of( + PipeSourceConstant.EXTRACTOR_MODE_DOUBLE_LIVING_KEY, + " false ", + PipeSourceConstant.SOURCE_MODE_DOUBLE_LIVING_KEY, + " true ")))); + + final Map<String, String> attributes = new HashMap<>(); + attributes.put(" EXTRACTOR.MODE.DOUBLE-LIVING ", " TRUE "); + attributes.put(" EXTRACTOR.FORWARDING-PIPE-REQUESTS ", " TRUE "); + Assert.assertTrue(PipeSourceConstant.isDoubleLiving(new PipeParameters(attributes))); + Assert.assertTrue( + PipeSourceConstant.isForwardingPipeRequestsEnabled(new PipeParameters(attributes))); + + PipeSourceConstant.removeDoubleLivingAttributes(attributes); + PipeSourceConstant.disableForwardingPipeRequests(attributes); + Assert.assertFalse(PipeSourceConstant.isDoubleLiving(new PipeParameters(attributes))); + Assert.assertFalse( + PipeSourceConstant.isForwardingPipeRequestsEnabled(new PipeParameters(attributes))); + Assert.assertEquals( + Boolean.FALSE, + new PipeParameters(attributes) + .getBoolean(PipeSourceConstant.SOURCE_FORWARDING_PIPE_REQUESTS_KEY)); + } + private void assertVisibility( final Visibility expectedVisibility, final Map<String, String> attributes,
diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/task/PipeMetaDeSerTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/task/PipeMetaDeSerTest.java index 15923f0..d5c1379 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/task/PipeMetaDeSerTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/task/PipeMetaDeSerTest.java
@@ -125,6 +125,70 @@ } @Test + public void testBuiltinParametersAreNormalizedAfterLegacyDeserialization() throws IOException { + final PipeStaticMeta legacyStaticMeta = + new PipeStaticMeta("pipe", 1L, Map.of(), Map.of(), Map.of()); + legacyStaticMeta.getSourceParameters().getAttribute().put(" SOURCE ", " IOTDB-EXTRACTOR "); + legacyStaticMeta.getSourceParameters().getAttribute().put(" Source.Path ", " Root.SG.** "); + legacyStaticMeta + .getSourceParameters() + .getAttribute() + .put(" Source.Custom.Option ", " Mixed Value "); + legacyStaticMeta + .getProcessorParameters() + .getAttribute() + .put( + " PROCESSOR ", + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName().toUpperCase()); + legacyStaticMeta.getProcessorParameters().getAttribute().put(" Processor.Mode ", " ON "); + legacyStaticMeta + .getSinkParameters() + .getAttribute() + .put( + " CONNECTOR ", + BuiltinPipePlugin.IOTDB_THRIFT_CONNECTOR.getPipePluginName().toUpperCase()); + legacyStaticMeta.getSinkParameters().getAttribute().put(" Connector.User ", " ROOT "); + legacyStaticMeta + .getSinkParameters() + .getAttribute() + .put(" Connector.Node-URLs ", " https://NODEA:6667,NodeB:6667 "); + legacyStaticMeta.getSinkParameters().getAttribute().put(" Connector.Host ", " NODE.EXAMPLE "); + legacyStaticMeta.getSinkParameters().getAttribute().put(" Connector.IP ", " 2001:DB8::1 "); + legacyStaticMeta + .getSinkParameters() + .getAttribute() + .put(" Connector.Custom.Option ", " Mixed Value "); + + final ByteBuffer serialized = legacyStaticMeta.serialize(); + final PipeStaticMeta fromByteBuffer = PipeStaticMeta.deserialize(serialized.duplicate()); + final byte[] bytes = new byte[serialized.remaining()]; + serialized.get(bytes); + final PipeStaticMeta fromInputStream = + PipeStaticMeta.deserialize(new ByteArrayInputStream(bytes)); + + for (final PipeStaticMeta deserialized : + new PipeStaticMeta[] {fromByteBuffer, fromInputStream}) { + Assert.assertEquals( + "iotdb-extractor", deserialized.getSourceParameters().getString("source")); + Assert.assertEquals( + " Root.SG.** ", deserialized.getSourceParameters().getString("source.path")); + Assert.assertEquals( + "mixed value", deserialized.getSourceParameters().getString("source.custom.option")); + Assert.assertEquals("on", deserialized.getProcessorParameters().getString("processor.mode")); + Assert.assertEquals(" ROOT ", deserialized.getSinkParameters().getString("connector.user")); + Assert.assertEquals( + " https://NODEA:6667,NodeB:6667 ", + deserialized.getSinkParameters().getString("connector.node-urls")); + Assert.assertEquals( + " NODE.EXAMPLE ", deserialized.getSinkParameters().getString("connector.host")); + Assert.assertEquals( + " 2001:DB8::1 ", deserialized.getSinkParameters().getString("connector.ip")); + Assert.assertEquals( + "mixed value", deserialized.getSinkParameters().getString("connector.custom.option")); + } + } + + @Test public void testPipeStatusTypeCompatibility() { Assert.assertEquals((byte) 0, PipeStatus.RUNNING.getType()); Assert.assertEquals((byte) 1, PipeStatus.STOPPED.getType());
diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/subscription/topic/TopicMetaTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/subscription/topic/TopicMetaTest.java index 29a1643..63d5c7f 100644 --- a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/subscription/topic/TopicMetaTest.java +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/subscription/topic/TopicMetaTest.java
@@ -38,14 +38,14 @@ "topic", 1L, Map.of( - "Tag-Filter", - "region = \"north\"", + " Tag-Filter ", + " region = \"north\" ", "RealTime.Mode", " BATCH ", "source.CustomOption", "CaseSensitive")); final TopicMeta updated = - original.deepCopyWithUpdatedAttributes(Map.of(" TAG-FILTER ", "region = \"North\"")); + original.deepCopyWithUpdatedAttributes(Map.of(" TAG-FILTER ", " region = \"North\" ")); Assert.assertEquals(3, updated.getConfig().getAttribute().size()); Assert.assertEquals("region = \"North\"", updated.getConfig().getTagFilter()); Assert.assertEquals(