-
Notifications
You must be signed in to change notification settings - Fork 0
[Improve] add connection check when get connection #7
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
base: master
Are you sure you want to change the base?
Conversation
Signed-off-by: yuluo-yx <[email protected]>
Signed-off-by: yuluo-yx <[email protected]>
…luo-yx/hertzbeat into 0722-yuluo/optimize-collector
hi, the connection cache is the underlying code. If it throws an exception, more upper-level code logic should be considered. |
WalkthroughThis update introduces a standardized runtime validation mechanism for connection classes within the collector module. An abstract Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant Cache
participant Connection
Caller->>Cache: getConnection()
Cache->>Connection: check()
alt Connection is valid
Cache-->>Caller: return connection
else Connection is invalid
Cache->>Cache: log error
Cache-->>Caller: return null
end
Poem
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
@coderabbitai full review |
✅ Actions performedFull review triggered. |
There was a problem hiding this 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
🧹 Nitpick comments (6)
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/SshConnect.java (1)
41-47
: Good implementation of connection validationThe
check()
method properly verifies that the SSH session is open before it's used, improving connection reliability.Consider using a more specific exception type rather than generic
Exception
for better error handling by callers.@Override public void check() throws Exception { if (!clientSession.isOpen()) { - throw new Exception("ssh connection is not open"); + throw new IllegalStateException("ssh connection is not open"); } }collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/RedfishConnect.java (1)
41-47
: Good implementation of connection validationThe
check()
method properly validates the Redfish connection before use.Note that this implementation uses
RuntimeException
whileSshConnect
uses a checkedException
. Consider standardizing exception types across similar implementations for consistency.@Override public void check() throws Exception { if (!reddishConnectSession.isOpen()) { - throw new RuntimeException("Connection is closed"); + throw new IllegalStateException("Redfish connection is closed"); } }collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/RedisConnect.java (1)
51-60
: Consider enhanced error logging for better troubleshootingWhile the error handling works correctly, logging only the error message without the stack trace might make debugging harder in production environments.
try { this.check(); } catch (Exception e) { - log.error(e.getMessage()); + log.error("Redis connection check failed", e); return null; }collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/MongodbConnect.java (1)
48-58
: Improve error logging and remove unnecessary whitespaceThe implementation correctly handles connection validation before returning the client, but could benefit from enhanced error logging and removal of unnecessary whitespace.
@Override public MongoClient getConnection() { try { this.check(); } catch (Exception e) { - log.error(e.getMessage()); + log.error("MongoDB connection check failed", e); return null; } - return mongoClient; }collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/JmxConnect.java (1)
51-61
: Consider enhanced error logging for better diagnosticsWhile the implementation works correctly, logging only the error message without the stack trace might make troubleshooting more difficult in production environments.
try { this.check(); } catch (Exception e) { - log.error(e.getMessage()); + log.error("JMX connection check failed", e); return null; }collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/JdbcConnect.java (1)
51-61
: Consider enhanced error logging for better diagnosticsWhile the error handling works correctly, logging only the error message without the stack trace might make debugging more challenging.
try { this.check(); } catch (SQLException e) { - log.error(e.getMessage()); + log.error("JDBC connection check failed", e); return null; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/AbstractConnection.java
(2 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/JdbcConnect.java
(2 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/JmxConnect.java
(1 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/MongodbConnect.java
(2 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/RedfishConnect.java
(1 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/RedisConnect.java
(1 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/SshConnect.java
(1 hunks)collector/src/main/java/org/apache/hertzbeat/collector/collect/redis/RedisCommonCollectImpl.java
(1 hunks)collector/src/test/java/org/apache/hertzbeat/collector/collect/common/cache/CommonCacheTest.java
(1 hunks)
🔇 Additional comments (10)
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/AbstractConnection.java (2)
36-39
: Good addition of abstractcheck()
methodAdding this abstract method establishes a consistent validation contract across all connection implementations, ensuring connections are verified before being returned to clients.
43-44
: Improved clarity with explicitthis
referenceMaking the call to
closeConnection()
explicit withthis
prefix improves code readability and clarity.collector/src/test/java/org/apache/hertzbeat/collector/collect/common/cache/CommonCacheTest.java (1)
49-51
: Appropriate test implementation for abstract methodThe empty implementation of the
check()
method satisfies the new abstract method requirement without changing test behavior.collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/SshConnect.java (1)
50-58
: Proper error handling in getConnection()Good implementation of try-catch block to handle connection check failures gracefully. Returning null when the connection is invalid allows higher-level code to handle the situation appropriately.
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/RedfishConnect.java (1)
51-58
: Proper error handling in getConnection()Effective implementation of try-catch pattern to handle connection validation failures gracefully. This approach aligns with the PR objective of improving connection handling.
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/RedisConnect.java (1)
42-48
: Robust connection validation addedThe implementation correctly validates that the Redis connection is open before use, throwing a clear RuntimeException when the connection is closed. This is a valuable addition for preventing downstream errors.
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/MongodbConnect.java (1)
42-46
: Effective MongoDB connection validationThe implementation appropriately validates the MongoDB connection by running a ping command on the admin database, which is the standard way to check MongoDB connection health.
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/JmxConnect.java (1)
43-49
: Good JMX connection validation approachThe implementation validates the JMX connection by checking if the connection ID is empty, which is appropriate for detecting closed JMX connections.
collector/src/main/java/org/apache/hertzbeat/collector/collect/common/cache/JdbcConnect.java (1)
43-49
: Proper JDBC connection validationThe implementation correctly validates that the JDBC connection is not closed before use, throwing a SQLException with a clear message when the connection is invalid.
collector/src/main/java/org/apache/hertzbeat/collector/collect/redis/RedisCommonCollectImpl.java (1)
239-259
: Improved error handling with connection validation.The refactored
getStatefulConnection
method now properly handles invalid Redis connections by leveraging the newcheck()
mechanism implemented inRedisConnect
. This approach correctly catches exceptions from invalid connections, logs the issue, cleans up resources, and removes the invalid connection from the cache.However, I have a few suggestions to further enhance the implementation:
- Consider catching more specific exceptions rather than the broad
RuntimeException
- Include the full stack trace in the first log message to aid debugging
- Consider adding a comment explaining the relationship with the new
check()
methodtry { return redisConnect.getConnection(); - } catch (RuntimeException e) { - log.info("The Redis connection from cache is invalid, closing and removing: {}", e.getMessage()); + } catch (RuntimeException e) { + // RedisConnect.check() throws RuntimeException for invalid connections + log.info("The Redis connection from cache is invalid, closing and removing: {}", e.getMessage(), e); try { redisConnect.getConnection().closeAsync(); } catch (Exception closeException) { log.info("Error closing Redis connection: {}", closeException.getMessage()); } connectionCommonCache.removeCache(identifier); }
public Connection getConnection() { | ||
|
||
try { | ||
this.check(); | ||
} | ||
catch (SQLException e) { | ||
log.error(e.getMessage()); | ||
return null; | ||
} | ||
return connection; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Verification agent
🧩 Analysis chain
Consider handling null returns consistently across all connection classes
All connection classes now return null when validation fails. Ensure that callers are aware of this possibility and check for null before using the connection to prevent NullPointerExceptions.
🏁 Script executed:
#!/bin/bash
# Find places in the codebase where getConnection() is called without null check
echo "Searching for potential NullPointerException risks in getConnection() usages..."
# Search for patterns where getConnection() is called without null checks
rg -U "(\w+\.getConnection\(\)(?!\s*[!=]=\s*null|\s*\?\?|\s*\|\||\s*&&|\s*!=\s*null))" --type java
Length of output: 574
🏁 Script executed:
#!/bin/bash
# List every occurrence of getConnection() in Java source files
echo "Listing all usages of getConnection() in Java files..."
rg --type java "getConnection\s*\(\)" -n
Length of output: 3821
#!/bin/bash
set -e
echo "=== Context in JdbcCommonCollect.java around line 148 ==="
sed -n '135,165p' collector/src/main/java/org/apache/hertzbeat/collector/collect/database/JdbcCommonCollect.java
echo -e "\n=== Context in MongodbSingleCollectImpl.java around lines 170-210 ==="
sed -n '170,210p' collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java
echo -e "\n=== Context in JmxCollectImpl.java around lines 175-215 ==="
sed -n '175,215p' collector/src/main/java/org/apache/hertzbeat/collector/collect/jmx/JmxCollectImpl.java
echo -e "\n=== Context in SshCollectImpl.java around lines 280-330 ==="
sed -n '280,330p' collector/src/main/java/org/apache/hertzbeat/collector/collect/ssh/SshCollectImpl.java
echo -e "\n=== Context in RedfishCollectImpl.java around lines 90-120 ==="
sed -n '90,120p' collector/src/main/java/org/apache/hertzbeat/collector/collect/redfish/RedfishCollectImpl.java
echo -e "\n=== Context in RedisCommonCollectImpl.java around lines 235-270 ==="
sed -n '235,270p' collector/src/main/java/org/apache/hertzbeat/collector/collect/redis/RedisCommonCollectImpl.java
Add null‑checks for getConnection() return values
The new behavior in all *Connect.getConnection()
implementations is to return null
on validation failure. Callers must guard against a null
connection to avoid NullPointerException
s. Please update the following usages to check for null
before invoking methods on the returned connection (or consider throwing a checked exception / returning Optional<T>
instead):
• collector/src/main/java/org/apache/hertzbeat/collector/collect/database/JdbcCommonCollect.java:148
// before
statement = jdbcConnect.getConnection().createStatement();
// guard
Connection conn = jdbcConnect.getConnection();
if (conn == null) { /* handle error */ }
statement = conn.createStatement();
• collector/src/main/java/org/apache/hertzbeat/collector/collect/redis/RedisCommonCollectImpl.java
- Line 246:
return redisConnect.getConnection();
- Line 250:
redisConnect.getConnection().closeAsync();
• collector/src/main/java/org/apache/hertzbeat/collector/collect/mongodb/MongodbSingleCollectImpl.java:188
MongoClient client = mongodbConnect.getConnection();
// add null-check here
• collector/src/main/java/org/apache/hertzbeat/collector/collect/jmx/JmxCollectImpl.java:191
JMXConnector conn = jmxConnect.getConnection();
// add null-check here
• collector/src/main/java/org/apache/hertzbeat/collector/collect/ssh/SshCollectImpl.java:304
ClientSession session = cacheOption.get().getConnection();
// add null-check here
• collector/src/main/java/org/apache/hertzbeat/collector/collect/redfish/RedfishCollectImpl.java:105
ConnectSession session = redfishConnect.getConnection();
// add null-check here
Summary by CodeRabbit