yandrey321 commented on code in PR #12150: URL: https://github.com/apache/ozone/pull/12150#discussion_r4691597711
########## hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/ShortCircuitStreamCache.java: ########## @@ -0,0 +1,233 @@ +/* + * 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.hadoop.hdds.scm.storage; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.stats.CacheStats; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.hadoop.hdds.client.BlockID; +import org.apache.hadoop.hdds.client.ContainerBlockID; +import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.BlockData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Caches local block replicas obtained through short-circuit GetBlock, so that another stream opening the same + * block reuses the block metadata and file descriptor instead of sending GetBlock to the datanode again. + * <p> + * Entries are keyed by container and local block ID only. A reader can only look up a block whose location it + * received from OM, so the cache does not bypass OM authorization. + * <p> + * The datanode does not notify the client about deleted or repaired replicas, so entries expire a fixed time after + * they were last accessed. A replica is closed only after it has been removed from the cache and released by every + * stream. + */ +public class ShortCircuitStreamCache implements Closeable { + + private static final Logger LOG = LoggerFactory.getLogger(ShortCircuitStreamCache.class); + + private final Cache<ContainerBlockID, Replica> cache; + private final ExecutorService closeExecutor; + + public ShortCircuitStreamCache(int maxSize, long expiryMs, ExecutorService closeExecutor, + ScheduledExecutorService cleanupExecutor) { + this.cache = Caffeine.newBuilder() + .recordStats() + .maximumSize(maxSize) + .expireAfterWrite(expiryMs, MILLISECONDS) + // run the maintenance and the removal listener on the calling thread, so that close() collects the clients + .executor(Runnable::run) + .removalListener((key, info, cause) -> onRemoval((Replica) info)) + .build(); + this.closeExecutor = closeExecutor; + cleanupExecutor.scheduleAtFixedRate(this::cleanUp, expiryMs, expiryMs, MILLISECONDS); Review Comment: An expiry of 0 (or negative) makes every XceiverClientManager constructor throw. Scenario: ozone.client.read.short-circuit.streams.cache.expiry=0 with short-circuit enabled and cache size > 0. scheduleAtFixedRate(..., 0, 0, MILLISECONDS) throws IllegalArgumentException (period <= 0), so creating an OzoneClient fails. The existing client cache in XceiverClientManager guards the same call with staleThresholdMs > 0. Fix option(-s): validate the expiry (treat <= 0 as "cache disabled" or reject it with a clear message), and only schedule the cleanup tasks when expiryMs > 0. ########## hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/storage/ShortCircuitStreamCache.java: ########## @@ -0,0 +1,233 @@ +/* + * 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.hadoop.hdds.scm.storage; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.stats.CacheStats; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import java.io.Closeable; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.atomic.AtomicInteger; +import org.apache.hadoop.hdds.client.BlockID; +import org.apache.hadoop.hdds.client.ContainerBlockID; +import org.apache.hadoop.hdds.protocol.datanode.proto.ContainerProtos.BlockData; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Caches local block replicas obtained through short-circuit GetBlock, so that another stream opening the same + * block reuses the block metadata and file descriptor instead of sending GetBlock to the datanode again. + * <p> + * Entries are keyed by container and local block ID only. A reader can only look up a block whose location it + * received from OM, so the cache does not bypass OM authorization. + * <p> + * The datanode does not notify the client about deleted or repaired replicas, so entries expire a fixed time after + * they were last accessed. A replica is closed only after it has been removed from the cache and released by every + * stream. + */ +public class ShortCircuitStreamCache implements Closeable { + + private static final Logger LOG = LoggerFactory.getLogger(ShortCircuitStreamCache.class); + + private final Cache<ContainerBlockID, Replica> cache; + private final ExecutorService closeExecutor; + + public ShortCircuitStreamCache(int maxSize, long expiryMs, ExecutorService closeExecutor, + ScheduledExecutorService cleanupExecutor) { + this.cache = Caffeine.newBuilder() + .recordStats() + .maximumSize(maxSize) + .expireAfterWrite(expiryMs, MILLISECONDS) + // run the maintenance and the removal listener on the calling thread, so that close() collects the clients + .executor(Runnable::run) + .removalListener((key, info, cause) -> onRemoval((Replica) info)) + .build(); + this.closeExecutor = closeExecutor; + cleanupExecutor.scheduleAtFixedRate(this::cleanUp, expiryMs, expiryMs, MILLISECONDS); + cleanupExecutor.scheduleAtFixedRate(this::logCacheStats, expiryMs, expiryMs, MILLISECONDS); + LOG.info("{} is created with maxSize {}, expiryMs {}", this.hashCode(), maxSize, expiryMs); + } + + /** + * @return a cached replica that covers the given block commit sequence ID and length, or null. + * The caller must {@link #release} the returned replica. + */ + public synchronized Replica acquire(BlockID blockID, long length) { + final ContainerBlockID key = blockID.getContainerBlockID(); + final Replica replica = cache.getIfPresent(key); + if (replica == null) { + return null; + } + if (replica.getBlockCommitSequenceId() < blockID.getBlockCommitSequenceId() + || replica.getBlockData().getSize() < length) { + cache.asMap().remove(key, replica); + return null; + } + replica.getRefCount().incrementAndGet(); + if (replica.isEvicted()) { + release(replica); + return null; + } + return replica; + } + + /** + * Add a replica, replacing any cached replica of the same block. + * @return the added replica, already acquired by the caller, who must {@link #release} it. + */ + public synchronized Replica put(BlockID blockID, BlockData blockData, FileInputStream stream) { + final Replica replica = new Replica(blockID.getContainerBlockID(), blockData, stream); + replica.getRefCount().incrementAndGet(); + cache.put(replica.blockID, replica); + return replica; + } + + public synchronized void release(Replica replica) { + if (replica.getRefCount().decrementAndGet() == 0) { + if (replica.shouldClose()) { + closeAsync(replica); + } + } + Preconditions.checkState(replica.getRefCount().get() >= 0, Review Comment: The over-release check runs after the decrement, so an over-release leaves refCount negative and throws IllegalStateException from BlockInputStream#close. Scenario: a double release (e.g. a future code path calling releaseCachedReplica twice) drives refCount to -1; the replica can no longer be closed (closeIfUnused requires 0), so its file descriptor leaks, and close() throws an unchecked exception to the caller. Fix option(-s): check before decrementing (or use updateAndGet that refuses to go below 0) and log instead of throwing from the close path. -- 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]
