Skip to content

[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

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,11 @@

package org.apache.hertzbeat.collector.collect.common.cache;

import lombok.extern.slf4j.Slf4j;

/**
* AbstractConnection
*/
@Slf4j
public abstract class AbstractConnection<T> implements AutoCloseable {

public abstract class AbstractConnection<T> implements AutoCloseable {

/**
* @return Returns the connection.
Expand All @@ -35,8 +33,15 @@ public abstract class AbstractConnection<T> implements AutoCloseable {
*/
public abstract void closeConnection() throws Exception;

/**
* Check connection when get connection.
*/
public abstract void check() throws Exception;

@Override
public void close() throws Exception{
closeConnection();

this.closeConnection();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
package org.apache.hertzbeat.collector.collect.common.cache;

import java.sql.Connection;
import java.sql.SQLException;
import lombok.extern.slf4j.Slf4j;

/**
Expand All @@ -39,8 +40,24 @@ public void closeConnection() throws Exception {
}
}

@Override
public void check() throws SQLException {

if (connection.isClosed()) {
throw new SQLException("Connection is closed");
}
}

@Override
public Connection getConnection() {

try {
this.check();
}
catch (SQLException e) {
log.error(e.getMessage());
return null;
}
return connection;
Comment on lines 52 to 61
Copy link

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 NullPointerExceptions. 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

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,24 @@ public void closeConnection() throws Exception {
}
}

@Override
public void check() throws Exception {

if (connection.getConnectionId().isEmpty()) {
throw new RuntimeException("connection is closed");
}
}

@Override
public JMXConnector getConnection() {

try {
this.check();
}
catch (Exception e) {
log.error(e.getMessage());
return null;
}
return connection;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import com.mongodb.client.MongoClient;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;

/**
* mongodb connect client
Expand All @@ -38,8 +39,23 @@ public void closeConnection() throws Exception {
}
}

@Override
public void check() throws Exception {

mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));
}

@Override
public MongoClient getConnection() {

try {
this.check();
}
catch (Exception e) {
log.error(e.getMessage());
return null;
}

return mongoClient;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,24 @@ public void closeConnection() throws Exception {
}
}

@Override
public void check() throws Exception {

if (!reddishConnectSession.isOpen()) {
throw new RuntimeException("Connection is closed");
}
}

@Override
public ConnectSession getConnection() {

try {
this.check();
}
catch (Exception e) {
log.error(e.getMessage());
return null;
}
return reddishConnectSession;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,24 @@ public void closeConnection() throws Exception {
}
}

@Override
public void check() throws Exception {

if (!connection.isOpen()) {
throw new RuntimeException("Connection is closed");
}
}

@Override
public StatefulConnection<String, String> getConnection() {

try {
this.check();
}
catch (Exception e) {
log.error(e.getMessage());
return null;
}
return connection;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,23 @@ public void closeConnection() throws Exception {
}
}

@Override
public void check() throws Exception {

if (!clientSession.isOpen()) {
throw new Exception("ssh connection is not open");
}
}

public ClientSession getConnection() {

try {
this.check();
}
catch (Exception e) {
log.error(e.getMessage());
return null;
}
return clientSession;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -236,22 +236,26 @@ private StatefulRedisClusterConnection<String, String> getClusterConnection(Redi
* @return connection
*/
private StatefulConnection<String, String> getStatefulConnection(CacheIdentifier identifier) {
StatefulConnection<String, String> connection = null;

Optional<RedisConnect> cacheOption = connectionCommonCache.getCache(identifier, true);

if (cacheOption.isPresent()) {
RedisConnect redisConnect = cacheOption.get();
connection = redisConnect.getConnection();
if (!connection.isOpen()) {

try {
return redisConnect.getConnection();
} catch (RuntimeException e) {
log.info("The Redis connection from cache is invalid, closing and removing: {}", e.getMessage());
try {
connection.closeAsync();
} catch (Exception e) {
log.info("The redis connect form cache, close error: {}", e.getMessage());
redisConnect.getConnection().closeAsync();
} catch (Exception closeException) {
log.info("Error closing Redis connection: {}", closeException.getMessage());
}
connection = null;
connectionCommonCache.removeCache(identifier);
}
}
return connection;

return null;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ public Object getConnection() {
@Override
public void closeConnection() throws Exception {
}

@Override
public void check() throws Exception {
}
};
}

Expand Down
Loading