diff --git a/paimon-api/src/main/java/org/apache/paimon/rest/RESTCatalogOptions.java b/paimon-api/src/main/java/org/apache/paimon/rest/RESTCatalogOptions.java index 46608cda8bd1..7371f4512b49 100644 --- a/paimon-api/src/main/java/org/apache/paimon/rest/RESTCatalogOptions.java +++ b/paimon-api/src/main/java/org/apache/paimon/rest/RESTCatalogOptions.java @@ -121,6 +121,21 @@ public class RESTCatalogOptions { .withDescription( "Enable cache for visiting files using file io (currently only JindoFileIO supports cache)."); + public static final ConfigOption IO_CACHE_ORIGIN_ENDPOINT = + ConfigOptions.key("io-cache.origin.endpoint") + .stringType() + .noDefaultValue() + .withDescription("The original OSS endpoint used when cache is bypassed."); + + public static final ConfigOption IO_CACHE_WHITELIST = + ConfigOptions.key("io-cache.whitelist") + .stringType() + .defaultValue("*") + .withDescription( + "Comma-separated list of file types allowed to use the cache endpoint. " + + "Supported values: meta, global-index, bucket-index, data, file-index. " + + "Use * to allow all file types."); + public static final ConfigOption IO_CACHE_WHITELIST_PATH = ConfigOptions.key("io-cache.whitelist-path") .stringType() diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/BaseMultiPartUploadCommitter.java b/paimon-common/src/main/java/org/apache/paimon/fs/BaseMultiPartUploadCommitter.java index 9d16620dd2d3..d53abe806173 100644 --- a/paimon-common/src/main/java/org/apache/paimon/fs/BaseMultiPartUploadCommitter.java +++ b/paimon-common/src/main/java/org/apache/paimon/fs/BaseMultiPartUploadCommitter.java @@ -19,6 +19,7 @@ package org.apache.paimon.fs; import org.apache.paimon.annotation.VisibleForTesting; +import org.apache.paimon.fs.cache.CachePolicyFileIO; import org.apache.paimon.rest.RESTTokenFileIO; import org.slf4j.Logger; @@ -111,14 +112,17 @@ private void abortMultipartUpload(FileIO fileIO) throws IOException { } private MultiPartUploadStore multiPartUploadStore(FileIO fileIO) throws IOException { - if (fileIO instanceof RESTTokenFileIO) { - RESTTokenFileIO restTokenFileIO = (RESTTokenFileIO) fileIO; - fileIO = restTokenFileIO.fileIO(); - } - if (fileIO instanceof ResolvingFileIO) { - // The upload was started on the FileIO this resolver resolved to, and - // multiPartUploadStore casts to that concrete type, so resolve again here. - fileIO = ((ResolvingFileIO) fileIO).fileIO(targetPath()); + while (true) { + if (fileIO instanceof RESTTokenFileIO) { + fileIO = ((RESTTokenFileIO) fileIO).fileIO(); + } else if (fileIO instanceof CachePolicyFileIO) { + // Transactional uploads are always started on the origin endpoint. + fileIO = ((CachePolicyFileIO) fileIO).originFileIO(); + } else if (fileIO instanceof ResolvingFileIO) { + fileIO = ((ResolvingFileIO) fileIO).fileIO(targetPath()); + } else { + break; + } } return multiPartUploadStore(fileIO, targetPath()); } diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CacheConnectionFailure.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CacheConnectionFailure.java new file mode 100644 index 000000000000..80ced2e0a7e2 --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CacheConnectionFailure.java @@ -0,0 +1,101 @@ +/* + * 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.paimon.fs.cache; + +import java.io.FileNotFoundException; +import java.io.InterruptedIOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.nio.file.AccessDeniedException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.NoSuchFileException; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +/** Identifies transport failures without depending on a filesystem SDK or its class loader. */ +final class CacheConnectionFailure { + + private CacheConnectionFailure() {} + + static boolean isConnectionFailure(Throwable failure) { + Set visited = + Collections.newSetFromMap(new IdentityHashMap()); + if (hasLogicalFailure(failure, visited)) { + return false; + } + return isConnectionFailure( + failure, Collections.newSetFromMap(new IdentityHashMap())); + } + + private static boolean hasLogicalFailure(Throwable failure, Set visited) { + if (failure == null || !visited.add(failure)) { + return false; + } + if (failure instanceof FileNotFoundException + || failure instanceof NoSuchFileException + || failure instanceof FileAlreadyExistsException + || failure instanceof AccessDeniedException + || failure instanceof SecurityException + || failure instanceof InterruptedException + || (failure instanceof InterruptedIOException + && !(failure instanceof SocketTimeoutException) + && !isConnectTimeout(failure))) { + return true; + } + return hasLogicalFailure(failure.getCause(), visited); + } + + private static boolean isConnectTimeout(Throwable failure) { + // Apache HTTP's connect timeout extends InterruptedIOException, not SocketTimeoutException. + return failure.getClass().getName().endsWith(".ConnectTimeoutException"); + } + + private static boolean isConnectionFailure(Throwable failure, Set visited) { + if (failure == null || !visited.add(failure)) { + return false; + } + if (failure instanceof SocketException + || failure instanceof SocketTimeoutException + || failure instanceof UnknownHostException + || isConnectTimeout(failure)) { + return true; + } + // Jindo's JNI bridge loses the socket exception and exposes this native error text. + // Match its transport diagnostic, not arbitrary strings such as "timeout" or "failed". + String message = failure.getMessage(); + if (message != null + && (message.startsWith("Failed to connect Http service:") + || (message.startsWith("ErrorCode : 2001, ErrorMessage :") + && message.contains("Failed to connect Http service:")))) { + return true; + } + if (isConnectionFailure(failure.getCause(), visited)) { + return true; + } + // FileIO.get retains failed loader probes as suppressed exceptions. + for (Throwable suppressed : failure.getSuppressed()) { + if (isConnectionFailure(suppressed, visited)) { + return true; + } + } + return false; + } +} diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java new file mode 100644 index 000000000000..7bcde2d3d74c --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java @@ -0,0 +1,97 @@ +/* + * 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.paimon.fs.cache; + +import org.apache.paimon.fs.Path; +import org.apache.paimon.options.Options; +import org.apache.paimon.utils.FileType; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; + +/** Backend-independent routing policy supplied by the REST server. */ +public final class CachePolicy implements Serializable { + + private static final long serialVersionUID = 1L; + + private final boolean enabled; + private final boolean metaEnabled; + private final boolean readEnabled; + private final boolean writeEnabled; + private final Set whitelist; + private final boolean allPaths; + private final List paths; + + public CachePolicy(Options options) { + String policy = options.get(IO_CACHE_POLICY); + enabled = policy != null && !policy.contains("none"); + metaEnabled = enabled && policy.contains("meta"); + readEnabled = enabled && policy.contains("read"); + writeEnabled = enabled && policy.contains("write"); + whitelist = FileType.parseWhitelist(options.get(IO_CACHE_WHITELIST)); + // Keep the option's original default for legacy JindoCache while remote endpoint + // routing allows all paths by default. + String whitelistPath = + options.contains(IO_CACHE_WHITELIST_PATH) + ? options.get(IO_CACHE_WHITELIST_PATH) + : "*"; + allPaths = whitelistPath != null && "*".equals(whitelistPath.trim()); + paths = new ArrayList<>(); + if (whitelistPath != null && !allPaths) { + for (String pattern : whitelistPath.split(",")) { + pattern = pattern.trim(); + if (!pattern.isEmpty()) { + paths.add(pattern); + } + } + } + } + + public boolean enabled() { + return enabled; + } + + public boolean shouldCache(Path path, String operation) { + boolean operationEnabled = + (metaEnabled && "meta".equalsIgnoreCase(operation)) + || (readEnabled && "read".equalsIgnoreCase(operation)) + || (writeEnabled && "write".equalsIgnoreCase(operation)); + if (!operationEnabled + || FileType.isMutable(path) + || !whitelist.contains(FileType.classify(path))) { + return false; + } + if (allPaths) { + return true; + } + String uriPath = path.toUri().getPath(); + for (String pattern : paths) { + if (uriPath.contains(pattern)) { + return true; + } + } + return false; + } +} diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java new file mode 100644 index 000000000000..5e36b925adbf --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java @@ -0,0 +1,381 @@ +/* + * 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.paimon.fs.cache; + +import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.data.BlobDescriptor; +import org.apache.paimon.fs.FileIO; +import org.apache.paimon.fs.FileStatus; +import org.apache.paimon.fs.HadoopOptionsProvider; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.PositionOutputStream; +import org.apache.paimon.fs.RemoteIterator; +import org.apache.paimon.fs.ResolvingFileIO; +import org.apache.paimon.fs.SeekableInputStream; +import org.apache.paimon.fs.StorageType; +import org.apache.paimon.fs.TwoPhaseOutputStream; +import org.apache.paimon.options.Options; +import org.apache.paimon.utils.FileType; +import org.apache.paimon.utils.StringUtils; + +import org.apache.hadoop.conf.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.UncheckedIOException; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; + +/** + * Routes operations between origin and cache FileIOs without depending on a storage backend. + * + *

The cache uses {@code fs.oss.endpoint}. Operations bypassing cache use {@code + * io-cache.origin.endpoint} when provided. + */ +public class CachePolicyFileIO implements FileIO, HadoopOptionsProvider { + + private static final long serialVersionUID = 1L; + private static final Logger LOG = LoggerFactory.getLogger(CachePolicyFileIO.class); + + private final Path tablePath; + private final CachePolicy policy; + private final FileIO origin; + private final CatalogContext originContext; + private final CatalogContext cacheContext; + private final Map runtimeOptions = new HashMap<>(); + + private transient volatile FileIO cache; + private volatile boolean cacheUnavailable; + private volatile boolean closed; + + private CachePolicyFileIO( + Path tablePath, + CachePolicy policy, + FileIO origin, + CatalogContext originContext, + CatalogContext cacheContext) { + this.tablePath = tablePath; + this.policy = policy; + this.origin = origin; + this.originContext = originContext; + this.cacheContext = cacheContext; + } + + /** Creates the origin FileIO, wrapping it only when the REST cache policy is enabled. */ + public static FileIO create(Path path, CatalogContext context) throws IOException { + CachePolicy policy = new CachePolicy(context.options()); + CatalogContext originContext = + withEndpoint(context, context.options().get(IO_CACHE_ORIGIN_ENDPOINT)); + FileIO origin = FileIO.get(path, originContext); + if (!policy.enabled() || Objects.equals(endpoint(context), endpoint(originContext))) { + return origin; + } + return new CachePolicyFileIO( + path, policy, origin, originContext, withEndpoint(context, endpoint(context))); + } + + private static String endpoint(CatalogContext context) { + return context.options() + .getString("fs.oss.endpoint", context.hadoopConf().get("fs.oss.endpoint")); + } + + private static CatalogContext withEndpoint(CatalogContext context, String endpoint) { + Options options = new Options(context.options().toMap()); + Configuration hadoopConf = new Configuration(context.hadoopConf()); + if (!StringUtils.isNullOrWhitespaceOnly(endpoint)) { + options.set("fs.oss.endpoint", endpoint); + hadoopConf.set("fs.oss.endpoint", endpoint); + } + // Delegates receive one endpoint. Retain the legacy JindoCache options so that its + // deprecated, opt-in implementation keeps working independently of endpoint routing. + for (String key : context.options().keySet()) { + if (key.startsWith("io-cache.") + && !key.equals(IO_CACHE_ENABLED.key()) + && !key.equals(IO_CACHE_POLICY.key()) + && !key.equals(IO_CACHE_WHITELIST_PATH.key())) { + options.remove(key); + } + } + return CatalogContext.create(options, hadoopConf, context.preferIO(), context.fallbackIO()); + } + + /** Returns the origin delegate for committing uploads started by this wrapper. */ + public FileIO originFileIO() throws IOException { + ensureOpen(); + return origin; + } + + private void ensureOpen() throws IOException { + if (closed) { + throw new IOException("CachePolicyFileIO is closed."); + } + } + + private FileIO fileIO(Path path, String operation) throws IOException { + ensureOpen(); + boolean useCache = !cacheUnavailable && policy.shouldCache(path, operation); + LOG.debug( + "CACHE_POLICY_ROUTE operation={} route={} endpoint={} file_type={} path={}", + operation, + useCache ? "cache" : "origin", + (useCache ? cacheContext : originContext).options().get("fs.oss.endpoint"), + FileType.classify(path), + path); + if (!useCache) { + return origin; + } + FileIO current = cache; + if (current == null) { + synchronized (this) { + ensureOpen(); + if (cacheUnavailable) { + return origin; + } + current = cache; + if (current == null) { + try { + current = FileIO.get(tablePath, cacheContext); + current.setRuntimeContext(new HashMap<>(runtimeOptions)); + // Some SDKs defer all network I/O until an output stream is closed. + // Confirm connectivity before returning such a stream or native options. + // A false result is valid: a newly written file need not exist yet. + current.exists(path); + } catch (IOException | RuntimeException | Error e) { + if (current != null) { + try { + current.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + } + if (CacheConnectionFailure.isConnectionFailure(e)) { + disableCache(path, operation, e); + return origin; + } + throw e; + } + cache = current; + } + } + } + return current; + } + + private synchronized void disableCache(Path path, String operation, Throwable failure) { + if (!cacheUnavailable) { + cacheUnavailable = true; + LOG.warn( + "CACHE_POLICY_FALLBACK operation={} cache_endpoint={} origin_endpoint={} path={} failure_type={}; " + + "using origin for subsequent operations on this FileIO", + operation, + cacheContext.options().get("fs.oss.endpoint"), + originContext.options().get("fs.oss.endpoint"), + path, + failure.getClass().getName(), + failure); + } + } + + private T execute(Path path, String operation, IOAction action) throws IOException { + FileIO delegate = fileIO(path, operation); + try { + return action.apply(delegate); + } catch (IOException | RuntimeException failure) { + if (delegate == origin || !CacheConnectionFailure.isConnectionFailure(failure)) { + throw failure; + } + disableCache(path, operation, failure); + try { + return action.apply(origin); + } catch (IOException | RuntimeException originFailure) { + if (originFailure != failure) { + originFailure.addSuppressed(failure); + } + throw originFailure; + } + } + } + + @FunctionalInterface + private interface IOAction { + T apply(FileIO fileIO) throws IOException; + } + + @Override + public SeekableInputStream newInputStream(Path path) throws IOException { + return execute(path, "read", io -> io.newInputStream(path)); + } + + @Override + public PositionOutputStream newOutputStream(Path path, boolean overwrite) throws IOException { + return execute(path, "write", io -> io.newOutputStream(path, overwrite)); + } + + @Override + public FileStatus getFileStatus(Path path) throws IOException { + return execute(path, "meta", io -> io.getFileStatus(path)); + } + + @Override + public boolean exists(Path path) throws IOException { + return execute(path, "meta", io -> io.exists(path)); + } + + @Override + public long getFileSize(Path path) throws IOException { + return execute(path, "meta", io -> io.getFileSize(path)); + } + + @Override + public boolean isDir(Path path) throws IOException { + return execute(path, "meta", io -> io.isDir(path)); + } + + @Override + public FileStatus[] listStatus(Path path) throws IOException { + return fileIO(path, "list").listStatus(path); + } + + @Override + public RemoteIterator listFilesIterative(Path path, boolean recursive) + throws IOException { + return fileIO(path, "list").listFilesIterative(path, recursive); + } + + @Override + public FileStatus[] listDirectories(Path path) throws IOException { + return fileIO(path, "list").listDirectories(path); + } + + @Override + public boolean delete(Path path, boolean recursive) throws IOException { + return fileIO(path, "delete").delete(path, recursive); + } + + @Override + public boolean mkdirs(Path path) throws IOException { + return fileIO(path, "mkdirs").mkdirs(path); + } + + @Override + public boolean rename(Path src, Path dst) throws IOException { + return fileIO(src, "rename").rename(src, dst); + } + + @Override + public boolean tryToWriteAtomic(Path path, String content) throws IOException { + return fileIO(path, "atomic-write").tryToWriteAtomic(path, content); + } + + @Override + public TwoPhaseOutputStream newTwoPhaseOutputStream(Path path, boolean overwrite) + throws IOException { + return fileIO(path, "two-phase-write").newTwoPhaseOutputStream(path, overwrite); + } + + @Override + public String createBlobPresignedUrl( + Path tableRoot, BlobDescriptor descriptor, Duration validity) throws IOException { + return fileIO(tableRoot, "presign").createBlobPresignedUrl(tableRoot, descriptor, validity); + } + + @Override + public Optional archive(Path path, StorageType type) throws IOException { + return fileIO(path, "archive").archive(path, type); + } + + @Override + public void restoreArchive(Path path, Duration duration) throws IOException { + fileIO(path, "restore").restoreArchive(path, duration); + } + + @Override + public Optional unarchive(Path path, StorageType type) throws IOException { + return fileIO(path, "unarchive").unarchive(path, type); + } + + @Override + public Options hadoopOptions(Path path, String opType) { + try { + FileIO delegate = fileIO(path, opType); + boolean useCache = delegate != origin; + while (delegate instanceof ResolvingFileIO) { + delegate = ((ResolvingFileIO) delegate).fileIO(path); + } + if (delegate instanceof HadoopOptionsProvider) { + return ((HadoopOptionsProvider) delegate).hadoopOptions(path, opType); + } + Options options = + new Options((useCache ? cacheContext : originContext).options().toMap()); + synchronized (this) { + runtimeOptions.forEach(options::set); + } + return options; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + + @Override + public boolean isObjectStore() { + return origin.isObjectStore(); + } + + @Override + public void configure(CatalogContext context) { + throw new UnsupportedOperationException("Use CachePolicyFileIO.create to configure."); + } + + @Override + public synchronized void setRuntimeContext(Map options) { + if (closed) { + throw new IllegalStateException("CachePolicyFileIO is closed."); + } + runtimeOptions.putAll(options); + origin.setRuntimeContext(options); + if (cache != null) { + cache.setRuntimeContext(options); + } + } + + @Override + public void close() throws IOException { + FileIO current; + synchronized (this) { + if (closed) { + return; + } + closed = true; + current = cache; + cache = null; + } + try (FileIO cacheToClose = current) { + origin.close(); + } + } +} diff --git a/paimon-common/src/main/java/org/apache/paimon/rest/RESTTokenFileIO.java b/paimon-common/src/main/java/org/apache/paimon/rest/RESTTokenFileIO.java index 3d48361eff1b..6e905855c00c 100644 --- a/paimon-common/src/main/java/org/apache/paimon/rest/RESTTokenFileIO.java +++ b/paimon-common/src/main/java/org/apache/paimon/rest/RESTTokenFileIO.java @@ -28,11 +28,13 @@ import org.apache.paimon.fs.RemoteIterator; import org.apache.paimon.fs.SeekableInputStream; import org.apache.paimon.fs.TwoPhaseOutputStream; +import org.apache.paimon.fs.cache.CachePolicyFileIO; import org.apache.paimon.options.ConfigOption; import org.apache.paimon.options.ConfigOptions; import org.apache.paimon.options.Options; import org.apache.paimon.rest.responses.GetTableTokenResponse; import org.apache.paimon.utils.IOUtils; +import org.apache.paimon.utils.StringUtils; import org.apache.paimon.utils.ThreadUtils; import org.apache.paimon.shade.caffeine2.com.github.benmanes.caffeine.cache.Cache; @@ -53,7 +55,6 @@ import static org.apache.paimon.options.CatalogOptions.FILE_IO_ALLOW_CACHE; import static org.apache.paimon.rest.RESTApi.TOKEN_EXPIRATION_SAFE_TIME_MILLIS; import static org.apache.paimon.rest.RESTCatalogOptions.DLF_OSS_ENDPOINT; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; import static org.apache.paimon.utils.Preconditions.checkArgument; /** A {@link FileIO} to support getting token from REST Server. */ @@ -270,7 +271,7 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc catalogContext.hadoopConf(), catalogContext.preferIO(), catalogContext.fallbackIO()); - fileIO = FileIO.get(path, context); + fileIO = CachePolicyFileIO.create(path, context); FILE_IO_CACHE.put(currentToken, fileIO); return new FileIOWithToken(fileIO, currentToken); } @@ -344,15 +345,19 @@ private void refreshToken() { private Map mergeTokenWithCatalogOptions(Map token) { Map newToken = Maps.newLinkedHashMap(token); Options catalogOptions = catalogContext.options(); - // DLF OSS endpoint should override the standard OSS endpoint. + // Include client routing overrides in the token used by both native callers and the + // token-keyed FileIO cache. Credentials still come from the server token. + for (Map.Entry entry : catalogOptions.toMap().entrySet()) { + String key = entry.getKey(); + if ((key.equals("fs.oss.endpoint") || key.startsWith("io-cache.")) + && entry.getValue() != null) { + newToken.put(key, entry.getValue()); + } + } String dlfOssEndpoint = catalogOptions.get(DLF_OSS_ENDPOINT.key()); - if (dlfOssEndpoint != null && !dlfOssEndpoint.isEmpty()) { + if (!StringUtils.isNullOrWhitespaceOnly(dlfOssEndpoint)) { newToken.put("fs.oss.endpoint", dlfOssEndpoint); } - if (catalogOptions.contains(IO_CACHE_ENABLED)) { - newToken.put( - IO_CACHE_ENABLED.key(), String.valueOf(catalogOptions.get(IO_CACHE_ENABLED))); - } return ImmutableMap.copyOf(newToken); } diff --git a/paimon-common/src/main/java/org/apache/paimon/utils/FileType.java b/paimon-common/src/main/java/org/apache/paimon/utils/FileType.java index a668e9051019..4f296754d6ab 100644 --- a/paimon-common/src/main/java/org/apache/paimon/utils/FileType.java +++ b/paimon-common/src/main/java/org/apache/paimon/utils/FileType.java @@ -89,6 +89,9 @@ public boolean isIndex() { /** Parse a comma-separated whitelist string into a set of {@link FileType}s. */ public static Set parseWhitelist(String whitelist) { Set result = EnumSet.noneOf(FileType.class); + if (whitelist == null) { + return result; + } for (String name : whitelist.split(",")) { name = name.trim(); switch (name) { @@ -113,7 +116,7 @@ public static Set parseWhitelist(String whitelist) { default: if (!name.isEmpty()) { LOG.warn( - "Unknown local-cache.whitelist value '{}'. " + "Unknown whitelist value '{}'. " + "Supported values: meta, global-index, bucket-index, data, file-index, " + "or * for all of them.", name); diff --git a/paimon-common/src/test/java/org/apache/paimon/fs/BaseMultiPartUploadCommitterTest.java b/paimon-common/src/test/java/org/apache/paimon/fs/BaseMultiPartUploadCommitterTest.java index c23fa5896f23..3510f78cea97 100644 --- a/paimon-common/src/test/java/org/apache/paimon/fs/BaseMultiPartUploadCommitterTest.java +++ b/paimon-common/src/test/java/org/apache/paimon/fs/BaseMultiPartUploadCommitterTest.java @@ -19,7 +19,9 @@ package org.apache.paimon.fs; import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.fs.cache.CachePolicyFileIO; import org.apache.paimon.options.Options; +import org.apache.paimon.rest.RESTTokenFileIO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,6 +29,8 @@ import java.io.IOException; import java.util.Collections; +import static org.apache.paimon.options.CatalogOptions.RESOLVING_FILE_IO_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -73,6 +77,25 @@ public void testConcreteFileIOIsPassedThroughUnchanged() throws IOException { assertThat(committer.received).isSameAs(resolved); } + @Test + public void testCommitAndDiscardResolveRestPolicyAndResolverWrappers() throws IOException { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "write"); + options.set(RESOLVING_FILE_IO_ENABLED, true); + FileIOLoader loader = mock(FileIOLoader.class); + when(loader.load(any())).thenReturn(resolved); + try (FileIO policy = + CachePolicyFileIO.create(TARGET, CatalogContext.create(options, loader, null))) { + RESTTokenFileIO rest = mock(RESTTokenFileIO.class); + when(rest.fileIO()).thenReturn(policy); + RecordingCommitter committer = new RecordingCommitter(); + committer.commit(rest); + assertThat(committer.received).isSameAs(resolved); + committer.discardStaging(rest); + assertThat(committer.received).isSameAs(resolved); + } + } + private static class RecordingCommitter extends BaseMultiPartUploadCommitter { private FileIO received; diff --git a/paimon-common/src/test/java/org/apache/paimon/fs/cache/CacheConnectionFailureTest.java b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CacheConnectionFailureTest.java new file mode 100644 index 000000000000..c830033c2ff8 --- /dev/null +++ b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CacheConnectionFailureTest.java @@ -0,0 +1,75 @@ +/* + * 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.paimon.fs.cache; + +import org.junit.jupiter.api.Test; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InterruptedIOException; +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.nio.file.AccessDeniedException; + +import static org.assertj.core.api.Assertions.assertThat; + +class CacheConnectionFailureTest { + + @Test + void testSocketAndNativeTransportFailures() { + for (Throwable failure : + new Throwable[] { + new ConnectException("refused"), + new SocketTimeoutException("timed out"), + new UnknownHostException("cache"), + new IOException("SDK", new ConnectException("refused")), + new IOException("Failed to connect Http service: http://cache/object"), + new IOException( + "ErrorCode : 2001, ErrorMessage : open failed, get file internal error:" + + "Failed to connect Http service: http://cache/object") + }) { + assertThat(CacheConnectionFailure.isConnectionFailure(failure)).isTrue(); + } + IOException loader = new IOException("Could not load FileIO"); + loader.addSuppressed(new IOException("SDK", new ConnectException("refused"))); + assertThat(CacheConnectionFailure.isConnectionFailure(loader)).isTrue(); + } + + @Test + void testLogicalErrorsAndCancellationDoNotTriggerFallback() { + for (Throwable failure : + new Throwable[] { + new FileNotFoundException("missing"), + new AccessDeniedException("denied"), + new SecurityException("denied"), + new InterruptedIOException("cancelled"), + new IOException("file read failed"), + new IOException("request timeout"), + new IOException("ErrorCode : 133, ErrorMessage : No such file"), + new IOException("ErrorCode : 403, ErrorMessage : AccessDenied"), + new IOException("SDK", new FileNotFoundException("missing")) + }) { + assertThat(CacheConnectionFailure.isConnectionFailure(failure)).isFalse(); + } + FileNotFoundException missing = new FileNotFoundException("missing"); + missing.addSuppressed(new ConnectException("unrelated close failure")); + assertThat(CacheConnectionFailure.isConnectionFailure(new IOException(missing))).isFalse(); + } +} diff --git a/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyFileIOTest.java b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyFileIOTest.java new file mode 100644 index 000000000000..69ba8e92329c --- /dev/null +++ b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyFileIOTest.java @@ -0,0 +1,643 @@ +/* + * 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.paimon.fs.cache; + +import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.data.BlobDescriptor; +import org.apache.paimon.fs.FileIO; +import org.apache.paimon.fs.FileIOLoader; +import org.apache.paimon.fs.FileStatus; +import org.apache.paimon.fs.HadoopOptionsProvider; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.PositionOutputStream; +import org.apache.paimon.fs.RemoteIterator; +import org.apache.paimon.fs.SeekableInputStream; +import org.apache.paimon.fs.StorageType; +import org.apache.paimon.fs.TwoPhaseOutputStream; +import org.apache.paimon.fs.local.LocalFileIO; +import org.apache.paimon.options.Options; +import org.apache.paimon.utils.InstantiationUtil; + +import org.apache.hadoop.conf.Configuration; +import org.junit.jupiter.api.Test; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.net.ConnectException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.apache.paimon.options.CatalogOptions.RESOLVING_FILE_IO_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +/** Tests policy routing with a FileIO that does not depend on Jindo or OSS SDKs. */ +class CachePolicyFileIOTest { + + private static final Path ROOT = new Path("oss://bucket/table"); + private static final Path DATA = new Path(ROOT, "bucket-0/data.orc"); + private static final Path MUTABLE = new Path(ROOT, "snapshot/LATEST"); + + @Test + void testRoutesStreamsAndMetadataAndKeepsMutableFilesOnOrigin() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + fileIO.newInputStream(DATA); + fileIO.newOutputStream(DATA, false); + fileIO.getFileStatus(DATA); + fileIO.exists(DATA); + fileIO.getFileSize(DATA); + fileIO.isDir(DATA); + assertThat(loader.delegate("cache").calls) + .containsSubsequence("read", "write", "stat", "exists", "stat", "stat"); + RecordingFileIO origin = loader.delegate("origin"); + origin.calls.clear(); + fileIO.newInputStream(MUTABLE); + fileIO.newOutputStream(MUTABLE, true); + fileIO.getFileStatus(MUTABLE); + assertThat(origin.calls).containsExactly("read", "write", "stat"); + } + } + + @Test + void testOriginOnlyOperationsPreserveDelegateOverrides() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + RecordingFileIO origin = loader.delegate("origin"); + origin.calls.clear(); + int created = loader.created.size(); + fileIO.listStatus(ROOT); + fileIO.listFilesIterative(ROOT, true); + fileIO.listDirectories(ROOT); + fileIO.delete(DATA, false); + fileIO.mkdirs(ROOT); + fileIO.rename(DATA, MUTABLE); + fileIO.tryToWriteAtomic(MUTABLE, "value"); + fileIO.newTwoPhaseOutputStream(DATA, true); + fileIO.createBlobPresignedUrl( + ROOT, new BlobDescriptor(DATA.toString(), 0, 1), Duration.ofMinutes(1)); + fileIO.archive(DATA, null); + fileIO.restoreArchive(DATA, Duration.ofMinutes(1)); + fileIO.unarchive(DATA, null); + assertThat(origin.calls) + .containsExactly( + "list", + "iterate", + "directories", + "delete", + "mkdirs", + "rename", + "atomic", + "two-phase", + "presign", + "archive", + "restore", + "unarchive"); + assertThat(loader.created).hasSize(created); + } + } + + @Test + void testDisabledPolicyStillAppliesOriginEndpoint() throws Exception { + for (String policy : new String[] {null, "none"}) { + Options options = options(); + if (policy == null) { + options.remove(IO_CACHE_POLICY); + } else { + options.set(IO_CACHE_POLICY, policy); + } + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options, loader)) { + assertThat(fileIO).isInstanceOf(RecordingFileIO.class); + assertThat( + ((HadoopOptionsProvider) fileIO) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(options.get("fs.oss.endpoint")).isEqualTo("cache"); + assertThat(loader.delegate("origin").options.keySet()) + .doesNotContain(IO_CACHE_ORIGIN_ENDPOINT.key()); + } + } + } + + @Test + void testEqualEndpointsUseOrdinaryFileIOWithoutCacheProbe() throws Exception { + for (String origin : new String[] {null, "", " ", "cache"}) { + Options options = options(); + if (origin == null) { + options.remove(IO_CACHE_ORIGIN_ENDPOINT); + } else { + options.set(IO_CACHE_ORIGIN_ENDPOINT, origin); + } + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options, loader)) { + assertThat(fileIO).isInstanceOf(RecordingFileIO.class); + int created = loader.created.size(); + fileIO.newInputStream(DATA); + fileIO.newOutputStream(DATA, false); + fileIO.getFileStatus(DATA); + assertThat(loader.created).hasSize(created); + assertThat(loader.delegate("cache").calls).containsExactly("read", "write", "stat"); + } + } + } + + @Test + void testEqualEndpointsIncludeHadoopConfigurationFallback() throws Exception { + Options options = options(); + options.remove("fs.oss.endpoint"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); + Configuration conf = new Configuration(false); + conf.set("fs.oss.endpoint", "origin"); + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = + CachePolicyFileIO.create( + ROOT, CatalogContext.create(options, conf, loader, null))) { + assertThat(fileIO).isInstanceOf(RecordingFileIO.class); + assertThat(loader.delegate("origin").options.get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(options.get("fs.oss.endpoint")).isNull(); + assertThat(conf.get("fs.oss.endpoint")).isEqualTo("origin"); + } + } + + @Test + void testLegacyJindoCacheSwitchDoesNotControlEndpointRouting() throws Exception { + for (boolean legacyEnabled : new boolean[] {false, true}) { + Options options = options(); + options.set(IO_CACHE_ENABLED, legacyEnabled); + options.set(IO_CACHE_WHITELIST_PATH, "bucket-0"); + options.set("fs.jindocache.namespace.rpc.address", "legacy-cache:1234"); + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options, loader)) { + fileIO.newInputStream(DATA); + assertThat(loader.delegate("cache").calls).contains("read"); + for (String endpoint : new String[] {"origin", "cache"}) { + Options delegateOptions = loader.delegate(endpoint).options; + assertThat(delegateOptions.get(IO_CACHE_ENABLED)).isEqualTo(legacyEnabled); + assertThat(delegateOptions.get(IO_CACHE_POLICY)).isEqualTo("meta,read,write"); + assertThat(delegateOptions.get(IO_CACHE_WHITELIST_PATH)).isEqualTo("bucket-0"); + assertThat(delegateOptions.get("fs.jindocache.namespace.rpc.address")) + .isEqualTo("legacy-cache:1234"); + } + } + } + } + + @Test + void testNativeOptionsUseTheSamePolicyWithResolvingFileIO() throws Exception { + Options options = options(); + options.set(RESOLVING_FILE_IO_ENABLED, true); + options.set(IO_CACHE_POLICY, "read"); + options.set(IO_CACHE_WHITELIST_PATH, "bucket-0"); + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options, loader)) { + HadoopOptionsProvider provider = (HadoopOptionsProvider) fileIO; + assertThat(provider.hadoopOptions(DATA, "read").get("fs.oss.endpoint")) + .isEqualTo("cache"); + assertThat(provider.hadoopOptions(DATA, "write").get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(provider.hadoopOptions(MUTABLE, "read").get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(provider.hadoopOptions(DATA, "read").get("fs.oss.securityToken")) + .isEqualTo("test-token"); + } + } + + @Test + void testMissingOriginEndpointRetainsCacheEndpoint() throws Exception { + Options options = options(); + options.remove(IO_CACHE_ORIGIN_ENDPOINT); + try (FileIO fileIO = create(options, new RecordingLoader())) { + HadoopOptionsProvider provider = (HadoopOptionsProvider) fileIO; + assertThat(provider.hadoopOptions(DATA, "write").get("fs.oss.endpoint")) + .isEqualTo("cache"); + assertThat(provider.hadoopOptions(DATA, "read").get("fs.oss.endpoint")) + .isEqualTo("cache"); + } + } + + @Test + void testCacheAlwaysUsesStandardOssEndpoint() throws Exception { + Options options = options(); + options.set("io-cache.endpoint", "unused-cache"); + try (FileIO fileIO = create(options, new RecordingLoader())) { + HadoopOptionsProvider provider = (HadoopOptionsProvider) fileIO; + assertThat(provider.hadoopOptions(DATA, "read").get("fs.oss.endpoint")) + .isEqualTo("cache"); + assertThat(provider.hadoopOptions(MUTABLE, "read").get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(options.get("fs.oss.endpoint")).isEqualTo("cache"); + } + } + + @Test + void testLazyConcurrentInitializationAndRuntimeContext() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + int originCreated = loader.created.size(); + fileIO.setRuntimeContext(Collections.singletonMap("runtime", "before")); + ExecutorService executor = Executors.newFixedThreadPool(4); + try { + List> tasks = new ArrayList<>(); + for (int i = 0; i < 16; i++) { + tasks.add(() -> ((HadoopOptionsProvider) fileIO).hadoopOptions(DATA, "read")); + } + for (Future result : executor.invokeAll(tasks)) { + assertThat(result.get().get("fs.oss.endpoint")).isEqualTo("cache"); + } + } finally { + executor.shutdownNow(); + } + // FileIO.get probes the preferred loader once before loading the actual delegate. + assertThat(loader.created).hasSize(originCreated + 2); + assertThat(loader.delegate("cache").runtime).containsEntry("runtime", "before"); + fileIO.setRuntimeContext(Collections.singletonMap("runtime", "after")); + assertThat(loader.delegate("origin").runtime).containsEntry("runtime", "after"); + assertThat(loader.delegate("cache").runtime).containsEntry("runtime", "after"); + } + } + + @Test + void testSerializationRecreatesLazyCacheAndRetainsRuntimeContext() throws Exception { + try (FileIO original = create(options(), new RecordingLoader())) { + original.setRuntimeContext(Collections.singletonMap("runtime", "serialized")); + original.newInputStream(DATA); + try (FileIO cloned = InstantiationUtil.clone(original)) { + assertThat( + ((HadoopOptionsProvider) cloned) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("cache"); + assertThat( + ((HadoopOptionsProvider) cloned) + .hadoopOptions(DATA, "read") + .get("runtime")) + .isEqualTo("serialized"); + assertThat(((CachePolicyFileIO) cloned).originFileIO()) + .isNotSameAs(((CachePolicyFileIO) original).originFileIO()); + } + } + } + + @Test + void testCloseDoesNotCreateCacheAndPreventsReopening() throws Exception { + RecordingLoader loader = new RecordingLoader(); + FileIO fileIO = create(options(), loader); + int created = loader.created.size(); + fileIO.close(); + fileIO.close(); + assertThat(loader.created).hasSize(created); + assertThat(loader.delegate("origin").closeCount).isEqualTo(1); + assertThatThrownBy(() -> fileIO.newInputStream(DATA)) + .isInstanceOf(IOException.class) + .hasMessageContaining("closed"); + assertThatThrownBy(() -> fileIO.setRuntimeContext(Collections.emptyMap())) + .isInstanceOf(IllegalStateException.class); + } + + @Test + void testCloseAttemptsBothDelegatesAndPreservesFailures() throws Exception { + RecordingLoader loader = new RecordingLoader(); + FileIO fileIO = create(options(), loader); + fileIO.newInputStream(DATA); + RecordingFileIO origin = loader.delegate("origin"); + RecordingFileIO cache = loader.delegate("cache"); + origin.failClose = true; + cache.failClose = true; + assertThatThrownBy(fileIO::close) + .isInstanceOf(IOException.class) + .hasMessage("origin") + .satisfies(error -> assertThat(error.getSuppressed()).hasSize(1)); + fileIO.close(); + assertThat(origin.closeCount).isEqualTo(1); + assertThat(cache.closeCount).isEqualTo(1); + } + + @Test + void testCacheReadFailuresAreNotRetriedOnOrigin() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + fileIO.newInputStream(DATA); + loader.delegate("cache").failRead = true; + assertThatThrownBy(() -> fileIO.newInputStream(DATA)) + .isInstanceOf(IOException.class) + .hasMessage("cache read failed"); + assertThat(loader.delegate("origin").calls).doesNotContain("read"); + } + } + + @Test + void testUnreachableCacheIsDisabledBeforeOpeningWriteAndAfterSerialization() throws Exception { + RecordingLoader loader = new RecordingLoader(); + loader.cacheProbeFailure = new ConnectException("Connection refused"); + try (FileIO fileIO = create(options(), loader)) { + fileIO.newOutputStream(DATA, false); + RecordingFileIO cache = loader.delegate("cache"); + assertThat(cache.calls).containsExactly("exists"); + assertThat(cache.closeCount).isEqualTo(1); + fileIO.newInputStream(DATA); + fileIO.getFileStatus(DATA); + fileIO.exists(DATA); + assertThat(loader.delegate("origin").calls) + .containsSubsequence("write", "read", "stat", "exists"); + assertThat(cache.calls).containsExactly("exists"); + try (FileIO cloned = InstantiationUtil.clone(fileIO)) { + assertThat( + ((HadoopOptionsProvider) cloned) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("origin"); + } + } + } + + @Test + void testConnectionFailureAfterInitializationRetriesOriginAndDisablesCache() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + fileIO.newInputStream(DATA); + RecordingFileIO cache = loader.delegate("cache"); + cache.readFailure = new IOException("SDK failure", new ConnectException("refused")); + fileIO.newInputStream(DATA); + int calls = cache.calls.size(); + fileIO.newInputStream(DATA); + fileIO.newOutputStream(DATA, true); + assertThat(cache.calls).hasSize(calls); + assertThat(loader.delegate("origin").calls) + .containsSubsequence("read", "read", "write"); + } + } + + @Test + void testMissingCacheFileDoesNotRetryOrDisableCache() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + fileIO.newInputStream(DATA); + RecordingFileIO cache = loader.delegate("cache"); + cache.readFailure = new FileNotFoundException("missing cache object"); + assertThatThrownBy(() -> fileIO.newInputStream(DATA)).isSameAs(cache.readFailure); + assertThat(loader.delegate("origin").calls).doesNotContain("read"); + cache.readFailure = null; + fileIO.newInputStream(DATA); + assertThat( + ((HadoopOptionsProvider) fileIO) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("cache"); + } + } + + @Test + void testOriginFailureIsPreservedWhenRetryFails() throws Exception { + RecordingLoader loader = new RecordingLoader(); + try (FileIO fileIO = create(options(), loader)) { + fileIO.newInputStream(DATA); + IOException cacheFailure = new ConnectException("refused"); + IOException originFailure = new FileNotFoundException("origin missing"); + loader.delegate("cache").readFailure = cacheFailure; + loader.delegate("origin").readFailure = originFailure; + assertThatThrownBy(() -> fileIO.newInputStream(DATA)) + .isSameAs(originFailure) + .satisfies(error -> assertThat(error.getSuppressed()).contains(cacheFailure)); + } + } + + @Test + void testConcurrentUnreachableCacheIsProbedOnlyOnce() throws Exception { + RecordingLoader loader = new RecordingLoader(); + loader.cacheProbeFailure = new ConnectException("refused"); + try (FileIO fileIO = create(options(), loader)) { + ExecutorService executor = Executors.newFixedThreadPool(4); + try { + List> tasks = new ArrayList<>(); + for (int i = 0; i < 16; i++) { + tasks.add(() -> ((HadoopOptionsProvider) fileIO).hadoopOptions(DATA, "read")); + } + for (Future result : executor.invokeAll(tasks)) { + assertThat(result.get().get("fs.oss.endpoint")).isEqualTo("origin"); + } + assertThat(loader.delegate("cache").calls).containsExactly("exists"); + } finally { + executor.shutdownNow(); + } + } + } + + private static Options options() { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "meta,read,write"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); + options.set("fs.oss.endpoint", "cache"); + options.set("fs.oss.securityToken", "test-token"); + return options; + } + + private static FileIO create(Options options, RecordingLoader loader) throws IOException { + return CachePolicyFileIO.create(ROOT, CatalogContext.create(options, loader, null)); + } + + private static class RecordingLoader implements FileIOLoader { + + private final List created = new ArrayList<>(); + private IOException cacheProbeFailure; + + @Override + public String getScheme() { + return "oss"; + } + + @Override + public FileIO load(Path path) { + RecordingFileIO fileIO = new RecordingFileIO(); + fileIO.probeFailure = cacheProbeFailure; + created.add(fileIO); + return fileIO; + } + + private RecordingFileIO delegate(String endpoint) { + for (int i = created.size() - 1; i >= 0; i--) { + RecordingFileIO fileIO = created.get(i); + if (endpoint.equals(fileIO.options.get("fs.oss.endpoint"))) { + return fileIO; + } + } + throw new AssertionError("No delegate for " + endpoint); + } + } + + private static class RecordingFileIO extends LocalFileIO implements HadoopOptionsProvider { + + private Options options; + private final List calls = new ArrayList<>(); + private final Map runtime = new HashMap<>(); + private int closeCount; + private boolean failClose; + private boolean failRead; + private IOException readFailure; + private IOException probeFailure; + + @Override + public void configure(CatalogContext context) { + options = context.options(); + } + + @Override + public Options hadoopOptions(Path path, String opType) { + Options result = new Options(options.toMap()); + runtime.forEach(result::set); + return result; + } + + @Override + public SeekableInputStream newInputStream(Path path) throws IOException { + calls.add("read"); + if (readFailure != null) { + throw readFailure; + } + if (failRead) { + throw new IOException("cache read failed"); + } + return mock(SeekableInputStream.class); + } + + @Override + public PositionOutputStream newOutputStream(Path path, boolean overwrite) { + calls.add("write"); + return mock(PositionOutputStream.class); + } + + @Override + public FileStatus getFileStatus(Path path) { + calls.add("stat"); + return mock(FileStatus.class); + } + + @Override + public boolean exists(Path path) throws IOException { + calls.add("exists"); + if (probeFailure != null + && !ROOT.equals(path) + && "cache".equals(options.get("fs.oss.endpoint"))) { + throw probeFailure; + } + return true; + } + + @Override + public FileStatus[] listStatus(Path path) { + calls.add("list"); + return new FileStatus[0]; + } + + @Override + @SuppressWarnings("unchecked") + public RemoteIterator listFilesIterative(Path path, boolean recursive) { + calls.add("iterate"); + return mock(RemoteIterator.class); + } + + @Override + public FileStatus[] listDirectories(Path path) { + calls.add("directories"); + return new FileStatus[0]; + } + + @Override + public boolean delete(Path path, boolean recursive) { + calls.add("delete"); + return true; + } + + @Override + public boolean mkdirs(Path path) { + calls.add("mkdirs"); + return true; + } + + @Override + public boolean rename(Path src, Path dst) { + calls.add("rename"); + return true; + } + + @Override + public boolean tryToWriteAtomic(Path path, String content) { + calls.add("atomic"); + return true; + } + + @Override + public TwoPhaseOutputStream newTwoPhaseOutputStream(Path path, boolean overwrite) { + calls.add("two-phase"); + return mock(TwoPhaseOutputStream.class); + } + + @Override + public String createBlobPresignedUrl(Path root, BlobDescriptor blob, Duration validity) { + calls.add("presign"); + return "https://origin"; + } + + @Override + public Optional archive(Path path, StorageType type) { + calls.add("archive"); + return Optional.of(path); + } + + @Override + public void restoreArchive(Path path, Duration duration) { + calls.add("restore"); + } + + @Override + public Optional unarchive(Path path, StorageType type) { + calls.add("unarchive"); + return Optional.of(path); + } + + @Override + public void setRuntimeContext(Map options) { + runtime.putAll(options); + } + + @Override + public void close() throws IOException { + closeCount++; + if (failClose) { + throw new IOException(options.get("fs.oss.endpoint")); + } + } + } +} diff --git a/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyTest.java b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyTest.java new file mode 100644 index 000000000000..2cec9f6289c6 --- /dev/null +++ b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyTest.java @@ -0,0 +1,168 @@ +/* + * 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.paimon.fs.cache; + +import org.apache.paimon.fs.Path; +import org.apache.paimon.options.Options; +import org.apache.paimon.utils.InstantiationUtil; + +import org.junit.jupiter.api.Test; + +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; +import static org.assertj.core.api.Assertions.assertThat; + +/** Tests for backend-independent REST cache policy semantics. */ +class CachePolicyTest { + + private static final String ROOT = "oss://bucket/database/table"; + private static final Path DATA = new Path(ROOT + "/bucket-0/data-a1b2c3d4-0.orc"); + private static final Path META = new Path(ROOT + "/snapshot/snapshot-1"); + private static final Path MANIFEST = new Path(ROOT + "/manifest/manifest-a1b2c3d4-0"); + + @Test + void testOperationTagsAndCombinations() { + for (String tags : new String[] {"meta", "read", "write", "meta,read,write"}) { + CachePolicy policy = new CachePolicy(options(tags)); + for (String operation : new String[] {"meta", "read", "write"}) { + assertThat(policy.shouldCache(DATA, operation)) + .as("%s with %s", tags, operation) + .isEqualTo(tags.contains(operation)); + } + assertThat(policy.shouldCache(DATA, "list")).isFalse(); + assertThat(policy.shouldCache(DATA, "delete")).isFalse(); + } + } + + @Test + void testDisabledPolicies() { + for (String tags : new String[] {null, "none", "none,read"}) { + Options options = options(tags); + CachePolicy policy = new CachePolicy(options); + assertThat(policy.enabled()).isFalse(); + assertThat(policy.shouldCache(DATA, "read")).isFalse(); + } + } + + @Test + void testPolicyDoesNotRequireVpcValidation() { + Options options = options("read"); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isTrue(); + options.set("io-cache.vpc-validated", "false"); + options.set("io-cache.ignore-vpc-validate", "false"); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isTrue(); + } + + @Test + void testDefaultAndExplicitFileTypes() { + Path[] paths = { + META, + MANIFEST, + DATA, + new Path(ROOT + "/index/btree-global-index-a1b2c3d4.index"), + new Path(ROOT + "/index/index-a1b2c3d4-0"), + new Path(ROOT + "/bucket-0/data-a1b2c3d4-0.orc.index") + }; + Options options = options("read"); + for (String whitelist : + new String[] {"*", "meta,global-index,bucket-index,data,file-index"}) { + options.set(IO_CACHE_WHITELIST, whitelist); + CachePolicy policy = new CachePolicy(options); + for (Path path : paths) { + assertThat(policy.shouldCache(path, "read")).as("%s", path).isTrue(); + } + } + options.set(IO_CACHE_WHITELIST, "data,file-index"); + assertThat(new CachePolicy(options).shouldCache(META, "read")).isFalse(); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isTrue(); + } + + @Test + void testPathAndTypeWhitelistMustBothMatch() { + Options options = options("read"); + options.set(IO_CACHE_WHITELIST_PATH, " manifest, bucket-0, "); + CachePolicy policy = new CachePolicy(options); + assertThat(policy.shouldCache(MANIFEST, "read")).isTrue(); + assertThat(policy.shouldCache(DATA, "read")).isTrue(); + assertThat(policy.shouldCache(META, "read")).isFalse(); + assertThat(policy.shouldCache(new Path(ROOT + "/bucket-1/data.orc"), "read")).isFalse(); + options.set(IO_CACHE_WHITELIST, "meta"); + policy = new CachePolicy(options); + assertThat(policy.shouldCache(MANIFEST, "read")).isTrue(); + assertThat(policy.shouldCache(DATA, "read")).isFalse(); + } + + @Test + void testEmptyAndUnknownWhitelistsFailClosed() { + Options options = options("read"); + for (String whitelist : new String[] {"", "manifest,unknown"}) { + options.set(IO_CACHE_WHITELIST, whitelist); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isFalse(); + assertThat(new CachePolicy(options).shouldCache(META, "read")).isFalse(); + } + options.set(IO_CACHE_WHITELIST, "*"); + options.set(IO_CACHE_WHITELIST_PATH, " , "); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isFalse(); + } + + @Test + void testPathMatchingExcludesSchemeAndAuthority() { + Options options = options("read"); + for (String pattern : new String[] {"oss", "bucket/", "?bucket-0"}) { + options.set(IO_CACHE_WHITELIST_PATH, pattern); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isFalse(); + } + options.set(IO_CACHE_WHITELIST_PATH, " /database/table/bucket-0 "); + assertThat(new CachePolicy(options).shouldCache(DATA, "READ")).isTrue(); + } + + @Test + void testMutableFilesBypassAllOperations() { + CachePolicy policy = new CachePolicy(options("meta,read,write")); + for (String suffix : + new String[] { + "/snapshot/LATEST", "/snapshot/EARLIEST", "/consumer/consumer-user" + }) { + for (String operation : new String[] {"meta", "read", "write"}) { + assertThat(policy.shouldCache(new Path(ROOT + suffix), operation)).isFalse(); + } + } + assertThat(policy.shouldCache(META, "meta")).isTrue(); + } + + @Test + void testPolicyIsASerializableSnapshot() throws Exception { + Options options = options("read"); + options.set(IO_CACHE_WHITELIST_PATH, "bucket-0"); + CachePolicy policy = InstantiationUtil.clone(new CachePolicy(options)); + options.set(IO_CACHE_POLICY, "none"); + options.set(IO_CACHE_WHITELIST_PATH, "*"); + assertThat(policy.shouldCache(DATA, "read")).isTrue(); + assertThat(policy.shouldCache(META, "read")).isFalse(); + } + + private static Options options(String tags) { + Options options = new Options(); + if (tags != null) { + options.set(IO_CACHE_POLICY, tags); + } + return options; + } +} diff --git a/paimon-common/src/test/java/org/apache/paimon/rest/RESTTokenFileIOTest.java b/paimon-common/src/test/java/org/apache/paimon/rest/RESTTokenFileIOTest.java index 8d8c2d593c85..e04fed50270a 100644 --- a/paimon-common/src/test/java/org/apache/paimon/rest/RESTTokenFileIOTest.java +++ b/paimon-common/src/test/java/org/apache/paimon/rest/RESTTokenFileIOTest.java @@ -24,8 +24,10 @@ import org.apache.paimon.fs.FileIO; import org.apache.paimon.fs.FileIOLoader; import org.apache.paimon.fs.FileStatus; +import org.apache.paimon.fs.HadoopOptionsProvider; import org.apache.paimon.fs.Path; import org.apache.paimon.fs.RemoteIterator; +import org.apache.paimon.fs.cache.CachePolicyFileIO; import org.apache.paimon.options.Options; import org.apache.paimon.rest.responses.GetTableTokenResponse; @@ -34,9 +36,17 @@ import java.io.IOException; import java.time.Duration; import java.util.Collections; +import java.util.HashMap; +import java.util.Map; import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; +import static org.apache.paimon.rest.RESTCatalogOptions.DLF_OSS_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -49,6 +59,327 @@ /** Tests for {@link RESTTokenFileIO}. */ class RESTTokenFileIOTest { + @Test + void testClientEndpointOverridesTokenAndDlfEndpointHasHighestPriority() throws IOException { + for (String[] endpoints : + new String[][] { + {null, null, "server-cache"}, + {"client-endpoint", null, "client-endpoint"}, + {"client-endpoint", "client-dlf-endpoint", "client-dlf-endpoint"}, + {null, "client-dlf-endpoint", "client-dlf-endpoint"}, + {"client-endpoint", " ", "client-endpoint"} + }) { + Options options = new Options(); + if (endpoints[0] != null) { + options.set("fs.oss.endpoint", endpoints[0]); + } + if (endpoints[1] != null) { + options.set(DLF_OSS_ENDPOINT, endpoints[1]); + } + options.set(IO_CACHE_ORIGIN_ENDPOINT, "client-origin"); + Map tokenOptions = tokenOptions(); + RESTTokenFileIO rest = restFileIO(options, tokenOptions); + FileIO delegate = rest.fileIO(); + assertThat(delegate).isInstanceOf(CachePolicyFileIO.class); + HadoopOptionsProvider provider = (HadoopOptionsProvider) delegate; + Path data = new Path("oss://bucket/table/bucket-0/data.orc"); + assertThat(provider.hadoopOptions(data, "read").get("fs.oss.endpoint")) + .isEqualTo(endpoints[2]); + assertThat(provider.hadoopOptions(data, "write").get("fs.oss.endpoint")) + .isEqualTo("client-origin"); + assertThat(rest.validToken().token().get("fs.oss.endpoint")).isEqualTo(endpoints[2]); + assertThat(tokenOptions.get("fs.oss.endpoint")).isEqualTo("server-cache"); + assertThat(options.get("fs.oss.endpoint")).isEqualTo(endpoints[0]); + } + } + + @Test + void testClientCacheOptionsOverrideTokenIncludingNativeToken() throws IOException { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "meta,read"); + options.set(IO_CACHE_WHITELIST, "meta"); + options.set(IO_CACHE_WHITELIST_PATH, "manifest"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "client-origin"); + options.set(IO_CACHE_ENABLED, false); + options.set("io-cache.custom-option", "client-value"); + Map tokenOptions = tokenOptions(); + tokenOptions.put(IO_CACHE_POLICY.key(), "none"); + tokenOptions.put(IO_CACHE_WHITELIST.key(), "data"); + tokenOptions.put(IO_CACHE_WHITELIST_PATH.key(), "bucket-0"); + tokenOptions.put(IO_CACHE_ENABLED.key(), "true"); + tokenOptions.put("io-cache.custom-option", "server-value"); + RESTTokenFileIO rest = restFileIO(options, tokenOptions); + HadoopOptionsProvider provider = (HadoopOptionsProvider) rest.fileIO(); + Path manifest = new Path("oss://bucket/table/manifest/manifest-1"); + Path data = new Path("oss://bucket/table/bucket-0/data.orc"); + Path schema = new Path("oss://bucket/table/schema/schema-0"); + assertThat(provider.hadoopOptions(manifest, "read").get("fs.oss.endpoint")) + .isEqualTo("server-cache"); + assertThat(provider.hadoopOptions(manifest, "meta").get("fs.oss.endpoint")) + .isEqualTo("server-cache"); + assertThat(provider.hadoopOptions(data, "read").get("fs.oss.endpoint")) + .isEqualTo("client-origin"); + assertThat(provider.hadoopOptions(schema, "read").get("fs.oss.endpoint")) + .isEqualTo("client-origin"); + assertThat(provider.hadoopOptions(manifest, "write").get("fs.oss.endpoint")) + .isEqualTo("client-origin"); + assertThat(rest.validToken().token()).containsAllEntriesOf(options.toMap()); + } + + @Test + void testClientCanDisableServerCacheOrClearWhitelists() throws IOException { + for (String key : + new String[] { + IO_CACHE_POLICY.key(), IO_CACHE_WHITELIST.key(), IO_CACHE_WHITELIST_PATH.key() + }) { + for (String value : + new String[] {"", key.equals(IO_CACHE_POLICY.key()) ? "none" : " "}) { + Options options = new Options(); + options.set(key, value); + RESTTokenFileIO rest = restFileIO(options, tokenOptions()); + assertThat(rest.validToken().token()).containsEntry(key, value); + FileIO fileIO = rest.fileIO(); + if (fileIO instanceof HadoopOptionsProvider) { + assertThat( + ((HadoopOptionsProvider) fileIO) + .hadoopOptions( + new Path( + "oss://bucket/table/bucket-0/data.orc"), + "read") + .get("fs.oss.endpoint")) + .isEqualTo("server-origin"); + } else { + assertThat(fileIO).isNotInstanceOf(CachePolicyFileIO.class); + } + } + } + } + + @Test + void testIdenticalServerTokensRespectDifferentClientOverrides() throws IOException { + Map tokenOptions = tokenOptions(); + Options disabled = new Options(); + disabled.set(IO_CACHE_POLICY, "none"); + Options direct = new Options(); + direct.set(DLF_OSS_ENDPOINT, "server-origin"); + RESTTokenFileIO cached = restFileIO(new Options(), tokenOptions); + RESTTokenFileIO noCache = restFileIO(disabled, tokenOptions); + RESTTokenFileIO sameEndpoint = restFileIO(direct, tokenOptions); + assertThat(cached.fileIO()).isInstanceOf(CachePolicyFileIO.class); + assertThat(noCache.fileIO()) + .isNotSameAs(cached.fileIO()) + .isNotInstanceOf(CachePolicyFileIO.class); + assertThat(sameEndpoint.fileIO()) + .isNotSameAs(cached.fileIO()) + .isNotInstanceOf(CachePolicyFileIO.class); + assertThat(sameEndpoint.validToken().token()) + .containsEntry("fs.oss.endpoint", "server-origin"); + } + + private static Map tokenOptions() { + Map options = new HashMap<>(); + options.put("test.token", UUID.randomUUID().toString()); + options.put("fs.oss.endpoint", "server-cache"); + options.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "server-origin"); + options.put(IO_CACHE_POLICY.key(), "read"); + return options; + } + + private static RESTTokenFileIO restFileIO(Options options, Map tokenOptions) { + RESTApi api = mock(RESTApi.class); + Identifier identifier = Identifier.create("db", "table"); + when(api.loadTableToken(identifier)) + .thenReturn(new GetTableTokenResponse(tokenOptions, Long.MAX_VALUE)); + FileIOLoader loader = mock(FileIOLoader.class); + when(loader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); + return new RESTTokenFileIO( + CatalogContext.create(options, loader, null), + api, + identifier, + new Path("oss://bucket/table")); + } + + @Test + void testClientRoutingOverridesSurviveTokenRefresh() throws IOException { + Map firstToken = tokenOptions(); + firstToken.put(IO_CACHE_POLICY.key(), "none"); + firstToken.put("fs.oss.securityToken", "first-credentials"); + Map nextToken = new HashMap<>(firstToken); + nextToken.put("fs.oss.endpoint", "next-server-cache"); + nextToken.put(IO_CACHE_POLICY.key(), "write"); + nextToken.put("fs.oss.securityToken", "next-credentials"); + Options options = new Options(); + options.set(DLF_OSS_ENDPOINT, "client-cache"); + options.set(IO_CACHE_POLICY, "read"); + long now = System.currentTimeMillis(); + AtomicLong clock = new AtomicLong(now); + RESTApi api = mock(RESTApi.class); + Identifier identifier = Identifier.create("db", "table"); + when(api.loadTableToken(identifier)) + .thenReturn( + new GetTableTokenResponse(firstToken, now + 3_600_000), + new GetTableTokenResponse(nextToken, Long.MAX_VALUE)); + FileIOLoader loader = mock(FileIOLoader.class); + when(loader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); + RESTTokenFileIO rest = + new RESTTokenFileIO( + CatalogContext.create(options, loader, null), + api, + identifier, + new Path("oss://bucket/table")) { + @Override + long currentTimeMillis() { + return clock.get(); + } + }; + FileIO first = rest.fileIO(); + assertThat(first).isInstanceOf(CachePolicyFileIO.class); + assertThat(rest.validToken().token()) + .containsEntry("fs.oss.endpoint", "client-cache") + .containsEntry(IO_CACHE_POLICY.key(), "read") + .containsEntry("fs.oss.securityToken", "first-credentials"); + clock.set(now + 3_600_000); + assertThat(rest.fileIO()).isNotSameAs(first).isInstanceOf(CachePolicyFileIO.class); + assertThat(rest.validToken().token()) + .containsEntry("fs.oss.endpoint", "client-cache") + .containsEntry(IO_CACHE_POLICY.key(), "read") + .containsEntry("fs.oss.securityToken", "next-credentials"); + verify(api, times(2)).loadTableToken(identifier); + } + + @Test + void testTokenRefreshRebuildsPolicyWrapper() throws IOException { + Path root = new Path("oss://bucket/table"); + Path data = new Path(root, "bucket-0/data.orc"); + FileIOLoader loader = mock(FileIOLoader.class); + when(loader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); + RESTApi api = mock(RESTApi.class); + Identifier identifier = Identifier.create("db", "table"); + Map tokenOptions = new HashMap<>(); + tokenOptions.put(IO_CACHE_POLICY.key(), "read"); + tokenOptions.put("fs.oss.endpoint", "cache"); + tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "origin"); + Map disabledOptions = new HashMap<>(tokenOptions); + disabledOptions.put(IO_CACHE_POLICY.key(), "none"); + long now = System.currentTimeMillis(); + AtomicLong clock = new AtomicLong(now); + when(api.loadTableToken(identifier)) + .thenReturn( + new GetTableTokenResponse(tokenOptions, now + 3_600_000), + new GetTableTokenResponse(disabledOptions, Long.MAX_VALUE)); + RESTTokenFileIO rest = + new RESTTokenFileIO( + CatalogContext.create(new Options(), loader, null), api, identifier, root) { + @Override + long currentTimeMillis() { + return clock.get(); + } + }; + FileIO first = rest.fileIO(); + assertThat(first).isInstanceOf(CachePolicyFileIO.class); + assertThat( + ((HadoopOptionsProvider) first) + .hadoopOptions(data, "read") + .get("fs.oss.endpoint")) + .isEqualTo("cache"); + assertThat(rest.fileIO()).isSameAs(first); + clock.set(now + 3_600_000); + FileIO refreshed = rest.fileIO(); + assertThat(refreshed).isNotSameAs(first).isNotInstanceOf(CachePolicyFileIO.class); + verify(api, times(2)).loadTableToken(identifier); + } + + @Test + void testIdenticalTokensSharePolicyWrapperAcrossTablesAndContexts() throws IOException { + Path firstRoot = new Path("oss://bucket/table-one"); + Path secondRoot = new Path("oss://bucket/table-two"); + Path firstData = new Path(firstRoot, "bucket-0/data.orc"); + Path secondData = new Path(secondRoot, "bucket-0/data.orc"); + RESTApi api = mock(RESTApi.class); + Map tokenOptions = new HashMap<>(); + tokenOptions.put("test.token", UUID.randomUUID().toString()); + tokenOptions.put(IO_CACHE_POLICY.key(), "read"); + tokenOptions.put("fs.oss.endpoint", "cache"); + tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "origin"); + tokenOptions.put(IO_CACHE_WHITELIST_PATH.key(), "table-two"); + when(api.loadTableToken(any())) + .thenReturn(new GetTableTokenResponse(tokenOptions, Long.MAX_VALUE)); + FileIO origin = mock(FileIO.class); + FileIO cache = mock(FileIO.class); + FileIOLoader firstLoader = mock(FileIOLoader.class); + FileIOLoader secondLoader = mock(FileIOLoader.class); + // FileIO.get probes the loader before creating the actual delegate for each endpoint. + when(firstLoader.load(any())).thenReturn(origin, origin, cache, cache); + CatalogContext firstContext = CatalogContext.create(new Options(), firstLoader, null); + CatalogContext secondContext = CatalogContext.create(new Options(), secondLoader, null); + RESTTokenFileIO first = + new RESTTokenFileIO( + firstContext, api, Identifier.create("db", "table-one"), firstRoot); + RESTTokenFileIO second = + new RESTTokenFileIO( + secondContext, api, Identifier.create("db", "table-two"), secondRoot); + FileIO shared = first.fileIO(); + assertThat(shared).isInstanceOf(CachePolicyFileIO.class); + assertThat(second.fileIO()).isSameAs(shared); + first.newInputStream(firstData); + // Initialize cache only after another table has reused the wrapper. Route its actual path. + second.newInputStream(secondData); + verify(origin).newInputStream(firstData); + verify(cache).newInputStream(secondData); + assertThat( + ((HadoopOptionsProvider) shared) + .hadoopOptions(firstData, "read") + .get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat( + ((HadoopOptionsProvider) shared) + .hadoopOptions(secondData, "read") + .get("fs.oss.endpoint")) + .isEqualTo("cache"); + verify(secondLoader, never()).load(any()); + } + + @Test + void testIdenticalCredentialsWithDifferentCacheOptionsDoNotShareFileIO() throws IOException { + Path root = new Path("oss://bucket/table"); + Path data = new Path(root, "bucket-0/data.orc"); + Map tokenOptions = new HashMap<>(); + tokenOptions.put("fs.oss.securityToken", UUID.randomUUID().toString()); + tokenOptions.put(IO_CACHE_POLICY.key(), "read"); + tokenOptions.put("fs.oss.endpoint", "cache"); + tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "origin"); + Map disabledOptions = new HashMap<>(tokenOptions); + disabledOptions.put(IO_CACHE_POLICY.key(), "none"); + Map otherEndpointOptions = new HashMap<>(tokenOptions); + otherEndpointOptions.put("fs.oss.endpoint", "other-cache"); + RESTApi api = mock(RESTApi.class); + Identifier identifier = Identifier.create("db", "table"); + when(api.loadTableToken(identifier)) + .thenReturn( + new GetTableTokenResponse(tokenOptions, Long.MAX_VALUE), + new GetTableTokenResponse(disabledOptions, Long.MAX_VALUE), + new GetTableTokenResponse(otherEndpointOptions, Long.MAX_VALUE)); + FileIOLoader loader = mock(FileIOLoader.class); + when(loader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); + CatalogContext context = CatalogContext.create(new Options(), loader, null); + FileIO first = new RESTTokenFileIO(context, api, identifier, root).fileIO(); + FileIO disabled = new RESTTokenFileIO(context, api, identifier, root).fileIO(); + FileIO otherEndpoint = new RESTTokenFileIO(context, api, identifier, root).fileIO(); + assertThat(first).isInstanceOf(CachePolicyFileIO.class); + assertThat(disabled).isNotSameAs(first).isNotInstanceOf(CachePolicyFileIO.class); + assertThat(otherEndpoint).isNotSameAs(first).isInstanceOf(CachePolicyFileIO.class); + assertThat( + ((HadoopOptionsProvider) first) + .hadoopOptions(data, "read") + .get("fs.oss.endpoint")) + .isEqualTo("cache"); + assertThat( + ((HadoopOptionsProvider) otherEndpoint) + .hadoopOptions(data, "read") + .get("fs.oss.endpoint")) + .isEqualTo("other-cache"); + } + @Test void testSetFileIOCacheMaximumSize() { long originalMaximumSize = RESTTokenFileIO.fileIOCacheMaximumSize(); diff --git a/paimon-common/src/test/java/org/apache/paimon/utils/FileTypeTest.java b/paimon-common/src/test/java/org/apache/paimon/utils/FileTypeTest.java index da2a3a4e93e4..6c73878adc50 100644 --- a/paimon-common/src/test/java/org/apache/paimon/utils/FileTypeTest.java +++ b/paimon-common/src/test/java/org/apache/paimon/utils/FileTypeTest.java @@ -22,6 +22,8 @@ import org.junit.jupiter.api.Test; +import java.util.Collections; +import java.util.EnumSet; import java.util.UUID; import static org.assertj.core.api.Assertions.assertThat; @@ -105,6 +107,15 @@ public void testChangelogMetadataIsImmutable() { assertThat(FileType.isMutable(changelog)).isFalse(); } + @Test + public void testParseWhitelistWithNullAndUnknownValues() { + assertThat(FileType.parseWhitelist(" meta, global-index, bucket-index, data, file-index ")) + .containsExactlyInAnyOrderElementsOf(EnumSet.allOf(FileType.class)); + assertThat(FileType.parseWhitelist("")).isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist("manifest,unknown")).isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist(null)).isEqualTo(Collections.emptySet()); + } + // ===== META files ===== @Test diff --git a/paimon-core/src/test/java/org/apache/paimon/rest/RESTCatalogTest.java b/paimon-core/src/test/java/org/apache/paimon/rest/RESTCatalogTest.java index 8e1b2b8448aa..b47fcf2c034c 100644 --- a/paimon-core/src/test/java/org/apache/paimon/rest/RESTCatalogTest.java +++ b/paimon-core/src/test/java/org/apache/paimon/rest/RESTCatalogTest.java @@ -171,7 +171,6 @@ import static org.apache.paimon.predicate.SortValue.SortDirection.DESCENDING; import static org.apache.paimon.rest.RESTApi.PAGE_TOKEN; import static org.apache.paimon.rest.RESTCatalogOptions.DLF_OSS_ENDPOINT; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; import static org.apache.paimon.rest.auth.DLFToken.TOKEN_DATE_FORMATTER; import static org.apache.paimon.utils.SnapshotManagerTest.createSnapshotWithMillis; import static org.assertj.core.api.Assertions.assertThat; @@ -2172,24 +2171,33 @@ void testValidToken() throws Exception { } @Test - void testValidTokenWithIOCacheEnabled() throws Exception { + void testValidTokenPreservesServerCacheSettings() throws Exception { Map options = new HashMap<>(); - options.put(IO_CACHE_ENABLED.key(), "true"); + options.put("fs.oss.endpoint", "client-endpoint"); + options.put(DLF_OSS_ENDPOINT.key(), "client-dlf-endpoint"); this.catalog = newRestCatalogWithDataToken(options); Identifier identifier = - Identifier.create("test_data_token", "table_for_testing_io_cache_enabled"); - RESTToken expiredDataToken = + Identifier.create("test_data_token", "table_for_testing_server_cache_settings"); + RESTToken serverDataToken = new RESTToken( - ImmutableMap.of("akId", "akId", "akSecret", UUID.randomUUID().toString()), + ImmutableMap.of( + "akId", + "akId", + "akSecret", + UUID.randomUUID().toString(), + "io-cache.origin.endpoint", + "server-origin", + "fs.oss.endpoint", + "server-cache"), System.currentTimeMillis() + 3600_000L); - setDataTokenToRestServerForMock(identifier, expiredDataToken); + setDataTokenToRestServerForMock(identifier, serverDataToken); createTable(identifier, Maps.newHashMap(), Lists.newArrayList("col1")); FileStoreTable fileStoreTable = (FileStoreTable) catalog.getTable(identifier); RESTTokenFileIO fileIO = (RESTTokenFileIO) fileStoreTable.fileIO(); RESTToken fileDataToken = fileIO.validToken(); - // Verify IO_CACHE_ENABLED is merged into token - assertEquals("true", fileDataToken.token().get(IO_CACHE_ENABLED.key())); + assertEquals("server-origin", fileDataToken.token().get("io-cache.origin.endpoint")); + assertEquals("server-cache", fileDataToken.token().get("fs.oss.endpoint")); } @Test diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/CachePolicyJindoFileIOTest.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/CachePolicyJindoFileIOTest.java new file mode 100644 index 000000000000..66554dbf8ea2 --- /dev/null +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/CachePolicyJindoFileIOTest.java @@ -0,0 +1,178 @@ +/* + * 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.paimon.jindo; + +import org.apache.paimon.catalog.CatalogContext; +import org.apache.paimon.fs.FileIO; +import org.apache.paimon.fs.FileIOLoader; +import org.apache.paimon.fs.HadoopOptionsProvider; +import org.apache.paimon.fs.Path; +import org.apache.paimon.fs.cache.CachePolicyFileIO; +import org.apache.paimon.options.Options; +import org.apache.paimon.utils.InstantiationUtil; + +import org.apache.hadoop.conf.Configuration; +import org.junit.jupiter.api.Test; + +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; +import static org.assertj.core.api.Assertions.assertThat; + +/** Verifies that the common policy wrapper preserves Jindo's native options. */ +class CachePolicyJindoFileIOTest { + + private static final Path ROOT = new Path("oss://bucket/table"); + private static final Path DATA = new Path(ROOT, "bucket-0/data.orc"); + + @Test + void testRoutesNativeOptionsAndPreservesBackendConfiguration() throws Exception { + try (FileIO fileIO = create(options())) { + HadoopOptionsProvider provider = (HadoopOptionsProvider) fileIO; + Options read = provider.hadoopOptions(DATA, "read"); + assertThat(read.get("fs.oss.endpoint")).isEqualTo("cache"); + assertThat(provider.hadoopOptions(DATA, "write").get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat( + provider.hadoopOptions(new Path(ROOT, "snapshot/LATEST"), "read") + .get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(read.get("fs.oss.accessKeyId")).isEqualTo("test-ak"); + assertThat(read.get("fs.oss.securityToken")).isEqualTo("test-token"); + assertThat(read.get("fs.oss.show-dir-timestamp")).isEqualTo("false"); + assertThat(read.get("fs.oss.user.agent.extended")).contains("tracking-info"); + } + } + + @Test + void testSerialization() throws Exception { + try (FileIO fileIO = create(options()); + FileIO cloned = InstantiationUtil.clone(fileIO)) { + assertThat( + ((HadoopOptionsProvider) cloned) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("cache"); + } + } + + @Test + void testDisabledPolicyReturnsSingleEndpointJindo() throws Exception { + Options options = options(); + options.set(IO_CACHE_POLICY, "none"); + try (FileIO fileIO = create(options)) { + assertThat(fileIO).isInstanceOf(JindoFileIO.class); + assertThat( + ((HadoopOptionsProvider) fileIO) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("origin"); + } + } + + @Test + void testHadoopFallbackUsesRoutedEndpointWithoutChangingOriginalConfiguration() + throws Exception { + Options options = options(); + options.remove("fs.oss.accessKeyId"); + options.remove("fs.oss.accessKeySecret"); + options.remove("fs.oss.securityToken"); + Configuration hadoopConf = new Configuration(false); + hadoopConf.set("fs.oss.endpoint", "hadoop-configured"); + hadoopConf.set("fs.oss.securityToken", "hadoop-token"); + for (String policy : new String[] {"read", "none"}) { + options.set(IO_CACHE_POLICY, policy); + try (FileIO fileIO = + CachePolicyFileIO.create( + ROOT, + CatalogContext.create( + options, hadoopConf, new TestingJindoLoader(), null))) { + HadoopOptionsProvider provider = (HadoopOptionsProvider) fileIO; + assertThat(provider.hadoopOptions(DATA, "read").get("fs.oss.endpoint")) + .isEqualTo("read".equals(policy) ? "cache" : "origin"); + assertThat(provider.hadoopOptions(DATA, "write").get("fs.oss.endpoint")) + .isEqualTo("origin"); + assertThat(provider.hadoopOptions(DATA, "read").get("fs.oss.securityToken")) + .isEqualTo("hadoop-token"); + } + assertThat(hadoopConf.get("fs.oss.endpoint")).isEqualTo("hadoop-configured"); + assertThat(options.get("fs.oss.endpoint")).isEqualTo("cache"); + } + } + + @Test + void testDeprecatedJindoCacheKeepsItsOriginalSwitch() throws Exception { + for (boolean legacyEnabled : new boolean[] {false, true}) { + Options options = options(); + options.set(IO_CACHE_ENABLED, legacyEnabled); + options.set(IO_CACHE_WHITELIST_PATH, "bucket-0"); + options.set("fs.jindocache.namespace.rpc.address", "legacy-cache:1234"); + try (FileIO fileIO = create(options)) { + HadoopOptionsProvider provider = (HadoopOptionsProvider) fileIO; + Options read = provider.hadoopOptions(DATA, "read"); + assertThat(read.get("fs.oss.endpoint")).isEqualTo("cache"); + assertThat(read.get("fs.xengine")).isEqualTo(legacyEnabled ? "jindocache" : null); + assertThat(provider.hadoopOptions(DATA, "write").get("fs.xengine")).isNull(); + assertThat( + provider.hadoopOptions(new Path(ROOT, "snapshot/LATEST"), "read") + .get("fs.xengine")) + .isNull(); + } + } + } + + private static FileIO create(Options options) throws Exception { + return CachePolicyFileIO.create( + ROOT, CatalogContext.create(options, new TestingJindoLoader(), null)); + } + + private static Options options() { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "read"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); + options.set("fs.oss.endpoint", "cache"); + options.set("fs.oss.accessKeyId", "test-ak"); + options.set("fs.oss.accessKeySecret", "test-sk"); + options.set("fs.oss.securityToken", "test-token"); + options.set("dlf.access-tracking.extended-info", "tracking-info"); + return options; + } + + private static class TestingJindoLoader implements FileIOLoader { + + @Override + public String getScheme() { + return "oss"; + } + + @Override + public FileIO load(Path path) { + return new TestingJindoFileIO(); + } + } + + private static class TestingJindoFileIO extends JindoFileIO { + + @Override + public boolean exists(Path path) { + return false; + } + } +} diff --git a/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py b/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py index 580b7b99f31d..7e9b3e6dc6c6 100644 --- a/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py +++ b/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py @@ -35,6 +35,7 @@ from pypaimon.common.options import Options from pypaimon.common.options.config import CatalogOptions, OssOptions from pypaimon.common.uri_reader import UriReaderFactory +from pypaimon.filesystem.cache_policy_file_io import CachePolicyFileIO class RESTTokenFileIO(FileIO): @@ -129,6 +130,9 @@ def _after_fork_in_child(cls): def file_io(self) -> FileIO: return self._file_io_with_token()[0] + def for_path(self, path: str, operation: str): + return self.file_io().for_path(path, operation) + def _file_io_with_token(self, minimum_validity_millis: int = 0): with self._token_lock: if minimum_validity_millis: @@ -151,7 +155,8 @@ def _file_io_with_token(self, minimum_validity_millis: int = 0): cache = self._FILE_IO_CACHE file_io = cache.get(cache_key) if file_io is None: - file_io = FileIO.get(self.path, self._merged_options(token)) + file_io = CachePolicyFileIO.create( + self.path, self._merged_options(token)) self._log_file_io_created(cache) # Re-inserting on every access expires idle entries only, like expireAfterAccess. cache[cache_key] = file_io @@ -201,23 +206,28 @@ def _get_file_io_scope(self) -> str: def _merged_options(self, token: RESTToken) -> Options: merged_properties = RESTUtil.merge( self.catalog_options.to_map() if self.catalog_options else {}, - token.token + self._merge_token_with_catalog_options(token.token) ) - if self.catalog_options: - dlf_oss_endpoint = self.catalog_options.get(CatalogOptions.DLF_OSS_ENDPOINT) - if dlf_oss_endpoint and dlf_oss_endpoint.strip(): - merged_properties[OssOptions.OSS_ENDPOINT.key()] = dlf_oss_endpoint return Options(merged_properties) def _merge_token_with_catalog_options(self, token: dict) -> dict: - """Merge token with catalog options, DLF OSS endpoint should override the standard OSS endpoint.""" + """Apply this client's routing overrides without changing shared credentials.""" merged_token = dict(token) if self.catalog_options: + for key, value in self.catalog_options.to_map().items(): + if (key == OssOptions.OSS_ENDPOINT.key() or key.startswith("io-cache.")) and value is not None: + merged_token[key] = value dlf_oss_endpoint = self.catalog_options.get(CatalogOptions.DLF_OSS_ENDPOINT) if dlf_oss_endpoint and dlf_oss_endpoint.strip(): merged_token[OssOptions.OSS_ENDPOINT.key()] = dlf_oss_endpoint return merged_token + def _token_with_catalog_options(self, token: Optional[RESTToken]) -> Optional[RESTToken]: + if token is None: + return None + properties = self._merge_token_with_catalog_options(token.token) + return token if properties == token.token else RESTToken(properties, token.expire_at_millis) + def new_input_stream(self, path: str): return self.file_io().new_input_stream(path) @@ -413,8 +423,8 @@ def refresh_token(self): f"end refresh data token for identifier [{self.identifier}] expiresAtMillis [{response.expires_at_millis}]" ) - merged_token_dict = self._merge_token_with_catalog_options(response.token) - new_token = RESTToken(merged_token_dict, response.expires_at_millis) + # Shared tokens must not retain another client's endpoint or cache-policy overrides. + new_token = RESTToken(dict(response.token), response.expires_at_millis) self.token = new_token if self._is_token_expired(new_token): self._log_short_token(new_token) @@ -436,12 +446,12 @@ def _log_short_token(self, token: RESTToken): def valid_token(self): self.try_to_refresh_token() - return self.token + return self._token_with_catalog_options(self.token) def _existing_valid_token(self) -> Optional[RESTToken]: """Return this instance's valid token without locks or refresh requests.""" token = self.token - return token if not self._is_token_expired(token) else None + return self._token_with_catalog_options(token) if not self._is_token_expired(token) else None def close(self): pass diff --git a/paimon-python/pypaimon/common/file_io.py b/paimon-python/pypaimon/common/file_io.py index 6a1a31304715..6de3a39c4b48 100644 --- a/paimon-python/pypaimon/common/file_io.py +++ b/paimon-python/pypaimon/common/file_io.py @@ -600,6 +600,10 @@ def read_overwritten_file_utf8(self, path: str) -> Optional[str]: def to_filesystem_path(self, path: str) -> str: return path + def for_path(self, path: str, operation: str): + """Select the concrete backend for native format readers and writers.""" + return self + def parse_location(self, location: str): import os from urllib.parse import urlparse diff --git a/paimon-python/pypaimon/common/options/config.py b/paimon-python/pypaimon/common/options/config.py index 0d38bd58ef9a..8aef45dece53 100644 --- a/paimon-python/pypaimon/common/options/config.py +++ b/paimon-python/pypaimon/common/options/config.py @@ -136,7 +136,8 @@ class CatalogOptions: DLF_TOKEN_PATH = ConfigOptions.key("dlf.token-path").string_type().no_default_value().with_description( "DLF token file path") DLF_OSS_ENDPOINT = ConfigOptions.key("dlf.oss-endpoint").string_type().no_default_value().with_description( - "DLF OSS endpoint") + "REST Catalog client override for fs.oss.endpoint, taking precedence " + "over both client and REST token endpoint settings.") DLF_TOKEN_LOADER = ConfigOptions.key("dlf.token-loader").string_type().no_default_value().with_description( "DLF token loader") DLF_TOKEN_ECS_ROLE_NAME = ConfigOptions.key( @@ -149,6 +150,42 @@ class CatalogOptions: "'openapi-v4' (ACS4-HMAC-SHA256, for DlfNext/2026-01-18), " "'openapi' (the earlier ROA HMAC-SHA1 scheme). " "If not set, will be automatically selected based on endpoint host.") + IO_CACHE_ORIGIN_ENDPOINT = ( + ConfigOptions.key("io-cache.origin.endpoint") + .string_type() + .no_default_value() + .with_description("The original OSS endpoint used when cache is bypassed.") + ) + IO_CACHE_WHITELIST = ( + ConfigOptions.key("io-cache.whitelist") + .string_type() + .default_value("*") + .with_description( + "Comma-separated list of file types allowed to use the cache endpoint. " + "Supported values: meta, global-index, bucket-index, data, file-index. " + "Use * to allow all file types." + ) + ) + IO_CACHE_WHITELIST_PATH = ( + ConfigOptions.key("io-cache.whitelist-path") + .string_type() + .default_value("*") + .with_description( + "Comma-separated list of path substrings allowed to use the cache endpoint. " + "Use * to allow all paths. A path must match both io-cache.whitelist and " + "io-cache.whitelist-path to use the cache endpoint." + ) + ) + IO_CACHE_POLICY = ( + ConfigOptions.key("io-cache.policy") + .string_type() + .no_default_value() + .with_description( + "The file I/O cache policy. Explicit client settings override the REST token policy. Combined with: " + "meta,read,write. meta enables metadata operations, read enables file reads, " + "write enables file writes, and none disables the cache." + ) + ) PREFIX = ConfigOptions.key("prefix").string_type().no_default_value().with_description("Prefix") HTTP_USER_AGENT_HEADER = ConfigOptions.key( "header.User-Agent").string_type().no_default_value().with_description( diff --git a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py new file mode 100644 index 000000000000..572b205a6471 --- /dev/null +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -0,0 +1,543 @@ +# 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. + +import errno +import logging +import os +import socket +import threading +from typing import Dict, List +from urllib.parse import urlparse + +import pyarrow.fs as pafs +from pyarrow._fs import FileSystemHandler + +from pypaimon.common.file_io import FileIO +from pypaimon.common.options import Options +from pypaimon.common.options.config import CatalogOptions, OssOptions +from pypaimon.utils.file_type import FileType + + +_LOG = logging.getLogger(__name__) + + +def _is_connection_failure(error): + """Recognize transport diagnostics, including SDKs which lose socket causes.""" + visited = set() + pending = [error] + connected = False + while pending: + current = pending.pop() + if current is None or id(current) in visited: + continue + visited.add(id(current)) + if isinstance(current, (FileNotFoundError, FileExistsError, PermissionError, + InterruptedError)): + return False + if isinstance(current, (ConnectionError, TimeoutError, socket.gaierror)): + connected = True + if isinstance(current, OSError): + connected |= current.errno in ( + errno.ECONNREFUSED, errno.ECONNRESET, errno.ECONNABORTED, + errno.ENETUNREACH, errno.EHOSTUNREACH, errno.ETIMEDOUT, errno.EPIPE) + # pyjindo stores the native diagnostic as bytes in args[0]. + message = current.args[0] if current.args else "" + if isinstance(message, bytes): + message = message.decode("utf-8", errors="replace") + if isinstance(message, str): + connected |= ( + "Failed to connect Http service:" in message + or ("AWS Error NETWORK_CONNECTION" in message + and "curlCode:" in message)) + pending.extend((current.__cause__, current.__context__)) + return connected + + +class CachePolicyFileIO(FileIO): + """Routes OSS operations to origin or cache endpoints by REST cache policy. + + The routing layer sits above ``PyArrowFileIO``. Both the pyjindo and native + Arrow OSS implementations therefore use the same policy behavior. + Cache uses ``fs.oss.endpoint``; bypassed operations fall back to + ``io-cache.origin.endpoint`` when provided. + """ + + META_CACHE_ENABLED_TAG = "meta" + READ_CACHE_ENABLED_TAG = "read" + WRITE_CACHE_ENABLED_TAG = "write" + DISABLE_CACHE_TAG = "none" + + @classmethod + def create(cls, path: str, catalog_options: Options, file_io_factory=None) -> FileIO: + """Create an origin FileIO, wrapping it only when cache policy is active.""" + if file_io_factory is None: + file_io_factory = FileIO.get + + origin_options = cls._origin_options(catalog_options) + origin_file_io = file_io_factory(path, origin_options) + if (not cls._cache_enabled(catalog_options) + or catalog_options.get(OssOptions.OSS_ENDPOINT) == origin_options.get(OssOptions.OSS_ENDPOINT)): + return origin_file_io + + cache_options = catalog_options.copy() + return cls( + path, + catalog_options, + origin_file_io, + cache_options, + file_io_factory, + ) + + @staticmethod + def _origin_options(options: Options) -> Options: + result = options.copy() + endpoint = options.get(CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT) + if endpoint is not None and endpoint.strip(): + result.set(OssOptions.OSS_ENDPOINT, endpoint) + return result + + @classmethod + def _cache_enabled(cls, options: Options) -> bool: + policy = options.get(CatalogOptions.IO_CACHE_POLICY) + return ( + policy is not None + and cls.DISABLE_CACHE_TAG not in policy + ) + + def __init__( + self, + path: str, + catalog_options: Options, + origin_file_io: FileIO, + cache_options: Options, + file_io_factory): + self._path = path + self.properties = catalog_options + self._origin_delegate = origin_file_io + self._process_id = os.getpid() + self._cache_options = cache_options + self._file_io_factory = file_io_factory + self._cache_file_io = None + self._cache_unavailable = False + self._cache_file_io_lock = threading.RLock() + self._filesystem_path_prefix = self._infer_filesystem_path_prefix() + + policy = catalog_options.get(CatalogOptions.IO_CACHE_POLICY) or "" + self.meta_cache_enabled = self.META_CACHE_ENABLED_TAG in policy + self.read_cache_enabled = self.READ_CACHE_ENABLED_TAG in policy + self.write_cache_enabled = self.WRITE_CACHE_ENABLED_TAG in policy + + whitelist = catalog_options.get(CatalogOptions.IO_CACHE_WHITELIST) + if whitelist is not None and whitelist.strip() == "*": + self._cache_whitelist = set(FileType) + else: + self._cache_whitelist = FileType.parse_whitelist(whitelist) + + whitelist_path = catalog_options.get(CatalogOptions.IO_CACHE_WHITELIST_PATH) + self._cache_all_paths = ( + whitelist_path is not None and whitelist_path.strip() == "*") + self._cache_whitelist_paths = [] + if whitelist_path is not None and not self._cache_all_paths: + self._cache_whitelist_paths = [ + pattern.strip() + for pattern in whitelist_path.split(",") + if pattern.strip() + ] + + self._initialize_filesystem() + _LOG.info( + "Cache enabled with cache policy: meta cache enabled %s, read cache " + "enabled %s, write cache enabled %s, whitelist file types: %s, " + "whitelist path: %s", + self.meta_cache_enabled, + self.read_cache_enabled, + self.write_cache_enabled, + self._cache_whitelist, + whitelist_path, + ) + + def _initialize_filesystem(self): + self._filesystem_handler = _CachePolicyFileSystemHandler(self) + self.filesystem = pafs.PyFileSystem(self._filesystem_handler) + + def __getstate__(self): + state = self.__dict__.copy() + state.pop("_cache_file_io_lock", None) + state.pop("_filesystem_handler", None) + state.pop("filesystem", None) + return state + + def __setstate__(self, state): + self.__dict__.update(state) + self._process_id = os.getpid() + self._cache_file_io_lock = threading.RLock() + self._initialize_filesystem() + + def _ensure_process(self): + if self._process_id != os.getpid(): + # A fork does not run __setstate__. The thread holding the inherited + # lock may not exist in the child; rebuild its backends lazily too. + self._cache_file_io_lock = threading.RLock() + self._cache_file_io = None + self._origin_delegate = None + self._process_id = os.getpid() + + @property + def _origin_file_io(self): + self._ensure_process() + if self._origin_delegate is None: + with self._cache_file_io_lock: + if self._origin_delegate is None: + self._origin_delegate = self._file_io_factory( + self._path, self._origin_options(self.properties)) + return self._origin_delegate + + def _get_cache_file_io(self, path, operation) -> FileIO: + self._ensure_process() + if self._cache_file_io is None: + with self._cache_file_io_lock: + if self._cache_unavailable: + return self._origin_file_io + if self._cache_file_io is None: + candidate = None + try: + candidate = self._file_io_factory(self._path, self._cache_options) + # Native writers may defer the connection until close. Probe the + # first allowed path before handing out a stream or filesystem. + # False is valid for a file that has not been created yet. + candidate.exists(path) + except Exception as error: + if candidate is not None: + try: + candidate.close() + except Exception: + pass + if not _is_connection_failure(error): + raise + self._disable_cache(path, operation, error) + return self._origin_file_io + self._cache_file_io = candidate + return self._cache_file_io + + def _disable_cache(self, path, operation, error): + self._ensure_process() + with self._cache_file_io_lock: + if not self._cache_unavailable: + self._cache_unavailable = True + _LOG.warning( + "CACHE_POLICY_FALLBACK operation=%s cache_endpoint=%s " + "origin_endpoint=%s path=%s failure_type=%s; " + "using origin for subsequent operations on this FileIO", + operation, self._cache_options.get(OssOptions.OSS_ENDPOINT), + self._origin_file_io.properties.get(OssOptions.OSS_ENDPOINT), + path, type(error).__name__, + exc_info=(type(error), error, error.__traceback__)) + + def _execute(self, path, operation, action, retry=True): + delegate = self._file_io_for(path, operation) + try: + return action(delegate) + except Exception as error: + if delegate is self._origin_file_io or not _is_connection_failure(error): + raise + self._disable_cache(path, operation, error) + if not retry: + # A format writer may have consumed an iterator or persisted partial data. + raise + # Python retains the cache failure as context if origin also fails. + return action(self._origin_file_io) + + def _infer_filesystem_path_prefix(self) -> str: + """Find the backend-only prefix, such as the bucket in Arrow S3 paths.""" + parsed = urlparse(self._path) + if not parsed.scheme: + return "" + + uri_path = parsed.path.lstrip("/") + filesystem_path = self._origin_file_io.to_filesystem_path( + self._path).lstrip("/") + if uri_path and filesystem_path.endswith(uri_path): + return filesystem_path[:-len(uri_path)].rstrip("/") + if not uri_path and parsed.netloc and filesystem_path == parsed.netloc: + return parsed.netloc + return "" + + def _policy_path(self, path: str) -> str: + parsed = urlparse(path) + if parsed.scheme: + return parsed.path or path + + normalized = path.lstrip("/") + prefix = self._filesystem_path_prefix + if prefix and normalized == prefix: + normalized = "" + elif prefix and normalized.startswith(prefix + "/"): + normalized = normalized[len(prefix) + 1:] + return "/" + normalized if normalized else "/" + + def should_cache(self, path: str) -> bool: + policy_path = self._policy_path(path) + if FileType.is_mutable(policy_path): + return False + if FileType.classify(policy_path) not in self._cache_whitelist: + return False + if self._cache_all_paths: + return True + + return any( + pattern in policy_path for pattern in self._cache_whitelist_paths) + + def _should_use_cache(self, path: str, operation: str) -> bool: + enabled = ( + (operation == "meta" and self.meta_cache_enabled) + or (operation == "read" and self.read_cache_enabled) + or (operation == "write" and self.write_cache_enabled) + ) + return not self._cache_unavailable and enabled and self.should_cache(path) + + def _log_route(self, path: str, operation: str, use_cache: bool): + options = ( + self._cache_options + if use_cache else self._origin_file_io.properties) + policy_path = self._policy_path(path) + _LOG.debug( + "CACHE_POLICY_ROUTE operation=%s route=%s endpoint=%s file_type=%s " + "path=%s policy_path=%s", + operation, + "cache" if use_cache else "origin", + options.get(OssOptions.OSS_ENDPOINT), + FileType.classify(policy_path).value, + path, + policy_path, + ) + + def _file_io_for(self, path: str, operation: str) -> FileIO: + self._ensure_process() + use_cache = self._should_use_cache(path, operation) + self._log_route(path, operation, use_cache) + if use_cache: + return self._get_cache_file_io(path, operation) + return self._origin_file_io + + def _origin_file_io_for(self, path: str, operation: str) -> FileIO: + self._log_route(path, operation, False) + return self._origin_file_io + + def new_input_stream(self, path: str): + return self._execute(path, "read", lambda io: io.new_input_stream(path)) + + def new_output_stream(self, path: str): + return self._execute(path, "write", lambda io: io.new_output_stream(path)) + + def get_file_status(self, path: str): + return self._execute(path, "meta", lambda io: io.get_file_status(path)) + + def list_status(self, path: str): + return self._origin_file_io_for(path, "list").list_status(path) + + def exists(self, path: str) -> bool: + return self._execute(path, "meta", lambda io: io.exists(path)) + + def exists_batch(self, paths: List[str]) -> Dict[str, bool]: + grouped = {} + for path in paths: + use_cache = self._should_use_cache(path, "meta") + self._log_route(path, "meta", use_cache) + grouped.setdefault(use_cache, []).append(path) + + result = {} + for use_cache, grouped_paths in grouped.items(): + if use_cache: + values = self._execute( + grouped_paths[0], "meta", lambda io: io.exists_batch(grouped_paths)) + else: + values = self._origin_file_io.exists_batch(grouped_paths) + result.update(values) + return result + + def delete(self, path: str, recursive: bool = False) -> bool: + return self._origin_file_io_for(path, "delete").delete(path, recursive) + + def mkdirs(self, path: str) -> bool: + return self._origin_file_io_for(path, "mkdirs").mkdirs(path) + + def rename(self, src: str, dst: str) -> bool: + return self._origin_file_io_for(src, "rename").rename(src, dst) + + def get_file_size(self, path: str) -> int: + return self._execute(path, "meta", lambda io: io.get_file_size(path)) + + def is_dir(self, path: str) -> bool: + return self._execute(path, "meta", lambda io: io.is_dir(path)) + + def to_filesystem_path(self, path: str) -> str: + # The policy filesystem needs the URI scheme/authority to resolve each + # routed delegate, which may use a different physical path convention. + return path + + def for_path(self, path: str, operation: str): + return self._file_io_for(path, operation).for_path(path, operation) + + def try_to_write_atomic(self, path: str, content: str) -> bool: + return self._origin_file_io_for( + path, "atomic-write").try_to_write_atomic(path, content) + + def create_blob_presigned_url(self, table_root, descriptor, validity) -> str: + return self._origin_file_io.create_blob_presigned_url( + table_root, descriptor, validity) + + @property + def uri_reader_factory(self): + from pypaimon.common.uri_reader import UriReaderFactory + return UriReaderFactory.from_file_io(self) + + def write_parquet(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_parquet(path, *args, **kwargs), retry=False) + + def write_orc(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_orc(path, *args, **kwargs), retry=False) + + def write_avro(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_avro(path, *args, **kwargs), retry=False) + + def write_lance(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_lance(path, *args, **kwargs), retry=False) + + def write_blob(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_blob(path, *args, **kwargs), retry=False) + + def write_mosaic(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_mosaic(path, *args, **kwargs), retry=False) + + def write_vortex(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_vortex(path, *args, **kwargs), retry=False) + + def write_row(self, path: str, *args, **kwargs): + return self._execute(path, "write", lambda io: io.write_row(path, *args, **kwargs), retry=False) + + def __getattr__(self, name): + return getattr(self._origin_file_io, name) + + def close(self): + try: + self._origin_file_io.close() + finally: + if self._cache_file_io is not None: + self._cache_file_io.close() + + +class _CachePolicyFileSystemHandler(FileSystemHandler): + """PyArrow filesystem view that applies the same operation-level policy.""" + + def __init__(self, file_io: CachePolicyFileIO): + self._file_io = file_io + + def _execute(self, path, operation, action): + def apply(io): + backend = io.for_path(path, operation) + return action(backend.filesystem, backend.to_filesystem_path(path)) + return self._file_io._execute(path, operation, apply) + + def _origin_execute(self, path, operation, action): + origin = self._file_io._origin_file_io_for(path, operation).for_path(path, operation) + return action(origin.filesystem, origin.to_filesystem_path(path)) + + @staticmethod + def _logical_info(info, path): + if isinstance(info, pafs.FileInfo): + return pafs.FileInfo(path, info.type, mtime_ns=info.mtime_ns, size=info.size) + return info + + def get_type_name(self) -> str: + return "cache-policy" + + def normalize_path(self, path: str) -> str: + return path + + def get_file_info(self, paths) -> list: + paths = list(paths) + result = [None] * len(paths) + grouped = {} + for index, path in enumerate(paths): + use_cache = self._file_io._should_use_cache(path, "meta") + self._file_io._log_route(path, "meta", use_cache) + parsed = urlparse(path) + grouped.setdefault((use_cache, parsed.scheme, parsed.netloc), []).append((index, path)) + + for (use_cache, _, _), indexed_paths in grouped.items(): + grouped_paths = [path for _, path in indexed_paths] + + def get_infos(io): + backend = io.for_path(grouped_paths[0], "meta") + return backend.filesystem.get_file_info( + [backend.to_filesystem_path(path) for path in grouped_paths]) + if use_cache: + infos = self._file_io._execute(grouped_paths[0], "meta", get_infos) + else: + infos = get_infos(self._file_io._origin_file_io) + for (index, path), info in zip(indexed_paths, infos): + result[index] = self._logical_info(info, path) + return result + + def get_file_info_selector(self, selector: pafs.FileSelector) -> list: + def get_infos(fs, backend_path): + backend_selector = pafs.FileSelector( + backend_path, recursive=selector.recursive, allow_not_found=selector.allow_not_found) + infos = fs.get_file_info(backend_selector) + return [self._logical_info( + info, selector.base_dir.rstrip("/") + "/" + info.path[len(backend_path.rstrip("/")):].lstrip("/")) + for info in infos] + return self._origin_execute(selector.base_dir, "list", get_infos) + + def create_dir(self, path: str, recursive: bool): + return self._origin_execute(path, "mkdirs", lambda fs, p: fs.create_dir(p, recursive=recursive)) + + def delete_dir(self, path: str): + return self._origin_execute(path, "delete", lambda fs, p: fs.delete_dir(p)) + + def delete_dir_contents(self, path: str, missing_dir_ok: bool = False): + return self._origin_execute( + path, "delete", lambda fs, p: fs.delete_dir_contents(p, missing_dir_ok=missing_dir_ok)) + + def delete_root_dir_contents(self): + return self._origin_execute( + self._file_io._path, "delete", lambda fs, p: fs.delete_dir_contents("/", accept_root_dir=True)) + + def delete_file(self, path: str): + return self._origin_execute(path, "delete", lambda fs, p: fs.delete_file(p)) + + def move(self, src: str, dest: str): + origin = self._file_io._origin_file_io_for(src, "rename").for_path(src, "rename") + return origin.filesystem.move(origin.to_filesystem_path(src), origin.to_filesystem_path(dest)) + + def copy_file(self, src: str, dest: str): + origin = self._file_io._origin_file_io_for(src, "copy").for_path(src, "copy") + return origin.filesystem.copy_file(origin.to_filesystem_path(src), origin.to_filesystem_path(dest)) + + def open_input_stream(self, path: str): + return self._execute(path, "read", lambda fs, p: fs.open_input_stream(p)) + + def open_input_file(self, path: str): + return self._execute(path, "read", lambda fs, p: fs.open_input_file(p)) + + def open_output_stream(self, path: str, metadata): + kwargs = {} if metadata is None else {"metadata": metadata} + return self._execute(path, "write", lambda fs, p: fs.open_output_stream(p, **kwargs)) + + def open_append_stream(self, path: str, metadata): + kwargs = {} if metadata is None else {"metadata": metadata} + return self._execute(path, "write", lambda fs, p: fs.open_append_stream(p, **kwargs)) diff --git a/paimon-python/pypaimon/filesystem/caching_file_io.py b/paimon-python/pypaimon/filesystem/caching_file_io.py index 6b88c45b26bf..7f10ebe9f366 100644 --- a/paimon-python/pypaimon/filesystem/caching_file_io.py +++ b/paimon-python/pypaimon/filesystem/caching_file_io.py @@ -517,6 +517,9 @@ def wrap_with_caching_if_needed(file_io, options, cache=None): def properties(self): return self._delegate.properties + def for_path(self, path: str, operation: str): + return self._delegate.for_path(path, operation) + def _is_cacheable(self, path: str): file_type = FileType.classify(path) return (self._cache is not None diff --git a/paimon-python/pypaimon/filesystem/resolving_file_io.py b/paimon-python/pypaimon/filesystem/resolving_file_io.py index b5fd25bc8846..9d7ec405a248 100644 --- a/paimon-python/pypaimon/filesystem/resolving_file_io.py +++ b/paimon-python/pypaimon/filesystem/resolving_file_io.py @@ -115,6 +115,9 @@ def is_dir(self, path: str) -> bool: def to_filesystem_path(self, path: str) -> str: return self._get_fileio(path).to_filesystem_path(path) + def for_path(self, path: str, operation: str): + return self._get_fileio(path).for_path(path, operation) + def write_parquet(self, path: str, data, compression: str = 'zstd', zstd_level: int = 1, **kwargs): return self._get_fileio(path).write_parquet(path, data, compression, diff --git a/paimon-python/pypaimon/filesystem/vortex_utils.py b/paimon-python/pypaimon/filesystem/vortex_utils.py index 2b4a16c45a1d..c81fd9050669 100644 --- a/paimon-python/pypaimon/filesystem/vortex_utils.py +++ b/paimon-python/pypaimon/filesystem/vortex_utils.py @@ -25,7 +25,8 @@ from pypaimon.common.options.config import OssOptions -def to_vortex_specified(file_io: FileIO, file_path: str) -> Tuple[str, Optional[Dict[str, str]]]: +def to_vortex_specified(file_io: FileIO, file_path: str, + operation: str = "read") -> Tuple[str, Optional[Dict[str, str]]]: """Convert path and extract storage options for Vortex store.from_url(). Returns (url, store_kwargs) where store_kwargs can be passed as @@ -34,6 +35,7 @@ def to_vortex_specified(file_io: FileIO, file_path: str) -> Tuple[str, Optional[ """ if hasattr(file_io, 'file_io'): file_io = file_io.file_io() + file_io = file_io.for_path(file_path, operation) if hasattr(file_io, 'get_merged_properties'): properties = file_io.get_merged_properties() @@ -187,7 +189,7 @@ def write_vortex_file(file_io: FileIO, path: str, data: Any, compact: bool = Fal if edition: options = options.with_edition(edition) - file_path_for_vortex, store_kwargs = to_vortex_specified(file_io, path) + file_path_for_vortex, store_kwargs = to_vortex_specified(file_io, path, "write") if store_kwargs: vortex_store, key = _store_for(file_path_for_vortex, store_kwargs) options.write(vortex.array(data), key, store=vortex_store) diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py new file mode 100644 index 000000000000..b05a7b1b907e --- /dev/null +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -0,0 +1,749 @@ +# 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. + +import os +import pickle +import signal +import socket +import tempfile +import threading +import types +import unittest +from concurrent.futures import ThreadPoolExecutor +from unittest.mock import patch +from urllib.parse import urlparse + +import pyarrow.fs as pafs + +from pypaimon.common.file_io import FileIO +from pypaimon.common.options import Options +from pypaimon.common.options.config import CatalogOptions, OssOptions +from pypaimon.filesystem.cache_policy_file_io import CachePolicyFileIO, _is_connection_failure + + +TABLE_ROOT = "oss://test-bucket/database/table" +META_PATH = TABLE_ROOT + "/snapshot/snapshot-1" +MANIFEST_PATH = TABLE_ROOT + "/manifest/manifest-a1b2c3d4-0" +DATA_PATH = TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc" +OTHER_DATA_PATH = TABLE_ROOT + "/bucket-1/data-a1b2c3d4-0.orc" +LATEST_PATH = TABLE_ROOT + "/snapshot/LATEST" + + +class _RecordingFileSystem: + def __init__(self, name): + self.name = name + self.calls = [] + + def normalize_path(self, path): + self.calls.append(("normalize_path", path)) + return path + + def get_file_info(self, value): + self.calls.append(("get_file_info", value)) + if isinstance(value, pafs.FileSelector): + return [(self.name, value.base_dir)] + return [(self.name, path) for path in value] + + def create_dir(self, path, recursive=True): + self.calls.append(("create_dir", path, recursive)) + + def delete_dir(self, path): + self.calls.append(("delete_dir", path)) + + def delete_dir_contents(self, path, **kwargs): + self.calls.append(("delete_dir_contents", path, kwargs)) + + def delete_file(self, path): + self.calls.append(("delete_file", path)) + + def move(self, src, dest): + self.calls.append(("move", src, dest)) + + def copy_file(self, src, dest): + self.calls.append(("copy_file", src, dest)) + + def open_input_stream(self, path): + self.calls.append(("open_input_stream", path)) + return self.name, "open_input_stream", path + + def open_input_file(self, path): + self.calls.append(("open_input_file", path)) + return self.name, "open_input_file", path + + def open_output_stream(self, path, **kwargs): + self.calls.append(("open_output_stream", path, kwargs)) + return self.name, "open_output_stream", path + + def open_append_stream(self, path, **kwargs): + self.calls.append(("open_append_stream", path, kwargs)) + return self.name, "open_append_stream", path + + +class _RecordingFileIO(FileIO): + def __init__(self, name, options): + self.name = name + self.properties = options + self.filesystem = _RecordingFileSystem(name) + self.calls = [] + + def _record(self, operation, *paths): + self.calls.append((operation,) + paths) + return (self.name, operation) + paths + + def new_input_stream(self, path: str): + return self._record("read", path) + + def new_output_stream(self, path: str): + return self._record("write", path) + + def get_file_status(self, path: str): + return self._record("status", path) + + def list_status(self, path: str): + return self._record("list", path) + + def exists(self, path: str) -> bool: + self._record("exists", path) + return True + + def exists_batch(self, paths): + self._record("exists_batch", *paths) + return {path: True for path in paths} + + def delete(self, path: str, recursive: bool = False) -> bool: + self._record("delete", path, recursive) + return True + + def mkdirs(self, path: str) -> bool: + self._record("mkdirs", path) + return True + + def rename(self, src: str, dst: str) -> bool: + self._record("rename", src, dst) + return True + + def get_file_size(self, path: str) -> int: + self._record("size", path) + return 1 + + def is_dir(self, path: str) -> bool: + self._record("is_dir", path) + return False + + def to_filesystem_path(self, path: str) -> str: + parsed = urlparse(path) + if not parsed.scheme: + return path + if self.properties.get(OssOptions.OSS_IMPL) == "jindo": + return parsed.path.lstrip("/") + path_part = parsed.path.lstrip("/") + return parsed.netloc + "/" + path_part if path_part else parsed.netloc + + def write_parquet(self, path: str, *args, **kwargs): + return self._record("write_parquet", path) + + def close(self): + self._record("close") + + +class _RecordingFactory: + def __init__(self): + self.calls = [] + + def __call__(self, path, options): + endpoint = options.get(OssOptions.OSS_ENDPOINT) + impl = options.get(OssOptions.OSS_IMPL) + name = "{}:{}".format(impl, endpoint) + file_io = _RecordingFileIO(name, options) + self.calls.append((path, options, file_io)) + return file_io + + +class _LocalArrowFileIO(_RecordingFileIO): + def __init__(self, name, options, root): + super().__init__(name, options) + self.filesystem = pafs.SubTreeFileSystem(root, pafs.LocalFileSystem()) + + def to_filesystem_path(self, path: str) -> str: + parsed = urlparse(path) + return parsed.path.lstrip("/") if parsed.scheme else path + + +def _options(**overrides): + values = { + CatalogOptions.IO_CACHE_POLICY.key(): "meta,read,write", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "origin-endpoint", + CatalogOptions.IO_CACHE_WHITELIST.key(): "*", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "*", + OssOptions.OSS_ENDPOINT.key(): "cache-endpoint", + OssOptions.OSS_IMPL.key(): "jindo", + } + values.update(overrides) + return Options(values) + + +class CachePolicyFileIOTest(unittest.TestCase): + + def test_equal_endpoints_use_plain_file_io_without_cache_probe(self): + for impl in ("jindo", "legacy"): + for origin in (None, "", " ", "cache-endpoint"): + with self.subTest(impl=impl, origin=origin): + options = _options(**{ + OssOptions.OSS_IMPL.key(): impl, + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): origin}) + factory = _RecordingFactory() + io = CachePolicyFileIO.create(TABLE_ROOT, options, factory) + self.assertIsInstance(io, _RecordingFileIO) + self.assertNotIsInstance(io, CachePolicyFileIO) + io.new_input_stream(DATA_PATH) + io.new_output_stream(DATA_PATH) + io.get_file_status(DATA_PATH) + self.assertEqual(1, len(factory.calls)) + self.assertEqual([("read", DATA_PATH), ("write", DATA_PATH), + ("status", DATA_PATH)], io.calls) + self.assertEqual("cache-endpoint", io.properties.get(OssOptions.OSS_ENDPOINT)) + + def test_vortex_native_options_follow_operation_path_and_disabled_state(self): + from pypaimon.filesystem.vortex_utils import to_vortex_specified + + path = TABLE_ROOT + "/bucket-0/data-a.vortex" + for policy, operation, expected in ( + ("meta", "read", "origin-endpoint"), + ("read", "write", "origin-endpoint"), + ("read", "read", "cache-endpoint"), + ("write", "write", "cache-endpoint")): + io = CachePolicyFileIO.create( + TABLE_ROOT, _options(**{"io-cache.policy": policy}), _RecordingFactory()) + _, storage = to_vortex_specified(io, path, operation) + self.assertIn(expected, storage["endpoint"]) + + factory = _RecordingFactory() + io = CachePolicyFileIO.create( + TABLE_ROOT, _options(**{CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "bucket-1"}), factory) + self.assertIn("origin-endpoint", to_vortex_specified(io, path)[1]["endpoint"]) + self.assertEqual(1, len(factory.calls)) + + io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + io.new_input_stream(path) + with patch.object(factory.calls[-1][2], "new_input_stream", side_effect=ConnectionRefusedError("refused")), \ + self.assertLogs("pypaimon.filesystem.cache_policy_file_io", level="WARNING"): + io.new_input_stream(path) + for operation in ("read", "write"): + self.assertIn("origin-endpoint", to_vortex_specified(io, path, operation)[1]["endpoint"]) + + def test_vortex_writer_selects_write_options(self): + from unittest.mock import MagicMock + from pypaimon.execution.python.write.format_file_writer import write_vortex_file + from pypaimon.filesystem import vortex_utils + + for policy, endpoint, compact, edition in ( + ("read", "origin-endpoint", False, None), + ("write", "cache-endpoint", True, "core2026.08.3")): + with self.subTest(policy=policy): + fake = types.ModuleType("vortex") + fake.array = MagicMock(return_value="array") + fake.store = types.SimpleNamespace(from_url=MagicMock()) + fake_io = types.ModuleType("vortex.io") + fake_io.VortexWriteOptions = MagicMock() + options = MagicMock() + fake_io.VortexWriteOptions.default.return_value = options + fake_io.VortexWriteOptions.compact.return_value = options + options.with_edition.return_value = options + io = CachePolicyFileIO.create( + TABLE_ROOT, _options(**{"io-cache.policy": policy}), _RecordingFactory()) + with patch.dict("sys.modules", {"vortex": fake, "vortex.io": fake_io}), \ + patch.object(vortex_utils, "_store_cache", {}): + write_vortex_file(io, TABLE_ROOT + "/bucket-0/data-a.vortex", [], + compact=compact, edition=edition) + self.assertIn(endpoint, fake.store.from_url.call_args.kwargs["endpoint"]) + options.write.assert_called_once_with( + "array", "database/table/bucket-0/data-a.vortex", + store=fake.store.from_url.return_value) + if compact: + fake_io.VortexWriteOptions.compact.assert_called_once_with() + else: + fake_io.VortexWriteOptions.default.assert_called_once_with() + if edition: + options.with_edition.assert_called_once_with(edition) + else: + options.with_edition.assert_not_called() + + def test_vortex_options_resolve_policy_inside_local_block_cache(self): + from pypaimon.filesystem.caching_file_io import CachingFileIO + from pypaimon.filesystem.vortex_utils import to_vortex_specified + + policy = CachePolicyFileIO.create( + TABLE_ROOT, _options(**{"io-cache.policy": "meta"}), _RecordingFactory()) + wrapped = CachingFileIO(policy, None) + self.assertIn("origin-endpoint", to_vortex_specified( + wrapped, TABLE_ROOT + "/bucket-0/data-a.vortex")[1]["endpoint"]) + + def test_arrow_format_reader_with_resolving_delegates(self): + import pyarrow as pa + import pyarrow.orc as orc + import pyarrow.parquet as pq + from pypaimon.execution.python.read.reader.format_pyarrow_reader import FormatPyArrowReader + from pypaimon.schema.data_types import DataField, AtomicType + + data = pa.table({"id": pa.array([1, 2, 3], type=pa.int64())}) + with tempfile.TemporaryDirectory() as root: + for fmt, write in (("parquet", pq.write_table), ("orc", orc.write_table)): + path = os.path.join(root, "bucket-0", "data-a." + fmt) + os.makedirs(os.path.dirname(path), exist_ok=True) + write(data, path) + for policy in ("meta", "read"): + options = _options(**{ + "resolving-file-io.enabled": "true", "io-cache.policy": policy}) + uri = "file://" + path + with self.subTest(format=fmt, policy=policy): + io = CachePolicyFileIO.create("file://" + root, options) + reader = FormatPyArrowReader(io, fmt, uri, [DataField(0, "id", AtomicType("BIGINT"))], None) + try: + batches = [] + while True: + batch = reader.read_arrow_batch() + if batch is None: + break + batches.append(batch) + self.assertEqual(data.to_pylist(), pa.Table.from_batches(batches).to_pylist()) + info = io.filesystem.get_file_info([uri])[0] + self.assertEqual(uri, info.path) + self.assertEqual(pafs.FileType.File, info.type) + selector = pafs.FileSelector("file://" + os.path.dirname(path)) + self.assertIn(uri, [entry.path for entry in io.filesystem.get_file_info(selector)]) + finally: + reader.close() + io.close() + + @unittest.skipUnless(hasattr(os, "fork"), "requires fork") + def test_fork_during_cache_initialization_recreates_lock_and_backends(self): + parent_pid = os.getpid() + entered, release = threading.Event(), threading.Event() + factory = _RecordingFactory() + + def blocking_factory(path, options): + if os.getpid() == parent_pid and options.get(OssOptions.OSS_ENDPOINT) == "cache-endpoint": + entered.set() + if not release.wait(10): + raise RuntimeError("parent initialization was not released") + return factory(path, options) + + io = CachePolicyFileIO.create(TABLE_ROOT, _options(), blocking_factory) + from pypaimon.catalog.rest.rest_token_file_io import RESTTokenFileIO + key = ("cache-policy-fork", "test") + RESTTokenFileIO._FILE_IO_CACHE[key] = io + self.addCleanup(RESTTokenFileIO._FILE_IO_CACHE.pop, key, None) + origin = io._origin_file_io + worker = threading.Thread(target=io.new_input_stream, args=(DATA_PATH,)) + worker.start() + self.assertTrue(entered.wait(5)) + child = os.fork() + if child == 0: + signal.alarm(8) + try: + retained = RESTTokenFileIO._FILE_IO_CACHE[key] + self.assertIs(io, retained) + self.assertIn("cache-endpoint", retained.new_input_stream(DATA_PATH)[0]) + self.assertIn("origin-endpoint", io.new_input_stream(LATEST_PATH)[0]) + self.assertIsNot(origin, io._origin_file_io) + os._exit(0) + except BaseException: + os._exit(1) + release.set() + worker.join(5) + _, status = os.waitpid(child, 0) + self.assertFalse(worker.is_alive()) + self.assertTrue(os.WIFEXITED(status), status) + self.assertEqual(0, os.WEXITSTATUS(status)) + io.close() + + def test_transport_classifier_preserves_logical_errors(self): + for error in (ConnectionRefusedError("refused"), socket.gaierror("DNS"), + TimeoutError("timeout"), + OSError(b"open file reader failed: Failed to connect Http service: http://cache"), + OSError("AWS Error NETWORK_CONNECTION during HeadObject operation: " + "curlCode: 28, Timeout was reached")): + self.assertTrue(_is_connection_failure(error), repr(error)) + for error in (FileNotFoundError("missing"), PermissionError("denied"), + FileExistsError("exists"), InterruptedError("cancelled"), + OSError("read failed"), OSError("timeout"), + OSError("ErrorCode : 133, No such file"), + OSError("AWS Error ACCESS_DENIED: HTTP 403")): + self.assertFalse(_is_connection_failure(error), repr(error)) + + def test_unreachable_cache_is_probed_once_and_warns_once(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + with patch.object(_RecordingFileIO, "exists", side_effect=ConnectionRefusedError("refused")), \ + self.assertLogs("pypaimon.filesystem.cache_policy_file_io", level="WARNING") as logs: + with ThreadPoolExecutor(max_workers=4) as executor: + results = list(executor.map(file_io.new_input_stream, [DATA_PATH] * 16)) + self.assertTrue(all("origin-endpoint" in result[0] for result in results)) + self.assertIn("origin-endpoint", file_io.new_output_stream(DATA_PATH)[0]) + self.assertEqual(2, len(factory.calls)) + self.assertEqual(1, len(logs.output)) + self.assertIn("CACHE_POLICY_FALLBACK", logs.output[0]) + restored = pickle.loads(pickle.dumps(file_io)) + self.assertIn("origin-endpoint", restored.new_input_stream(DATA_PATH)[0]) + self.assertEqual(2, len(restored._file_io_factory.calls)) + + def test_operation_failure_retries_origin_and_batch_handler_obeys_disabled_state(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + file_io.new_input_stream(DATA_PATH) + cache = factory.calls[1][2] + with patch.object(cache, "exists_batch", side_effect=ConnectionResetError("reset")) as batch, \ + self.assertLogs("pypaimon.filesystem.cache_policy_file_io", level="WARNING"): + self.assertEqual({DATA_PATH: True, LATEST_PATH: True}, + file_io.exists_batch([DATA_PATH, LATEST_PATH])) + self.assertIn("origin-endpoint", file_io.new_input_stream(DATA_PATH)[0]) + infos = file_io._filesystem_handler.get_file_info([DATA_PATH, LATEST_PATH]) + self.assertTrue(all("origin-endpoint" in info[0] for info in infos)) + batch.assert_called_once() + + def test_arrow_handler_operation_failure_retries_origin(self): + for method, args in (("open_input_file", (DATA_PATH,)), + ("open_output_stream", (DATA_PATH, None)), + ("get_file_info", ([DATA_PATH, LATEST_PATH],))): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + file_io.new_input_stream(DATA_PATH) + cache_fs = factory.calls[1][2].filesystem + with patch.object(cache_fs, method, side_effect=TimeoutError("timeout")), \ + self.assertLogs("pypaimon.filesystem.cache_policy_file_io", level="WARNING"): + result = getattr(file_io._filesystem_handler, method)(*args) + self.assertIn("origin-endpoint", str(result)) + self.assertIn("origin-endpoint", file_io.new_input_stream(DATA_PATH)[0]) + + def test_missing_permission_and_generic_errors_do_not_disable_cache(self): + for error in (FileNotFoundError("missing"), PermissionError("denied"), + OSError("read failed")): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + file_io.new_input_stream(DATA_PATH) + with patch.object(factory.calls[1][2], "new_input_stream", side_effect=error): + with self.assertRaises(type(error)) as caught: + file_io.new_input_stream(DATA_PATH) + self.assertIs(error, caught.exception) + self.assertIn("cache-endpoint", file_io.new_input_stream(DATA_PATH)[0]) + self.assertNotIn(("read", DATA_PATH), factory.calls[0][2].calls) + + def test_origin_failure_retains_cache_failure_as_context(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + file_io.new_input_stream(DATA_PATH) + cache_error = ConnectionRefusedError("refused") + origin_error = FileNotFoundError("origin missing") + with patch.object(factory.calls[1][2], "new_input_stream", side_effect=cache_error), \ + patch.object(factory.calls[0][2], "new_input_stream", side_effect=origin_error), \ + self.assertLogs("pypaimon.filesystem.cache_policy_file_io", level="WARNING"): + with self.assertRaises(FileNotFoundError) as caught: + file_io.new_input_stream(DATA_PATH) + self.assertIs(origin_error, caught.exception) + self.assertIs(cache_error, caught.exception.__context__) + + def test_real_native_arrow_unreachable_endpoint_falls_back(self): + self._assert_real_backend_fallback("legacy") + + def test_real_pyjindo_unreachable_endpoint_falls_back(self): + from pypaimon.filesystem.pyarrow_file_io import JINDO_AVAILABLE + if not JINDO_AVAILABLE: + self.skipTest("pyjindosdk is not installed") + self._assert_real_backend_fallback("jindo") + + def _assert_real_backend_fallback(self, impl): + from pypaimon.filesystem.pyarrow_file_io import PyArrowFileIO + + class FastFileIO(PyArrowFileIO): + def _create_s3_retry_config(self, **kwargs): + return super()._create_s3_retry_config( + max_attempts=1, request_timeout=1, connect_timeout=1) + + for first in ("new_input_stream", "new_output_stream", "get_file_status"): + options = _options(**{ + OssOptions.OSS_IMPL.key(): impl, + OssOptions.OSS_ENDPOINT.key(): "127.0.0.1:1", + "fs.oss.accessKeyId": "probe-id", + "fs.oss.accessKeySecret": "probe-secret", + "fs.oss.region": "cn-hangzhou", + "fs.oss.connection.timeout.millisecond": "500", + "fs.oss.timeout.millisecond": "1000", + "fs.oss.retry.count": "0", + }) + origin_options = CachePolicyFileIO._origin_options(options) + origin = _RecordingFileIO("origin", origin_options) + cache = FastFileIO(TABLE_ROOT, options) + self.assertEqual(impl == "jindo", cache._use_jindo) + file_io = CachePolicyFileIO( + TABLE_ROOT, options, origin, options, lambda path, opts: cache) + with self.assertLogs("pypaimon.filesystem.cache_policy_file_io", level="WARNING") as logs: + self.assertEqual("origin", getattr(file_io, first)(DATA_PATH)[0]) + self.assertEqual("origin", file_io.new_input_stream(DATA_PATH)[0]) + self.assertEqual("origin", file_io.new_output_stream(DATA_PATH)[0]) + self.assertEqual(1, len(logs.output)) + file_io.close() + + def test_cache_uses_standard_endpoint_and_origin_is_only_a_fallback(self): + factory = _RecordingFactory() + options = _options(**{"io-cache.endpoint": "unused-cache"}) + file_io = CachePolicyFileIO.create(TABLE_ROOT, options, factory) + self.assertIn("cache-endpoint", file_io.new_input_stream(DATA_PATH)[0]) + self.assertIn("origin-endpoint", file_io.new_input_stream(LATEST_PATH)[0]) + self.assertEqual("cache-endpoint", options.get(OssOptions.OSS_ENDPOINT)) + + options.to_map().pop(CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key()) + file_io = CachePolicyFileIO.create(TABLE_ROOT, options, _RecordingFactory()) + self.assertIn("cache-endpoint", file_io.new_input_stream(LATEST_PATH)[0]) + + def test_routes_jindo_and_native_file_io_above_concrete_implementation(self): + for impl in ("jindo", "legacy"): + with self.subTest(impl=impl): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{OssOptions.OSS_IMPL.key(): impl}), + factory, + ) + + self.assertIsInstance(file_io, CachePolicyFileIO) + self.assertEqual("origin-endpoint", factory.calls[0][1].get( + OssOptions.OSS_ENDPOINT)) + self.assertEqual(impl, factory.calls[0][1].get(OssOptions.OSS_IMPL)) + + self.assertEqual( + ("{}:cache-endpoint".format(impl), "read", DATA_PATH), + file_io.new_input_stream(DATA_PATH), + ) + self.assertEqual(2, len(factory.calls)) + self.assertEqual("cache-endpoint", factory.calls[1][1].get( + OssOptions.OSS_ENDPOINT)) + self.assertEqual(impl, factory.calls[1][1].get(OssOptions.OSS_IMPL)) + + def test_policy_operation_routing(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), factory) + + self.assertIn("cache-endpoint", file_io.new_input_stream(DATA_PATH)[0]) + self.assertIn("cache-endpoint", file_io.new_output_stream(DATA_PATH)[0]) + self.assertIn("cache-endpoint", file_io.get_file_status(DATA_PATH)[0]) + self.assertTrue(file_io.exists(DATA_PATH)) + self.assertIn("origin-endpoint", file_io.list_status(TABLE_ROOT)[0]) + self.assertTrue(file_io.delete(DATA_PATH)) + self.assertTrue(file_io.mkdirs(TABLE_ROOT + "/new-dir")) + self.assertTrue(file_io.rename(DATA_PATH, OTHER_DATA_PATH)) + + origin_calls = factory.calls[0][2].calls + self.assertIn(("list", TABLE_ROOT), origin_calls) + self.assertIn(("delete", DATA_PATH, False), origin_calls) + self.assertIn(("mkdirs", TABLE_ROOT + "/new-dir"), origin_calls) + self.assertIn(("rename", DATA_PATH, OTHER_DATA_PATH), origin_calls) + + def test_debug_log_contains_path_route_and_endpoint(self): + file_io = CachePolicyFileIO.create( + TABLE_ROOT, _options(), _RecordingFactory()) + + with self.assertLogs( + "pypaimon.filesystem.cache_policy_file_io", level="DEBUG") as logs: + file_io.new_input_stream(DATA_PATH) + file_io.delete(META_PATH) + + output = "\n".join(logs.output) + self.assertIn("CACHE_POLICY_ROUTE operation=read route=cache", output) + self.assertIn("endpoint=cache-endpoint", output) + self.assertIn("file_type=STRUCTURED_DATA", output) + self.assertIn("path=" + DATA_PATH, output) + self.assertIn("CACHE_POLICY_ROUTE operation=delete route=origin", output) + self.assertIn("endpoint=origin-endpoint", output) + + def test_individual_policy_tags(self): + cases = [ + ("meta", (True, False, False)), + ("read", (False, True, False)), + ("write", (False, False, True)), + ("meta,read,write", (True, True, True)), + ] + for policy, expected in cases: + with self.subTest(policy=policy): + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{CatalogOptions.IO_CACHE_POLICY.key(): policy}), + _RecordingFactory(), + ) + actual = ( + "cache-endpoint" in file_io.get_file_status(DATA_PATH)[0], + "cache-endpoint" in file_io.new_input_stream(DATA_PATH)[0], + "cache-endpoint" in file_io.new_output_stream(DATA_PATH)[0], + ) + self.assertEqual(expected, actual) + + def test_file_type_path_whitelist_and_mutable_files(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{ + CatalogOptions.IO_CACHE_WHITELIST.key(): "meta,data", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "manifest,bucket-0", + }), + factory, + ) + + self.assertTrue(file_io.should_cache(MANIFEST_PATH)) + self.assertTrue(file_io.should_cache(DATA_PATH)) + self.assertFalse(file_io.should_cache(META_PATH)) + self.assertFalse(file_io.should_cache(OTHER_DATA_PATH)) + self.assertFalse(file_io.should_cache(LATEST_PATH)) + + def test_native_filesystem_bucket_prefix_is_not_part_of_policy_path(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{ + OssOptions.OSS_IMPL.key(): "legacy", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "test-bucket", + }), + factory, + ) + + converted_path = "test-bucket/database/table/bucket-0/data.orc" + self.assertFalse(file_io.should_cache(converted_path)) + + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{ + OssOptions.OSS_IMPL.key(): "legacy", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "bucket-0", + }), + _RecordingFactory(), + ) + self.assertTrue(file_io.should_cache(converted_path)) + + def test_default_and_invalid_whitelists(self): + options = _options() + options.to_map().pop(CatalogOptions.IO_CACHE_WHITELIST.key()) + options.to_map().pop(CatalogOptions.IO_CACHE_WHITELIST_PATH.key()) + file_io = CachePolicyFileIO.create( + TABLE_ROOT, options, _RecordingFactory()) + self.assertTrue(file_io.should_cache(META_PATH)) + self.assertTrue(file_io.should_cache(DATA_PATH)) + + for whitelist in ("", "manifest,unknown"): + with self.subTest(whitelist=whitelist): + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{ + CatalogOptions.IO_CACHE_WHITELIST.key(): whitelist, + }), + _RecordingFactory(), + ) + self.assertFalse(file_io.should_cache(META_PATH)) + self.assertFalse(file_io.should_cache(DATA_PATH)) + + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): ""}), + _RecordingFactory(), + ) + self.assertFalse(file_io.should_cache(DATA_PATH)) + + def test_filesystem_routes_direct_pyarrow_access(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{CatalogOptions.IO_CACHE_WHITELIST.key(): "data"}), + factory, + ) + handler = file_io._filesystem_handler + + self.assertIsInstance(file_io.filesystem, pafs.PyFileSystem) + self.assertIn("cache-endpoint", handler.open_input_file(DATA_PATH)[0]) + self.assertIn("origin-endpoint", handler.open_input_file(META_PATH)[0]) + self.assertIn("cache-endpoint", handler.open_output_stream(DATA_PATH, None)[0]) + + infos = handler.get_file_info([META_PATH, DATA_PATH, OTHER_DATA_PATH]) + self.assertIn("origin-endpoint", infos[0][0]) + self.assertIn("cache-endpoint", infos[1][0]) + self.assertIn("cache-endpoint", infos[2][0]) + + def test_pyarrow_filesystem_invokes_policy_handler(self): + with tempfile.TemporaryDirectory() as origin_dir, \ + tempfile.TemporaryDirectory() as cache_dir: + relative_path = "bucket-0/data.orc" + for root, content in ((origin_dir, b"origin"), (cache_dir, b"cache")): + full_path = os.path.join(root, relative_path) + os.makedirs(os.path.dirname(full_path)) + with open(full_path, "wb") as output: + output.write(content) + + options = _options(**{ + CatalogOptions.IO_CACHE_POLICY.key(): "read", + CatalogOptions.IO_CACHE_WHITELIST.key(): "data", + }) + origin_file_io = _LocalArrowFileIO("origin", options, origin_dir) + cache_file_io = _LocalArrowFileIO("cache", options, cache_dir) + file_io = CachePolicyFileIO( + TABLE_ROOT, + options, + origin_file_io, + options, + lambda path, cache_options: cache_file_io, + ) + + with file_io.filesystem.open_input_file(relative_path) as input_file: + self.assertEqual(b"cache", input_file.read()) + + def test_missing_or_none_policy_disables_wrapper(self): + for policy in (None, "none", "none,read"): + with self.subTest(policy=policy): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{CatalogOptions.IO_CACHE_POLICY.key(): policy}), + factory, + ) + self.assertNotIsInstance(file_io, CachePolicyFileIO) + self.assertEqual(1, len(factory.calls)) + self.assertEqual( + "origin-endpoint", factory.calls[0][1].get(OssOptions.OSS_ENDPOINT)) + + def test_policy_does_not_require_vpc_validation(self): + file_io = CachePolicyFileIO.create(TABLE_ROOT, _options(), _RecordingFactory()) + self.assertIsInstance(file_io, CachePolicyFileIO) + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{ + "io-cache.vpc-validated": False, + "io-cache.ignore-vpc-validate": False, + }), + _RecordingFactory(), + ) + self.assertIn("cache-endpoint", file_io.new_input_stream(DATA_PATH)[0]) + + def test_serialization_restores_policy_filesystem(self): + file_io = CachePolicyFileIO.create( + TABLE_ROOT, _options(), _RecordingFactory()) + restored = pickle.loads(pickle.dumps(file_io)) + + self.assertTrue(restored.should_cache(DATA_PATH)) + self.assertIsInstance(restored.filesystem, pafs.PyFileSystem) + self.assertIn( + "cache-endpoint", + restored._filesystem_handler.open_input_file(DATA_PATH)[0], + ) + + +if __name__ == '__main__': + unittest.main() diff --git a/paimon-python/pypaimon/tests/file_type_test.py b/paimon-python/pypaimon/tests/file_type_test.py index 31f9bdb56a41..840329fcdec5 100644 --- a/paimon-python/pypaimon/tests/file_type_test.py +++ b/paimon-python/pypaimon/tests/file_type_test.py @@ -126,6 +126,15 @@ def test_parse_whitelist(self): FileType.parse_whitelist("data")) self.assertEqual(set(FileType), FileType.parse_whitelist("*")) + def test_parse_whitelist(self): + self.assertEqual( + set(FileType), + FileType.parse_whitelist( + " meta, global-index, bucket-index, data, file-index ")) + self.assertEqual(set(), FileType.parse_whitelist("")) + self.assertEqual(set(), FileType.parse_whitelist("manifest,unknown")) + self.assertEqual(set(), FileType.parse_whitelist(None)) + class FileTypeMutableTest(unittest.TestCase): diff --git a/paimon-python/pypaimon/tests/rest/rest_token_file_io_test.py b/paimon-python/pypaimon/tests/rest/rest_token_file_io_test.py index ad76d12d03d6..c56c077d5e8d 100644 --- a/paimon-python/pypaimon/tests/rest/rest_token_file_io_test.py +++ b/paimon-python/pypaimon/tests/rest/rest_token_file_io_test.py @@ -37,6 +37,7 @@ from pypaimon.common.identifier import Identifier from pypaimon.common.options import Options from pypaimon.common.options.config import CatalogOptions, OssOptions +from pypaimon.filesystem.cache_policy_file_io import CachePolicyFileIO from pypaimon.filesystem.local_file_io import LocalFileIO from pypaimon.table.row.blob import BlobDescriptor @@ -666,11 +667,12 @@ def test_pickle_serialization(self): with open(expected_path, 'rb') as f: self.assertEqual(f.read(), test_content) - def test_dlf_oss_endpoint_overrides_token_endpoint(self): - """Test that DLF OSS endpoint overrides the standard OSS endpoint in token.""" + def test_dlf_endpoint_has_highest_priority(self): + """A client DLF endpoint overrides both client and server OSS endpoints.""" dlf_oss_endpoint = "https://dlf-custom-endpoint.oss-cn-hangzhou.aliyuncs.com" catalog_options = { - CatalogOptions.DLF_OSS_ENDPOINT.key(): dlf_oss_endpoint + CatalogOptions.DLF_OSS_ENDPOINT.key(): dlf_oss_endpoint, + OssOptions.OSS_ENDPOINT.key(): "client-standard-endpoint", } with patch.object(RESTTokenFileIO, 'try_to_refresh_token'): @@ -690,11 +692,13 @@ def test_dlf_oss_endpoint_overrides_token_endpoint(self): # Merge token with catalog options merged_token = file_io._merge_token_with_catalog_options(token) - # Verify DLF OSS endpoint overrides the standard endpoint self.assertEqual( merged_token[OssOptions.OSS_ENDPOINT.key()], dlf_oss_endpoint, - "DLF OSS endpoint should override the standard OSS endpoint in token" + ) + self.assertEqual( + dlf_oss_endpoint, + file_io._merged_options(RESTToken(token, 0)).get(OssOptions.OSS_ENDPOINT), ) # Verify other token properties are preserved self.assertEqual( @@ -702,12 +706,169 @@ def test_dlf_oss_endpoint_overrides_token_endpoint(self): "test-access-key", "Other token properties should be preserved" ) + + token.pop(OssOptions.OSS_ENDPOINT.key()) + merged_token = file_io._merge_token_with_catalog_options(token) + self.assertEqual(dlf_oss_endpoint, merged_token[OssOptions.OSS_ENDPOINT.key()]) self.assertEqual( merged_token["fs.oss.accessKeySecret"], "test-secret-key", "Other token properties should be preserved" ) + def test_client_cache_settings_take_precedence(self): + catalog_options = Options({ + OssOptions.OSS_ENDPOINT.key(): "client-endpoint", + CatalogOptions.DLF_OSS_ENDPOINT.key(): "client-dlf-endpoint", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "client-origin", + CatalogOptions.IO_CACHE_POLICY.key(): "meta,read", + CatalogOptions.IO_CACHE_WHITELIST.key(): "meta", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "manifest", + "io-cache.enabled": "false", + "io-cache.custom-option": "client-value", + }) + file_io = RESTTokenFileIO( + self.identifier, self.warehouse_path, catalog_options) + server_options = { + OssOptions.OSS_ENDPOINT.key(): "server-cache", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "server-origin", + CatalogOptions.IO_CACHE_POLICY.key(): "none", + CatalogOptions.IO_CACHE_WHITELIST.key(): "data", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "bucket-0", + "io-cache.enabled": "true", + "io-cache.custom-option": "server-value", + OssOptions.OSS_SECURITY_TOKEN.key(): "server-credentials", + } + merged_token = file_io._merge_token_with_catalog_options(server_options) + options = file_io._merged_options(RESTToken(server_options, 0)) + for key, value in catalog_options.to_map().items(): + if key.startswith("io-cache."): + self.assertEqual(value, merged_token[key]) + self.assertEqual(value, options.to_map()[key]) + self.assertEqual("client-dlf-endpoint", options.get(OssOptions.OSS_ENDPOINT)) + self.assertEqual("server-credentials", options.get(OssOptions.OSS_SECURITY_TOKEN)) + self.assertEqual("server-cache", server_options[OssOptions.OSS_ENDPOINT.key()]) + self.assertEqual("client-endpoint", catalog_options.get(OssOptions.OSS_ENDPOINT)) + + def test_standard_client_endpoint_and_empty_cache_overrides(self): + server = { + OssOptions.OSS_ENDPOINT.key(): "server-cache", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "server-origin", + CatalogOptions.IO_CACHE_POLICY.key(): "read", + CatalogOptions.IO_CACHE_WHITELIST.key(): "data", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "bucket-0", + } + for key in (CatalogOptions.IO_CACHE_POLICY.key(), + CatalogOptions.IO_CACHE_WHITELIST.key(), + CatalogOptions.IO_CACHE_WHITELIST_PATH.key()): + for value in ("", "none" if key == CatalogOptions.IO_CACHE_POLICY.key() else " "): + with self.subTest(key=key, value=value): + client = Options({OssOptions.OSS_ENDPOINT.key(): "client-endpoint", key: value, + CatalogOptions.DLF_OSS_ENDPOINT.key(): " "}) + file_io = RESTTokenFileIO(self.identifier, self.warehouse_path, client) + options = file_io._merged_options(RESTToken(server, 0)) + self.assertEqual("client-endpoint", options.get(OssOptions.OSS_ENDPOINT)) + self.assertEqual(value, options.to_map()[key]) + io = CachePolicyFileIO.create(self.warehouse_path, options) + self.addCleanup(io.close) + if isinstance(io, CachePolicyFileIO): + self.assertIs(io._origin_file_io, io.for_path( + "oss://bucket/table/bucket-0/data.orc", "read")) + + def test_shared_server_token_does_not_leak_client_routing_overrides(self): + server = { + OssOptions.OSS_ENDPOINT.key(): "server-cache", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "server-origin", + CatalogOptions.IO_CACHE_POLICY.key(): "read", + } + clients = ( + Options({CatalogOptions.DLF_OSS_ENDPOINT.key(): "client-endpoint", + CatalogOptions.IO_CACHE_POLICY.key(): "none"}), + Options({}), + Options({CatalogOptions.DLF_OSS_ENDPOINT.key(): "server-origin"}), + ) + api = MagicMock() + api.load_table_token.return_value = types.SimpleNamespace( + token=server, expires_at_millis=int(time.time() * 1000) + 7_200_000) + with patch.object(RESTTokenFileIO, '_TOKEN_CACHE', {}), \ + patch.object(RESTTokenFileIO, '_TOKEN_LOCKS', {}), \ + patch.object(RESTTokenFileIO, '_build_cache_key', return_value='routing-overrides'): + instances = [RESTTokenFileIO(self.identifier, self.warehouse_path, options) + for options in clients] + for instance in instances: + instance.api_instance = api + delegates = [instance.file_io() for instance in instances] + for delegate in delegates: + self.addCleanup(delegate.close) + self.assertNotIsInstance(delegates[0], CachePolicyFileIO) + self.assertIsInstance(delegates[1], CachePolicyFileIO) + self.assertNotIsInstance(delegates[2], CachePolicyFileIO) + self.assertEqual(server, RESTTokenFileIO._TOKEN_CACHE['routing-overrides'].token) + self.assertEqual("client-endpoint", instances[0].valid_token().token['fs.oss.endpoint']) + self.assertEqual("server-cache", instances[1].valid_token().token['fs.oss.endpoint']) + self.assertEqual("server-origin", instances[2].valid_token().token['fs.oss.endpoint']) + self.assertEqual("none", instances[0]._existing_valid_token().token['io-cache.policy']) + self.assertEqual("read", instances[1]._existing_valid_token().token['io-cache.policy']) + api.load_table_token.assert_called_once_with(self.identifier) + self.assertEqual("server-cache", server['fs.oss.endpoint']) + + def test_client_overrides_survive_token_refresh(self): + client = Options({CatalogOptions.DLF_OSS_ENDPOINT.key(): "client-endpoint", + CatalogOptions.IO_CACHE_POLICY.key(): "none"}) + file_io = RESTTokenFileIO(self.identifier, self.warehouse_path, client) + now = [1700000000] + file_io.api_instance = MagicMock() + file_io.api_instance.load_table_token.side_effect = [types.SimpleNamespace( + token={"fs.oss.endpoint": endpoint, "io-cache.policy": policy, + "fs.oss.securityToken": endpoint}, expires_at_millis=expiry * 1000) + for endpoint, policy, expiry in ( + ("server-first", "read", now[0] + 7200), + ("server-second", "write", now[0] + 14400))] + with patch('pypaimon.catalog.rest.rest_token_file_io.time.time', side_effect=lambda: now[0]), \ + patch.object(RESTTokenFileIO, '_TOKEN_CACHE', {}), \ + patch.object(RESTTokenFileIO, '_TOKEN_LOCKS', {}), \ + patch.object(file_io, '_build_cache_key', return_value='routing-refresh'): + for endpoint in ("server-first", "server-second"): + token = file_io.valid_token() + self.assertEqual("client-endpoint", token.token['fs.oss.endpoint']) + self.assertEqual("none", token.token['io-cache.policy']) + self.assertEqual(endpoint, token.token['fs.oss.securityToken']) + self.assertEqual(endpoint, file_io.token.token['fs.oss.endpoint']) + now[0] += 7200 + self.assertEqual(2, file_io.api_instance.load_table_token.call_count) + + def test_token_file_io_uses_cache_policy_factory(self): + file_io = RESTTokenFileIO( + self.identifier, + "oss://test-bucket/database/table", + Options({OssOptions.OSS_IMPL.key(): "legacy"}), + ) + file_io.token = RESTToken( + { + CatalogOptions.IO_CACHE_POLICY.key(): "read", + OssOptions.OSS_ENDPOINT.key(): "cache-endpoint", + }, + int(time.time() * 1000) + 7_200_000, + ) + + cache = TTLCache( + maxsize=RESTTokenFileIO._FILE_IO_CACHE_MAXSIZE, + ttl=RESTTokenFileIO._FILE_IO_CACHE_TTL, + ) + with patch.object(RESTTokenFileIO, "_FILE_IO_CACHE", cache): + expected = MagicMock() + with patch.object(RESTTokenFileIO, "try_to_refresh_token"), \ + patch.object( + CachePolicyFileIO, "create", return_value=expected) as create: + self.assertIs(expected, file_io.file_io()) + + create.assert_called_once() + path, options = create.call_args[0] + self.assertEqual("oss://test-bucket/database/table", path) + self.assertEqual("legacy", options.get(OssOptions.OSS_IMPL)) + self.assertEqual("read", options.get(CatalogOptions.IO_CACHE_POLICY)) + self.assertEqual("cache-endpoint", options.get(OssOptions.OSS_ENDPOINT)) + def test_catalog_options_not_modified(self): from pypaimon.api.rest_util import RESTUtil diff --git a/paimon-python/pypaimon/utils/file_type.py b/paimon-python/pypaimon/utils/file_type.py index 2d3514c04bd0..ecd28917e131 100644 --- a/paimon-python/pypaimon/utils/file_type.py +++ b/paimon-python/pypaimon/utils/file_type.py @@ -111,6 +111,8 @@ def parse_whitelist(whitelist_str: str) -> set: "file-index": (FileType.FILE_INDEX,), } result = set() + if whitelist_str is None: + return result for name in whitelist_str.split(","): name = name.strip() if name == "*": @@ -119,7 +121,7 @@ def parse_whitelist(whitelist_str: str) -> set: result.update(mapping[name]) elif name: logger.warning( - "Unknown local-cache.whitelist value '%s'. " + "Unknown whitelist value '%s'. " "Supported values: meta, global-index, bucket-index, data, " "structured-data, file-index, or * for all of them.", name,