-
Notifications
You must be signed in to change notification settings - Fork 488
Support Runtime JDBC Driver Loading and Dynamic Datasource Creation #4984
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
Draft
flyrain
wants to merge
3
commits into
apache:main
Choose a base branch
from
flyrain:poc-jdbc-managed-datasource
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.
Draft
Changes from all commits
Commits
Show all changes
3 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 |
|---|---|---|
|
|
@@ -49,7 +49,7 @@ | |
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| public class DatasourceOperations { | ||
| public class DatasourceOperations implements AutoCloseable { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(DatasourceOperations.class); | ||
|
|
||
|
|
@@ -69,14 +69,23 @@ public class DatasourceOperations { | |
|
|
||
| private final DataSource datasource; | ||
| private final RelationalJdbcConfiguration relationalJdbcConfiguration; | ||
| private final boolean closeDataSourceOnClose; | ||
| private final DatabaseType databaseType; | ||
|
|
||
| private static final Random random = new Random(); | ||
|
|
||
| public DatasourceOperations( | ||
| DataSource datasource, RelationalJdbcConfiguration relationalJdbcConfiguration) { | ||
| this(datasource, relationalJdbcConfiguration, false); | ||
| } | ||
|
|
||
| DatasourceOperations( | ||
| DataSource datasource, | ||
| RelationalJdbcConfiguration relationalJdbcConfiguration, | ||
| boolean closeDataSourceOnClose) { | ||
| this.datasource = datasource; | ||
| this.relationalJdbcConfiguration = relationalJdbcConfiguration; | ||
| this.closeDataSourceOnClose = closeDataSourceOnClose; | ||
| try (Connection connection = this.datasource.getConnection()) { | ||
| // Get explicitly configured database type, if any | ||
| DatabaseType configuredType = | ||
|
|
@@ -98,6 +107,21 @@ DatabaseType getDatabaseType() { | |
| return databaseType; | ||
| } | ||
|
|
||
| boolean ownsDataSource() { | ||
| return closeDataSourceOnClose; | ||
| } | ||
|
|
||
| @Override | ||
| 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. When is this |
||
| if (closeDataSourceOnClose && datasource instanceof AutoCloseable closeable) { | ||
| try { | ||
| closeable.close(); | ||
| } catch (Exception e) { | ||
| throw new RuntimeException("Failed to close datasource", e); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Execute SQL script and close the associated input stream | ||
| * | ||
|
|
||
217 changes: 217 additions & 0 deletions
217
...c/src/main/java/org/apache/polaris/persistence/relational/jdbc/JdbcDataSourceFactory.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,217 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you 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 org.apache.polaris.persistence.relational.jdbc; | ||
|
|
||
| import com.zaxxer.hikari.HikariConfig; | ||
| import com.zaxxer.hikari.HikariDataSource; | ||
| import java.io.IOException; | ||
| import java.net.URL; | ||
| import java.net.URLClassLoader; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.util.Comparator; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.Optional; | ||
| import java.util.stream.Stream; | ||
| import javax.sql.DataSource; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
| final class JdbcDataSourceFactory { | ||
|
|
||
| private static final Logger LOGGER = LoggerFactory.getLogger(JdbcDataSourceFactory.class); | ||
|
|
||
| private static final String DEFAULT_DRIVER_DIRECTORY = "jdbc-drivers"; | ||
| private static final String POOL_NAME = "polaris-relational-jdbc"; | ||
|
|
||
| private JdbcDataSourceFactory() {} | ||
|
|
||
| static Optional<DataSource> create(RelationalJdbcConfiguration configuration) { | ||
| Optional<String> jdbcUrl = nonBlank(configuration.jdbcUrl()); | ||
| if (jdbcUrl.isEmpty()) { | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| Optional<URLClassLoader> driverClassLoader = createDriverClassLoader(configuration); | ||
| if (driverClassLoader.isPresent()) { | ||
| return Optional.of( | ||
| createHikariDataSource(configuration, jdbcUrl.get(), driverClassLoader.get())); | ||
| } | ||
|
|
||
| return Optional.of(new HikariDataSource(createHikariConfig(configuration, jdbcUrl.get()))); | ||
| } | ||
|
|
||
| private static HikariDataSource createHikariDataSource( | ||
| RelationalJdbcConfiguration configuration, String jdbcUrl, URLClassLoader driverClassLoader) { | ||
| ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader(); | ||
| boolean success = false; | ||
| try { | ||
| Thread.currentThread().setContextClassLoader(driverClassLoader); | ||
| HikariDataSource dataSource = | ||
|
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. don't you want to override |
||
| new DriverClassLoaderHikariDataSource( | ||
| createHikariConfig(configuration, jdbcUrl), driverClassLoader); | ||
| success = true; | ||
| return dataSource; | ||
| } finally { | ||
| Thread.currentThread().setContextClassLoader(previousContextClassLoader); | ||
| if (!success) { | ||
| closeDriverClassLoader(driverClassLoader); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static HikariConfig createHikariConfig( | ||
| RelationalJdbcConfiguration configuration, String jdbcUrl) { | ||
| HikariConfig hikariConfig = new HikariConfig(); | ||
| hikariConfig.setPoolName(POOL_NAME); | ||
| hikariConfig.setJdbcUrl(jdbcUrl); | ||
| nonBlank(configuration.driver()).ifPresent(hikariConfig::setDriverClassName); | ||
| nonBlank(configuration.username()).ifPresent(hikariConfig::setUsername); | ||
| configuration.password().ifPresent(hikariConfig::setPassword); | ||
| configuration.maximumPoolSize().ifPresent(hikariConfig::setMaximumPoolSize); | ||
| configuration.minimumIdle().ifPresent(hikariConfig::setMinimumIdle); | ||
| configuration.connectionTimeoutInMs().ifPresent(hikariConfig::setConnectionTimeout); | ||
|
|
||
| return hikariConfig; | ||
| } | ||
|
|
||
| private static Optional<URLClassLoader> createDriverClassLoader( | ||
| RelationalJdbcConfiguration configuration) { | ||
| Optional<String> configuredDriverDirectory = nonBlank(configuration.driverDirectory()); | ||
| Optional<Path> driverDirectory = | ||
| configuredDriverDirectory | ||
| .map(Path::of) | ||
| .or(() -> defaultDriverDirectory().filter(Files::isDirectory)); | ||
|
|
||
| if (driverDirectory.isEmpty()) { | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| Path directory = driverDirectory.get(); | ||
| if (!Files.isDirectory(directory)) { | ||
| throw new IllegalArgumentException( | ||
| "Configured JDBC driver directory does not exist: " + directory); | ||
| } | ||
|
|
||
| List<Path> driverJars = driverJars(directory); | ||
| if (driverJars.isEmpty()) { | ||
| if (configuredDriverDirectory.isPresent()) { | ||
| throw new IllegalArgumentException( | ||
| "Configured JDBC driver directory does not contain any .jar files: " + directory); | ||
| } | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| LOGGER.info("Loading JDBC driver jars from {}", directory); | ||
| URL[] urls = driverJars.stream().map(JdbcDataSourceFactory::toUrl).toArray(URL[]::new); | ||
| ClassLoader parent = Thread.currentThread().getContextClassLoader(); | ||
| if (parent == null) { | ||
| parent = JdbcDataSourceFactory.class.getClassLoader(); | ||
| } | ||
| return Optional.of(new URLClassLoader(urls, parent)); | ||
| } | ||
|
|
||
| private static Optional<Path> defaultDriverDirectory() { | ||
| String classPath = System.getProperty("java.class.path", ""); | ||
| for (String classPathEntry : classPath.split(System.getProperty("path.separator"))) { | ||
| if (classPathEntry.isEmpty()) { | ||
| continue; | ||
| } | ||
| Path path = Path.of(classPathEntry); | ||
| Path fileName = path.getFileName(); | ||
| if (fileName != null && "quarkus-run.jar".equals(fileName.toString())) { | ||
| Path parent = path.getParent(); | ||
| return Optional.of( | ||
| parent == null | ||
| ? Path.of(DEFAULT_DRIVER_DIRECTORY) | ||
| : parent.resolve(DEFAULT_DRIVER_DIRECTORY)); | ||
| } | ||
| } | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| private static List<Path> driverJars(Path driverDirectory) { | ||
| try (Stream<Path> entries = Files.list(driverDirectory)) { | ||
| return entries | ||
| .filter(Files::isRegularFile) | ||
| .filter(path -> path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(".jar")) | ||
| .sorted(Comparator.comparing(path -> path.getFileName().toString())) | ||
| .toList(); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Failed to list JDBC driver directory: " + driverDirectory, e); | ||
| } | ||
| } | ||
|
|
||
| private static URL toUrl(Path driverJar) { | ||
| try { | ||
| return driverJar.toUri().toURL(); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Failed to load JDBC driver jar: " + driverJar, e); | ||
| } | ||
| } | ||
|
|
||
| private static void closeDriverClassLoader(URLClassLoader driverClassLoader) { | ||
| try { | ||
| driverClassLoader.close(); | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Failed to close JDBC driver classloader", e); | ||
| } | ||
| } | ||
|
|
||
| private static Optional<String> nonBlank(Optional<String> value) { | ||
| return value.map(String::trim).filter(s -> !s.isEmpty()); | ||
| } | ||
|
|
||
| private static final class DriverClassLoaderHikariDataSource extends HikariDataSource { | ||
| private final URLClassLoader driverClassLoader; | ||
|
|
||
| private DriverClassLoaderHikariDataSource( | ||
| HikariConfig configuration, URLClassLoader driverClassLoader) { | ||
| super(configuration); | ||
| this.driverClassLoader = driverClassLoader; | ||
| } | ||
|
|
||
| @Override | ||
| public void close() { | ||
| RuntimeException closeFailure = null; | ||
| try { | ||
| super.close(); | ||
| } catch (RuntimeException e) { | ||
| closeFailure = e; | ||
| } | ||
|
|
||
| try { | ||
| driverClassLoader.close(); | ||
| } catch (IOException e) { | ||
| RuntimeException classLoaderFailure = | ||
| new RuntimeException("Failed to close JDBC driver classloader", e); | ||
| if (closeFailure != null) { | ||
| closeFailure.addSuppressed(classLoaderFailure); | ||
| } else { | ||
| closeFailure = classLoaderFailure; | ||
| } | ||
| } | ||
|
|
||
| if (closeFailure != null) { | ||
| throw closeFailure; | ||
| } | ||
| } | ||
| } | ||
| } | ||
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
Oops, something went wrong.
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.
closeDataSourceOnCloseis awkward to read. How aboutassumeDataSourceOwnership?