You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pinot.apache.org by xi...@apache.org on 2026/04/02 06:00:20 UTC

(pinot) branch master updated: Fail the config file reading if there are duplicated keys in the file (#15648)

This is an automated email from the ASF dual-hosted git repository.

xiangfu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/pinot.git


The following commit(s) were added to refs/heads/master by this push:
     new 82d003835ca Fail the config file reading if there are duplicated keys in the file (#15648)
82d003835ca is described below

commit 82d003835ca2b14ca118dcd9203743f369a4d20e
Author: Xiang Fu <xi...@apache.org>
AuthorDate: Wed Apr 1 23:00:15 2026 -0700

    Fail the config file reading if there are duplicated keys in the file (#15648)
    
    * Fail the config file reading if there are duplicated keys in the file
    
    * Adding tests for PinotConfigUtils
    
    * Update sample_filesystem_benchmark.conf
    
    * Validate duplicate keys only for service config files
    
    * Address PR review comments: move validateNoDuplicateKeys to CommonsConfigurationUtils
    
    - Move validateNoDuplicateKeys and DuplicateKeyTrackingReader to
      CommonsConfigurationUtils as a common util
    - Add DuplicateKeyTrackingReader to try-with-resources block
    - Use containsKey/put instead of putIfAbsent pattern
    - Revert unrelated pom.xml blank line removal
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <no...@anthropic.com>
    
    ---------
    
    Co-authored-by: Claude Opus 4.6 (1M context) <no...@anthropic.com>
---
 .../pinot/spi/env/CommonsConfigurationUtils.java   | 113 +++++++++++--
 .../apache/pinot/tools/utils/PinotConfigUtils.java |   3 +-
 .../conf/sample_filesystem_benchmark.conf          |   2 +-
 .../pinot/tools/utils/PinotConfigUtilsTest.java    | 174 +++++++++++++++++++++
 4 files changed, 279 insertions(+), 13 deletions(-)

diff --git a/pinot-spi/src/main/java/org/apache/pinot/spi/env/CommonsConfigurationUtils.java b/pinot-spi/src/main/java/org/apache/pinot/spi/env/CommonsConfigurationUtils.java
index efc3f54aba5..6bee6076299 100644
--- a/pinot-spi/src/main/java/org/apache/pinot/spi/env/CommonsConfigurationUtils.java
+++ b/pinot-spi/src/main/java/org/apache/pinot/spi/env/CommonsConfigurationUtils.java
@@ -23,8 +23,12 @@ import java.io.File;
 import java.io.FileReader;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.Reader;
 import java.io.Writer;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
 import java.util.Arrays;
+import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -111,8 +115,8 @@ public class CommonsConfigurationUtils {
    * @param ioFactoryKind representing to set IOFactory. It can be null.
    * @return a {@link PropertiesConfiguration} instance.
    */
-  public static PropertiesConfiguration fromInputStream(@Nullable InputStream stream,
-      boolean setDefaultDelimiter, @Nullable PropertyIOFactoryKind ioFactoryKind)
+  public static PropertiesConfiguration fromInputStream(@Nullable InputStream stream, boolean setDefaultDelimiter,
+      @Nullable PropertyIOFactoryKind ioFactoryKind)
       throws ConfigurationException {
     PropertiesConfiguration config = createPropertiesConfiguration(setDefaultDelimiter, ioFactoryKind);
     // if provided stream is not null, load the existing properties from provided input stream.
@@ -153,13 +157,14 @@ public class CommonsConfigurationUtils {
 
   /**
    * Instantiate a {@link PropertiesConfiguration} from a {@link File}.
+   * This method will merge duplicate keys to a list.
    * @param file containing properties
    * @param setDefaultDelimiter representing to set the default list delimiter.
    * @param ioFactoryKind representing to set IOFactory. It can be null.
    * @return a {@link PropertiesConfiguration} instance.
    */
-  public static PropertiesConfiguration fromFile(@Nullable File file,
-      boolean setDefaultDelimiter, @Nullable PropertyIOFactoryKind ioFactoryKind)
+  public static PropertiesConfiguration fromFile(@Nullable File file, boolean setDefaultDelimiter,
+      @Nullable PropertyIOFactoryKind ioFactoryKind)
       throws ConfigurationException {
     PropertiesConfiguration config = createPropertiesConfiguration(setDefaultDelimiter, ioFactoryKind);
     // check if file exists, load the existing properties.
@@ -338,16 +343,16 @@ public class CommonsConfigurationUtils {
   }
 
   /**
-   * creates the instance of the {@link org.apache.commons.configuration2.PropertiesConfiguration}
-   * with custom IO factory based on kind {@link org.apache.commons.configuration2.PropertiesConfiguration.IOFactory}
-   * and legacy list delimiter {@link org.apache.commons.configuration2.convert.LegacyListDelimiterHandler}
+   * creates the instance of the {@link PropertiesConfiguration}
+   * with custom IO factory based on kind {@link PropertiesConfiguration.IOFactory}
+   * and legacy list delimiter {@link LegacyListDelimiterHandler}
    *
    * @param setDefaultDelimiter sets the default list delimiter.
    * @param ioFactoryKind IOFactory kind, can be null.
    * @return PropertiesConfiguration
    */
   private static PropertiesConfiguration createPropertiesConfiguration(boolean setDefaultDelimiter,
-     @Nullable PropertyIOFactoryKind ioFactoryKind) {
+      @Nullable PropertyIOFactoryKind ioFactoryKind) {
     PropertiesConfiguration config = new PropertiesConfiguration();
 
     // setting IO Reader Factory of the configuration.
@@ -359,7 +364,6 @@ public class CommonsConfigurationUtils {
     if (setDefaultDelimiter) {
       config.setListDelimiterHandler(new LegacyListDelimiterHandler(DEFAULT_LIST_DELIMITER));
     }
-
     return config;
   }
 
@@ -385,8 +389,8 @@ public class CommonsConfigurationUtils {
           }
         }
       } catch (IOException exception) {
-        throw new ConfigurationException(
-            "Error occurred while reading configuration file " + file.getName(), exception);
+        throw new ConfigurationException("Error occurred while reading configuration file " + file.getName(),
+            exception);
       }
     }
     return versionValue;
@@ -411,4 +415,91 @@ public class CommonsConfigurationUtils {
     propertiesWriter.setGlobalSeparator(VERSIONED_CONFIG_SEPARATOR);
     return propertiesWriter;
   }
+
+  /**
+   * Validates that the given config file does not contain duplicate keys.
+   * @param configFile the config file to validate.
+   * @throws ConfigurationException if duplicate keys are found or the file cannot be read.
+   */
+  public static void validateNoDuplicateKeys(File configFile)
+      throws ConfigurationException {
+    try (Reader reader = Files.newBufferedReader(configFile.toPath(), StandardCharsets.UTF_8);
+         DuplicateKeyTrackingReader propertiesReader = new DuplicateKeyTrackingReader(reader)) {
+      Map<String, Integer> seenKeyLines = new HashMap<>();
+      while (propertiesReader.nextProperty()) {
+        String key = propertiesReader.getPropertyName();
+        if (seenKeyLines.containsKey(key)) {
+          throw new ConfigurationException(String.format(
+              "Duplicate key '%s' found in config file %s at line %d (first defined at line %d)", key,
+              configFile.getAbsolutePath(), propertiesReader.getPropertyLineNumber(), seenKeyLines.get(key)));
+        }
+        seenKeyLines.put(key, propertiesReader.getPropertyLineNumber());
+      }
+    } catch (IOException e) {
+      throw new ConfigurationException("Failed to validate config file " + configFile.getAbsolutePath(), e);
+    }
+  }
+
+  private static final class DuplicateKeyTrackingReader extends PropertiesConfiguration.PropertiesReader {
+    private int _propertyLineNumber;
+
+    private DuplicateKeyTrackingReader(Reader reader) {
+      super(reader);
+    }
+
+    private int getPropertyLineNumber() {
+      return _propertyLineNumber;
+    }
+
+    @Override
+    public String readProperty()
+        throws IOException {
+      getCommentLines().clear();
+      StringBuilder buffer = new StringBuilder();
+      _propertyLineNumber = -1;
+
+      while (true) {
+        String line = readLine();
+        if (line == null) {
+          return buffer.length() > 0 ? buffer.toString() : null;
+        }
+
+        if (isPropertiesCommentLine(line) || (_propertyLineNumber < 0 && isDoubleSlashCommentLine(line))) {
+          getCommentLines().add(line);
+          continue;
+        }
+
+        if (_propertyLineNumber < 0) {
+          _propertyLineNumber = getLineNumber();
+        }
+
+        line = line.trim();
+        if (!hasLineContinuation(line)) {
+          buffer.append(line);
+          break;
+        }
+        buffer.append(line, 0, line.length() - 1);
+      }
+
+      return buffer.toString();
+    }
+
+    private static boolean hasLineContinuation(String line) {
+      int trailingBackslashCount = 0;
+      for (int index = line.length() - 1; index >= 0 && line.charAt(index) == '\\'; index--) {
+        trailingBackslashCount++;
+      }
+      return trailingBackslashCount % 2 != 0;
+    }
+
+    private static boolean isDoubleSlashCommentLine(String line) {
+      String trimmed = line.trim();
+      return trimmed.startsWith("//");
+    }
+
+    private static boolean isPropertiesCommentLine(String line) {
+      String trimmed = line.trim();
+      return trimmed.isEmpty() || trimmed.charAt(0) == '#' || trimmed.charAt(0) == '!';
+    }
+  }
 }
diff --git a/pinot-tools/src/main/java/org/apache/pinot/tools/utils/PinotConfigUtils.java b/pinot-tools/src/main/java/org/apache/pinot/tools/utils/PinotConfigUtils.java
index eb1b965ac1b..abe7b938c81 100644
--- a/pinot-tools/src/main/java/org/apache/pinot/tools/utils/PinotConfigUtils.java
+++ b/pinot-tools/src/main/java/org/apache/pinot/tools/utils/PinotConfigUtils.java
@@ -99,6 +99,7 @@ public class PinotConfigUtils {
       return null;
     }
 
+    CommonsConfigurationUtils.validateNoDuplicateKeys(configFile);
     Configurations configs = new Configurations();
     Map<String, Object> properties = CommonsConfigurationUtils.toMap(configs.properties(configFile));
     ControllerConf conf = new ControllerConf(properties);
@@ -144,10 +145,10 @@ public class PinotConfigUtils {
     }
     File configFile = new File(configFileName);
     if (configFile.exists()) {
+      CommonsConfigurationUtils.validateNoDuplicateKeys(configFile);
       Configurations configs = new Configurations();
       return CommonsConfigurationUtils.toMap(configs.properties(configFile));
     }
-
     return null;
   }
 
diff --git a/pinot-tools/src/main/resources/conf/sample_filesystem_benchmark.conf b/pinot-tools/src/main/resources/conf/sample_filesystem_benchmark.conf
index d9f573b3b77..3531ed9e110 100644
--- a/pinot-tools/src/main/resources/conf/sample_filesystem_benchmark.conf
+++ b/pinot-tools/src/main/resources/conf/sample_filesystem_benchmark.conf
@@ -21,4 +21,4 @@
 class.abfss=org.apache.pinot.plugin.filesystem.AzureGen2PinotFS
 abfss.accountName=<account_name>
 abfss.accessKey=<access_key>
-abfss.fileSystemName=<file_system_name>
\ No newline at end of file
+abfss.fileSystemName=<file_system_name>
diff --git a/pinot-tools/src/test/java/org/apache/pinot/tools/utils/PinotConfigUtilsTest.java b/pinot-tools/src/test/java/org/apache/pinot/tools/utils/PinotConfigUtilsTest.java
new file mode 100644
index 00000000000..cb31d247482
--- /dev/null
+++ b/pinot-tools/src/test/java/org/apache/pinot/tools/utils/PinotConfigUtilsTest.java
@@ -0,0 +1,174 @@
+/**
+ * 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.pinot.tools.utils;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.SocketException;
+import java.net.UnknownHostException;
+import java.nio.charset.StandardCharsets;
+import java.util.Map;
+import org.apache.commons.configuration2.ex.ConfigurationException;
+import org.apache.commons.io.FileUtils;
+import org.apache.pinot.controller.ControllerConf;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.fail;
+
+
+public class PinotConfigUtilsTest {
+
+  @Test
+  public void testGenerateControllerConf()
+      throws SocketException, UnknownHostException {
+    // Test with all parameters provided
+    String zkAddress = "localhost:2181";
+    String clusterName = "testCluster";
+    String controllerHost = "localhost";
+    String controllerPort = "9000";
+    String dataDir = "/tmp/pinot";
+    ControllerConf.ControllerMode controllerMode = ControllerConf.ControllerMode.DUAL;
+    boolean tenantIsolation = true;
+
+    Map<String, Object> config = PinotConfigUtils.generateControllerConf(
+        zkAddress, clusterName, controllerHost, controllerPort, dataDir, controllerMode, tenantIsolation);
+
+    assertEquals(config.get(ControllerConf.ZK_STR), zkAddress);
+    assertEquals(config.get(ControllerConf.HELIX_CLUSTER_NAME), clusterName);
+    assertEquals(config.get(ControllerConf.CONTROLLER_HOST), controllerHost);
+    assertEquals(config.get(ControllerConf.CONTROLLER_PORT), controllerPort);
+    assertEquals(config.get(ControllerConf.DATA_DIR), dataDir);
+    assertEquals(config.get(ControllerConf.CONTROLLER_VIP_HOST), controllerHost);
+    assertEquals(config.get(ControllerConf.CLUSTER_TENANT_ISOLATION_ENABLE), tenantIsolation);
+  }
+
+  @Test(expectedExceptions = RuntimeException.class)
+  public void testGenerateControllerConfWithEmptyZkAddress()
+      throws SocketException, UnknownHostException {
+    PinotConfigUtils.generateControllerConf(
+        "", "testCluster", "localhost", "9000", "/tmp/pinot", ControllerConf.ControllerMode.DUAL, true);
+  }
+
+  @Test(expectedExceptions = RuntimeException.class)
+  public void testGenerateControllerConfWithEmptyClusterName()
+      throws SocketException, UnknownHostException {
+    PinotConfigUtils.generateControllerConf(
+        "localhost:2181", "", "localhost", "9000", "/tmp/pinot", ControllerConf.ControllerMode.DUAL, true);
+  }
+
+  @Test
+  public void testGenerateMinionConf()
+      throws SocketException, UnknownHostException {
+    String clusterName = "testCluster";
+    String zkAddress = "localhost:2181";
+    String minionHost = "localhost";
+    int minionPort = 9000;
+
+    Map<String, Object> config = PinotConfigUtils.generateMinionConf(clusterName, zkAddress, minionHost, minionPort);
+
+    assertEquals(config.get(CommonConstants.Helix.CONFIG_OF_CLUSTER_NAME), clusterName);
+    assertEquals(config.get(CommonConstants.Helix.CONFIG_OF_ZOOKEEPR_SERVER), zkAddress);
+    assertEquals(config.get(CommonConstants.Helix.KEY_OF_MINION_HOST), minionHost);
+    assertEquals(config.get(CommonConstants.Helix.KEY_OF_MINION_PORT), minionPort);
+  }
+
+  @Test
+  public void testGetResourceTrackingConf() {
+    Map<String, Object> config = PinotConfigUtils.getResourceTrackingConf();
+
+    assertTrue((Boolean) config.get(CommonConstants.Server.CONFIG_OF_ENABLE_THREAD_CPU_TIME_MEASUREMENT));
+    assertTrue((Boolean) config.get(CommonConstants.Server.CONFIG_OF_ENABLE_THREAD_ALLOCATED_BYTES_MEASUREMENT));
+    assertTrue((Boolean) config.get(CommonConstants.Broker.CONFIG_OF_ENABLE_THREAD_CPU_TIME_MEASUREMENT));
+    assertTrue((Boolean) config.get(CommonConstants.Broker.CONFIG_OF_ENABLE_THREAD_ALLOCATED_BYTES_MEASUREMENT));
+    assertTrue((Boolean) config.get(CommonConstants.Accounting.CONFIG_OF_ENABLE_THREAD_CPU_SAMPLING));
+    assertTrue((Boolean) config.get(CommonConstants.Accounting.CONFIG_OF_ENABLE_THREAD_MEMORY_SAMPLING));
+  }
+
+  @Test
+  public void testReadConfigWithDuplicateKeys()
+      throws IOException {
+    File tempFile = File.createTempFile("test-config", ".properties");
+    try {
+      String configContent = "key1=value1\n"
+          + "key2=value2\n"
+          + "key1=value3\n"
+          + "key4=value4\n";
+      FileUtils.writeStringToFile(tempFile, configContent, StandardCharsets.UTF_8);
+
+      try {
+        PinotConfigUtils.readConfigFromFile(tempFile.getAbsolutePath());
+        fail("Expected ConfigurationException for duplicate keys");
+      } catch (ConfigurationException e) {
+        assertTrue(e.getMessage().contains("Duplicate key 'key1'"));
+        assertTrue(e.getMessage().contains("line 3"));
+        assertTrue(e.getMessage().contains("line 1"));
+      }
+    } finally {
+      FileUtils.deleteQuietly(tempFile);
+    }
+  }
+
+  @Test
+  public void testReadConfigWithValidKeys()
+      throws IOException, ConfigurationException {
+    // Create a temporary config file with valid keys
+    File tempFile = File.createTempFile("test-config", ".properties");
+    try {
+      String configContent = "key1=value1\n"
+          + "key2=value2\n"
+          + "key3=value3\n"
+          + "key4=value4\n";
+      FileUtils.writeStringToFile(tempFile, configContent, StandardCharsets.UTF_8);
+
+      Map<String, Object> config = PinotConfigUtils.readConfigFromFile(tempFile.getAbsolutePath());
+      assertNotNull(config);
+      assertEquals(config.get("key1"), "value1");
+      assertEquals(config.get("key2"), "value2");
+      assertEquals(config.get("key3"), "value3");
+      assertEquals(config.get("key4"), "value4");
+    } finally {
+      FileUtils.deleteQuietly(tempFile);
+    }
+  }
+
+  @Test
+  public void testReadConfigWithDoubleSlashComments()
+      throws IOException, ConfigurationException {
+    File tempFile = File.createTempFile("test-config", ".conf");
+    try {
+      String configContent = "//\n"
+          + "// Licensed header line\n"
+          + "//\n"
+          + "key1=value1\n"
+          + "key2=value2\n";
+      FileUtils.writeStringToFile(tempFile, configContent, StandardCharsets.UTF_8);
+
+      Map<String, Object> config = PinotConfigUtils.readConfigFromFile(tempFile.getAbsolutePath());
+      assertNotNull(config);
+      assertEquals(config.get("key1"), "value1");
+      assertEquals(config.get("key2"), "value2");
+    } finally {
+      FileUtils.deleteQuietly(tempFile);
+    }
+  }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@pinot.apache.org
For additional commands, e-mail: commits-help@pinot.apache.org