-
Notifications
You must be signed in to change notification settings - Fork 121
Add db connection pool support #791
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
arturmkr
wants to merge
2
commits into
trinodb:main
Choose a base branch
from
arturmkr:feature/add-db-connection-pool-support
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,6 +14,8 @@ | |
| package io.trino.gateway.ha.persistence; | ||
|
|
||
| import com.google.common.annotations.VisibleForTesting; | ||
| import com.zaxxer.hikari.HikariConfig; | ||
| import com.zaxxer.hikari.HikariDataSource; | ||
| import io.airlift.log.Logger; | ||
| import io.trino.gateway.ha.config.DataStoreConfiguration; | ||
| import io.trino.gateway.ha.persistence.dao.QueryHistoryDao; | ||
|
|
@@ -24,6 +26,8 @@ | |
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.nio.file.Path; | ||
| import java.util.Map; | ||
| import java.util.concurrent.ConcurrentHashMap; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.ScheduledExecutorService; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
@@ -39,6 +43,8 @@ public class JdbcConnectionManager | |
| private final ScheduledExecutorService executorService = | ||
| Executors.newSingleThreadScheduledExecutor(); | ||
|
|
||
| private final Map<String, HikariDataSource> pools = new ConcurrentHashMap<>(); | ||
|
|
||
| public JdbcConnectionManager(Jdbi jdbi, DataStoreConfiguration configuration) | ||
| { | ||
| this.jdbi = requireNonNull(jdbi, "jdbi is null") | ||
|
|
@@ -59,7 +65,18 @@ public Jdbi getJdbi(@Nullable String routingGroupDatabase) | |
| return jdbi; | ||
| } | ||
|
|
||
| return Jdbi.create(buildJdbcUrl(routingGroupDatabase), configuration.getUser(), configuration.getPassword()) | ||
| Integer maxPoolSize = configuration.getMaxPoolSize(); | ||
| if (maxPoolSize != null && maxPoolSize > 0) { | ||
| HikariDataSource ds = getOrCreateDataSource(routingGroupDatabase, maxPoolSize); | ||
| return Jdbi.create(ds) | ||
| .installPlugin(new SqlObjectPlugin()) | ||
| .registerRowMapper(new RecordAndAnnotatedConstructorMapper()); | ||
| } | ||
|
|
||
| return Jdbi.create( | ||
| buildJdbcUrl(routingGroupDatabase), | ||
| configuration.getUser(), | ||
| configuration.getPassword()) | ||
| .installPlugin(new SqlObjectPlugin()) | ||
| .registerRowMapper(new RecordAndAnnotatedConstructorMapper()); | ||
| } | ||
|
|
@@ -107,11 +124,51 @@ private void startCleanUps() | |
| executorService.scheduleWithFixedDelay( | ||
| () -> { | ||
| log.info("Performing query history cleanup task"); | ||
| long created = System.currentTimeMillis() - TimeUnit.HOURS.toMillis(this.configuration.getQueryHistoryHoursRetention()); | ||
| long created = System.currentTimeMillis() | ||
| - TimeUnit.HOURS.toMillis(this.configuration.getQueryHistoryHoursRetention()); | ||
| jdbi.onDemand(QueryHistoryDao.class).deleteOldHistory(created); | ||
| }, | ||
| 1, | ||
| 120, | ||
| TimeUnit.MINUTES); | ||
| } | ||
|
|
||
| private HikariDataSource getOrCreateDataSource(String routingGroupDatabase, int maxPoolSize) | ||
| { | ||
| return pools.compute(routingGroupDatabase, (key, existing) -> { | ||
| if (existing != null && !existing.isClosed()) { | ||
| return existing; | ||
| } | ||
|
|
||
| HikariConfig cfg = new HikariConfig(); | ||
| cfg.setJdbcUrl(buildJdbcUrl(key)); | ||
| cfg.setUsername(configuration.getUser()); | ||
| cfg.setPassword(configuration.getPassword()); | ||
| if (configuration.getDriver() != null) { | ||
| cfg.setDriverClassName(configuration.getDriver()); | ||
| } | ||
| cfg.setMaximumPoolSize(maxPoolSize); | ||
| cfg.setPoolName("gateway-ha-" + key); | ||
|
|
||
| return new HikariDataSource(cfg); | ||
| }); | ||
| } | ||
|
|
||
| public void close() | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. question: is this only used by tests? I don't see where it's being called otherwise
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. fixed |
||
| { | ||
| for (Map.Entry<String, HikariDataSource> e : pools.entrySet()) { | ||
| HikariDataSource ds = e.getValue(); | ||
| if (ds != null && !ds.isClosed()) { | ||
| try { | ||
| ds.close(); | ||
| } | ||
| catch (RuntimeException ex) { | ||
| log.warn(ex, "Failed to close datasource for key: %s", e.getKey()); | ||
| } | ||
| } | ||
| } | ||
| pools.clear(); | ||
|
|
||
| executorService.shutdownNow(); | ||
| } | ||
| } | ||
175 changes: 175 additions & 0 deletions
175
gateway-ha/src/test/java/io/trino/gateway/ha/persistence/TestJdbcConnectionManagerPool.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| /* | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package io.trino.gateway.ha.persistence; | ||
|
|
||
| import io.trino.gateway.ha.config.DataStoreConfiguration; | ||
| import org.jdbi.v3.core.Jdbi; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| import java.nio.file.Path; | ||
| import java.sql.Connection; | ||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.concurrent.CountDownLatch; | ||
| import java.util.concurrent.ExecutorService; | ||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.Future; | ||
| import java.util.concurrent.TimeUnit; | ||
| import java.util.concurrent.TimeoutException; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| final class TestJdbcConnectionManagerPool | ||
| { | ||
| @Test | ||
| void blocksWhenExceedingMaxPoolSize() | ||
| throws Exception | ||
| { | ||
| String dbPath = Path.of(System.getProperty("java.io.tmpdir"), "h2db-pool-" + System.currentTimeMillis()).toString(); | ||
| String jdbcUrl = "jdbc:h2:" + dbPath; | ||
|
|
||
| DataStoreConfiguration cfg = new DataStoreConfiguration( | ||
| jdbcUrl, "sa", "sa", "org.h2.Driver", | ||
| 4, true, | ||
| 2); | ||
|
|
||
| JdbcConnectionManager cm = new JdbcConnectionManager(Jdbi.create(jdbcUrl, "sa", "sa"), cfg); | ||
| Jdbi jdbi = cm.getJdbi("testdb"); | ||
|
|
||
| try (ExecutorService es = Executors.newFixedThreadPool(3)) { | ||
| List<Future<Connection>> acquired = new ArrayList<>(); | ||
|
|
||
| CountDownLatch hold = new CountDownLatch(1); | ||
| CountDownLatch acquiredLatch = new CountDownLatch(2); | ||
|
|
||
| // Open exactly maxPoolSize connections and keep them open | ||
| for (int i = 0; i < 2; i++) { | ||
| acquired.add(es.submit(() -> { | ||
| try (var h = jdbi.open()) { | ||
| acquiredLatch.countDown(); | ||
| boolean released = hold.await(10, TimeUnit.SECONDS); | ||
| assertThat(released).as("hold latch should be released by the test").isTrue(); | ||
| } | ||
| return null; | ||
| })); | ||
| } | ||
|
|
||
| // Wait until both connections are actually acquired (avoid race) | ||
| boolean bothAcquired = acquiredLatch.await(3, TimeUnit.SECONDS); | ||
| assertThat(bothAcquired).as("both connections should be acquired before third attempt").isTrue(); | ||
|
|
||
| // Third attempt should block since the pool is full | ||
| Future<Boolean> third = es.submit(() -> { | ||
| var h = jdbi.open(); | ||
| h.close(); | ||
| return true; | ||
| }); | ||
|
|
||
| boolean completedIn200ms = false; | ||
| try { | ||
| third.get(200, TimeUnit.MILLISECONDS); | ||
| completedIn200ms = true; // if this happens when connection was not blocked, which is wrong | ||
| } | ||
| catch (TimeoutException expected) { | ||
| // expected, means the request was blocked on the pool | ||
| } | ||
|
|
||
| assertThat(completedIn200ms) | ||
| .as("third getJdbi().open() should be blocked by maxPoolSize=2") | ||
| .isFalse(); | ||
|
|
||
| // Release the first two connections, the third one should complete now | ||
| hold.countDown(); | ||
| assertThat(third.get(3, TimeUnit.SECONDS)).isTrue(); | ||
|
|
||
| // Wait for the first two to finish gracefully | ||
| for (Future<Connection> f : acquired) { | ||
| f.get(3, TimeUnit.SECONDS); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void doesNotBlockWhenMaxPoolSizeIsNull() | ||
| throws Exception | ||
| { | ||
| String dbPath = Path.of(System.getProperty("java.io.tmpdir"), "h2db-nopool-" + System.currentTimeMillis()).toString(); | ||
| String jdbcUrl = "jdbc:h2:" + dbPath; | ||
|
|
||
| // maxPoolSize == null -> no pool path | ||
| DataStoreConfiguration cfg = new DataStoreConfiguration( | ||
| jdbcUrl, "sa", "sa", "org.h2.Driver", | ||
| 4, true); | ||
|
|
||
| JdbcConnectionManager cm = new JdbcConnectionManager(Jdbi.create(jdbcUrl, "sa", "sa"), cfg); | ||
| Jdbi jdbi = cm.getJdbi("testdb"); | ||
|
|
||
| try (ExecutorService es = Executors.newFixedThreadPool(3)) { | ||
| try { | ||
| CountDownLatch hold = new CountDownLatch(1); | ||
| CountDownLatch acquiredLatch = new CountDownLatch(2); | ||
|
|
||
| // Open two connections and keep them open | ||
| for (int i = 0; i < 2; i++) { | ||
| es.submit(() -> { | ||
| try (var h = jdbi.open()) { | ||
| acquiredLatch.countDown(); | ||
| boolean released = hold.await(10, TimeUnit.SECONDS); | ||
| assertThat(released).isTrue(); | ||
| } | ||
| return null; | ||
| }); | ||
| } | ||
|
|
||
| // Wait until both connections are really open (avoid race conditions) | ||
| boolean bothAcquired = acquiredLatch.await(3, TimeUnit.SECONDS); | ||
| assertThat(bothAcquired).isTrue(); | ||
|
|
||
| // Third connection attempt should NOT block since no pool is used | ||
| Future<Boolean> third = es.submit(() -> { | ||
| var h = jdbi.open(); | ||
| h.close(); | ||
| return true; | ||
| }); | ||
|
|
||
| boolean completedIn200ms; | ||
| try { | ||
| third.get(200, TimeUnit.MILLISECONDS); | ||
| completedIn200ms = true; // not blocked - expected behavior | ||
| } | ||
| catch (TimeoutException ignore) { | ||
| completedIn200ms = false; // blocked - incorrect for no-pool case | ||
| } | ||
|
|
||
| assertThat(completedIn200ms) | ||
| .as("third getJdbi().open() should NOT block when no pool is configured") | ||
| .isTrue(); | ||
|
|
||
| // check H2 session count to confirm multiple physical connections were opened | ||
| int sessions = jdbi.withHandle(h -> | ||
| h.createQuery("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SESSIONS") | ||
| .mapTo(int.class) | ||
| .one()); | ||
| assertThat(sessions).isGreaterThanOrEqualTo(3); | ||
|
|
||
| // Release the first two connections | ||
| hold.countDown(); | ||
| assertThat(third.get(3, TimeUnit.SECONDS)).isTrue(); | ||
| } | ||
| finally { | ||
| es.shutdownNow(); | ||
| } | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
nit: IMO if we're adding HikariCP we should be giving the users complete flexibility to all of it's settings and not just max pool size:
Example of what I mean from previously unpushed code I had laying around:
For the above to work with your logic max pool size can default to 0
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.
Thanks for the suggestion! I think exposing all HikariCP parameters would add unnecessary complexity for this use case as Hikari’s default settings are already well-optimized and sufficient.
For now I kept it minimal with maxPoolSize, since it’s the only setting that typically needs adjustment.