diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java
index 726075da1d..cd4d966b18 100644
--- a/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java
+++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/Metrics.java
@@ -62,6 +62,7 @@ public class Metrics {
public final Counter namedBlobDBDeleteErrorCount;
public final Counter namedBlobDBInsertErrorCount;
public final Counter namedBlobDBUpdateErrorCount;
+ final Counter connectionCloseErrorCount;
/**
* Constructor to create the Metrics.
@@ -129,6 +130,8 @@ public Metrics(MetricRegistry metricRegistry, String prefix) {
metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBInsertErrorCount"));
namedBlobDBUpdateErrorCount =
metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "NamedBlobDBUpdateErrorCount"));
+ connectionCloseErrorCount =
+ metricRegistry.counter(MetricRegistry.name(MySqlNamedBlobDb.class, prefix + "ConnectionCloseErrorCount"));
}
/**
diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java
index b21e869f13..1ff933229e 100644
--- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java
+++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java
@@ -36,6 +36,7 @@
import com.github.ambry.utils.SystemTime;
import com.github.ambry.utils.Time;
import com.github.ambry.utils.Utils;
+import com.zaxxer.hikari.HikariDataSource;
import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
@@ -729,9 +730,8 @@ private static class TransactionExecutor implements Closeable {
* exception" class (08001/08003/08004/08006/08007/08S01).
*
*
- *
The walk traverses both {@link Throwable#getCause()} and {@link SQLException#getNextException()}
- * so wrapped/chained variants (e.g. RuntimeException-wrapped, Hikari-wrapped, batch error chains)
- * are detected. SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other
+ *
The walk includes causes, chained SQL exceptions and suppressed cleanup failures.
+ * SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other
* adjacent classes are intentionally NOT counted — those are not connection failures.
*/
private static boolean isConnectionFailure(Throwable t) {
@@ -763,78 +763,106 @@ private static boolean isConnectionFailure(Throwable t) {
if (cause != null) {
stack.push(cause);
}
+ Collections.addAll(stack, cur.getSuppressed());
}
return false;
}
void executeTransaction(Container container, boolean autoCommit, Transaction transaction,
Callback callback) {
+ executeTransactionGeneric(autoCommit,
+ connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback);
+ }
+
+ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) {
final long enqueueTimeMs = System.currentTimeMillis();
try {
executor.submit(() -> {
enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs);
- try (Connection connection = dataSource.getConnection()) {
- T result;
- if (autoCommit) {
- result = transaction.run(container.getParentAccountId(), container.getId(), connection);
- } else {
- // if autocommit is set to false, treat this as a multi-step txn that requires an explicit commit/rollback
- connection.setAutoCommit(false);
- try {
- result = transaction.run(container.getParentAccountId(), container.getId(), connection);
- connection.commit();
- } catch (Exception e) {
- connection.rollback();
- throw e;
- } finally {
- connection.setAutoCommit(true);
- }
- }
- callback.onCompletion(result, null);
- } catch (Exception e) {
+ T result;
+ try {
+ result = runTransaction(autoCommit, transaction);
+ } catch (Exception | Error e) {
if (isConnectionFailure(e)) {
connectionFailureCount.inc();
}
- callback.onCompletion(null, e);
+ callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e));
+ return;
}
+ callback.onCompletion(result, null);
});
} catch (RejectedExecutionException e) {
rejectTransaction(callback, e);
}
}
- void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) {
- final long enqueueTimeMs = System.currentTimeMillis();
+ private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception {
+ Connection connection = dataSource.getConnection();
+ final T result;
try {
- executor.submit(() -> {
- enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs);
- try (Connection connection = dataSource.getConnection()) {
- T result;
- if (autoCommit) {
- result = transaction.run(connection);
- } else {
- // if autocommit is set to false, treat this as a multi-step txn that requires an explicit commit/rollback
- connection.setAutoCommit(false);
- try {
- result = transaction.run(connection);
- connection.commit();
- } catch (Exception e) {
- connection.rollback();
- throw e;
- } finally {
- connection.setAutoCommit(true);
- }
- }
- callback.onCompletion(result, null);
- } catch (Exception e) {
- if (isConnectionFailure(e)) {
- connectionFailureCount.inc();
+ if (!autoCommit) {
+ connection.setAutoCommit(false);
+ }
+ result = transaction.run(connection);
+ if (!autoCommit) {
+ connection.commit();
+ }
+ } catch (Exception | Error failure) {
+ if (!autoCommit) {
+ try {
+ connection.rollback();
+ } catch (Exception | Error rollbackFailure) {
+ // Returning an unresolved transaction to the pool could commit it when autocommit is restored.
+ discardConnection(connection, rollbackFailure);
+ if (failure != rollbackFailure) {
+ failure.addSuppressed(rollbackFailure);
}
- callback.onCompletion(null, e);
+ throw failure;
}
- });
- } catch (RejectedExecutionException e) {
- rejectTransaction(callback, e);
+ }
+ returnConnection(connection, autoCommit, failure);
+ throw failure;
+ }
+ returnConnection(connection, autoCommit, null);
+ return result;
+ }
+
+ private void returnConnection(Connection connection, boolean autoCommit, Throwable operationFailure) {
+ try {
+ if (!autoCommit) {
+ try {
+ connection.setAutoCommit(true);
+ } catch (Exception | Error resetFailure) {
+ // Hikari can recycle a connection even when a reset inside close() fails.
+ discardConnection(connection, resetFailure);
+ throw resetFailure;
+ }
+ }
+ connection.close();
+ } catch (Exception | Error cleanupFailure) {
+ metrics.connectionCloseErrorCount.inc();
+ if (operationFailure == null) {
+ if (isConnectionFailure(cleanupFailure)) {
+ connectionFailureCount.inc();
+ }
+ } else if (operationFailure != cleanupFailure) {
+ operationFailure.addSuppressed(cleanupFailure);
+ }
+ logger.error("Failed to return a named blob DB connection in {}", datacenter, cleanupFailure);
+ }
+ }
+
+ private void discardConnection(Connection connection, Throwable failure) {
+ try {
+ if (dataSource instanceof HikariDataSource) {
+ ((HikariDataSource) dataSource).evictConnection(connection);
+ } else {
+ connection.abort(Runnable::run);
+ }
+ } catch (Exception | Error discardFailure) {
+ if (failure != discardFailure) {
+ failure.addSuppressed(discardFailure);
+ }
}
}
diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java
index 397bf14def..bb89f0b2c1 100644
--- a/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java
+++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/MySqlNamedBlobDbTest.java
@@ -34,6 +34,7 @@
import com.github.ambry.rest.RestServiceException;
import com.github.ambry.utils.TestUtils;
import com.github.ambry.utils.Utils;
+import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
@@ -62,6 +63,7 @@
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
+import org.mockito.InOrder;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
@@ -124,6 +126,169 @@ public void testRetryDeleteNamedBlob() throws Exception {
checkErrorCode(() -> namedBlobDb.delete(account.getName(), container.getName(), "blobName"), RestServiceErrorCode.NotFound);
}
+ @Test
+ public void testHardDeleteReturnsVersionsWhenPoolReturnFails() throws Exception {
+ Connection connection = mock(Connection.class);
+ DataSource source = mock(DataSource.class);
+ when(source.getConnection()).thenReturn(connection);
+ PreparedStatement mutation = mockHardDelete(connection);
+ doThrow(new SQLException("Failed to return connection", "08006")).when(connection).close();
+ Metrics metrics = new Metrics(new MetricRegistry(), "");
+ try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) {
+ DeleteResult result = db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS);
+ assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false)),
+ result.getBlobVersions());
+ InOrder order = inOrder(mutation, connection);
+ order.verify(mutation).executeUpdate();
+ order.verify(connection).commit();
+ order.verify(connection).close();
+ verify(connection, never()).rollback();
+ assertEquals(1, metrics.connectionCloseErrorCount.getCount());
+ assertEquals(0, metrics.namedBlobDBDeleteErrorCount.getCount());
+ assertEquals(1, localConnectionFailures(metrics));
+ }
+ }
+
+ @Test
+ public void testCommitFailureRemainsPrimaryWhenPoolReturnFails() throws Exception {
+ Connection connection = mock(Connection.class);
+ DataSource source = mock(DataSource.class);
+ when(source.getConnection()).thenReturn(connection);
+ mockHardDelete(connection);
+ SQLException commitFailure = new SQLException("Commit not acknowledged");
+ doThrow(commitFailure).when(connection).commit();
+ doThrow(new SQLException("Failed to return connection")).when(connection).close();
+ Metrics metrics = new Metrics(new MetricRegistry(), "");
+ try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) {
+ TestUtils.assertException(ExecutionException.class,
+ () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS),
+ e -> assertSame(commitFailure, e.getCause()));
+ verify(connection).rollback();
+ assertEquals(1, metrics.connectionCloseErrorCount.getCount());
+ assertEquals(1, metrics.namedBlobDBDeleteErrorCount.getCount());
+ }
+ }
+
+ @Test
+ public void testResetFailureAfterCommitEvictsHikariConnection() throws Exception {
+ Connection broken = mock(Connection.class);
+ Connection replacement = mock(Connection.class);
+ mockHardDelete(broken);
+ // A non-connection SQLState is not fatal to Hikari. The executor must evict before returning this connection.
+ doThrow(new SQLException("Autocommit reset failed", "HY000")).doNothing().when(broken).setAutoCommit(true);
+ Metrics metrics = new Metrics(new MetricRegistry(), "");
+ try (HikariDataSource pool = singleConnectionPool(broken, replacement);
+ MySqlNamedBlobDb db = hardDeleteDb(pool, metrics)) {
+ DeleteResult result = db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS);
+ assertEquals(Arrays.asList(new DeleteResult.BlobVersion(id, 2, false), new DeleteResult.BlobVersion(id, 1, false)),
+ result.getBlobVersions());
+ InOrder order = inOrder(broken);
+ order.verify(broken).commit();
+ order.verify(broken).setAutoCommit(true);
+ verify(broken, never()).rollback();
+ try (Connection next = pool.getConnection()) {
+ assertSame(replacement, next.unwrap(Connection.class));
+ }
+ assertEquals(0, metrics.namedBlobDBDeleteErrorCount.getCount());
+ assertEquals(1, metrics.connectionCloseErrorCount.getCount());
+ assertEquals(0, localConnectionFailures(metrics));
+ }
+ }
+
+ @Test
+ public void testResetFailureAfterRollbackPreservesCommitFailure() throws Exception {
+ Connection connection = mock(Connection.class);
+ DataSource source = mock(DataSource.class);
+ when(source.getConnection()).thenReturn(connection);
+ mockHardDelete(connection);
+ SQLException commitFailure = new SQLException("Commit not acknowledged");
+ SQLException resetFailure = new SQLException("Connection lost resetting autocommit", "08006");
+ doThrow(commitFailure).when(connection).commit();
+ doThrow(resetFailure).when(connection).setAutoCommit(true);
+ Metrics metrics = new Metrics(new MetricRegistry(), "");
+ try (MySqlNamedBlobDb db = hardDeleteDb(source, metrics)) {
+ TestUtils.assertException(ExecutionException.class,
+ () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS),
+ e -> assertSame(commitFailure, e.getCause()));
+ assertArrayEquals(new Throwable[]{resetFailure}, commitFailure.getSuppressed());
+ InOrder order = inOrder(connection);
+ order.verify(connection).rollback();
+ order.verify(connection).setAutoCommit(true);
+ order.verify(connection).abort(any());
+ verify(connection, never()).close();
+ assertEquals(1, metrics.namedBlobDBDeleteErrorCount.getCount());
+ assertEquals(1, metrics.connectionCloseErrorCount.getCount());
+ assertEquals(1, localConnectionFailures(metrics));
+ }
+ }
+
+ private long localConnectionFailures(Metrics metrics) {
+ return metrics.getMetricRegistry().getCounters()
+ .get(MetricRegistry.name(MySqlNamedBlobDb.class, "NamedBlobDBConnectionFailureCount." + localDatacenter))
+ .getCount();
+ }
+
+ private HikariDataSource singleConnectionPool(Connection broken, Connection replacement) throws SQLException {
+ DataSource physicalSource = mock(DataSource.class);
+ for (Connection physical : Arrays.asList(broken, replacement)) {
+ when(physical.getAutoCommit()).thenReturn(true);
+ when(physical.isValid(anyInt())).thenReturn(true);
+ }
+ when(physicalSource.getConnection()).thenReturn(broken, replacement);
+ HikariDataSource pool = new HikariDataSource();
+ pool.setDataSource(physicalSource);
+ pool.setMaximumPoolSize(1);
+ pool.setMinimumIdle(0);
+ pool.setInitializationFailTimeout(-1);
+ pool.setConnectionTimeout(3000);
+ return pool;
+ }
+
+ @Test
+ public void testRollbackFailureEvictsHikariConnection() throws Exception {
+ Connection broken = mock(Connection.class);
+ Connection replacement = mock(Connection.class);
+ AssertionError failure = new AssertionError("Transaction interrupted");
+ when(broken.prepareStatement(startsWith("SELECT"))).thenThrow(failure);
+ SQLException rollbackFailure = new SQLException("Rollback failed");
+ doThrow(rollbackFailure).when(broken).rollback();
+ try (HikariDataSource pool = singleConnectionPool(broken, replacement)) {
+ try (MySqlNamedBlobDb db = hardDeleteDb(pool, new Metrics(new MetricRegistry(), ""))) {
+ TestUtils.assertException(ExecutionException.class,
+ () -> db.delete(account.getName(), container.getName(), "name").get(5, TimeUnit.SECONDS),
+ e -> assertSame(failure, e.getCause().getCause()));
+ assertArrayEquals(new Throwable[]{rollbackFailure}, failure.getSuppressed());
+ try (Connection next = pool.getConnection()) {
+ assertSame(replacement, next.unwrap(Connection.class));
+ }
+ verify(broken, never()).setAutoCommit(true);
+ verify(broken, never()).commit();
+ }
+ }
+ }
+
+ private MySqlNamedBlobDb hardDeleteDb(DataSource localSource, Metrics metrics) {
+ Properties props = new Properties();
+ props.setProperty(MySqlNamedBlobDbConfig.DB_INFO, buildSmallPoolConfig(1, 1, 1).dbInfo);
+ props.setProperty(MySqlNamedBlobDbConfig.ENABLE_HARD_DELETE, "true");
+ return new MySqlNamedBlobDb(accountService, new MySqlNamedBlobDbConfig(new VerifiableProperties(props)),
+ endpoint -> localDatacenter.equals(endpoint.getDatacenter()) ? localSource : mock(DataSource.class),
+ localDatacenter, metrics);
+ }
+
+ private PreparedStatement mockHardDelete(Connection connection) throws SQLException {
+ PreparedStatement select = mock(PreparedStatement.class);
+ ResultSet versions = mock(ResultSet.class);
+ when(connection.prepareStatement(startsWith("SELECT"))).thenReturn(select);
+ when(select.executeQuery()).thenReturn(versions);
+ when(versions.next()).thenReturn(true, true, false);
+ when(versions.getBytes(1)).thenReturn(Utils.base64DecodeUrlSafe(id));
+ when(versions.getLong(2)).thenReturn(2L, 1L);
+ PreparedStatement mutation = mock(PreparedStatement.class);
+ when(connection.prepareStatement(startsWith("DELETE"))).thenReturn(mutation);
+ return mutation;
+ }
+
/**
* Test connection failure.
*/