-
Notifications
You must be signed in to change notification settings - Fork 140
Add cache in HaGatewayManager #783
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,55 @@ | ||||||||||
| /* | ||||||||||
| * 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.config; | ||||||||||
|
|
||||||||||
| import io.airlift.units.Duration; | ||||||||||
|
|
||||||||||
| import java.util.concurrent.TimeUnit; | ||||||||||
|
|
||||||||||
| public class DatabaseCacheConfiguration | ||||||||||
| { | ||||||||||
| private boolean enabled; | ||||||||||
| private Duration expireAfterWrite = Duration.succinctDuration(60, TimeUnit.MINUTES); | ||||||||||
| private Duration refreshAfterWrite = Duration.succinctDuration(5, TimeUnit.SECONDS); | ||||||||||
|
Comment on lines
+23
to
+24
Member
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.
Suggested change
|
||||||||||
|
|
||||||||||
| public boolean isEnabled() | ||||||||||
| { | ||||||||||
| return enabled; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| public void setEnabled(boolean enabled) | ||||||||||
| { | ||||||||||
| this.enabled = enabled; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| public Duration getExpireAfterWrite() | ||||||||||
| { | ||||||||||
| return expireAfterWrite; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| public void setExpireAfterWrite(Duration expireAfterWrite) | ||||||||||
| { | ||||||||||
| this.expireAfterWrite = expireAfterWrite; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| public Duration getRefreshAfterWrite() | ||||||||||
| { | ||||||||||
| return refreshAfterWrite; | ||||||||||
| } | ||||||||||
|
|
||||||||||
| public void setRefreshAfterWrite(Duration refreshAfterWrite) | ||||||||||
| { | ||||||||||
| this.refreshAfterWrite = refreshAfterWrite; | ||||||||||
| } | ||||||||||
| } | ||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -13,9 +13,15 @@ | |
| */ | ||
| package io.trino.gateway.ha.router; | ||
|
|
||
| import com.github.benmanes.caffeine.cache.Caffeine; | ||
| import com.github.benmanes.caffeine.cache.LoadingCache; | ||
| import com.github.benmanes.caffeine.cache.Ticker; | ||
| import com.google.common.annotations.VisibleForTesting; | ||
| import com.google.common.collect.ImmutableList; | ||
| import com.google.inject.Inject; | ||
| import io.airlift.log.Logger; | ||
| import io.airlift.stats.CounterStat; | ||
| import io.trino.gateway.ha.config.DatabaseCacheConfiguration; | ||
| import io.trino.gateway.ha.config.ProxyBackendConfiguration; | ||
| import io.trino.gateway.ha.config.RoutingConfiguration; | ||
| import io.trino.gateway.ha.persistence.dao.GatewayBackend; | ||
|
|
@@ -28,34 +34,111 @@ | |
|
|
||
| import static com.google.common.base.Preconditions.checkArgument; | ||
| import static com.google.common.base.Preconditions.checkState; | ||
| import static com.google.common.collect.ImmutableList.toImmutableList; | ||
| import static java.util.Objects.requireNonNull; | ||
|
|
||
| public class HaGatewayManager | ||
| implements GatewayBackendManager | ||
| { | ||
| private static final Logger log = Logger.get(HaGatewayManager.class); | ||
| private static final Object ALL_BACKEND_CACHE_KEY = new Object(); | ||
|
|
||
| private final GatewayBackendDao dao; | ||
| private final String defaultRoutingGroup; | ||
| private final boolean cacheEnabled; | ||
| private final LoadingCache<Object, List<GatewayBackend>> backendCache; | ||
|
|
||
| private final CounterStat backendLookupSuccesses = new CounterStat(); | ||
| private final CounterStat backendLookupFailures = new CounterStat(); | ||
|
|
||
| @Inject | ||
| public HaGatewayManager(Jdbi jdbi, RoutingConfiguration routingConfiguration) | ||
| public HaGatewayManager(Jdbi jdbi, RoutingConfiguration routingConfiguration, DatabaseCacheConfiguration databaseCacheConfiguration) | ||
| { | ||
| this(jdbi, routingConfiguration, databaseCacheConfiguration, Ticker.systemTicker()); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| public HaGatewayManager(Jdbi jdbi, RoutingConfiguration routingConfiguration, DatabaseCacheConfiguration databaseCacheConfiguration, Ticker ticker) | ||
| { | ||
| dao = requireNonNull(jdbi, "jdbi is null").onDemand(GatewayBackendDao.class); | ||
| this.defaultRoutingGroup = routingConfiguration.getDefaultRoutingGroup(); | ||
| defaultRoutingGroup = routingConfiguration.getDefaultRoutingGroup(); | ||
| cacheEnabled = databaseCacheConfiguration.isEnabled(); | ||
| if (cacheEnabled) { | ||
| Caffeine<Object, Object> caffeineBuilder = Caffeine.newBuilder() | ||
| .initialCapacity(1) | ||
| .ticker(ticker); | ||
| if (databaseCacheConfiguration.getExpireAfterWrite() != null) { | ||
|
Member
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 does this getter return null when cacheEnabled is true? |
||
| caffeineBuilder = caffeineBuilder.expireAfterWrite(databaseCacheConfiguration.getExpireAfterWrite().toJavaTime()); | ||
| } | ||
| if (databaseCacheConfiguration.getRefreshAfterWrite() != null) { | ||
| caffeineBuilder = caffeineBuilder.refreshAfterWrite(databaseCacheConfiguration.getRefreshAfterWrite().toJavaTime()); | ||
| } | ||
| backendCache = caffeineBuilder.build(this::fetchAllBackends); | ||
|
|
||
| // Load the data once during initialization. This ensures a fail-fast behavior in case of database misconfiguration. | ||
| try { | ||
| List<GatewayBackend> _ = backendCache.get(ALL_BACKEND_CACHE_KEY); | ||
| } | ||
| catch (Exception e) { | ||
| throw new RuntimeException("Failed to warm up backend cache", e); | ||
| } | ||
| } | ||
| else { | ||
| backendCache = null; | ||
| } | ||
| } | ||
|
|
||
| private List<GatewayBackend> fetchAllBackends(Object ignored) | ||
| { | ||
| try { | ||
| List<GatewayBackend> backends = dao.findAll(); | ||
| backendLookupSuccesses.update(1); | ||
| return backends; | ||
| } | ||
| catch (Exception e) { | ||
| backendLookupFailures.update(1); | ||
| log.warn(e, "Failed to fetch backends"); | ||
| throw e; | ||
|
oneonestar marked this conversation as resolved.
|
||
| } | ||
| } | ||
|
|
||
| private void invalidateBackendCache() | ||
| { | ||
| if (cacheEnabled) { | ||
| // Avoid using bulk invalidation like invalidateAll(), in order to invalidate in-flight loads properly. | ||
| // See https://github.com/trinodb/trino/issues/10512#issuecomment-1016398117 | ||
| backendCache.invalidate(ALL_BACKEND_CACHE_KEY); | ||
| } | ||
| } | ||
|
|
||
| private List<GatewayBackend> getAllBackendsInternal() | ||
| { | ||
| if (cacheEnabled) { | ||
| try { | ||
| return backendCache.get(ALL_BACKEND_CACHE_KEY); | ||
| } | ||
| catch (Exception e) { | ||
| throw new RuntimeException("Failed to load backends from database to cache", e); | ||
| } | ||
| } | ||
| else { | ||
|
Member
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. Remove redundant else.
|
||
| return fetchAllBackends(ALL_BACKEND_CACHE_KEY); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public List<ProxyBackendConfiguration> getAllBackends() | ||
| { | ||
| List<GatewayBackend> proxyBackendList = dao.findAll(); | ||
| List<GatewayBackend> proxyBackendList = getAllBackendsInternal(); | ||
| return upcast(proxyBackendList); | ||
| } | ||
|
|
||
| @Override | ||
| public List<ProxyBackendConfiguration> getAllActiveBackends() | ||
| { | ||
| List<GatewayBackend> proxyBackendList = dao.findActiveBackend(); | ||
| List<GatewayBackend> proxyBackendList = getAllBackendsInternal().stream() | ||
| .filter(GatewayBackend::active) | ||
| .collect(toImmutableList()); | ||
| return upcast(proxyBackendList); | ||
| } | ||
|
|
||
|
|
@@ -74,14 +157,19 @@ public List<ProxyBackendConfiguration> getActiveDefaultBackends() | |
| @Override | ||
| public List<ProxyBackendConfiguration> getActiveBackends(String routingGroup) | ||
| { | ||
| List<GatewayBackend> proxyBackendList = dao.findActiveBackendByRoutingGroup(routingGroup); | ||
| List<GatewayBackend> proxyBackendList = getAllBackendsInternal().stream() | ||
| .filter(GatewayBackend::active) | ||
| .filter(backend -> backend.routingGroup().equals(routingGroup)) | ||
| .collect(toImmutableList()); | ||
| return upcast(proxyBackendList); | ||
| } | ||
|
|
||
| @Override | ||
| public Optional<ProxyBackendConfiguration> getBackendByName(String name) | ||
| { | ||
| List<GatewayBackend> proxyBackendList = dao.findByName(name); | ||
| List<GatewayBackend> proxyBackendList = getAllBackendsInternal().stream() | ||
| .filter(backend -> backend.name().equals(name)) | ||
| .collect(toImmutableList()); | ||
| return upcast(proxyBackendList).stream().findAny(); | ||
| } | ||
|
|
||
|
|
@@ -105,6 +193,7 @@ private void updateClusterActivationStatus(String clusterName, boolean newStatus | |
| boolean previousStatus = model.active(); | ||
| changeActiveStatus.run(); | ||
| logActivationStatusChange(clusterName, newStatus, previousStatus); | ||
| invalidateBackendCache(); | ||
| } | ||
|
|
||
| private static void logActivationStatusChange(String clusterName, boolean newStatus, boolean previousStatus) | ||
|
|
@@ -121,6 +210,7 @@ public ProxyBackendConfiguration addBackend(ProxyBackendConfiguration backend) | |
| String backendProxyTo = removeTrailingSlash(backend.getProxyTo()); | ||
| String backendExternalUrl = removeTrailingSlash(backend.getExternalUrl()); | ||
| dao.create(backend.getName(), backend.getRoutingGroup(), backendProxyTo, backendExternalUrl, backend.isActive()); | ||
| invalidateBackendCache(); | ||
| return backend; | ||
| } | ||
|
|
||
|
|
@@ -138,6 +228,7 @@ public ProxyBackendConfiguration updateBackend(ProxyBackendConfiguration backend | |
| dao.update(backend.getName(), backend.getRoutingGroup(), backendProxyTo, backendExternalUrl, backend.isActive()); | ||
| logActivationStatusChange(backend.getName(), backend.isActive(), model.active()); | ||
| } | ||
| invalidateBackendCache(); | ||
| return backend; | ||
| } | ||
|
|
||
|
|
@@ -152,6 +243,7 @@ private static void validateBackendConfiguration(ProxyBackendConfiguration backe | |
| public void deleteBackend(String name) | ||
| { | ||
| dao.deleteByName(name); | ||
| invalidateBackendCache(); | ||
| } | ||
|
|
||
| private static List<ProxyBackendConfiguration> upcast(List<GatewayBackend> gatewayBackendList) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -19,6 +19,8 @@ | |
| import org.jdbi.v3.core.Jdbi; | ||
|
|
||
| import java.io.File; | ||
| import java.io.IOException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
|
|
||
| public final class TestingJdbcConnectionManager | ||
|
|
@@ -39,4 +41,25 @@ public static JdbcConnectionManager createTestingJdbcConnectionManager(DataStore | |
| Jdbi jdbi = HaGatewayProviderModule.createJdbi(config); | ||
| return new JdbcConnectionManager(jdbi, config); | ||
| } | ||
|
|
||
| public static void destroyTestingDatabase(DataStoreConfiguration config) | ||
| { | ||
| String tempH2DbDirPath = config.getJdbcUrl().replace("jdbc:h2:", "").replace(";NON_KEYWORDS=NAME,VALUE", ""); | ||
| File dbFile = Path.of(tempH2DbDirPath).toFile(); | ||
| File parentDir = dbFile.getParentFile(); | ||
|
|
||
| if (parentDir != null && parentDir.exists()) { | ||
|
Member
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.
|
||
| File[] files = parentDir.listFiles((dir, name) -> name.startsWith(dbFile.getName())); | ||
| if (files != null) { | ||
| for (File file : files) { | ||
| try { | ||
| Files.deleteIfExists(file.toPath()); | ||
| } | ||
| catch (IOException e) { | ||
| // Ignore deletion errors in test cleanup | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.