diff --git a/modules/jdbc-pool/doc/jdbc-pool.xml b/modules/jdbc-pool/doc/jdbc-pool.xml index a51acb9c7b4a..10ffb2f40f1d 100644 --- a/modules/jdbc-pool/doc/jdbc-pool.xml +++ b/modules/jdbc-pool/doc/jdbc-pool.xml @@ -584,6 +584,16 @@ Default value is false.

+ +

(boolean) If true, the pool sends the JDBC 4.3 request boundary hints to the driver: + Connection.beginRequest() when a connection is borrowed and + Connection.endRequest() when it is returned. The behaviour of these hints is vendor specific + and some drivers close the statements created during the request in endRequest(), so the + hints are not sent for a connection that uses the StatementCache interceptor. Do not enable + this attribute if a custom interceptor or the application keeps statements across borrows. + Default value is false.
+

+

(boolean) If autoCommit==false then the pool can complete the transaction by calling commit on the connection as it is returned to the pool If rollbackOnReturn==true then this attribute is ignored. diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java index efeffef9d994..44dd28b99664 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java @@ -585,7 +585,9 @@ private Connection setupConnection(PooledConnection con, boolean countBorrow) th // optimises per-request session handling knows the unit of work // begins here. The matching endRequest() is sent at the return, // in returnConnection(). - invokeRequestHint(BEGIN_REQUEST, con.getConnection()); + if (sendRequestHints(con)) { + invokeRequestHint(BEGIN_REQUEST, con.getConnection()); + } } catch (Throwable x) { ExceptionUtils.handleThrowable(x); SQLException s = new SQLException(); @@ -680,6 +682,30 @@ private static Method getRequestHintMethod(String methodName) { } } + /** + * Determines whether the JDBC 4.3 request boundary hints are sent for a pooled connection. + * + * @param con the pooled connection, with its interceptor chain already built + * + * @return {@code true} if the hints are enabled and no statement cache is part of the connection's interceptor + * chain + */ + private boolean sendRequestHints(PooledConnection con) { + if (!getPoolProperties().isUseRequestBoundaries()) { + return false; + } + // The driver may close the statements of a request in endRequest() - the behaviour of the hints is vendor + // specific - while a statement cache hands a statement of one borrow to the next borrow of the session. + JdbcInterceptor interceptor = con.getHandler(); + while (interceptor != null) { + if (interceptor instanceof StatementCache) { + return false; + } + interceptor = interceptor.getNext(); + } + return true; + } + /** * Sends one of the JDBC 4.3 request boundary hints to a physical connection. The hint is advisory - the * specification lets the driver treat it as a no-op - so a driver that refuses one does not fail the borrow or the @@ -2224,7 +2250,9 @@ private void returnConnection(PooledConnection con, boolean countReturn) { // discarded instead of going back to the pool is // not hinted; it is about to be closed, which // subsumes the hint. - invokeRequestHint(END_REQUEST, con.getConnection()); + if (sendRequestHints(con)) { + invokeRequestHint(END_REQUEST, con.getConnection()); + } if (isClosed()) { // The pool closed while this return was in // flight: the checks above each read the flag diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java index cbeb20e4524d..eb15ac05be75 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceFactory.java @@ -207,6 +207,9 @@ public DataSourceFactory() { /** The {@code rollbackOnReturn} property name. */ protected static final String PROP_ROLLBACKONRETURN = "rollbackOnReturn"; + /** The {@code useRequestBoundaries} property name. */ + protected static final String PROP_USEREQUESTBOUNDARIES = "useRequestBoundaries"; + /** * Property name for useDisposableConnectionFacade. The property is deprecated and has no effect; the disposable * connection facade is always used. @@ -254,7 +257,7 @@ public DataSourceFactory() { PROP_ABANDONWHENPERCENTAGEFULL, PROP_MAXAGE, PROP_USE_LOCK, PROP_DATASOURCE, PROP_DATASOURCE_JNDI, PROP_SUSPECT_TIMEOUT, PROP_ALTERNATE_USERNAME_ALLOWED, PROP_COMMITONRETURN, PROP_ROLLBACKONRETURN, PROP_USEDISPOSABLECONNECTIONFACADE, PROP_LOGVALIDATIONERRORS, PROP_PROPAGATEINTERRUPTSTATE, - PROP_IGNOREEXCEPTIONONPRELOAD, PROP_USESTATEMENTFACADE }; + PROP_IGNOREEXCEPTIONONPRELOAD, PROP_USESTATEMENTFACADE, PROP_USEREQUESTBOUNDARIES }; /** * Names of the reference addresses that the JNDI container itself places @@ -917,6 +920,14 @@ public static PoolConfiguration parsePoolProperties(Properties properties) { } } + value = properties.getProperty(PROP_USEREQUESTBOUNDARIES); + if (value != null) { + Boolean b = parseBoolean(PROP_USEREQUESTBOUNDARIES, value); + if (b != null) { + poolProperties.setUseRequestBoundaries(b.booleanValue()); + } + } + value = properties.getProperty(PROP_USEDISPOSABLECONNECTIONFACADE); if (value != null) { Boolean b = parseBoolean(PROP_USEDISPOSABLECONNECTIONFACADE, value); diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java index fcbd3045c188..8196a9caf49d 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/DataSourceProxy.java @@ -1589,6 +1589,16 @@ public boolean getRollbackOnReturn() { return getPoolProperties().getRollbackOnReturn(); } + @Override + public void setUseRequestBoundaries(boolean useRequestBoundaries) { + getPoolProperties().setUseRequestBoundaries(useRequestBoundaries); + } + + @Override + public boolean isUseRequestBoundaries() { + return getPoolProperties().isUseRequestBoundaries(); + } + /** * {@inheritDoc} * diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java index 8323a70db4a8..865643dea851 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolConfiguration.java @@ -1077,6 +1077,27 @@ public interface PoolConfiguration { */ boolean getRollbackOnReturn(); + /** + * Set to true if you want the connection pool to send the JDBC 4.3 request boundary hints to the driver: + * {@link java.sql.Connection#beginRequest()} when a connection is borrowed and + * {@link java.sql.Connection#endRequest()} when it is returned. The behaviour of these hints is vendor specific and + * some drivers close the statements created during the request in {@code endRequest()}, so the hints are never + * sent for a connection whose interceptor chain includes a + * {@link org.apache.tomcat.jdbc.pool.interceptor.StatementCache}. The hints are not sent on a runtime that + * predates JDBC 4.3. The default value is false. + * + * @param useRequestBoundaries set to true if the pool should send the request boundary hints + */ + void setUseRequestBoundaries(boolean useRequestBoundaries); + + /** + * Returns whether the pool sends the JDBC 4.3 request boundary hints. See + * {@link PoolConfiguration#setUseRequestBoundaries(boolean)} for details. + * + * @return {@code true} if the pool should send the request boundary hints + */ + boolean isUseRequestBoundaries(); + /** * Stores the value of the deprecated {@code useDisposableConnectionFacade} property. The pool always wraps the * connection handle in a facade that disallows use of the connection after {@link java.sql.Connection#close()} has diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java index aa143ce6891d..fe0414f19c77 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.java @@ -181,6 +181,8 @@ public PoolProperties() { private volatile boolean commitOnReturn = false; /** Whether to rollback on connection return. */ private volatile boolean rollbackOnReturn = false; + /** Whether to send the JDBC 4.3 request boundary hints. */ + private volatile boolean useRequestBoundaries = false; /** * Whether to use a disposable connection facade. * @@ -2288,6 +2290,16 @@ public boolean getRollbackOnReturn() { return this.rollbackOnReturn; } + @Override + public void setUseRequestBoundaries(boolean useRequestBoundaries) { + this.useRequestBoundaries = useRequestBoundaries; + } + + @Override + public boolean isUseRequestBoundaries() { + return this.useRequestBoundaries; + } + /** * {@inheritDoc} * diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java index 054104531033..86cf1df45903 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/jmx/ConnectionPool.java @@ -1253,6 +1253,16 @@ public boolean getRollbackOnReturn() { return getPoolProperties().getRollbackOnReturn(); } + @Override + public void setUseRequestBoundaries(boolean useRequestBoundaries) { + getPoolProperties().setUseRequestBoundaries(useRequestBoundaries); + } + + @Override + public boolean isUseRequestBoundaries() { + return getPoolProperties().isUseRequestBoundaries(); + } + /** * {@inheritDoc} * diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml index 1e78ab914d0c..20cbf6cca0ae 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/mbeans-descriptors.xml @@ -277,6 +277,12 @@ is="false" writeable="false"/> + + driverClass) throws SQLException { + return hintCountingDataSource(driverClass, true, null); + } + + private DataSource hintCountingDataSource(Class driverClass, boolean useRequestBoundaries, + String jdbcInterceptors) throws SQLException { BEGIN_REQUEST_COUNT.set(0); END_REQUEST_COUNT.set(0); DataSource ds = newDataSource(); ds.setDriverClassName(driverClass.getName()); + ds.getPoolProperties().setUseRequestBoundaries(useRequestBoundaries); + ds.getPoolProperties().setJdbcInterceptors(jdbcInterceptors); // start empty: no physical connection, so no pool-start traffic to // discount from the counts asserted below ds.getPoolProperties().setInitialSize(0); @@ -121,6 +133,30 @@ void hintsBracketEachBorrowOfTheSameSession() throws Exception { "both borrows ran on the same physical session"); } + @Test + void hintsAreNotSentByDefault() throws Exception { + assumeRequestHintsExist(); + DataSource ds = hintCountingDataSource(HintCountingDriver.class, false, null); + + try (@SuppressWarnings("unused") Connection con = ds.getConnection()) { + Assertions.assertEquals(0, BEGIN_REQUEST_COUNT.get(), "the hints are disabled by default"); + } + Assertions.assertEquals(0, END_REQUEST_COUNT.get(), "the hints are disabled by default"); + } + + @Test + void hintsAreNotSentWithAStatementCache() throws Exception { + assumeRequestHintsExist(); + DataSource ds = hintCountingDataSource(HintCountingDriver.class, true, "StatementCache"); + + try (@SuppressWarnings("unused") Connection con = ds.getConnection()) { + Assertions.assertEquals(0, BEGIN_REQUEST_COUNT.get(), + "a cached statement outlives the request, so no request is started"); + } + Assertions.assertEquals(0, END_REQUEST_COUNT.get(), + "a cached statement outlives the request, so no request is ended"); + } + @Test void aDriverThatRefusesTheHintsNeitherFailsTheBorrowNorTheReturn() throws Exception { assumeRequestHintsExist(); @@ -143,6 +179,47 @@ void aDriverThatRefusesTheHintsNeitherFailsTheBorrowNorTheReturn() throws Except "the refused hints must not have cost the pool its session"); } + /* + * https://bz.apache.org/bugzilla/show_bug.cgi?id=70370 + * + * The JDBC 4.3 hints leave the behaviour of endRequest() to the driver, and some drivers (e.g. the Microsoft SQL + * Server driver) close every statement created during the request. A statement parked by StatementCache outlives + * the request it was prepared in, so the next borrower must not be handed a statement the driver has closed. + */ + @Test + void aStatementCacheSurvivesADriverThatClosesTheStatementsOfTheRequest() throws Exception { + doTestStatementCacheWithStatementClosingDriver(false); + } + + @Test + void aStatementCacheSurvivesADriverThatClosesTheStatementsOfTheRequestWithHintsEnabled() throws Exception { + doTestStatementCacheWithStatementClosingDriver(true); + } + + private void doTestStatementCacheWithStatementClosingDriver(boolean useRequestBoundaries) throws Exception { + assumeRequestHintsExist(); + DataSource ds = newDataSource(); + ds.setDriverClassName(StatementClosingDriver.class.getName()); + ds.getPoolProperties().setUseRequestBoundaries(useRequestBoundaries); + ds.getPoolProperties().setInitialSize(0); + ds.getPoolProperties().setMaxActive(1); + ds.getPoolProperties().setJdbcInterceptors("StatementCache(prepared=true,callable=false,max=50)"); + ds.createPool(); + + for (int i = 0; i < 3; i++) { + try (Connection con = ds.getConnection(); + PreparedStatement ps = con.prepareStatement("SELECT ?")) { + ps.setInt(1, i); + try (ResultSet rs = ps.executeQuery()) { + Assertions.assertTrue(rs.next()); + Assertions.assertEquals(i, rs.getInt(1)); + } + } + } + Assertions.assertEquals(1, poolSessions(), "all borrows ran on the same physical session"); + } + + /** * Driver that counts the request boundary hints reaching the physical * connection it returns. Configured through {@code driverClassName}, @@ -214,6 +291,83 @@ protected boolean refuseHints() { } } + /** + * Driver that behaves like a driver whose endRequest() closes the statements created since beginRequest(), as the + * Microsoft SQL Server driver does. Configured through {@code driverClassName}, so it must stay a public static + * class with a no-arg constructor. + */ + public static class StatementClosingDriver extends HintCountingDriver { + + @Override + public Connection connect(String url, Properties info) throws SQLException { + Connection connection = new org.h2.Driver().connect(url, info); + if (connection == null) { + return null; + } + return (Connection) Proxy.newProxyInstance( + StatementClosingDriver.class.getClassLoader(), + new Class[] { Connection.class }, + statementCloser(connection)); + } + } + + private static Object statementOf(Statement vendor, Class type, Connection connection) { + return Proxy.newProxyInstance(StatementClosingDriver.class.getClassLoader(), new Class[] { type }, + new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if ("getConnection".equals(method.getName())) { + return connection; + } + try { + return method.invoke(vendor, args); + } catch (InvocationTargetException x) { + throw x.getCause(); + } + } + }); + } + + private static InvocationHandler statementCloser(Connection vendor) { + return new InvocationHandler() { + private List requestStatements = null; + + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + String name = method.getName(); + if ("beginRequest".equals(name)) { + if (requestStatements == null) { + requestStatements = new ArrayList<>(); + } + return null; + } else if ("endRequest".equals(name)) { + if (requestStatements != null) { + for (Statement statement : requestStatements) { + statement.close(); + } + requestStatements = null; + } + return null; + } + Object result; + try { + result = method.invoke(vendor, args); + } catch (InvocationTargetException x) { + throw x.getCause(); + } + if (result instanceof Statement) { + // A driver's statement answers getConnection() with the driver's connection, here the proxy + result = statementOf((Statement) result, method.getReturnType(), (Connection) proxy); + if (requestStatements != null) { + requestStatements.add((Statement) result); + } + } + return result; + } + }; + } + + /* * Counts the two hint methods by name and delegates everything, the * hints included, to the H2 connection; by name, because this suite diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml index 5bffc731850e..7edf06d688e2 100644 --- a/webapps/docs/changelog.xml +++ b/webapps/docs/changelog.xml @@ -524,6 +524,15 @@ + + 70370: Only send the JDBC 4.3 request boundary hints when the + new useRequestBoundaries attribute is enabled, and never + for a connection that uses the StatementCache interceptor. + Some drivers, such as the Microsoft SQL Server driver, close the + statements created during a request when the request ends, so a + statement cached by StatementCache was closed before it + was used again. Pull request 1268 provided by Arturo Bernal. +