Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: 支持模块启动时通过传递env参数动态指定模块的启动类 (#999) #1029

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

liufeng-xiwo
Copy link

@liufeng-xiwo liufeng-xiwo commented Nov 14, 2024

模块启动时,可以通过 envs["sofa.ark.biz.main.class"] 参数传递指定的类作为模块的启动类

Summary by CodeRabbit

  • New Features

    • Enhanced dynamic configuration of the main class during startup based on environment variables.
    • Introduced a new constant BIZ_MAIN_CLASS for improved configuration options related to business logic.
    • Added a new test for verifying the installation of business operations with a dynamic main class.
  • Bug Fixes

    • Improved error handling to ensure a valid main class is set before startup, preventing runtime exceptions.

Copy link

sofastack-cla bot commented Nov 14, 2024

Hi @liufeng-xiwo, welcome to SOFAStack community, Please sign Contributor License Agreement!

After you signed CLA, we will automatically sync the status of this pull request in 3 minutes.

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes involve modifications to the BizModel class to improve the handling of the main class during startup by introducing a new mechanism for retrieving the main class name from environment variables. Additionally, a new constant BIZ_MAIN_CLASS has been added to the Constants class to support this functionality. Error handling has also been enhanced to throw an exception if the main class is not defined. A new test method has been introduced to validate the dynamic configuration of the main class.

Changes

File Change Summary
.../sofa/ark/container/model/BizModel.java Modified doStart method to retrieve main class from environment variable and added error handling.
.../sofa/ark/spi/constant/Constants.java Added new constant BIZ_MAIN_CLASS with value "sofa.ark.biz.main.class".
.../sofa/ark/container/service/api/ArkClientTest.java Added new test method testInstallOperationWithDynamicMainClass and variable bizUrl5 for testing dynamic main class configuration.

Possibly related PRs

  • 统一静态合并部署 #949: The changes in Constants.java introduce a new constant BIZ_MAIN_CLASS, which is utilized in the BizModel class for dynamic configuration of the mainClass based on environment variables.
  • enable not clean biz instance when stop biz failed  #1013: Modifications in BizModel.java enhance error handling in the doStart method, which is relevant to the changes made in the main PR regarding the startup process and exception handling.
  • feat: support multiple version module as activated #1018: The changes in BizModel.java regarding the activation of business modules based on configurations are related to the enhancements made in the main PR for dynamic configuration and error handling in the doStart method.

Suggested reviewers

  • lvjing2

Poem

In the world of code, a change we see,
A main class set, as easy as can be.
With constants added, our paths align,
In the startup dance, everything's fine!
So hop along, let the biz begin,
With a joyful start, let the coding win! 🐇✨

Warning

Rate limit exceeded

@liufeng-xiwo has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 3 minutes and 3 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 6833d9c and 50b6b6e.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java (1)

206-206: LGTM! Consider adding a Javadoc comment for better maintainability.

The new constant BIZ_MAIN_CLASS is well-defined and follows the established naming conventions. Its purpose aligns with the PR objective of supporting dynamic module startup class specification.

Consider adding a Javadoc comment to document the purpose and usage of this constant, similar to other sections in the file. Example:

+    /**
+     * Environment property to dynamically specify the module's startup class
+     */
     public final static String       BIZ_MAIN_CLASS                                = "sofa.ark.biz.main.class";
sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java (1)

326-332: Add validation and documentation for the main class override feature.

While the implementation allows for dynamic specification of the main class, consider these improvements:

  1. Validate that mainClassFromEnv contains a valid class name
  2. Add Javadoc to document this feature in the start and doStart methods
 // 支持运行时根据环境变量动态设置模块的启动类
 String mainClassFromEnv = envs.get(Constants.BIZ_MAIN_CLASS);
-if (mainClassFromEnv != null){
+if (!StringUtils.isEmpty(mainClassFromEnv)) {
+    // Validate class name format
+    AssertUtils.isFalse(StringUtils.isEmpty(mainClassFromEnv), "Main Class from environment must not be empty!");
     mainClass = mainClassFromEnv;
     ArkLoggerFactory.getDefaultLogger().info("Ark biz {} will start with main class {} from envs", getIdentity(), mainClassFromEnv);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7ab39b4 and ef6826b.

📒 Files selected for processing (2)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java (1 hunks)
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java (1 hunks)
🔇 Additional comments (1)
sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java (1)

333-333: LGTM: Appropriate error handling for missing main class.

The error handling is well implemented with a descriptive error message that includes the biz name for better debugging context.

Comment on lines 326 to 336

// 支持运行时根据环境变量动态设置模块的启动类
String mainClassFromEnv = envs.get(Constants.BIZ_MAIN_CLASS);
if (mainClassFromEnv != null){
mainClass = mainClassFromEnv;
ArkLoggerFactory.getDefaultLogger().info("Ark biz {} will start with main class {} from envs", getIdentity(), mainClassFromEnv);
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

Test coverage needed for environment-based main class configuration

The verification reveals:

  1. The BIZ_MAIN_CLASS constant is properly defined in Constants.java
  2. The only usage of this constant is in the new implementation
  3. No test coverage found for this new environment-based main class configuration feature

Action items:

  • Add test cases to verify the environment-based main class configuration
  • Include both positive (when env var is set) and negative (when env var is not set) test scenarios
  • Test the logging behavior when environment variable is used
🔗 Analysis chain

Verify constant usage and test coverage.

Let's verify the implementation of this feature:

  1. Check if the BIZ_MAIN_CLASS constant is properly defined
  2. Look for test coverage of this new functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for constant definition
echo "Checking for BIZ_MAIN_CLASS constant definition..."
rg -p "BIZ_MAIN_CLASS.*=.*\"sofa.ark.biz.main.class\""

# Check for test coverage
echo "Checking for test coverage..."
fd -e java -e groovy -e scala test | rg -l "BIZ_MAIN_CLASS|mainClassFromEnv"

Length of output: 516


Script:

#!/bin/bash
# Let's check for test files that might cover BizModel or main class configuration
echo "Checking for BizModel test coverage..."
rg -p "class.*Test.*BizModel" -g "*.java"

# Check for any test files that might test environment variable configuration
echo "Checking for environment variable test coverage..."
rg -p "test.*[Ee]nv.*main.*class" -g "*.java"

# Check for actual usage of this constant in the codebase
echo "Checking for usage of BIZ_MAIN_CLASS constant..."
rg -p "Constants\.BIZ_MAIN_CLASS" -A 2 -g "*.java"

Length of output: 712

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (3)

318-318: Convert comment to English for consistency

The comment should be in English to maintain consistency with the codebase.

-        // 传 env 参数,使用动态的模块启动类
+        // Pass env parameter to use dynamic module startup class

315-330: Enhance test coverage for dynamic main class feature

While the happy path is tested, consider adding test cases for:

  1. Invalid main class name
  2. Empty main class name
  3. Non-existent main class

This would ensure the feature handles error cases gracefully.

Example addition:

@Test
public void testInstallOperationWithInvalidDynamicMainClass() throws Throwable {
    BizOperation bizOperation = new BizOperation();
    bizOperation.setOperationType(INSTALL);
    bizOperation.getParameters().put(CONFIG_BIZ_URL, bizUrl5.toString());
    bizOperation.setBizName("biz-demo");
    bizOperation.setBizVersion("5.0.0");

    // Test with non-existent class
    Map<String, String> envs = Collections.singletonMap(Constants.BIZ_MAIN_CLASS, "org.example.NonExistentClass");
    ClientResponse response = installOperation(bizOperation, new String[] {}, envs);
    // Add appropriate assertions based on expected behavior
}

327-329: Make assertions more descriptive

The assertions could be more descriptive to better document the test's intent and make failures more informative.

-        ClientResponse response2 = installOperation(bizOperation, new String[] {}, envs);
-        assertEquals(SUCCESS, response2.getCode());
-        assertEquals("org.example.Main2", (new ArrayList<>(response2.getBizInfos())).get(0).getMainClass());
+        ClientResponse response = installOperation(bizOperation, new String[] {}, envs);
+        assertEquals("Installation should succeed", SUCCESS, response.getCode());
+        BizInfo bizInfo = (new ArrayList<>(response.getBizInfos())).get(0);
+        assertEquals("Main class should be set to the specified class", 
+                    "org.example.Main2", 
+                    bizInfo.getMainClass());
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dc93ed7 and e1c3dd2.

⛔ Files ignored due to path filters (1)
  • sofa-ark-parent/core-impl/container/src/test/resources/sample-ark-5.0.0-ark-biz.jar is excluded by !**/*.jar
📒 Files selected for processing (3)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java (1 hunks)
  • sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (5 hunks)
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java

@liufeng-xiwo liufeng-xiwo changed the title feat: fix issue999, 支持模块启动时通过传递env参数动态指定模块的启动类 feat: 支持模块启动时通过传递env参数动态指定模块的启动类 (#999) Nov 14, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (1)
sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (1)

322-349: Good test implementation, but some improvements suggested.

The test comprehensively validates the dynamic main class functionality. However, consider these improvements:

  1. Replace Chinese comments with English for international collaboration
  2. Extract magic strings as constants
  3. Add test cases for error scenarios

Consider applying these improvements:

-        // 传 env 参数,使用动态的模块启动类 org.example.Main2
+        // Test dynamic module startup class using env parameter
+        private static final String DYNAMIC_MAIN_CLASS = "org.example.Main2";
+        private static final String ORIGINAL_MAIN_CLASS = "org.example.Main1";
 
         BizOperation bizOperation = new BizOperation();
         bizOperation.setOperationType(INSTALL);
         bizOperation.getParameters().put(CONFIG_BIZ_URL, bizUrl5.toString());
         bizOperation.setBizName("biz-demo");
         bizOperation.setBizVersion("5.0.0");

-        Map<String, String> envs = Collections.singletonMap(Constants.BIZ_MAIN_CLASS, "org.example.Main2");
+        Map<String, String> envs = Collections.singletonMap(Constants.BIZ_MAIN_CLASS, DYNAMIC_MAIN_CLASS);

         ClientResponse response2 = installOperation(bizOperation, new String[] {}, envs);
         assertEquals(SUCCESS, response2.getCode());
-        assertEquals("org.example.Main2", (new ArrayList<>(response2.getBizInfos())).get(0).getMainClass());
+        assertEquals(DYNAMIC_MAIN_CLASS, (new ArrayList<>(response2.getBizInfos())).get(0).getMainClass());

-        // 实际模块jar包里配置启动类是 org.example.Main1
+        // Verify original main class in module JAR manifest

Consider adding these test cases:

  1. Test with invalid main class
  2. Test with empty/null main class
  3. Test with non-existent main class

Would you like me to help implement these additional test cases?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eaed6ae and 6833d9c.

⛔ Files ignored due to path filters (1)
  • sofa-ark-parent/core-impl/container/src/test/resources/sample-ark-5.0.0-ark-biz.jar is excluded by !**/*.jar
📒 Files selected for processing (3)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java (1 hunks)
  • sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (5 hunks)
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java
🔇 Additional comments (2)
sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (2)

106-107: LGTM! Field declaration follows existing patterns.

The new field bizUrl5 is well-documented and maintains consistency with the existing field declarations.


120-121: LGTM! Field initialization is consistent.

The initialization of bizUrl5 follows the established pattern and maintains consistency with other URL initializations.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (2)

322-349: LGTM! Consider adding more test cases for comprehensive coverage.

The test effectively validates the dynamic main class specification feature. Consider adding these test cases for more thorough coverage:

  1. Negative test case when the specified main class doesn't exist
  2. Test behavior when environment parameter is not set
  3. Test with invalid main class values

341-347: Ensure proper resource cleanup.

The test creates temporary files and opens JarFile resources. While the InputStream is properly closed using try-with-resources, the JarFile and JarFileArchive resources should also be closed.

Apply this diff to ensure proper resource cleanup:

-        JarFile bizFile = new JarFile(file);
-        JarFileArchive jarFileArchive = new JarFileArchive(bizFile);
-        BizArchive bizArchive = new JarBizArchive(jarFileArchive);
-        assertEquals("org.example.Main1", bizArchive.getManifest().getMainAttributes().getValue(Constants.MAIN_CLASS_ATTRIBUTE));
-        assertEquals("org.example.Main1", bizArchive.getManifest().getMainAttributes().getValue(Constants.START_CLASS_ATTRIBUTE));
+        try (JarFile bizFile = new JarFile(file)) {
+            JarFileArchive jarFileArchive = new JarFileArchive(bizFile);
+            BizArchive bizArchive = new JarBizArchive(jarFileArchive);
+            assertEquals("org.example.Main1", bizArchive.getManifest().getMainAttributes().getValue(Constants.MAIN_CLASS_ATTRIBUTE));
+            assertEquals("org.example.Main1", bizArchive.getManifest().getMainAttributes().getValue(Constants.START_CLASS_ATTRIBUTE));
+        }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6833d9c and 50b6b6e.

⛔ Files ignored due to path filters (1)
  • sofa-ark-parent/core-impl/container/src/test/resources/sample-ark-5.0.0-ark-biz.jar is excluded by !**/*.jar
📒 Files selected for processing (3)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java (1 hunks)
  • sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (5 hunks)
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • sofa-ark-parent/core-impl/container/src/main/java/com/alipay/sofa/ark/container/model/BizModel.java
  • sofa-ark-parent/core/spi/src/main/java/com/alipay/sofa/ark/spi/constant/Constants.java
🔇 Additional comments (1)
sofa-ark-parent/core-impl/container/src/test/java/com/alipay/sofa/ark/container/service/api/ArkClientTest.java (1)

106-107: LGTM! Variable declaration and initialization are consistent.

The new URL variable bizUrl5 follows the established pattern and is properly initialized in the before() method.

Also applies to: 120-121

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant