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 f8ce112f03e93..d70da99e10433 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 @@ -29,6 +29,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -43,7 +44,7 @@ public TopicConfig() { } public TopicConfig(final Map attributes) { - super(attributes); + super(TopicProperty.normalizeAttributes(attributes)); } private static final Map REALTIME_BATCH_MODE_CONFIG = @@ -132,7 +133,7 @@ public Map getAttributesWithSourcePrefix() { final Map attributesWithProcessorPrefix = new HashMap<>(); attributes.forEach( (key, value) -> { - if (key.toLowerCase().startsWith("source")) { + if (key != null && key.trim().toLowerCase(Locale.ROOT).startsWith("source")) { attributesWithProcessorPrefix.put(key, value); } }); @@ -145,7 +146,7 @@ public Map getAttributesWithProcessorPrefix() { final Map attributesWithProcessorPrefix = new HashMap<>(); attributes.forEach( (key, value) -> { - if (key.toLowerCase().startsWith("processor")) { + if (key != null && key.trim().toLowerCase(Locale.ROOT).startsWith("processor")) { attributesWithProcessorPrefix.put(key, value); } }); @@ -171,7 +172,7 @@ public Map getAttributesWithSinkPrefix() { final Map 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); } }); 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 new file mode 100644 index 0000000000000..989faeeaa4382 --- /dev/null +++ b/iotdb-client/subscription/src/main/java/org/apache/iotdb/rpc/subscription/config/TopicProperty.java @@ -0,0 +1,130 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.rpc.subscription.config; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +public enum TopicProperty { + PATH(TopicConstant.PATH_KEY), + PATTERN(TopicConstant.PATTERN_KEY), + START_TIME(TopicConstant.START_TIME_KEY), + END_TIME(TopicConstant.END_TIME_KEY), + LOOSE_RANGE(TopicConstant.LOOSE_RANGE_KEY), + MODE(TopicConstant.MODE_KEY), + FORMAT(TopicConstant.FORMAT_KEY); + + private static final Map PROPERTIES_BY_KEY; + + static { + final Map properties = new HashMap<>(); + for (final TopicProperty property : values()) { + properties.put(property.key, property); + } + PROPERTIES_BY_KEY = Collections.unmodifiableMap(properties); + } + + private final String key; + + TopicProperty(final String key) { + this.key = key; + } + + public String getKey() { + return key; + } + + public static TopicProperty fromKey(final String key) { + return key == null ? null : PROPERTIES_BY_KEY.get(key.trim().toLowerCase(Locale.ROOT)); + } + + public static Map normalizeAttributes(final Map attributes) { + final Map 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 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 attributes, final String expectedKey) { + return attributes.keySet().stream() + .filter(key -> key != null) + .anyMatch(key -> expectedKey.equalsIgnoreCase(key.trim())); + } + + public static String getAttributeValue( + final Map 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 getDuplicateAttributeKey(final Map attributes) { + if (attributes == null) { + return null; + } + final Set normalizedKeys = new HashSet<>(); + for (final String key : attributes.keySet()) { + final TopicProperty property = fromKey(key); + if (property != null && !normalizedKeys.add(property.key)) { + return property.key; + } + } + return null; + } + + public static String canonicalizeKey(final String key) { + final TopicProperty property = fromKey(key); + return property == null ? key : property.key; + } + + 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 new file mode 100644 index 0000000000000..c411aa59b2a72 --- /dev/null +++ b/iotdb-client/subscription/src/test/java/org/apache/iotdb/rpc/subscription/config/TopicConfigTest.java @@ -0,0 +1,93 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.rpc.subscription.config; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +public class TopicConfigTest { + + @Test + public void testNormalizeBuiltinAttributesAndPreserveExtensionAttributes() { + final Map attributes = new HashMap<>(); + attributes.put(" PATH ", " Root.SG.** "); + attributes.put(" START-TIME ", " 100 "); + attributes.put(" Extension.Option ", " Mixed Value "); + + final TopicConfig topicConfig = new TopicConfig(attributes); + + Assert.assertEquals("Root.SG.**", topicConfig.getAttribute().get(TopicConstant.PATH_KEY)); + Assert.assertEquals("100", topicConfig.getAttribute().get(TopicConstant.START_TIME_KEY)); + Assert.assertEquals(" Mixed Value ", topicConfig.getAttribute().get(" Extension.Option ")); + Assert.assertFalse(topicConfig.getAttribute().containsKey(" PATH ")); + } + + @Test + public void testNowTimeValuesUseNormalizedBuiltinKeysAndValues() { + final Map attributes = new HashMap<>(); + attributes.put(" START-TIME ", " NoW "); + attributes.put("eNd-TiMe", "nOw"); + attributes.put("extension.end-time", " now "); + + TopicProperty.replaceNowTimeValues(attributes, "12345"); + + Assert.assertEquals("12345", attributes.get(" START-TIME ")); + Assert.assertEquals("12345", attributes.get("eNd-TiMe")); + Assert.assertEquals(" now ", attributes.get("extension.end-time")); + } + + @Test + public void testPrefixedAttributesAcceptCaseAndWhitespace() { + final Map attributes = new HashMap<>(); + attributes.put(" Source.Custom.Option ", " Mixed Value "); + attributes.put(" Processor.Custom.Option ", " Mixed Value "); + attributes.put(" Sink.Custom.Option ", " Mixed Value "); + + final TopicConfig topicConfig = new TopicConfig(attributes); + + Assert.assertTrue( + topicConfig.getAttributesWithSourcePrefix().containsKey(" Source.Custom.Option ")); + Assert.assertTrue( + topicConfig.getAttributesWithProcessorPrefix().containsKey(" Processor.Custom.Option ")); + Assert.assertTrue( + topicConfig.getAttributesWithSinkPrefix().containsKey(" Sink.Custom.Option ")); + } + + @Test + public void testDuplicateAttributeDetectionUsesTrimmedCaseInsensitiveKeys() { + final Map attributes = new HashMap<>(); + attributes.put("path", "root.sg.**"); + attributes.put(" PATH ", "root.other.**"); + + Assert.assertEquals("path", TopicProperty.getDuplicateAttributeKey(attributes)); + } + + @Test + public void testDuplicateAttributeDetectionPreservesExtensionKeys() { + final Map attributes = new HashMap<>(); + attributes.put("Extension.Option", "first"); + attributes.put(" extension.option ", "second"); + + Assert.assertNull(TopicProperty.getDuplicateAttributeKey(attributes)); + } +} diff --git a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java index 4e60e599e1d5c..d17f282caee5e 100644 --- a/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java +++ b/iotdb-core/confignode/src/main/i18n/en/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java @@ -21,6 +21,10 @@ public final class ConfigNodeMessages { + public static final String + EXCEPTION_DUPLICATE_TOPIC_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_4A81A799 = + "Duplicate topic attribute key after trimming and case normalization: %s."; + public static final String MESSAGE_SUBSCRIPTION_IS_DISABLED_WHEN_DATA_REGION_CONSENSUS_PROTOCOL_IS_RATIS_194CE431 = "Subscription is disabled when data region consensus protocol is Ratis."; diff --git a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java index 726a87487f44e..b83c847a90190 100644 --- a/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java +++ b/iotdb-core/confignode/src/main/i18n/zh/org/apache/iotdb/confignode/i18n/ConfigNodeMessages.java @@ -21,6 +21,10 @@ public final class ConfigNodeMessages { + public static final String + EXCEPTION_DUPLICATE_TOPIC_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_4A81A799 = + "Topic 属性键去除首尾空格并忽略大小写后必须唯一:%s。"; + public static final String MESSAGE_SUBSCRIPTION_IS_DISABLED_WHEN_DATA_REGION_CONSENSUS_PROTOCOL_IS_RATIS_194CE431 = "当数据区域共识协议为 Ratis 时,Subscription 功能不可用。"; 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 cd94bd1e86a6e..d344aae54ec28 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; @@ -115,7 +116,8 @@ private void initExtractor(final Map extractorAttributes) throws } private void initProcessor(final Map processorAttributes) { - final PipeParameters processorParameters = new PipeParameters(processorAttributes); + final PipeParameters processorParameters = + PipePluginAgent.normalizeProcessorParameters(new PipeParameters(processorAttributes)); final PipeTaskRuntimeConfiguration runtimeConfiguration = new PipeTaskRuntimeConfiguration( 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 5686a635a65bf..04c79eae884e6 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 @@ -24,6 +24,7 @@ import org.apache.iotdb.commons.consensus.index.impl.MinimumProgressIndex; import org.apache.iotdb.commons.exception.pipe.PipeRuntimeCriticalException; 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.PipeTaskAgent; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMeta; @@ -255,11 +256,15 @@ private boolean checkAndUpdateRequestBeforeAlterPipeInternal(final TAlterPipeReq alterPipeRequest.setExtractorAttributes( copiedPipeStaticMetaFromCoordinator.getExtractorParameters().getAttribute()); } else { + final PipeParameters existingSourceParameters = + copiedPipeStaticMetaFromCoordinator.getExtractorParameters(); alterPipeRequest.setExtractorAttributes( copiedPipeStaticMetaFromCoordinator .getExtractorParameters() .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeRequest.getExtractorAttributes())) + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(alterPipeRequest.getExtractorAttributes()), + existingSourceParameters)) .getAttribute()); } } @@ -269,11 +274,14 @@ private boolean checkAndUpdateRequestBeforeAlterPipeInternal(final TAlterPipeReq 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()); } } @@ -283,11 +291,15 @@ private boolean checkAndUpdateRequestBeforeAlterPipeInternal(final TAlterPipeReq alterPipeRequest.setConnectorAttributes( copiedPipeStaticMetaFromCoordinator.getConnectorParameters().getAttribute()); } else { + final PipeParameters existingSinkParameters = + copiedPipeStaticMetaFromCoordinator.getConnectorParameters(); alterPipeRequest.setConnectorAttributes( copiedPipeStaticMetaFromCoordinator .getConnectorParameters() .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 a2758906f5bf4..df57d0a7c3dff 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 @@ -35,6 +35,7 @@ import org.apache.iotdb.confignode.consensus.request.write.subscription.topic.runtime.TopicHandleMetaChangePlan; import org.apache.iotdb.confignode.consensus.response.subscription.SubscriptionTableResp; import org.apache.iotdb.confignode.consensus.response.subscription.TopicTableResp; +import org.apache.iotdb.confignode.i18n.ConfigNodeMessages; import org.apache.iotdb.confignode.rpc.thrift.TCloseConsumerReq; import org.apache.iotdb.confignode.rpc.thrift.TCreateConsumerReq; import org.apache.iotdb.confignode.rpc.thrift.TCreateTopicReq; @@ -42,6 +43,7 @@ import org.apache.iotdb.confignode.rpc.thrift.TUnsubscribeReq; import org.apache.iotdb.consensus.common.DataSet; import org.apache.iotdb.rpc.TSStatusCode; +import org.apache.iotdb.rpc.subscription.config.TopicProperty; import org.apache.iotdb.rpc.subscription.exception.SubscriptionException; import org.apache.thrift.annotation.Nullable; @@ -159,6 +161,15 @@ public boolean validateBeforeCreatingTopic(TCreateTopicReq createTopicReq) private boolean checkBeforeCreateTopicInternal(TCreateTopicReq createTopicReq) throws SubscriptionException { if (!isTopicExisted(createTopicReq.getTopicName())) { + final String duplicateAttributeKey = + TopicProperty.getDuplicateAttributeKey(createTopicReq.getTopicAttributes()); + if (duplicateAttributeKey != null) { + throw new SubscriptionException( + String.format( + ConfigNodeMessages + .EXCEPTION_DUPLICATE_TOPIC_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_4A81A799, + duplicateAttributeKey)); + } return true; } diff --git a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2.java b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2.java index d809c1668ed7d..631fdc040a2ce 100644 --- a/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2.java +++ b/iotdb-core/confignode/src/main/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2.java @@ -25,6 +25,7 @@ import org.apache.iotdb.commons.consensus.index.impl.MinimumProgressIndex; import org.apache.iotdb.commons.consensus.index.impl.RecoverProgressIndex; import org.apache.iotdb.commons.consensus.index.impl.SimpleProgressIndex; +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.PipeRuntimeMeta; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeStaticMeta; @@ -134,6 +135,13 @@ public boolean executeFromValidateTask(ConfigNodeProcedureEnv env) throws PipeEx LOGGER.info( "CreatePipeProcedureV2: executeFromValidateTask({})", createPipeRequest.getPipeName()); + final Map extractorAttributes = createPipeRequest.getExtractorAttributes(); + if (Objects.nonNull(extractorAttributes)) { + createPipeRequest.setExtractorAttributes( + PipePluginAgent.normalizeSourceParameters(new PipeParameters(extractorAttributes)) + .getAttribute()); + } + final PipeManager pipeManager = env.getConfigManager().getPipeManager(); pipeManager .getPipePluginCoordinator() 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 40be432fe7531..13e9beb8ec68c 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 @@ -215,4 +215,35 @@ public void testConvertToTShowPipeRespIncludesStoppedStateAndExceptionMessage() Assert.assertTrue(showPipeInfo.getExceptionMessage().contains("construction failed")); Assert.assertTrue(showPipeInfo.getExceptionMessage().contains("nodeIds: [1]")); } + + @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 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 ")); + } } 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 new file mode 100644 index 0000000000000..ff6f8d20d9bca --- /dev/null +++ b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/persistence/subscription/SubscriptionInfoTopicValidationTest.java @@ -0,0 +1,65 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.confignode.persistence.subscription; + +import org.apache.iotdb.confignode.i18n.ConfigNodeMessages; +import org.apache.iotdb.confignode.rpc.thrift.TCreateTopicReq; +import org.apache.iotdb.rpc.subscription.config.TopicConstant; +import org.apache.iotdb.rpc.subscription.exception.SubscriptionException; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +public class SubscriptionInfoTopicValidationTest { + + @Test + public void testRejectDuplicateTopicAttributeKeysAfterNormalization() throws Exception { + final Map attributes = new HashMap<>(); + attributes.put(TopicConstant.PATH_KEY, "root.sg.**"); + attributes.put(" PATH ", "root.other.**"); + + try { + new SubscriptionInfo() + .validateBeforeCreatingTopic(new TCreateTopicReq("topic").setTopicAttributes(attributes)); + Assert.fail("Expected duplicate topic attributes to be rejected"); + } catch (final SubscriptionException e) { + Assert.assertEquals( + String.format( + ConfigNodeMessages + .EXCEPTION_DUPLICATE_TOPIC_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_4A81A799, + TopicConstant.PATH_KEY), + e.getMessage()); + } + } + + @Test + public void testAcceptSingleTopicAttributeWithWhitespace() throws Exception { + final Map attributes = new HashMap<>(); + attributes.put(" PATH ", "root.sg.**"); + + Assert.assertTrue( + new SubscriptionInfo() + .validateBeforeCreatingTopic( + new TCreateTopicReq("topic").setTopicAttributes(attributes))); + } +} diff --git a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2Test.java b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2Test.java index d34b050b61e85..0da998733d6bc 100644 --- a/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2Test.java +++ b/iotdb-core/confignode/src/test/java/org/apache/iotdb/confignode/procedure/impl/pipe/task/CreatePipeProcedureV2Test.java @@ -29,6 +29,9 @@ import org.apache.iotdb.confignode.manager.ConfigManager; import org.apache.iotdb.confignode.manager.PermissionManager; import org.apache.iotdb.confignode.manager.consensus.ConsensusManager; +import org.apache.iotdb.confignode.manager.pipe.coordinator.PipeManager; +import org.apache.iotdb.confignode.manager.pipe.coordinator.plugin.PipePluginCoordinator; +import org.apache.iotdb.confignode.persistence.pipe.PipePluginInfo; import org.apache.iotdb.confignode.persistence.pipe.PipeTaskInfo; import org.apache.iotdb.confignode.procedure.env.ConfigNodeProcedureEnv; import org.apache.iotdb.confignode.procedure.store.ProcedureFactory; @@ -55,6 +58,52 @@ import static org.junit.Assert.fail; public class CreatePipeProcedureV2Test { + @Test + public void testValidateNormalizesSourceAttributesBeforeAuthentication() throws Exception { + final Map sourceAttributes = new HashMap<>(); + sourceAttributes.put(" SOURCE ", " IOTDB-SOURCE "); + sourceAttributes.put(" Source.Username ", "user"); + sourceAttributes.put(" SOURCE.PASSWORD ", "raw-password"); + final TCreatePipeReq request = + new TCreatePipeReq("authPipe", new HashMap<>()) + .setExtractorAttributes(sourceAttributes) + .setProcessorAttributes(new HashMap<>()) + .setConnectorAttributes(new HashMap<>()); + + final PipeTaskInfo taskInfo = Mockito.mock(PipeTaskInfo.class); + Mockito.when(taskInfo.checkBeforeCreatePipe(request)).thenReturn(true); + final CreatePipeProcedureV2 procedure = + new CreatePipeProcedureV2(request, new AtomicReference<>(taskInfo)); + + final ConfigNodeProcedureEnv env = Mockito.mock(ConfigNodeProcedureEnv.class); + final ConfigManager configManager = Mockito.mock(ConfigManager.class); + final PipeManager pipeManager = Mockito.mock(PipeManager.class); + final PipePluginCoordinator pipePluginCoordinator = Mockito.mock(PipePluginCoordinator.class); + final PipePluginInfo pipePluginInfo = Mockito.mock(PipePluginInfo.class); + final PermissionManager permissionManager = Mockito.mock(PermissionManager.class); + Mockito.when(env.getConfigManager()).thenReturn(configManager); + Mockito.when(configManager.getPipeManager()).thenReturn(pipeManager); + Mockito.when(pipeManager.getPipePluginCoordinator()).thenReturn(pipePluginCoordinator); + Mockito.when(pipePluginCoordinator.getPipePluginInfo()).thenReturn(pipePluginInfo); + Mockito.when(configManager.getPermissionManager()).thenReturn(permissionManager); + + final TPermissionInfoResp loginResp = new TPermissionInfoResp(); + loginResp.setStatus(new TSStatus(TSStatusCode.WRONG_LOGIN_PASSWORD.getStatusCode())); + Mockito.when(permissionManager.login("user", "raw-password", true)).thenReturn(loginResp); + Mockito.when(permissionManager.login4Pipe("user", "raw-password")) + .thenReturn("hashed-password"); + + assertTrue(procedure.executeFromValidateTask(env)); + + Mockito.verify(pipePluginInfo) + .checkPipePluginExistence( + Mockito.eq(request.getExtractorAttributes()), Mockito.anyMap(), Mockito.anyMap()); + assertEquals( + "hashed-password", + request.getExtractorAttributes().get(PipeSourceConstant.SOURCE_IOTDB_PASSWORD_KEY)); + Mockito.verify(permissionManager).login4Pipe("user", "raw-password"); + } + @Test public void testDataNodeConstructionFailureIsRecorded() throws Exception { final String pipeName = "failedHistoryPipe"; 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 58e0da80074ee..c3ffbd3d54cf2 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; @@ -78,24 +79,20 @@ public PipeTaskProcessorStage( new PipeTaskRuntimeConfiguration( new PipeTaskProcessorRuntimeEnvironment( pipeName, creationTime, regionId, pipeTaskMeta, sourceUserEntity, sourcePassword)); + final boolean isDataRegionSource = + StorageEngine.getInstance().getAllDataRegionIds().contains(new DataRegionId(regionId)); + final PipeParameters normalizedProcessorParameters = + PipePluginAgent.normalizeProcessorParameters(pipeProcessorParameters); final PipeProcessor pipeProcessor = - StorageEngine.getInstance().getAllDataRegionIds().contains(new DataRegionId(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); + (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 2bbcc1248d8d1..fde7f83bb6461 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 @@ public PipeTaskSinkStage( Supplier 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 523f181cc26ca..2c43cd8037caf 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.PipeTaskMeta; import org.apache.iotdb.commons.pipe.agent.task.stage.PipeTaskStage; @@ -49,22 +50,27 @@ public PipeTaskSourceStage( PipeParameters sourceParameters, int regionId, PipeTaskMeta pipeTaskMeta) { + final PipeParameters normalizedSourceParameters = + PipePluginAgent.normalizeSourceParameters(sourceParameters); + final boolean isDataRegionSource = + StorageEngine.getInstance().getAllDataRegionIds().contains(new DataRegionId(regionId)); pipeExtractor = - StorageEngine.getInstance().getAllDataRegionIds().contains(new DataRegionId(regionId)) - ? PipeDataNodeAgent.plugin().dataRegion().reflectSource(sourceParameters) - : PipeDataNodeAgent.plugin().schemaRegion().reflectSource(sourceParameters); + (isDataRegionSource + ? PipeDataNodeAgent.plugin().dataRegion() + : 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 e) { try { pipeExtractor.close(); 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 8252426cebb60..141d5527fcfa7 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 @@ -46,6 +46,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.service.PipePluginClassLoader; import org.apache.iotdb.commons.pipe.agent.plugin.service.PipePluginExecutableManager; import org.apache.iotdb.commons.pipe.agent.task.meta.PipeMeta; @@ -259,10 +260,11 @@ import org.apache.iotdb.db.trigger.service.TriggerClassLoader; import org.apache.iotdb.pipe.api.PipePlugin; import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters; +import org.apache.iotdb.pipe.api.exception.PipeException; 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; @@ -1845,12 +1847,21 @@ public SettableFuture unsetSchemaTemplate( @Override public SettableFuture createPipe( final CreatePipeStatement createPipeStatement) { - if (!PipeDataNodeAgent.isPipeDataInsertionEnabled(createPipeStatement.getSourceAttributes())) { + final SettableFuture future = SettableFuture.create(); + final PipeParameters sourcePipeParameters; + try { + sourcePipeParameters = + PipePluginAgent.normalizeSourceParameters( + new PipeParameters(createPipeStatement.getSourceAttributes())); + } catch (final PipeException e) { + future.setException( + new IoTDBException(e.getMessage(), TSStatusCode.PIPE_ERROR.getStatusCode())); + return future; + } + if (!PipeDataNodeAgent.isPipeDataInsertionEnabled(sourcePipeParameters)) { return PIPE_DATA_INSERTION_DISABLED_BY_RATIS_ERROR_FUTURE; } - final SettableFuture future = SettableFuture.create(); - // Verify that Pipe is disabled if TSFile encryption is enabled final String pipeName = createPipeStatement.getPipeName(); if (pipeName.startsWith(PipeStaticMeta.SYSTEM_PIPE_PREFIX)) { @@ -1889,8 +1900,6 @@ public SettableFuture createPipe( // Syntactic sugar: if full-sync mode is detected (i.e. not snapshot mode, or both realtime // and history are true), the pipe is split into history-only and realtime–only modes. - final PipeParameters sourcePipeParameters = - new PipeParameters(createPipeStatement.getSourceAttributes()); final PipeParameters sinkPipeParameters = new PipeParameters(createPipeStatement.getSinkAttributes()); try (final ConfigNodeClient configNodeClient = @@ -2067,65 +2076,57 @@ public SettableFuture alterPipe(AlterPipeStatement alterPipeSt // Construct temporary pipe static meta for validation final String pipeName = alterPipeStatement.getPipeName(); - final PipeParameters sourceParameters = - alterPipeStatement.isReplaceAllExtractorAttributes() - ? new PipeParameters(alterPipeStatement.getExtractorAttributes()) - : new PipeParameters( - new HashMap<>( - pipeMetaFromCoordinator - .getStaticMeta() - .getExtractorParameters() - .getAttribute())) - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getExtractorAttributes())); - if (!PipeDataNodeAgent.isPipeDataInsertionEnabled(sourceParameters)) { - return PIPE_DATA_INSERTION_DISABLED_BY_RATIS_ERROR_FUTURE; - } try { + final PipeParameters existingSourceParameters = + pipeMetaFromCoordinator.getStaticMeta().getExtractorParameters(); + final PipeParameters updatedSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(alterPipeStatement.getExtractorAttributes()), + existingSourceParameters, + alterPipeStatement.isReplaceAllExtractorAttributes()); + final PipeParameters sourceParameters = + alterPipeStatement.isReplaceAllExtractorAttributes() + ? updatedSourceParameters + : new PipeParameters(new HashMap<>(existingSourceParameters.getAttribute())) + .addOrReplaceEquivalentAttributes(updatedSourceParameters); + if (!PipeDataNodeAgent.isPipeDataInsertionEnabled(sourceParameters)) { + return PIPE_DATA_INSERTION_DISABLED_BY_RATIS_ERROR_FUTURE; + } if (!alterPipeStatement.getExtractorAttributes().isEmpty()) { - if (alterPipeStatement.isReplaceAllExtractorAttributes()) { - PipeDataNodeAgent.plugin().validateSource(alterPipeStatement.getExtractorAttributes()); - } else { - pipeMetaFromCoordinator - .getStaticMeta() - .getExtractorParameters() - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getExtractorAttributes())); - PipeDataNodeAgent.plugin() - .validateSource( - pipeMetaFromCoordinator.getStaticMeta().getExtractorParameters().getAttribute()); - } + PipeDataNodeAgent.plugin().validateSource(sourceParameters.getAttribute()); } if (!alterPipeStatement.getProcessorAttributes().isEmpty()) { - if (alterPipeStatement.isReplaceAllProcessorAttributes()) { - PipeDataNodeAgent.plugin().validateProcessor(alterPipeStatement.getProcessorAttributes()); - } else { - pipeMetaFromCoordinator - .getStaticMeta() - .getProcessorParameters() - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getProcessorAttributes())); - PipeDataNodeAgent.plugin() - .validateProcessor( - pipeMetaFromCoordinator.getStaticMeta().getProcessorParameters().getAttribute()); - } + final PipeParameters existingProcessorParameters = + pipeMetaFromCoordinator.getStaticMeta().getProcessorParameters(); + final PipeParameters updatedProcessorParameters = + PipePluginAgent.normalizeProcessorParametersForUpdate( + new PipeParameters(alterPipeStatement.getProcessorAttributes()), + existingProcessorParameters); + final PipeParameters processorParameters = + alterPipeStatement.isReplaceAllProcessorAttributes() + ? updatedProcessorParameters + : new PipeParameters(new HashMap<>(existingProcessorParameters.getAttribute())) + .addOrReplaceEquivalentAttributes(updatedProcessorParameters); + PipeDataNodeAgent.plugin().validateProcessor(processorParameters.getAttribute()); } if (!alterPipeStatement.getConnectorAttributes().isEmpty()) { + final PipeParameters existingConnectorParameters = + pipeMetaFromCoordinator.getStaticMeta().getConnectorParameters(); + final PipeParameters updatedConnectorParameters = + PipePluginAgent.normalizeSinkParametersForUpdate( + new PipeParameters(alterPipeStatement.getConnectorAttributes()), + existingConnectorParameters); + final PipeParameters connectorParameters = + alterPipeStatement.isReplaceAllConnectorAttributes() + ? updatedConnectorParameters + : new PipeParameters(new HashMap<>(existingConnectorParameters.getAttribute())) + .addOrReplaceEquivalentAttributes(updatedConnectorParameters); if (alterPipeStatement.isReplaceAllConnectorAttributes()) { - PipeDataNodeAgent.plugin() - .validateSource(pipeName, alterPipeStatement.getConnectorAttributes()); + PipeDataNodeAgent.plugin().validateSource(pipeName, connectorParameters.getAttribute()); } else { - pipeMetaFromCoordinator - .getStaticMeta() - .getConnectorParameters() - .addOrReplaceEquivalentAttributes( - new PipeParameters(alterPipeStatement.getConnectorAttributes())); - PipeDataNodeAgent.plugin() - .validateSource( - pipeName, - pipeMetaFromCoordinator.getStaticMeta().getConnectorParameters().getAttribute()); + PipeDataNodeAgent.plugin().validateSource(pipeName, connectorParameters.getAttribute()); } } } catch (final Exception e) { @@ -2363,22 +2364,7 @@ public SettableFuture createTopic(CreateTopicStatement createT 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/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupport.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupport.java index 0edc18c3f0018..071d851465e42 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupport.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupport.java @@ -51,30 +51,34 @@ private static Pair getExtractorAttributesKeyAndValue( final Map extractorAttributes, final String sourceKey, final String extractorKey) { - String key = sourceKey; - String value = extractorAttributes.get(key); - if (value != null) { - return new Pair<>(key, value); + Pair pair = getAttributeByNormalizedKey(extractorAttributes, sourceKey); + if (pair != null) { + return pair; } - // "source.".length() == 7 try { - key = sourceKey.substring(7); - value = extractorAttributes.get(key); + pair = getAttributeByNormalizedKey(extractorAttributes, sourceKey.substring(7)); } catch (Exception e) { LOGGER.warn( "The prefix of sourceKey is not 'source.'. Please check the parameters passed in: {}", sourceKey, e); } - if (value != null) { - return new Pair<>(key, value); + if (pair != null) { + return pair; } - key = extractorKey; - value = extractorAttributes.get(key); - if (value != null) { - return new Pair<>(key, value); + return getAttributeByNormalizedKey(extractorAttributes, extractorKey); + } + + private static Pair getAttributeByNormalizedKey( + final Map extractorAttributes, final String normalizedKey) { + for (final Map.Entry entry : extractorAttributes.entrySet()) { + if (entry.getKey() != null + && entry.getValue() != null + && normalizedKey.equalsIgnoreCase(entry.getKey().trim())) { + return new Pair<>(entry.getKey(), entry.getValue()); + } } return null; } 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 1c081888b3577..d7bc05812fcd8 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; @@ -65,8 +66,9 @@ public class SubscriptionSinkSubtaskManager { 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/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 87755b015af23..47defc379eaa7 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,10 +19,12 @@ 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.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.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; @@ -41,6 +43,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"; @@ -150,4 +153,113 @@ public void testPipePluginAgent() { })) .getClass()); } + + @Test + public void testBuiltinAndCustomParametersAreNormalized() { + final PipeParameters builtinSourceParameters = + new PipeParameters( + Map.of( + " SOURCE ", " IOTDB-EXTRACTOR ", + " Source.Path ", " Root.SG.** ", + " Source.Mode ", " QUERY ", + " Source.Custom.Option ", " Mixed Value ")); + final PipeParameters normalizedSourceParameters = + PipePluginAgent.normalizeSourceParameters(builtinSourceParameters); + + Assert.assertEquals("iotdb-extractor", normalizedSourceParameters.getString("source")); + Assert.assertEquals(" Root.SG.** ", normalizedSourceParameters.getString("source.path")); + Assert.assertEquals("query", normalizedSourceParameters.getString("source.mode")); + Assert.assertEquals( + "mixed value", normalizedSourceParameters.getString("source.custom.option")); + + final PipeParameters customSourceParameters = + new PipeParameters( + Map.of(" SOURCE ", " CUSTOM-PLUGIN ", " Custom.Option ", " Mixed Value ")); + final PipeParameters normalizedCustomSourceParameters = + PipePluginAgent.normalizeSourceParameters(customSourceParameters); + Assert.assertEquals(" CUSTOM-PLUGIN ", normalizedCustomSourceParameters.getString("source")); + Assert.assertEquals( + " Mixed Value ", normalizedCustomSourceParameters.getAttribute().get(" Custom.Option ")); + Assert.assertEquals( + normalizedCustomSourceParameters.getAttribute(), + PipePluginAgent.normalizeSourceParameters(normalizedCustomSourceParameters).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 modifiedCustomSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(Map.of(" SOURCE.MODE ", " QUERY ")), existingCustomSourceParameters); + Assert.assertEquals( + " QUERY ", modifiedCustomSourceParameters.getAttribute().get(" SOURCE.MODE ")); + final PipeParameters replacementSourceParameters = + PipePluginAgent.normalizeSourceParametersForUpdate( + new PipeParameters(Map.of(" SOURCE.MODE ", " QUERY ")), + existingCustomSourceParameters, + true); + Assert.assertEquals("query", replacementSourceParameters.getString("source.mode")); + + Assert.assertEquals( + BuiltinPipePlugin.IOTDB_THRIFT_CONNECTOR.getPipePluginName(), + PipeSinkConstant.getConnectorOrSinkNameWithDefault( + new PipeParameters(Map.of(" CONNECTOR ", " ")))); + 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)); + 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)); + } + + @Test + public void testNormalizeLegacyStaticMetaParameters() { + final PipeStaticMeta pipeStaticMeta = + new PipeStaticMeta("pipe", 1L, new HashMap<>(), new HashMap<>(), new HashMap<>()); + pipeStaticMeta + .getExtractorParameters() + .getAttribute() + .put(" EXTRACTOR ", BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName().toUpperCase()); + + Assert.assertEquals( + BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName(), + PipePluginAgent.normalizeSourceParameters(pipeStaticMeta.getExtractorParameters()) + .getString("extractor")); + } } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/ClusterConfigTaskExecutorTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/ClusterConfigTaskExecutorTest.java index fa974463e5c25..044fffb69979a 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/ClusterConfigTaskExecutorTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/ClusterConfigTaskExecutorTest.java @@ -19,18 +19,44 @@ package org.apache.iotdb.db.queryengine.plan.execution; +import org.apache.iotdb.commons.exception.IoTDBException; import org.apache.iotdb.db.queryengine.plan.execution.config.executor.ClusterConfigTaskExecutor; +import org.apache.iotdb.db.queryengine.plan.statement.StatementType; import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipePluginStatement; +import org.apache.iotdb.db.queryengine.plan.statement.metadata.pipe.CreatePipeStatement; +import org.apache.iotdb.rpc.TSStatusCode; import org.junit.Assert; import org.junit.Test; import java.io.File; +import java.util.Map; +import java.util.concurrent.ExecutionException; import static org.junit.Assert.fail; public class ClusterConfigTaskExecutorTest { + @Test + public void testCreatePipeDuplicateNormalizedSourceKeysReturnPipeError() { + final CreatePipeStatement statement = new CreatePipeStatement(StatementType.CREATE_PIPE); + statement.setSourceAttributes( + Map.of( + "extractor", "iotdb-extractor", + "extractor.path", "root.sg.**", + " Extractor.Path ", "root.other.**")); + + final ExecutionException exception = + Assert.assertThrows( + ExecutionException.class, + () -> ClusterConfigTaskExecutor.getInstance().createPipe(statement).get()); + + Assert.assertTrue(exception.getCause() instanceof IoTDBException); + Assert.assertEquals( + TSStatusCode.PIPE_ERROR.getStatusCode(), + ((IoTDBException) exception.getCause()).getErrorCode()); + } + @Test public void testPipePlugin() { try { diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupportTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupportTest.java new file mode 100644 index 0000000000000..563f3633e01ae --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/execution/config/sys/pipe/PipeFunctionSupportTest.java @@ -0,0 +1,45 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.iotdb.db.queryengine.plan.execution.config.sys.pipe; + +import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant; + +import org.junit.Test; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertEquals; + +public class PipeFunctionSupportTest { + + @Test + public void testApplyNowFunctionToNormalizedSourceKeyVariant() { + final Map extractorAttributes = new HashMap<>(); + extractorAttributes.put(" SOURCE.START-TIME ", PipeSourceConstant.NOW_TIME_VALUE); + + PipeFunctionSupport.applyNowFunctionToExtractorAttributes( + extractorAttributes, + PipeSourceConstant.SOURCE_START_TIME_KEY, + PipeSourceConstant.EXTRACTOR_START_TIME_KEY, + 1234L); + + assertEquals("1234", extractorAttributes.get(" SOURCE.START-TIME ")); + } +} diff --git a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java index e4ea264564204..201f7ecc8144f 100644 --- a/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/en/org/apache/iotdb/commons/i18n/UtilMessages.java @@ -24,4 +24,8 @@ private UtilMessages() {} public static final String EXCEPTION_FILE_CHANNEL_WRITE_MADE_NO_PROGRESS_B0F24ACD = "File channel write made no progress"; + + public static final String + EXCEPTION_DUPLICATE_PIPE_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_2D62A336 = + "Duplicate pipe attribute key after trimming and case normalization: %s"; } diff --git a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java index dd7fa81e2bd4c..cc5bd3683ae84 100644 --- a/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java +++ b/iotdb-core/node-commons/src/main/i18n/zh/org/apache/iotdb/commons/i18n/UtilMessages.java @@ -22,6 +22,10 @@ public final class UtilMessages { private UtilMessages() {} + public static final String + EXCEPTION_DUPLICATE_PIPE_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_2D62A336 = + "去除首尾空格并统一大小写后,Pipe 属性键重复:%s"; + public static final String EXCEPTION_FILE_CHANNEL_WRITE_MADE_NO_PROGRESS_B0F24ACD = "文件通道写入未取得进展"; } 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 caffb9ef859eb..4bf9d90ffd724 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 @@ -19,11 +19,15 @@ package org.apache.iotdb.commons.pipe.agent.plugin; +import org.apache.iotdb.commons.i18n.UtilMessages; +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 +42,13 @@ 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; public abstract class PipePluginAgent { @@ -53,6 +60,46 @@ public abstract class PipePluginAgent { private final PipeProcessorConstructor pipeProcessorConstructor; private final PipeSinkConstructor pipeSinkConstructor; + private static final Set PARAMETER_VALUE_PRESERVATION_KEYS = + Set.of( + "path", + "path.inclusion", + "path.exclusion", + "database", + "operators", + "skipif", + "pattern", + "pattern.inclusion", + "pattern.exclusion", + "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", + "start-time", + "end-time", + "history.start-time", + "history.end-time", + "sliding.boundary-time", + "consensus.group-id", + "consensus.pipe-name"); + protected PipePluginAgent(final PipePluginMetaKeeper pipePluginMetaKeeper) { this.pipePluginMetaKeeper = pipePluginMetaKeeper; pipeSourceConstructor = createPipeSourceConstructor(pipePluginMetaKeeper); @@ -81,6 +128,241 @@ public final PipeConnector reflectSink(final PipeParameters sinkParameters) { return pipeSinkConstructor.reflectPlugin(sinkParameters); } + public static PipeParameters normalizeSourceParameters(final PipeParameters parameters) { + return normalizeSourceParameters(parameters, null); + } + + public static PipeParameters normalizeSourceParametersForDeserialization( + final PipeParameters parameters) { + return normalizeSourceParameters(parameters, null, false); + } + + 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 normalizeSourceParameters(parameters, existingParameters, true); + } + + private static PipeParameters normalizeSourceParameters( + final PipeParameters parameters, + final PipeParameters existingParameters, + final boolean rejectDuplicateKeys) { + return normalizePluginParameters( + parameters, + existingParameters, + Arrays.asList(PipeSourceConstant.EXTRACTOR_KEY, PipeSourceConstant.SOURCE_KEY), + null, + BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName(), + PipeExtractor.class, + rejectDuplicateKeys); + } + + public static PipeParameters normalizeProcessorParameters(final PipeParameters parameters) { + return normalizeProcessorParameters(parameters, null, null); + } + + public static PipeParameters normalizeProcessorParametersForDeserialization( + final PipeParameters parameters) { + return normalizeProcessorParameters(parameters, null, null, false); + } + + 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 normalizeProcessorParameters(parameters, existingParameters, selectedPluginName, true); + } + + private static PipeParameters normalizeProcessorParameters( + final PipeParameters parameters, + final PipeParameters existingParameters, + final String selectedPluginName, + final boolean rejectDuplicateKeys) { + return normalizePluginParameters( + parameters, + existingParameters, + Collections.singletonList(PipeProcessorConstant.PROCESSOR_KEY), + selectedPluginName, + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName(), + PipeProcessor.class, + rejectDuplicateKeys); + } + + public static PipeParameters normalizeSinkParameters(final PipeParameters parameters) { + return normalizeSinkParameters(parameters, null); + } + + public static PipeParameters normalizeSinkParametersForDeserialization( + final PipeParameters parameters) { + return normalizeSinkParameters(parameters, null, false); + } + + public static PipeParameters normalizeSinkParametersForUpdate( + final PipeParameters parameters, final PipeParameters existingParameters) { + return normalizeSinkParameters(parameters, existingParameters); + } + + private static PipeParameters normalizeSinkParameters( + final PipeParameters parameters, final PipeParameters existingParameters) { + return normalizeSinkParameters(parameters, existingParameters, true); + } + + private static PipeParameters normalizeSinkParameters( + final PipeParameters parameters, + final PipeParameters existingParameters, + final boolean rejectDuplicateKeys) { + 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, + rejectDuplicateKeys); + } + + private static PipeParameters normalizePluginParameters( + final PipeParameters parameters, + final PipeParameters existingParameters, + final List pluginNameKeys, + final String selectedPluginName, + final String defaultPluginName, + final Class pluginClass, + final boolean rejectDuplicateKeys) { + 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 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)) { + putNormalizedAttribute( + normalizedAttributes, + normalizedKey, + value == null || !builtinPlugin ? value : value.trim().toLowerCase(Locale.ROOT), + rejectDuplicateKeys); + } else if (builtinPlugin) { + putNormalizedAttribute( + normalizedAttributes, + normalizedKey, + value == null || shouldPreserveParameterValue(normalizedKey) + ? value + : value.trim().toLowerCase(Locale.ROOT), + rejectDuplicateKeys); + } else { + normalizedAttributes.put(key, value); + } + }); + return new PipeParameters(normalizedAttributes); + } + + private static void putNormalizedAttribute( + final Map normalizedAttributes, + final String normalizedKey, + final String value, + final boolean rejectDuplicateKeys) { + if (normalizedAttributes.containsKey(normalizedKey)) { + if (rejectDuplicateKeys) { + throw new PipeException( + String.format( + UtilMessages + .EXCEPTION_DUPLICATE_PIPE_ATTRIBUTE_KEY_AFTER_TRIMMING_AND_CASE_NORMALIZATION_ARG_2D62A336, + normalizedKey)); + } + return; + } + normalizedAttributes.put(normalizedKey, value); + } + + private static String getPluginName( + final PipeParameters parameters, final List pluginNameKeys) { + if (parameters == null) { + return null; + } + for (final String pluginNameKey : pluginNameKeys) { + for (final Map.Entry entry : parameters.getAttribute().entrySet()) { + if (entry.getKey() != null + && pluginNameKey.equalsIgnoreCase(entry.getKey().trim()) + && entry.getValue() != null + && !entry.getValue().trim().isEmpty()) { + return entry.getValue(); + } + } + } + return null; + } + + private static boolean isPluginNameKey(final String key, final List 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( + reduceParameterKey(normalizedKey).toLowerCase(Locale.ROOT)); + } + + private static String reduceParameterKey(final String key) { + for (final String prefix : + Arrays.asList("extractor.", "source.", "processor.", "connector.", "sink.")) { + if (key.regionMatches(true, 0, prefix, 0, prefix.length())) { + return key.substring(prefix.length()); + } + } + return key; + } + public void validate( final String pipeName, final Map sourceAttributes, @@ -93,7 +375,8 @@ public void validate( } public PipeExtractor validateSource(final Map sourceAttributes) throws Exception { - final PipeParameters sourceParameters = new PipeParameters(sourceAttributes); + final PipeParameters sourceParameters = + normalizeSourceParameters(new PipeParameters(sourceAttributes)); final PipeExtractor temporaryExtractor = reflectSource(sourceParameters); try { temporaryExtractor.validate(new PipeParameterValidator(sourceParameters)); @@ -108,7 +391,8 @@ public PipeExtractor validateSource(final Map sourceAttributes) } public void validateProcessor(Map 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)); @@ -123,7 +407,8 @@ public void validateProcessor(Map processorAttributes) throws Ex public PipeConnector validateSink(String pipeName, Map 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)); @@ -182,13 +467,16 @@ public final PipeProcessor getConfiguredProcessor( String pipeProcessorName, PipeParameters processorParameters, PipeProcessorRuntimeConfiguration runtimeConfigurations) { + final PipeParameters normalizedParameters = + normalizeProcessorParameters(processorParameters, null, pipeProcessorName); final HashMap 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/meta/PipeStaticMeta.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/agent/task/meta/PipeStaticMeta.java index 3e09c878f5551..d3a6caa9b1f30 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 @@ -19,6 +19,7 @@ package org.apache.iotdb.commons.pipe.agent.task.meta; +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; @@ -34,7 +35,7 @@ import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Arrays; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -66,6 +67,7 @@ public PipeStaticMeta( extractorParameters = new PipeParameters(extractorAttributes); processorParameters = new PipeParameters(processorAttributes); connectorParameters = new PipeParameters(connectorAttributes); + normalizePluginParameters(); updateCompletionSupport(); } @@ -152,9 +154,9 @@ public static PipeStaticMeta deserialize(final InputStream inputStream) throws I pipeStaticMeta.pipeName = ReadWriteIOUtils.readString(inputStream); pipeStaticMeta.creationTime = ReadWriteIOUtils.readLong(inputStream); - pipeStaticMeta.extractorParameters = new PipeParameters(new HashMap<>()); - pipeStaticMeta.processorParameters = new PipeParameters(new HashMap<>()); - pipeStaticMeta.connectorParameters = new PipeParameters(new HashMap<>()); + pipeStaticMeta.extractorParameters = new PipeParameters(new LinkedHashMap<>()); + pipeStaticMeta.processorParameters = new PipeParameters(new LinkedHashMap<>()); + pipeStaticMeta.connectorParameters = new PipeParameters(new LinkedHashMap<>()); int size = ReadWriteIOUtils.readInt(inputStream); for (int i = 0; i < size; ++i) { @@ -175,6 +177,7 @@ public static PipeStaticMeta deserialize(final InputStream inputStream) throws I pipeStaticMeta.connectorParameters.getAttribute().put(key, value); } + pipeStaticMeta.normalizePluginParametersForDeserialization(); pipeStaticMeta.updateCompletionSupport(); return pipeStaticMeta; } @@ -185,9 +188,9 @@ public static PipeStaticMeta deserialize(final ByteBuffer byteBuffer) { pipeStaticMeta.pipeName = ReadWriteIOUtils.readString(byteBuffer); pipeStaticMeta.creationTime = ReadWriteIOUtils.readLong(byteBuffer); - pipeStaticMeta.extractorParameters = new PipeParameters(new HashMap<>()); - pipeStaticMeta.processorParameters = new PipeParameters(new HashMap<>()); - pipeStaticMeta.connectorParameters = new PipeParameters(new HashMap<>()); + pipeStaticMeta.extractorParameters = new PipeParameters(new LinkedHashMap<>()); + pipeStaticMeta.processorParameters = new PipeParameters(new LinkedHashMap<>()); + pipeStaticMeta.connectorParameters = new PipeParameters(new LinkedHashMap<>()); int size = ReadWriteIOUtils.readInt(byteBuffer); for (int i = 0; i < size; ++i) { @@ -208,10 +211,26 @@ public static PipeStaticMeta deserialize(final ByteBuffer byteBuffer) { pipeStaticMeta.connectorParameters.getAttribute().put(key, value); } + pipeStaticMeta.normalizePluginParametersForDeserialization(); pipeStaticMeta.updateCompletionSupport(); return pipeStaticMeta; } + private void normalizePluginParameters() { + extractorParameters = PipePluginAgent.normalizeSourceParameters(extractorParameters); + processorParameters = PipePluginAgent.normalizeProcessorParameters(processorParameters); + connectorParameters = PipePluginAgent.normalizeSinkParameters(connectorParameters); + } + + private void normalizePluginParametersForDeserialization() { + extractorParameters = + PipePluginAgent.normalizeSourceParametersForDeserialization(extractorParameters); + processorParameters = + PipePluginAgent.normalizeProcessorParametersForDeserialization(processorParameters); + connectorParameters = + PipePluginAgent.normalizeSinkParametersForDeserialization(connectorParameters); + } + @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/config/constant/PipeSinkConstant.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/pipe/config/constant/PipeSinkConstant.java index bee10437739b0..a787e9db9008f 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 @@ -28,6 +28,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashSet; +import java.util.List; +import java.util.Map; import java.util.Set; import static org.apache.iotdb.commons.conf.IoTDBConstant.MB; @@ -69,14 +71,52 @@ public class PipeSinkConstant { 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 keys, final String defaultValue) { + for (final String key : keys) { + for (final Map.Entry 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 = reduceParameterKey(key); + for (final Map.Entry 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 reduceParameterKey(final String key) { + for (final String prefix : + Arrays.asList("extractor.", "source.", "processor.", "connector.", "sink.")) { + if (key.regionMatches(true, 0, prefix, 0, prefix.length())) { + return key.substring(prefix.length()); + } + } + return key; } private static String getDefaultConnectorOrSinkName(final PipeParameters parameters) { 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 832626707c152..385126777ca08 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 @@ -31,6 +31,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; @@ -195,19 +196,55 @@ public static Set parseOptions(String optionsString) throws Illegal } public static String getInclusionString(final PipeParameters parameters) { - return parameters.getStringOrDefault( + return getStringIgnoreCase( + parameters, Arrays.asList( PipeSourceConstant.EXTRACTOR_INCLUSION_KEY, PipeSourceConstant.SOURCE_INCLUSION_KEY), PipeSourceConstant.EXTRACTOR_INCLUSION_DEFAULT_VALUE); } public static String getExclusionString(final PipeParameters parameters) { - return parameters.getStringOrDefault( + return getStringIgnoreCase( + parameters, Arrays.asList( PipeSourceConstant.EXTRACTOR_EXCLUSION_KEY, PipeSourceConstant.SOURCE_EXCLUSION_KEY), PipeSourceConstant.EXTRACTOR_EXCLUSION_DEFAULT_VALUE); } + private static String getStringIgnoreCase( + final PipeParameters parameters, final List keys, final String defaultValue) { + for (final String key : keys) { + for (final Map.Entry 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 = reduceParameterKey(key); + for (final Map.Entry 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 reduceParameterKey(final String key) { + for (final String prefix : + Arrays.asList("extractor.", "source.", "processor.", "connector.", "sink.")) { + if (key.regionMatches(true, 0, prefix, 0, prefix.length())) { + return key.substring(prefix.length()); + } + } + return key; + } + public static boolean isDataInsertionIncluded(final PipeParameters parameters) throws IllegalPathException { // Match the data-region listening filter, including prefixes longer than the concrete option 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 ee9177112e710..58dff61582783 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 @@ -154,6 +154,7 @@ public static TopicMeta deserialize(final InputStream inputStream) throws IOExce topicMeta.subscribedConsumerGroupIds.add(ReadWriteIOUtils.readString(inputStream)); } + topicMeta.config = new TopicConfig(topicMeta.config.getAttribute()); return topicMeta; } @@ -175,6 +176,7 @@ public static TopicMeta deserialize(final ByteBuffer byteBuffer) { topicMeta.subscribedConsumerGroupIds.add(ReadWriteIOUtils.readString(byteBuffer)); } + topicMeta.config = new TopicConfig(topicMeta.config.getAttribute()); return topicMeta; } diff --git a/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgentNormalizationTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgentNormalizationTest.java new file mode 100644 index 0000000000000..b8c28d5510726 --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/agent/plugin/PipePluginAgentNormalizationTest.java @@ -0,0 +1,137 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.pipe.agent.plugin; + +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; +import org.apache.iotdb.commons.pipe.config.constant.PipeSourceConstant; +import org.apache.iotdb.pipe.api.customizer.parameter.PipeParameters; +import org.apache.iotdb.pipe.api.exception.PipeException; + +import org.junit.Assert; +import org.junit.Test; + +import java.util.Map; + +public class PipePluginAgentNormalizationTest { + + @Test + public void testNormalizeSinkParametersWithBlankConnectorName() { + final PipeParameters normalizedSinkParameters = + PipePluginAgent.normalizeSinkParameters( + new PipeParameters( + Map.of( + PipeSinkConstant.CONNECTOR_KEY, + " ", + " Connector.Node-URLs ", + "127.0.0.1:6667"))); + + Assert.assertEquals( + "127.0.0.1:6667", + normalizedSinkParameters.getString(PipeSinkConstant.CONNECTOR_IOTDB_NODE_URLS_KEY)); + } + + @Test + public void testPreserveTargetDatabaseCase() { + final PipeParameters normalizedSinkParameters = + PipePluginAgent.normalizeSinkParameters( + new PipeParameters( + Map.of( + "sink", + BuiltinPipePlugin.WRITE_BACK_SINK.getPipePluginName(), + "sink.database", + "TargetDB"))); + + Assert.assertEquals("TargetDB", normalizedSinkParameters.getString("sink.database")); + } + + @Test + public void testPreserveConsensusGroupIdCase() { + final PipeParameters normalizedSourceParameters = + PipePluginAgent.normalizeSourceParameters( + new PipeParameters( + Map.of( + PipeSourceConstant.EXTRACTOR_KEY, + BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName(), + PipeSourceConstant.EXTRACTOR_CONSENSUS_GROUP_ID_KEY, + "DataRegion[1]"))); + + Assert.assertEquals( + "DataRegion[1]", + normalizedSourceParameters.getString(PipeSourceConstant.EXTRACTOR_CONSENSUS_GROUP_ID_KEY)); + } + + @Test + public void testPreserveTimestampParameterValueCase() { + final String timestamp = "2024-01-01T00:00:00Z"; + final PipeParameters normalizedSourceParameters = + PipePluginAgent.normalizeSourceParameters( + new PipeParameters( + Map.of( + PipeSourceConstant.EXTRACTOR_KEY, + BuiltinPipePlugin.IOTDB_EXTRACTOR.getPipePluginName(), + PipeSourceConstant.EXTRACTOR_START_TIME_KEY, + timestamp, + PipeSourceConstant.SOURCE_END_TIME_KEY, + timestamp, + PipeSourceConstant.EXTRACTOR_HISTORY_START_TIME_KEY, + timestamp, + PipeSourceConstant.SOURCE_HISTORY_END_TIME_KEY, + timestamp))); + final PipeParameters normalizedProcessorParameters = + PipePluginAgent.normalizeProcessorParameters( + new PipeParameters( + Map.of( + PipeProcessorConstant.PROCESSOR_KEY, + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName(), + PipeProcessorConstant.PROCESSOR_SLIDING_BOUNDARY_TIME_KEY, + timestamp))); + + Assert.assertEquals( + timestamp, + normalizedSourceParameters.getString(PipeSourceConstant.EXTRACTOR_START_TIME_KEY)); + Assert.assertEquals( + timestamp, normalizedSourceParameters.getString(PipeSourceConstant.SOURCE_END_TIME_KEY)); + Assert.assertEquals( + timestamp, + normalizedSourceParameters.getString(PipeSourceConstant.EXTRACTOR_HISTORY_START_TIME_KEY)); + Assert.assertEquals( + timestamp, + normalizedSourceParameters.getString(PipeSourceConstant.SOURCE_HISTORY_END_TIME_KEY)); + Assert.assertEquals( + timestamp, + normalizedProcessorParameters.getString( + PipeProcessorConstant.PROCESSOR_SLIDING_BOUNDARY_TIME_KEY)); + } + + @Test + public void testRejectDuplicateKeysAfterNormalization() { + Assert.assertThrows( + PipeException.class, + () -> + PipePluginAgent.normalizeSourceParameters( + new PipeParameters( + Map.of( + "extractor", "iotdb-extractor", + "extractor.path", "root.sg.**", + " Extractor.Path ", "root.other.**")))); + } +} 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 f50b85e7e7979..7a1f5a7a171ad 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 @@ public void testDataInsertionUsesListeningPrefixSemantics() throws Exception { "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/task/PipeMetaDeSerTest.java b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/pipe/task/PipeMetaDeSerTest.java index 0f7117450cb04..39045123edcb6 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 @@ -252,6 +252,90 @@ public void test() throws IOException { Assert.assertEquals(pipeMeta, pipeMeta1); } + @Test + public void testBuiltinParametersAreNormalizedAfterLegacyDeserialization() throws IOException { + final PipeStaticMeta legacyStaticMeta = + new PipeStaticMeta("pipe", 1L, new HashMap<>(), new HashMap<>(), new HashMap<>()); + legacyStaticMeta + .getExtractorParameters() + .getAttribute() + .put(" EXTRACTOR ", " IOTDB-EXTRACTOR "); + legacyStaticMeta + .getExtractorParameters() + .getAttribute() + .put(" Extractor.Path ", " Root.SG.** "); + legacyStaticMeta + .getProcessorParameters() + .getAttribute() + .put( + " PROCESSOR ", + BuiltinPipePlugin.DO_NOTHING_PROCESSOR.getPipePluginName().toUpperCase()); + legacyStaticMeta.getProcessorParameters().getAttribute().put(" Processor.Mode ", " ON "); + legacyStaticMeta + .getConnectorParameters() + .getAttribute() + .put( + " CONNECTOR ", + BuiltinPipePlugin.IOTDB_THRIFT_CONNECTOR.getPipePluginName().toUpperCase()); + legacyStaticMeta.getConnectorParameters().getAttribute().put(" Connector.User ", " ROOT "); + legacyStaticMeta + .getConnectorParameters() + .getAttribute() + .put(" Connector.Host ", " NODE.EXAMPLE "); + legacyStaticMeta + .getConnectorParameters() + .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.getExtractorParameters().getString("extractor")); + Assert.assertEquals( + " Root.SG.** ", deserialized.getExtractorParameters().getString("extractor.path")); + Assert.assertEquals("on", deserialized.getProcessorParameters().getString("processor.mode")); + Assert.assertEquals( + " ROOT ", deserialized.getConnectorParameters().getString("connector.user")); + Assert.assertEquals( + " NODE.EXAMPLE ", deserialized.getConnectorParameters().getString("connector.host")); + Assert.assertEquals( + "mixed value", + deserialized.getConnectorParameters().getString("connector.custom.option")); + } + } + + @Test + public void testDuplicateBuiltinParametersDoNotBreakLegacyDeserialization() throws IOException { + final PipeStaticMeta legacyStaticMeta = + new PipeStaticMeta("pipe", 123L, Map.of(), Map.of(), Map.of()); + final Map extractorAttributes = + legacyStaticMeta.getExtractorParameters().getAttribute(); + extractorAttributes.put("source.path", "root.canonical.**"); + extractorAttributes.put(" SOURCE.PATH ", "root.variant.**"); + final String expectedPath = extractorAttributes.entrySet().iterator().next().getValue(); + + 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(1, deserialized.getExtractorParameters().getAttribute().size()); + Assert.assertEquals( + expectedPath, deserialized.getExtractorParameters().getString("source.path")); + } + } + @Test public void testClearExceptionMessagesBeforeClearTime() { final PipeTaskMeta staleTaskMeta = new PipeTaskMeta(MinimumProgressIndex.INSTANCE, 1); 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 new file mode 100644 index 0000000000000..796c5f07e865b --- /dev/null +++ b/iotdb-core/node-commons/src/test/java/org/apache/iotdb/commons/subscription/topic/TopicMetaTest.java @@ -0,0 +1,76 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.commons.subscription.topic; + +import org.apache.iotdb.commons.subscription.meta.topic.TopicMeta; +import org.apache.iotdb.rpc.subscription.config.TopicConstant; + +import org.apache.tsfile.utils.ReadWriteIOUtils; +import org.junit.Assert; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; + +public class TopicMetaTest { + + @Test + public void testNormalizeBuiltinAttributesAndPreserveExtensionAttributes() { + final Map attributes = new HashMap<>(); + attributes.put(" PATH ", " Root.SG.** "); + attributes.put(" Extension.Option ", " Mixed Value "); + + final TopicMeta topicMeta = new TopicMeta("topic", 1L, attributes); + + Assert.assertEquals( + "Root.SG.**", topicMeta.getConfig().getAttribute().get(TopicConstant.PATH_KEY)); + Assert.assertEquals( + " Mixed Value ", topicMeta.getConfig().getAttribute().get(" Extension.Option ")); + } + + @Test + public void testNormalizeAttributesAfterLegacyDeserialization() throws IOException { + final byte[] serialized = serializeLegacyTopicMeta(); + final TopicMeta fromInputStream = TopicMeta.deserialize(new ByteArrayInputStream(serialized)); + final TopicMeta fromByteBuffer = TopicMeta.deserialize(ByteBuffer.wrap(serialized)); + + Assert.assertEquals( + "Root.SG.**", fromInputStream.getConfig().getAttribute().get(TopicConstant.PATH_KEY)); + Assert.assertEquals( + "Root.SG.**", fromByteBuffer.getConfig().getAttribute().get(TopicConstant.PATH_KEY)); + } + + private byte[] serializeLegacyTopicMeta() throws IOException { + final ByteArrayOutputStream output = new ByteArrayOutputStream(); + final DataOutputStream dataOutput = new DataOutputStream(output); + ReadWriteIOUtils.write("topic", dataOutput); + ReadWriteIOUtils.write(1L, dataOutput); + ReadWriteIOUtils.write(1, dataOutput); + ReadWriteIOUtils.write(" PATH ", dataOutput); + ReadWriteIOUtils.write(" Root.SG.** ", dataOutput); + ReadWriteIOUtils.write(0, dataOutput); + return output.toByteArray(); + } +}