You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "corgy-w (via GitHub)" <gi...@apache.org> on 2025/02/04 16:27:17 UTC

[PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

corgy-w opened a new pull request, #8603:
URL: https://github.com/apache/seatunnel/pull/8603

   <!--
   
   Thank you for contributing to SeaTunnel! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   ## Contribution Checklist
     - Make sure that the pull request corresponds to a [GITHUB issue](https://github.com/apache/seatunnel/issues).
     - Name the pull request in the form "[Feature] [component] Title of the pull request", where *Feature* can be replaced by `Hotfix`, `Bug`, etc.
     - Minor fixes should be named following this pattern: `[hotfix] [docs] Fix typo in README.md doc`.
   -->
   
   ### Purpose of this pull request
   
   Optimize the plugin discovery mechanism
   
   <!-- Describe the purpose of this pull request. For example: This pull request adds checkstyle plugin.-->
   
   
   ### Does this PR introduce _any_ user-facing change?
   
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released SeaTunnel versions or within the unreleased branches such as dev.
   If no, write 'No'.
   If you are adding/modifying connector documents, please follow our new specifications: https://github.com/apache/seatunnel/issues/4544.
   -->
   
   
   ### How was this patch tested?
   ut
   
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If you are adding E2E test cases, maybe refer to https://github.com/apache/seatunnel/blob/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cdc-mysql-e2e/src/test/resources/mysqlcdc_to_mysql.conf, here is a good example.
   -->
   
   
   ### Check list
   
   * [ ] If any new Jar binary package adding in your PR, please add License Notice according
     [New License Guide](https://github.com/apache/seatunnel/blob/dev/docs/en/contribution/new-license.md)
   * [ ] If necessary, please update the documentation to describe the new feature. https://github.com/apache/seatunnel/tree/dev/docs
   * [ ] If you are contributing the connector code, please check that the following files are updated:
     1. Update [plugin-mapping.properties](https://github.com/apache/seatunnel/blob/dev/plugin-mapping.properties) and add new connector information in it
     2. Update the pom file of [seatunnel-dist](https://github.com/apache/seatunnel/blob/dev/seatunnel-dist/pom.xml)
     3. Add ci label in [label-scope-conf](https://github.com/apache/seatunnel/blob/dev/.github/workflows/labeler/label-scope-conf.yml)
     4. Add e2e testcase in [seatunnel-e2e](https://github.com/apache/seatunnel/tree/dev/seatunnel-e2e/seatunnel-connector-v2-e2e/)
     5. Update connector [plugin_config](https://github.com/apache/seatunnel/blob/dev/config/plugin_config)
   * [ ] Update the [`release-note`](https://github.com/apache/seatunnel/blob/dev/release-note.md).


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "hailin0 (via GitHub)" <gi...@apache.org>.
hailin0 commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1958234416


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -455,104 +453,53 @@ public boolean accept(File pathname) {
         }
     }
 
-    private static File findMostSimlarPluginJarFile(
-            File[] targetPluginFiles, String pluginJarPrefix) {
-        String splitRegex = "\\-|\\_|\\.";
-        double maxSimlarity = -Integer.MAX_VALUE;
-        int mostSimlarPluginJarFileIndex = -1;
-        for (int i = 0; i < targetPluginFiles.length; i++) {
-            File file = targetPluginFiles[i];
-            String fileName = file.getName();
-            double similarity =
-                    CosineSimilarityUtil.cosineSimilarity(pluginJarPrefix, fileName, splitRegex);
-            if (similarity > maxSimlarity) {
-                maxSimlarity = similarity;
-                mostSimlarPluginJarFileIndex = i;
-            }
+    private Optional<URL> selectPluginJar(
+            File[] targetPluginFiles, String pluginJarPrefix, String pluginName, PluginType type) {
+        List<URL> resMatchedUrls = new ArrayList<>();
+        for (File file : targetPluginFiles) {
+            Optional<URL> matchedUrl = findMatchingUrl(file, type);
+            matchedUrl.ifPresent(resMatchedUrls::add);
+        }
+        if (resMatchedUrls.size() != 1) {
+            throw new SeaTunnelException(
+                    String.format(
+                            "Cannot find unique plugin jar for pluginIdentifier: %s -> %s",
+                            pluginName, pluginJarPrefix));
+        } else {
+            return Optional.of(resMatchedUrls.get(0));
         }
-        return targetPluginFiles[mostSimlarPluginJarFileIndex];
     }
 
-    static class CosineSimilarityUtil {
-        public static double cosineSimilarity(String textA, String textB, String splitRegrex) {
-            Set<String> words1 =
-                    new HashSet<>(Arrays.asList(textA.toLowerCase().split(splitRegrex)));
-            Set<String> words2 =
-                    new HashSet<>(Arrays.asList(textB.toLowerCase().split(splitRegrex)));
-            int[] termFrequency1 = calculateTermFrequencyVector(textA, words1, splitRegrex);
-            int[] termFrequency2 = calculateTermFrequencyVector(textB, words2, splitRegrex);
-            return calculateCosineSimilarity(termFrequency1, termFrequency2);
+    private Optional<URL> findMatchingUrl(File file, PluginType type) {
+        Map<PluginIdentifier, String> pluginInstanceMap = null;
+        switch (type) {
+            case SINK:
+                pluginInstanceMap = sinkPluginInstance;
+                break;
+            case SOURCE:
+                pluginInstanceMap = sourcePluginInstance;
+                break;
+            case TRANSFORM:
+                pluginInstanceMap = transformPluginInstance;
+                break;
         }
-
-        private static int[] calculateTermFrequencyVector(
-                String text, Set<String> words, String splitRegrex) {
-            int[] termFrequencyVector = new int[words.size()];
-            String[] textArray = text.toLowerCase().split(splitRegrex);
-            List<String> orderedWords = new ArrayList<String>();
-            words.clear();
-            for (String word : textArray) {
-                if (!words.contains(word)) {
-                    orderedWords.add(word);
-                    words.add(word);
-                }
-            }
-            for (String word : textArray) {
-                if (words.contains(word)) {
-                    int index = 0;
-                    for (String w : orderedWords) {
-                        if (w.equals(word)) {
-                            termFrequencyVector[index]++;
-                            break;
-                        }
-                        index++;
-                    }
-                }
-            }
-            return termFrequencyVector;
+        if (pluginInstanceMap == null) {
+            return Optional.empty();
         }
-
-        private static double calculateCosineSimilarity(int[] vectorA, int[] vectorB) {
-            double dotProduct = 0.0;
-            double magnitudeA = 0.0;
-            double magnitudeB = 0.0;
-            int vectorALength = vectorA.length;
-            int vectorBLength = vectorB.length;
-            if (vectorALength < vectorBLength) {
-                int[] vectorTemp = new int[vectorBLength];
-                for (int i = 0; i < vectorB.length; i++) {
-                    if (i <= vectorALength - 1) {
-                        vectorTemp[i] = vectorA[i];
-                    } else {
-                        vectorTemp[i] = 0;
-                    }
+        List<URL> matchedUrls = new ArrayList<>();
+        for (Map.Entry<PluginIdentifier, String> entry : pluginInstanceMap.entrySet()) {
+            if (file.getName().startsWith(entry.getValue())) {
+                try {
+                    matchedUrls.add(file.toURI().toURL());
+                } catch (MalformedURLException e) {
+                    log.warn("Cannot get plugin URL for pluginIdentifier: {}", file, e);
                 }
-                vectorA = vectorTemp;
-            }
-            if (vectorALength > vectorBLength) {
-                int[] vectorTemp = new int[vectorALength];
-                for (int i = 0; i < vectorA.length; i++) {
-                    if (i <= vectorBLength - 1) {
-                        vectorTemp[i] = vectorB[i];
-                    } else {
-                        vectorTemp[i] = 0;
-                    }
-                }
-                vectorB = vectorTemp;
-            }
-            for (int i = 0; i < vectorA.length; i++) {
-                dotProduct += vectorA[i] * vectorB[i];
-                magnitudeA += Math.pow(vectorA[i], 2);
-                magnitudeB += Math.pow(vectorB[i], 2);
             }
+        }
 
-            magnitudeA = Math.sqrt(magnitudeA);
-            magnitudeB = Math.sqrt(magnitudeB);
-
-            if (magnitudeA == 0 || magnitudeB == 0) {
-                return 0.0; // Avoid dividing by 0
-            } else {
-                return dotProduct / (magnitudeA * magnitudeB);
-            }
+        if (matchedUrls.size() == 1) {
+            return Optional.of(matchedUrls.get(0));
         }
+        return Optional.empty();

Review Comment:
   add debug logs



##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -455,104 +453,53 @@ public boolean accept(File pathname) {
         }
     }
 
-    private static File findMostSimlarPluginJarFile(
-            File[] targetPluginFiles, String pluginJarPrefix) {
-        String splitRegex = "\\-|\\_|\\.";
-        double maxSimlarity = -Integer.MAX_VALUE;
-        int mostSimlarPluginJarFileIndex = -1;
-        for (int i = 0; i < targetPluginFiles.length; i++) {
-            File file = targetPluginFiles[i];
-            String fileName = file.getName();
-            double similarity =
-                    CosineSimilarityUtil.cosineSimilarity(pluginJarPrefix, fileName, splitRegex);
-            if (similarity > maxSimlarity) {
-                maxSimlarity = similarity;
-                mostSimlarPluginJarFileIndex = i;
-            }
+    private Optional<URL> selectPluginJar(
+            File[] targetPluginFiles, String pluginJarPrefix, String pluginName, PluginType type) {
+        List<URL> resMatchedUrls = new ArrayList<>();
+        for (File file : targetPluginFiles) {
+            Optional<URL> matchedUrl = findMatchingUrl(file, type);
+            matchedUrl.ifPresent(resMatchedUrls::add);
+        }
+        if (resMatchedUrls.size() != 1) {
+            throw new SeaTunnelException(
+                    String.format(
+                            "Cannot find unique plugin jar for pluginIdentifier: %s -> %s",

Review Comment:
   add matchedUrl into error message



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1948326962


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -114,6 +118,8 @@ public AbstractPluginDiscovery(
         this.pluginDir = pluginDir;
         this.pluginMappingConfig = pluginMappingConfig;
         this.addURLToClassLoaderConsumer = addURLToClassLoaderConsumer;
+        this.sourcePluginInstance = getAllSupportedPlugins(PluginType.SOURCE);
+        this.sinkPluginInstance = getAllSupportedPlugins(PluginType.SINK);

Review Comment:
   Transform plugin discovery logic same with source/sink. https://github.com/apache/seatunnel/blob/dev/plugin-mapping.properties#L145



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w commented on PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#issuecomment-2638721934

   cc @hailin0 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X merged PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1944064856


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -403,156 +409,104 @@ private Optional<URL> findPluginJarPath(PluginIdentifier pluginIdentifier) {
         final String engineType = pluginIdentifier.getEngineType().toLowerCase();
         final String pluginType = pluginIdentifier.getPluginType().toLowerCase();
         final String pluginName = pluginIdentifier.getPluginName().toLowerCase();
-        if (!pluginMappingConfig.hasPath(engineType)) {
-            return Optional.empty();
-        }
-        Config engineConfig = pluginMappingConfig.getConfig(engineType);
-        if (!engineConfig.hasPath(pluginType)) {
-            return Optional.empty();
-        }
-        Config typeConfig = engineConfig.getConfig(pluginType);
-        Optional<Map.Entry<String, ConfigValue>> optional =
-                typeConfig.entrySet().stream()
-                        .filter(entry -> StringUtils.equalsIgnoreCase(entry.getKey(), pluginName))
-                        .findFirst();
-        if (!optional.isPresent()) {
-            return Optional.empty();
-        }
-        String pluginJarPrefix = optional.get().getValue().unwrapped().toString();
-        File[] targetPluginFiles =
-                pluginDir
-                        .toFile()
-                        .listFiles(
-                                new FileFilter() {
-                                    @Override
-                                    public boolean accept(File pathname) {
-                                        return pathname.getName().endsWith(".jar")
-                                                && StringUtils.startsWithIgnoreCase(
-                                                        pathname.getName(), pluginJarPrefix);
-                                    }
-                                });
-        if (ArrayUtils.isEmpty(targetPluginFiles)) {
-            return Optional.empty();
-        }
-        try {
-            URL pluginJarPath;
-            if (targetPluginFiles.length == 1) {
-                pluginJarPath = targetPluginFiles[0].toURI().toURL();
-            } else {
-                pluginJarPath =
-                        findMostSimlarPluginJarFile(targetPluginFiles, pluginJarPrefix)
-                                .toURI()
-                                .toURL();
-            }
-            log.info("Discovery plugin jar for: {} at: {}", pluginIdentifier, pluginJarPath);
-            return Optional.of(pluginJarPath);
-        } catch (MalformedURLException e) {
-            log.warn(
-                    "Cannot get plugin URL: {} for pluginIdentifier: {}" + targetPluginFiles[0],
-                    pluginIdentifier,
-                    e);
-            return Optional.empty();
-        }
-    }
 
-    private static File findMostSimlarPluginJarFile(
-            File[] targetPluginFiles, String pluginJarPrefix) {
-        String splitRegex = "\\-|\\_|\\.";
-        double maxSimlarity = -Integer.MAX_VALUE;
-        int mostSimlarPluginJarFileIndex = -1;
-        for (int i = 0; i < targetPluginFiles.length; i++) {
-            File file = targetPluginFiles[i];
-            String fileName = file.getName();
-            double similarity =
-                    CosineSimilarityUtil.cosineSimilarity(pluginJarPrefix, fileName, splitRegex);
-            if (similarity > maxSimlarity) {
-                maxSimlarity = similarity;
-                mostSimlarPluginJarFileIndex = i;
-            }
-        }
-        return targetPluginFiles[mostSimlarPluginJarFileIndex];
+        return Optional.ofNullable(pluginMappingConfig.getConfig(engineType))
+                .flatMap(engineConfig -> Optional.ofNullable(engineConfig.getConfig(pluginType)))
+                .flatMap(
+                        typeConfig ->
+                                typeConfig.entrySet().stream()
+                                        .filter(
+                                                entry ->
+                                                        StringUtils.equalsIgnoreCase(
+                                                                entry.getKey(), pluginName))
+                                        .findFirst())
+                .map(entry -> entry.getValue().unwrapped().toString())
+                .map(
+                        pluginJarPrefix ->
+                                pluginDir
+                                        .toFile()
+                                        .listFiles(
+                                                pathname ->
+                                                        pathname.getName().endsWith(".jar")
+                                                                && StringUtils.startsWithIgnoreCase(
+                                                                        pathname.getName(),
+                                                                        pluginJarPrefix)))
+                .filter(files -> !ArrayUtils.isEmpty(files))
+                .flatMap(
+                        files -> {
+                            try {
+                                if (files.length == 1) {
+                                    return Optional.of(files[0].toURI().toURL());
+                                } else {
+                                    PluginType type = PluginType.valueOf(pluginType.toUpperCase());
+                                    String targetPluginName =
+                                            getTargetPluginName(pluginIdentifier, type);
+                                    return selectPluginJar(files, targetPluginName);
+                                }
+                            } catch (MalformedURLException e) {
+                                log.warn(
+                                        "Cannot get plugin URL for pluginIdentifier: {}",
+                                        pluginIdentifier,
+                                        e);
+                                return Optional.empty();
+                            }
+                        })
+                .map(
+                        pluginJarPath -> {
+                            log.info(
+                                    "Discovery plugin jar for: {} at: {}",
+                                    pluginIdentifier,
+                                    pluginJarPath);
+                            return pluginJarPath;
+                        });
     }
 
-    static class CosineSimilarityUtil {
-        public static double cosineSimilarity(String textA, String textB, String splitRegrex) {
-            Set<String> words1 =
-                    new HashSet<>(Arrays.asList(textA.toLowerCase().split(splitRegrex)));
-            Set<String> words2 =
-                    new HashSet<>(Arrays.asList(textB.toLowerCase().split(splitRegrex)));
-            int[] termFrequency1 = calculateTermFrequencyVector(textA, words1, splitRegrex);
-            int[] termFrequency2 = calculateTermFrequencyVector(textB, words2, splitRegrex);
-            return calculateCosineSimilarity(termFrequency1, termFrequency2);
+    private String getTargetPluginName(PluginIdentifier pluginIdentifier, PluginType type) {
+        switch (type) {
+            case SINK:

Review Comment:
   ditto



##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -114,6 +118,8 @@ public AbstractPluginDiscovery(
         this.pluginDir = pluginDir;
         this.pluginMappingConfig = pluginMappingConfig;
         this.addURLToClassLoaderConsumer = addURLToClassLoaderConsumer;
+        this.sourcePluginInstance = getAllSupportedPlugins(PluginType.SOURCE);
+        this.sinkPluginInstance = getAllSupportedPlugins(PluginType.SINK);

Review Comment:
   where is transform?



##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -403,156 +409,104 @@ private Optional<URL> findPluginJarPath(PluginIdentifier pluginIdentifier) {
         final String engineType = pluginIdentifier.getEngineType().toLowerCase();
         final String pluginType = pluginIdentifier.getPluginType().toLowerCase();
         final String pluginName = pluginIdentifier.getPluginName().toLowerCase();
-        if (!pluginMappingConfig.hasPath(engineType)) {
-            return Optional.empty();
-        }
-        Config engineConfig = pluginMappingConfig.getConfig(engineType);
-        if (!engineConfig.hasPath(pluginType)) {
-            return Optional.empty();
-        }
-        Config typeConfig = engineConfig.getConfig(pluginType);
-        Optional<Map.Entry<String, ConfigValue>> optional =
-                typeConfig.entrySet().stream()
-                        .filter(entry -> StringUtils.equalsIgnoreCase(entry.getKey(), pluginName))
-                        .findFirst();
-        if (!optional.isPresent()) {
-            return Optional.empty();
-        }
-        String pluginJarPrefix = optional.get().getValue().unwrapped().toString();
-        File[] targetPluginFiles =
-                pluginDir
-                        .toFile()
-                        .listFiles(
-                                new FileFilter() {
-                                    @Override
-                                    public boolean accept(File pathname) {
-                                        return pathname.getName().endsWith(".jar")
-                                                && StringUtils.startsWithIgnoreCase(
-                                                        pathname.getName(), pluginJarPrefix);
-                                    }
-                                });
-        if (ArrayUtils.isEmpty(targetPluginFiles)) {
-            return Optional.empty();
-        }
-        try {
-            URL pluginJarPath;
-            if (targetPluginFiles.length == 1) {
-                pluginJarPath = targetPluginFiles[0].toURI().toURL();
-            } else {
-                pluginJarPath =
-                        findMostSimlarPluginJarFile(targetPluginFiles, pluginJarPrefix)
-                                .toURI()
-                                .toURL();
-            }
-            log.info("Discovery plugin jar for: {} at: {}", pluginIdentifier, pluginJarPath);
-            return Optional.of(pluginJarPath);
-        } catch (MalformedURLException e) {
-            log.warn(
-                    "Cannot get plugin URL: {} for pluginIdentifier: {}" + targetPluginFiles[0],
-                    pluginIdentifier,
-                    e);
-            return Optional.empty();
-        }
-    }
 
-    private static File findMostSimlarPluginJarFile(
-            File[] targetPluginFiles, String pluginJarPrefix) {
-        String splitRegex = "\\-|\\_|\\.";
-        double maxSimlarity = -Integer.MAX_VALUE;
-        int mostSimlarPluginJarFileIndex = -1;
-        for (int i = 0; i < targetPluginFiles.length; i++) {
-            File file = targetPluginFiles[i];
-            String fileName = file.getName();
-            double similarity =
-                    CosineSimilarityUtil.cosineSimilarity(pluginJarPrefix, fileName, splitRegex);
-            if (similarity > maxSimlarity) {
-                maxSimlarity = similarity;
-                mostSimlarPluginJarFileIndex = i;
-            }
-        }
-        return targetPluginFiles[mostSimlarPluginJarFileIndex];
+        return Optional.ofNullable(pluginMappingConfig.getConfig(engineType))
+                .flatMap(engineConfig -> Optional.ofNullable(engineConfig.getConfig(pluginType)))
+                .flatMap(
+                        typeConfig ->
+                                typeConfig.entrySet().stream()
+                                        .filter(
+                                                entry ->
+                                                        StringUtils.equalsIgnoreCase(
+                                                                entry.getKey(), pluginName))
+                                        .findFirst())
+                .map(entry -> entry.getValue().unwrapped().toString())
+                .map(
+                        pluginJarPrefix ->
+                                pluginDir
+                                        .toFile()
+                                        .listFiles(
+                                                pathname ->
+                                                        pathname.getName().endsWith(".jar")
+                                                                && StringUtils.startsWithIgnoreCase(
+                                                                        pathname.getName(),
+                                                                        pluginJarPrefix)))
+                .filter(files -> !ArrayUtils.isEmpty(files))
+                .flatMap(
+                        files -> {
+                            try {
+                                if (files.length == 1) {
+                                    return Optional.of(files[0].toURI().toURL());
+                                } else {
+                                    PluginType type = PluginType.valueOf(pluginType.toUpperCase());
+                                    String targetPluginName =
+                                            getTargetPluginName(pluginIdentifier, type);
+                                    return selectPluginJar(files, targetPluginName);
+                                }
+                            } catch (MalformedURLException e) {
+                                log.warn(
+                                        "Cannot get plugin URL for pluginIdentifier: {}",
+                                        pluginIdentifier,
+                                        e);
+                                return Optional.empty();
+                            }
+                        })
+                .map(
+                        pluginJarPath -> {
+                            log.info(
+                                    "Discovery plugin jar for: {} at: {}",
+                                    pluginIdentifier,
+                                    pluginJarPath);
+                            return pluginJarPath;
+                        });
     }
 
-    static class CosineSimilarityUtil {
-        public static double cosineSimilarity(String textA, String textB, String splitRegrex) {
-            Set<String> words1 =
-                    new HashSet<>(Arrays.asList(textA.toLowerCase().split(splitRegrex)));
-            Set<String> words2 =
-                    new HashSet<>(Arrays.asList(textB.toLowerCase().split(splitRegrex)));
-            int[] termFrequency1 = calculateTermFrequencyVector(textA, words1, splitRegrex);
-            int[] termFrequency2 = calculateTermFrequencyVector(textB, words2, splitRegrex);
-            return calculateCosineSimilarity(termFrequency1, termFrequency2);
+    private String getTargetPluginName(PluginIdentifier pluginIdentifier, PluginType type) {
+        switch (type) {
+            case SINK:
+                return sinkPluginInstance.get(pluginIdentifier);
+            case SOURCE:
+                return sourcePluginInstance.get(pluginIdentifier);
+            default:
+                throw new SeaTunnelException("Unsupported plugin type: " + type);
         }
+    }
 
-        private static int[] calculateTermFrequencyVector(
-                String text, Set<String> words, String splitRegrex) {
-            int[] termFrequencyVector = new int[words.size()];
-            String[] textArray = text.toLowerCase().split(splitRegrex);
-            List<String> orderedWords = new ArrayList<String>();
-            words.clear();
-            for (String word : textArray) {
-                if (!words.contains(word)) {
-                    orderedWords.add(word);
-                    words.add(word);
+    private Optional<URL> selectPluginJar(File[] targetPluginFiles, String targetPluginName) {
+        for (File file : targetPluginFiles) {
+            if (readPomPropertiesJudgeJar(file.getPath(), targetPluginName)) {
+                try {
+                    return Optional.of(file.toURI().toURL());
+                } catch (MalformedURLException e) {
+                    log.error("Invalid URL for file: {}", file.getAbsolutePath(), e);
                 }
             }
-            for (String word : textArray) {
-                if (words.contains(word)) {
-                    int index = 0;
-                    for (String w : orderedWords) {
-                        if (w.equals(word)) {
-                            termFrequencyVector[index]++;
-                            break;
-                        }
-                        index++;
-                    }
-                }
-            }
-            return termFrequencyVector;
         }
+        return Optional.empty();
+    }
+
+    @SneakyThrows
+    private static boolean readPomPropertiesJudgeJar(String jarPath, String targetPluginPath) {
+        try (JarFile jarFile = new JarFile(jarPath)) {
+            Enumeration<JarEntry> entries = jarFile.entries();
+            while (entries.hasMoreElements()) {
+                JarEntry entry = entries.nextElement();
+                String entryName = entry.getName();
 
-        private static double calculateCosineSimilarity(int[] vectorA, int[] vectorB) {
-            double dotProduct = 0.0;
-            double magnitudeA = 0.0;
-            double magnitudeB = 0.0;
-            int vectorALength = vectorA.length;
-            int vectorBLength = vectorB.length;
-            if (vectorALength < vectorBLength) {
-                int[] vectorTemp = new int[vectorBLength];
-                for (int i = 0; i < vectorB.length; i++) {
-                    if (i <= vectorALength - 1) {
-                        vectorTemp[i] = vectorA[i];
-                    } else {
-                        vectorTemp[i] = 0;
+                if (entryName.endsWith("pom.properties") && entryName.contains("META-INF/maven/")) {
+

Review Comment:
   can we make sure all jar contains these file? Why not continue use jar file name to check it? cc @hailin0 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w commented on PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#issuecomment-2656274373

   @hailin0 PTAL
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1948105276


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -114,6 +118,8 @@ public AbstractPluginDiscovery(
         this.pluginDir = pluginDir;
         this.pluginMappingConfig = pluginMappingConfig;
         this.addURLToClassLoaderConsumer = addURLToClassLoaderConsumer;
+        this.sourcePluginInstance = getAllSupportedPlugins(PluginType.SOURCE);
+        this.sinkPluginInstance = getAllSupportedPlugins(PluginType.SINK);

Review Comment:
   transfrom seem not to need?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1946284628


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -403,156 +409,104 @@ private Optional<URL> findPluginJarPath(PluginIdentifier pluginIdentifier) {
         final String engineType = pluginIdentifier.getEngineType().toLowerCase();
         final String pluginType = pluginIdentifier.getPluginType().toLowerCase();
         final String pluginName = pluginIdentifier.getPluginName().toLowerCase();
-        if (!pluginMappingConfig.hasPath(engineType)) {
-            return Optional.empty();
-        }
-        Config engineConfig = pluginMappingConfig.getConfig(engineType);
-        if (!engineConfig.hasPath(pluginType)) {
-            return Optional.empty();
-        }
-        Config typeConfig = engineConfig.getConfig(pluginType);
-        Optional<Map.Entry<String, ConfigValue>> optional =
-                typeConfig.entrySet().stream()
-                        .filter(entry -> StringUtils.equalsIgnoreCase(entry.getKey(), pluginName))
-                        .findFirst();
-        if (!optional.isPresent()) {
-            return Optional.empty();
-        }
-        String pluginJarPrefix = optional.get().getValue().unwrapped().toString();
-        File[] targetPluginFiles =
-                pluginDir
-                        .toFile()
-                        .listFiles(
-                                new FileFilter() {
-                                    @Override
-                                    public boolean accept(File pathname) {
-                                        return pathname.getName().endsWith(".jar")
-                                                && StringUtils.startsWithIgnoreCase(
-                                                        pathname.getName(), pluginJarPrefix);
-                                    }
-                                });
-        if (ArrayUtils.isEmpty(targetPluginFiles)) {
-            return Optional.empty();
-        }
-        try {
-            URL pluginJarPath;
-            if (targetPluginFiles.length == 1) {
-                pluginJarPath = targetPluginFiles[0].toURI().toURL();
-            } else {
-                pluginJarPath =
-                        findMostSimlarPluginJarFile(targetPluginFiles, pluginJarPrefix)
-                                .toURI()
-                                .toURL();
-            }
-            log.info("Discovery plugin jar for: {} at: {}", pluginIdentifier, pluginJarPath);
-            return Optional.of(pluginJarPath);
-        } catch (MalformedURLException e) {
-            log.warn(
-                    "Cannot get plugin URL: {} for pluginIdentifier: {}" + targetPluginFiles[0],
-                    pluginIdentifier,
-                    e);
-            return Optional.empty();
-        }
-    }
 
-    private static File findMostSimlarPluginJarFile(
-            File[] targetPluginFiles, String pluginJarPrefix) {
-        String splitRegex = "\\-|\\_|\\.";
-        double maxSimlarity = -Integer.MAX_VALUE;
-        int mostSimlarPluginJarFileIndex = -1;
-        for (int i = 0; i < targetPluginFiles.length; i++) {
-            File file = targetPluginFiles[i];
-            String fileName = file.getName();
-            double similarity =
-                    CosineSimilarityUtil.cosineSimilarity(pluginJarPrefix, fileName, splitRegex);
-            if (similarity > maxSimlarity) {
-                maxSimlarity = similarity;
-                mostSimlarPluginJarFileIndex = i;
-            }
-        }
-        return targetPluginFiles[mostSimlarPluginJarFileIndex];
+        return Optional.ofNullable(pluginMappingConfig.getConfig(engineType))
+                .flatMap(engineConfig -> Optional.ofNullable(engineConfig.getConfig(pluginType)))
+                .flatMap(
+                        typeConfig ->
+                                typeConfig.entrySet().stream()
+                                        .filter(
+                                                entry ->
+                                                        StringUtils.equalsIgnoreCase(
+                                                                entry.getKey(), pluginName))
+                                        .findFirst())
+                .map(entry -> entry.getValue().unwrapped().toString())
+                .map(
+                        pluginJarPrefix ->
+                                pluginDir
+                                        .toFile()
+                                        .listFiles(
+                                                pathname ->
+                                                        pathname.getName().endsWith(".jar")
+                                                                && StringUtils.startsWithIgnoreCase(
+                                                                        pathname.getName(),
+                                                                        pluginJarPrefix)))
+                .filter(files -> !ArrayUtils.isEmpty(files))
+                .flatMap(
+                        files -> {
+                            try {
+                                if (files.length == 1) {
+                                    return Optional.of(files[0].toURI().toURL());
+                                } else {
+                                    PluginType type = PluginType.valueOf(pluginType.toUpperCase());
+                                    String targetPluginName =
+                                            getTargetPluginName(pluginIdentifier, type);
+                                    return selectPluginJar(files, targetPluginName);
+                                }
+                            } catch (MalformedURLException e) {
+                                log.warn(
+                                        "Cannot get plugin URL for pluginIdentifier: {}",
+                                        pluginIdentifier,
+                                        e);
+                                return Optional.empty();
+                            }
+                        })
+                .map(
+                        pluginJarPath -> {
+                            log.info(
+                                    "Discovery plugin jar for: {} at: {}",
+                                    pluginIdentifier,
+                                    pluginJarPath);
+                            return pluginJarPath;
+                        });
     }
 
-    static class CosineSimilarityUtil {
-        public static double cosineSimilarity(String textA, String textB, String splitRegrex) {
-            Set<String> words1 =
-                    new HashSet<>(Arrays.asList(textA.toLowerCase().split(splitRegrex)));
-            Set<String> words2 =
-                    new HashSet<>(Arrays.asList(textB.toLowerCase().split(splitRegrex)));
-            int[] termFrequency1 = calculateTermFrequencyVector(textA, words1, splitRegrex);
-            int[] termFrequency2 = calculateTermFrequencyVector(textB, words2, splitRegrex);
-            return calculateCosineSimilarity(termFrequency1, termFrequency2);
+    private String getTargetPluginName(PluginIdentifier pluginIdentifier, PluginType type) {
+        switch (type) {
+            case SINK:
+                return sinkPluginInstance.get(pluginIdentifier);
+            case SOURCE:
+                return sourcePluginInstance.get(pluginIdentifier);
+            default:
+                throw new SeaTunnelException("Unsupported plugin type: " + type);
         }
+    }
 
-        private static int[] calculateTermFrequencyVector(
-                String text, Set<String> words, String splitRegrex) {
-            int[] termFrequencyVector = new int[words.size()];
-            String[] textArray = text.toLowerCase().split(splitRegrex);
-            List<String> orderedWords = new ArrayList<String>();
-            words.clear();
-            for (String word : textArray) {
-                if (!words.contains(word)) {
-                    orderedWords.add(word);
-                    words.add(word);
+    private Optional<URL> selectPluginJar(File[] targetPluginFiles, String targetPluginName) {
+        for (File file : targetPluginFiles) {
+            if (readPomPropertiesJudgeJar(file.getPath(), targetPluginName)) {
+                try {
+                    return Optional.of(file.toURI().toURL());
+                } catch (MalformedURLException e) {
+                    log.error("Invalid URL for file: {}", file.getAbsolutePath(), e);
                 }
             }
-            for (String word : textArray) {
-                if (words.contains(word)) {
-                    int index = 0;
-                    for (String w : orderedWords) {
-                        if (w.equals(word)) {
-                            termFrequencyVector[index]++;
-                            break;
-                        }
-                        index++;
-                    }
-                }
-            }
-            return termFrequencyVector;
         }
+        return Optional.empty();
+    }
+
+    @SneakyThrows
+    private static boolean readPomPropertiesJudgeJar(String jarPath, String targetPluginPath) {
+        try (JarFile jarFile = new JarFile(jarPath)) {
+            Enumeration<JarEntry> entries = jarFile.entries();
+            while (entries.hasMoreElements()) {
+                JarEntry entry = entries.nextElement();
+                String entryName = entry.getName();
 
-        private static double calculateCosineSimilarity(int[] vectorA, int[] vectorB) {
-            double dotProduct = 0.0;
-            double magnitudeA = 0.0;
-            double magnitudeB = 0.0;
-            int vectorALength = vectorA.length;
-            int vectorBLength = vectorB.length;
-            if (vectorALength < vectorBLength) {
-                int[] vectorTemp = new int[vectorBLength];
-                for (int i = 0; i < vectorB.length; i++) {
-                    if (i <= vectorALength - 1) {
-                        vectorTemp[i] = vectorA[i];
-                    } else {
-                        vectorTemp[i] = 0;
+                if (entryName.endsWith("pom.properties") && entryName.contains("META-INF/maven/")) {
+

Review Comment:
   `pom.properties` it should be the specification of jar package



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "corgy-w (via GitHub)" <gi...@apache.org>.
corgy-w commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1946283371


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -114,6 +118,8 @@ public AbstractPluginDiscovery(
         this.pluginDir = pluginDir;
         this.pluginMappingConfig = pluginMappingConfig;
         this.addURLToClassLoaderConsumer = addURLToClassLoaderConsumer;
+        this.sourcePluginInstance = getAllSupportedPlugins(PluginType.SOURCE);
+        this.sinkPluginInstance = getAllSupportedPlugins(PluginType.SINK);

Review Comment:
   get
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] [Fix][Plugin] Optimize the plugin discovery mechanism [seatunnel]

Posted by "Hisoka-X (via GitHub)" <gi...@apache.org>.
Hisoka-X commented on code in PR #8603:
URL: https://github.com/apache/seatunnel/pull/8603#discussion_r1951943295


##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -114,6 +114,9 @@ public AbstractPluginDiscovery(
         this.pluginDir = pluginDir;
         this.pluginMappingConfig = pluginMappingConfig;
         this.addURLToClassLoaderConsumer = addURLToClassLoaderConsumer;
+        this.sourcePluginInstance = getAllSupportedPlugins(PluginType.SOURCE);
+        this.sinkPluginInstance = getAllSupportedPlugins(PluginType.SINK);
+        this.transformPluginInstance = getAllSupportedPlugins(PluginType.TRANSFORM);

Review Comment:
   why we should cache this? It just store the connector jar prefix mapping. We can get the connector prefix when we used it.



##########
seatunnel-plugin-discovery/src/main/java/org/apache/seatunnel/plugin/discovery/AbstractPluginDiscovery.java:
##########
@@ -439,10 +438,10 @@ public boolean accept(File pathname) {
             if (targetPluginFiles.length == 1) {
                 pluginJarPath = targetPluginFiles[0].toURI().toURL();
             } else {
+                PluginType type = PluginType.valueOf(pluginType.toUpperCase());
+                String targetPlugin = getTargetPluginName(pluginIdentifier, type);
                 pluginJarPath =
-                        findMostSimlarPluginJarFile(targetPluginFiles, pluginJarPrefix)
-                                .toURI()
-                                .toURL();
+                        selectPluginJar(targetPluginFiles, targetPlugin, pluginName, type).get();

Review Comment:
   The `pluginJarPrefix` equals `targetPlugin`. So we can just use `pluginJarPrefix`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org