kfaraz commented on code in PR #17653: URL: https://github.com/apache/druid/pull/17653#discussion_r1947547798
########## server/src/main/java/org/apache/druid/metadata/segment/cache/HeapMemorySegmentMetadataCache.java: ########## @@ -0,0 +1,623 @@ +/* + * 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.druid.metadata.segment.cache; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Supplier; +import com.google.errorprone.annotations.ThreadSafe; +import com.google.errorprone.annotations.concurrent.GuardedBy; +import com.google.inject.Inject; +import org.apache.druid.error.DruidException; +import org.apache.druid.java.util.common.DateTimes; +import org.apache.druid.java.util.common.Stopwatch; +import org.apache.druid.java.util.common.StringUtils; +import org.apache.druid.java.util.common.concurrent.ScheduledExecutorFactory; +import org.apache.druid.java.util.common.lifecycle.LifecycleStart; +import org.apache.druid.java.util.common.lifecycle.LifecycleStop; +import org.apache.druid.java.util.common.parsers.CloseableIterator; +import org.apache.druid.java.util.emitter.EmittingLogger; +import org.apache.druid.java.util.emitter.service.ServiceEmitter; +import org.apache.druid.java.util.emitter.service.ServiceMetricEvent; +import org.apache.druid.metadata.MetadataStorageTablesConfig; +import org.apache.druid.metadata.PendingSegmentRecord; +import org.apache.druid.metadata.SQLMetadataConnector; +import org.apache.druid.metadata.SegmentsMetadataManagerConfig; +import org.apache.druid.metadata.SqlSegmentsMetadataQuery; +import org.apache.druid.query.DruidMetrics; +import org.apache.druid.server.http.DataSegmentPlus; +import org.apache.druid.timeline.SegmentId; +import org.joda.time.DateTime; +import org.joda.time.Duration; +import org.joda.time.Interval; +import org.skife.jdbi.v2.ResultIterator; + +import javax.annotation.Nullable; +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +/** + * In-memory implementation of {@link SegmentMetadataCache}. + */ +@ThreadSafe +public class HeapMemorySegmentMetadataCache implements SegmentMetadataCache +{ + private static final EmittingLogger log = new EmittingLogger(HeapMemorySegmentMetadataCache.class); + private static final String METRIC_PREFIX = "segment/metadataCache/"; + + private enum CacheState + { + STOPPED, FOLLOWER, LEADER_FIRST_SYNC_PENDING, LEADER_FIRST_SYNC_STARTED, LEADER_READY + } + + private final ObjectMapper jsonMapper; + private final Duration pollDuration; + private final boolean isCacheEnabled; + private final MetadataStorageTablesConfig tablesConfig; + private final SQLMetadataConnector connector; + + private final ScheduledExecutorService pollExecutor; + private final ServiceEmitter emitter; + + private final Object cacheStateLock = new Object(); + + @GuardedBy("cacheStateLock") + private volatile CacheState currentCacheState = CacheState.STOPPED; + + private final ConcurrentHashMap<String, HeapMemoryDatasourceSegmentCache> + datasourceToSegmentCache = new ConcurrentHashMap<>(); + private final AtomicReference<DateTime> syncFinishTime = new AtomicReference<>(); + + @Inject + public HeapMemorySegmentMetadataCache( + ObjectMapper jsonMapper, + Supplier<SegmentsMetadataManagerConfig> config, + Supplier<MetadataStorageTablesConfig> tablesConfig, + SQLMetadataConnector connector, + ScheduledExecutorFactory executorFactory, + ServiceEmitter emitter + ) + { + this.jsonMapper = jsonMapper; + this.isCacheEnabled = config.get().isUseCache(); + this.pollDuration = config.get().getPollDuration().toStandardDuration(); + this.tablesConfig = tablesConfig.get(); + this.connector = connector; + this.pollExecutor = isCacheEnabled ? executorFactory.create(1, "SegmentMetadataCache-%s") : null; + this.emitter = emitter; + } + + + @Override + @LifecycleStart + public void start() + { + synchronized (cacheStateLock) { + if (isCacheEnabled && currentCacheState == CacheState.STOPPED) { + currentCacheState = CacheState.FOLLOWER; + pollExecutor.schedule(this::syncWithMetadataStore, pollDuration.getMillis(), TimeUnit.MILLISECONDS); + + log.info("Starting sync with metadata store. Cache is now in state[%s].", currentCacheState); + } + } + } + + @Override + @LifecycleStop + public void stop() + { + synchronized (cacheStateLock) { + if (isCacheEnabled) { + pollExecutor.shutdownNow(); + datasourceToSegmentCache.forEach((datasource, cache) -> cache.stop()); + datasourceToSegmentCache.clear(); + + currentCacheState = CacheState.STOPPED; + log.info("Stopped sync with metadata store. Cache is now in state[%s].", currentCacheState); + } + } + } + + @Override + public void becomeLeader() + { + synchronized (cacheStateLock) { + if (isCacheEnabled) { + if (currentCacheState == CacheState.STOPPED) { + throw DruidException.defensive("Cache has not been started yet"); + } + + currentCacheState = CacheState.LEADER_FIRST_SYNC_PENDING; + log.info("We are now leader. Waiting to sync latest updates from metadata store."); + } + } + } + + @Override + public void stopBeingLeader() + { + synchronized (cacheStateLock) { + if (isCacheEnabled) { + currentCacheState = CacheState.FOLLOWER; + log.info("Not leader anymore. Cache is now in state[%s].", currentCacheState); + } + } + } + + @Override + public boolean isEnabled() + { + return isCacheEnabled; + } + + @Override + public DatasourceSegmentCache getDatasource(String dataSource) + { + verifyCacheIsReady(); + return getCacheForDatasource(dataSource); + } + + private HeapMemoryDatasourceSegmentCache getCacheForDatasource(String dataSource) + { + return datasourceToSegmentCache.computeIfAbsent(dataSource, HeapMemoryDatasourceSegmentCache::new); + } + + /** + * Verifies that the cache is ready to serve requests, waiting if necessary. + * + * @throws DruidException if the cache is disabled, stopped or not leader. + */ + private void verifyCacheIsReady() + { + if (!isCacheEnabled) { + throw DruidException.defensive("Segment metadata cache is not enabled."); + } + + synchronized (cacheStateLock) { + switch (currentCacheState) { + case STOPPED: + throw DruidException.defensive("Segment metadata cache has not been started yet."); + case FOLLOWER: + throw DruidException.defensive("Not leader yet. Segment metadata cache is not usable."); + case LEADER_FIRST_SYNC_PENDING: + case LEADER_FIRST_SYNC_STARTED: + waitForCacheToFinishSync(); + verifyCacheIsReady(); + case LEADER_READY: + // Cache is now ready for use + } + } + } + + /** + * Waits for cache to become ready if we are leader and current state is + * {@link CacheState#LEADER_FIRST_SYNC_PENDING} or + * {@link CacheState#LEADER_FIRST_SYNC_STARTED}. + */ + private void waitForCacheToFinishSync() + { + synchronized (cacheStateLock) { + log.info("Waiting for cache to finish sync with metadata store."); + while (currentCacheState == CacheState.LEADER_FIRST_SYNC_PENDING + || currentCacheState == CacheState.LEADER_FIRST_SYNC_STARTED) { + try { + cacheStateLock.wait(5 * 60_000); + } + catch (Exception e) { + log.noStackTrace().error(e, "Error while waiting for cache to be ready"); + throw DruidException.defensive(e, "Error while waiting for cache to be ready"); + } + } + log.info("Wait complete. Cache is now in state[%s].", currentCacheState); + } + } + + private void markCacheAsReadyIfLeader() + { + synchronized (cacheStateLock) { + if (currentCacheState == CacheState.LEADER_FIRST_SYNC_STARTED) { + currentCacheState = CacheState.LEADER_READY; + log.info("Sync has finished. Cache is now ready to serve requests."); + + // Notify waiting threads waiting for cache to be ready + cacheStateLock.notifyAll(); + } + } + } + + /** + * Retrieves segments from the metadata store and updates the cache, if required. + * <p> + * The following actions are performed in every sync: + * <ul> + * <li>Retrieve all used and unused segment IDs along with their updated timestamps</li> + * <li>Retrieve payloads of used segments which have been updated in the metadata + * store but not in the cache</li> + * <li>Retrieve all pending segments and update the cache as needed</li> + * <li>Remove segments not present in the metadata store</li> + * <li>Reset the max unused partition IDs</li> + * <li>Change the cache state to ready if it is leader and waiting for first sync</li> + * <li>Emit metrics</li> + * </ul> + */ + private void syncWithMetadataStore() + { + final DateTime pollStartTime = DateTimes.nowUtc(); + final Stopwatch sincePollStart = Stopwatch.createStarted(); + try { + synchronized (cacheStateLock) { + if (currentCacheState == CacheState.LEADER_FIRST_SYNC_PENDING) { + log.info("Started sync of latest updates from metadata store."); + currentCacheState = CacheState.LEADER_FIRST_SYNC_STARTED; + } + } + + final Map<String, DatasourceSegmentSummary> datasourceToSummary = new HashMap<>(); + retrieveAllSegmentIds(datasourceToSummary); + + datasourceToSegmentCache.keySet().forEach( + dataSource -> removeUnknownSegmentsFromCache( + dataSource, + datasourceToSummary.computeIfAbsent(dataSource, ds -> new DatasourceSegmentSummary()), + pollStartTime + ) + ); + + datasourceToSummary.forEach(this::retrieveAndRefreshUsedSegments); + + retrieveAndRefreshAllPendingSegments(datasourceToSummary); + datasourceToSegmentCache.keySet().forEach( + dataSource -> removeUnknownPendingSegmentsFromCache( + dataSource, + datasourceToSummary.computeIfAbsent(dataSource, ds -> new DatasourceSegmentSummary()), + pollStartTime + ) + ); + + datasourceToSegmentCache.values().forEach( + HeapMemoryDatasourceSegmentCache::markCacheSynced + ); + + datasourceToSummary.forEach(this::emitSummaryMetrics); + + final long pollDurationMillis = sincePollStart.millisElapsed(); + emitMetric("sync/time", pollDurationMillis); + syncFinishTime.set(DateTimes.nowUtc()); + + markCacheAsReadyIfLeader(); + } + catch (Throwable t) { + log.error(t, "Error occurred while polling metadata store"); + log.makeAlert(t, "Error occurred while polling metadata store"); Review Comment: fixed. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
