From 4f0a920d554ebccc7917f12bd3fc33f5a95fdf08 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Thu, 23 Jul 2026 19:30:15 +0800 Subject: [PATCH 01/21] Support dlf cache policy control --- .../paimon/rest/RESTCatalogOptions.java | 2 +- .../paimon/jindo/HadoopCompliantFileIO.java | 35 ++--- .../org/apache/paimon/jindo/JindoFileIO.java | 132 +--------------- .../paimon/jindo/JindoHadoopOptions.java | 146 ++++++++++++++++++ 4 files changed, 169 insertions(+), 146 deletions(-) create mode 100644 paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java 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..6fd82f84047a 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 @@ -117,7 +117,7 @@ public class RESTCatalogOptions { public static final ConfigOption IO_CACHE_ENABLED = ConfigOptions.key("io-cache.enabled") .booleanType() - .defaultValue(false) + .defaultValue(true) .withDescription( "Enable cache for visiting files using file io (currently only JindoFileIO supports cache)."); diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java index f52e1d8c16dc..c514e1be0fcb 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java @@ -106,27 +106,20 @@ public void configure(CatalogContext context) { return; } // Enable file io cache - if (context.options().get("fs.jindocache.namespace.rpc.address") == null) { - LOG.info( - "FileIO cache is enabled but JindoCache RPC address is not set, fallback to no-cache"); - } else { - metaCacheEnabled = - context.options().get(IO_CACHE_POLICY).contains(META_CACHE_ENABLED_TAG); - readCacheEnabled = - context.options().get(IO_CACHE_POLICY).contains(READ_CACHE_ENABLED_TAG); - writeCacheEnabled = - context.options().get(IO_CACHE_POLICY).contains(WRITE_CACHE_ENABLED_TAG); - String whitelist = context.options().get(IO_CACHE_WHITELIST_PATH); - if (!whitelist.equals("*")) { - cacheWhitelistPaths = Lists.newArrayList(whitelist.split(",")); - } - LOG.info( - "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist path: {}", - metaCacheEnabled, - readCacheEnabled, - writeCacheEnabled, - whitelist); - } + metaCacheEnabled = context.options().get(IO_CACHE_POLICY).contains(META_CACHE_ENABLED_TAG); + readCacheEnabled = context.options().get(IO_CACHE_POLICY).contains(READ_CACHE_ENABLED_TAG); + writeCacheEnabled = + context.options().get(IO_CACHE_POLICY).contains(WRITE_CACHE_ENABLED_TAG); + String whitelist = context.options().get(IO_CACHE_WHITELIST_PATH); + if (!whitelist.equals("*")) { + cacheWhitelistPaths = Lists.newArrayList(whitelist.split(",")); + } + LOG.info( + "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist path: {}", + metaCacheEnabled, + readCacheEnabled, + writeCacheEnabled, + whitelist); } @Override diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java index 5afb528a6234..36954a589fb5 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java @@ -24,32 +24,24 @@ import org.apache.paimon.fs.HadoopOptionsProvider; import org.apache.paimon.fs.Path; import org.apache.paimon.fs.TwoPhaseOutputStream; -import org.apache.paimon.options.ConfigOption; -import org.apache.paimon.options.ConfigOptions; import org.apache.paimon.options.Options; import org.apache.paimon.plugin.PluginLoader; import org.apache.paimon.utils.IOUtils; import org.apache.paimon.utils.Pair; -import org.apache.paimon.utils.SensitiveConfigUtils; import com.aliyun.jindodata.common.JindoHadoopSystem; import com.aliyun.jindodata.dls.JindoDlsFileSystem; import com.aliyun.jindodata.oss.JindoOssFileSystem; -import com.aliyun.jindodata.oss.auth.SimpleCredentialsProvider; import com.aliyun.jindodata.store.JindoMpuStore; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; - import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; -import java.util.HashMap; -import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @@ -64,40 +56,6 @@ public class JindoFileIO extends HadoopCompliantFileIO implements HadoopOptionsP private static final Logger LOG = LoggerFactory.getLogger(JindoFileIO.class); - /** - * In order to simplify, we make paimon oss configuration keys same with hadoop oss module. So, - * we add all configuration key with prefix `fs.` in paimon conf to hadoop conf. - * - *

Not use fs.oss because this FileIO also access dlf/dls scheme. - */ - private static final String[] CONFIG_PREFIXES = {"fs."}; - - private static final String OSS_ACCESS_KEY_ID = "fs.oss.accessKeyId"; - private static final String OSS_ACCESS_KEY_SECRET = "fs.oss.accessKeySecret"; - private static final String OSS_SECURITY_TOKEN = "fs.oss.securityToken"; - private static final String OSS_SHOW_DIR_TIMESTAMP = "fs.oss.show-dir-timestamp"; - - private static final ConfigOption IO_STATS_INTERVAL = - ConfigOptions.key("jindo.io-stats.interval") - .durationType() - .defaultValue(Duration.ZERO) - .withDescription( - "Interval of logging Jindo stream and memory statistics while Jindo " - + "streams are in use, e.g. 1 min. Stream counts cover the " - + "class loader of paimon-jindo, which is the whole JVM unless " - + "jobs bundle their own copy. The shortest interval set in " - + "it is used. 0 (the default) disables it, and streams of " - + "this FileIO are not counted."); - - private static final Map CASE_SENSITIVE_KEYS = - new HashMap() { - { - put(OSS_ACCESS_KEY_ID.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_ID); - put(OSS_ACCESS_KEY_SECRET.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_SECRET); - put(OSS_SECURITY_TOKEN.toLowerCase(Locale.ROOT), OSS_SECURITY_TOKEN); - } - }; - /** * Cache JindoOssFileSystem, at present, there is no good mechanism to ensure that the file * system will be shut down, so here the fs cache is used to avoid resource leakage. @@ -105,10 +63,8 @@ public class JindoFileIO extends HadoopCompliantFileIO implements HadoopOptionsP private static final Map> CACHE = new ConcurrentHashMap<>(); - private Options hadoopOptions; - private Options hadoopOptionsWithCache; + private JindoHadoopOptions jindoHadoopOptions; private boolean allowCache = true; - private Duration ioStatsInterval = IO_STATS_INTERVAL.defaultValue(); private transient BlobPresigner blobPresigner; public JindoFileIO() {} @@ -126,61 +82,7 @@ public boolean isObjectStore() { public void configure(CatalogContext context) { super.configure(context); allowCache = context.options().get(FILE_IO_ALLOW_CACHE); - ioStatsInterval = context.options().get(IO_STATS_INTERVAL); - hadoopOptions = new Options(); - // read all configuration with prefix 'CONFIG_PREFIXES' - for (String key : context.options().keySet()) { - for (String prefix : CONFIG_PREFIXES) { - if (key.startsWith(prefix)) { - String value = context.options().get(key); - if (CASE_SENSITIVE_KEYS.containsKey(key.toLowerCase(Locale.ROOT))) { - key = CASE_SENSITIVE_KEYS.get(key.toLowerCase(Locale.ROOT)); - } - hadoopOptions.set(key, value); - - LOG.debug( - "Adding config entry for {} as {} to Hadoop config", - key, - SensitiveConfigUtils.redactValue(key, hadoopOptions.get(key))); - } - } - } - // as in rest catalog use could define ak for table so we need first use ak. - if (hadoopOptions.containsKey(OSS_ACCESS_KEY_ID) - && hadoopOptions.containsKey(OSS_ACCESS_KEY_SECRET)) { - LOG.info("Using Ak init Jindo."); - // https://github.com/aliyun/alibabacloud-jindodata/blob/master/docs/user/4.x/4.6.x/4.6.1/oss/hadoop/jindosdk_ide_hadoop.md - hadoopOptions.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem"); - hadoopOptions.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS"); - - // Misalignment can greatly affect performance, so the maximum buffer is set here - hadoopOptions.set("fs.oss.read.position.buffer.size", "8388608"); - hadoopOptions.set("fs.oss.credentials.provider", SimpleCredentialsProvider.NAME); - } else { - LOG.info("Using hadoop conf init Jindo."); - context.hadoopConf() - .iterator() - .forEachRemaining(entry -> hadoopOptions.set(entry.getKey(), entry.getValue())); - } - - // Resolving a timestamp for every listed directory is expensive in Jindo. - if (!hadoopOptions.containsKey(OSS_SHOW_DIR_TIMESTAMP)) { - hadoopOptions.set(OSS_SHOW_DIR_TIMESTAMP, "false"); - } - - JindoUserAgent.apply(context.options(), hadoopOptions); - - // another config when enable cache - hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); - hadoopOptionsWithCache.set("fs.xengine", "jindocache"); - if (!hadoopOptionsWithCache.containsKey("fs.jindocache.client.metrics.enable")) { - // enable metrics report by default - hadoopOptionsWithCache.set("fs.jindocache.client.metrics.enable", "true"); - } - // Workaround: following configurations to avoid bug in some JindoSDK versions - hadoopOptionsWithCache.set("fs.oss.read.profile.columnar.use-pread", "false"); - hadoopOptionsWithCache.set( - "fs.jindocache.read.profile.columnar.readahead.pread.enable", "false"); + jindoHadoopOptions = new JindoHadoopOptions(context); } /** @@ -200,11 +102,7 @@ public Options hadoopOptions(Path path, String opType) { } else if (opType.equalsIgnoreCase("meta")) { shouldCache = metaCacheEnabled && shouldCache(path); } - if (shouldCache) { - return hadoopOptionsWithCache; - } else { - return hadoopOptions; - } + return jindoHadoopOptions.get(shouldCache); } @Override @@ -224,10 +122,7 @@ public TwoPhaseOutputStream newTwoPhaseOutputStream(Path path, boolean overwrite return super.newTwoPhaseOutputStream(path, overwrite); } return new JindoTwoPhaseOutputStream( - new JindoMultiPartUpload(mpuStore, fs.getWorkingDirectory()), - hadoopPath, - path, - ioStatsInterval()); + new JindoMultiPartUpload(mpuStore, fs.getWorkingDirectory()), hadoopPath, path); } @Override @@ -253,7 +148,7 @@ private synchronized BlobPresigner blobPresigner() { thread.setContextClassLoader(loader.submoduleClassLoader()); BlobPresigner presigner = loader.newInstance("org.apache.paimon.jindo.JindoBlobPresigner"); - presigner.configure(hadoopOptions); + presigner.configure(jindoHadoopOptions.get(false)); blobPresigner = presigner; } finally { thread.setContextClassLoader(previous); @@ -279,7 +174,7 @@ protected Pair createFileSystem( org.apache.hadoop.fs.Path path, boolean enableCache) { final String scheme = path.toUri().getScheme(); final String authority = path.toUri().getAuthority(); - Options options = enableCache ? hadoopOptionsWithCache : hadoopOptions; + Options options = jindoHadoopOptions.get(enableCache); Supplier> supplier = () -> { Configuration hadoopConf = new Configuration(false); @@ -314,24 +209,13 @@ protected Pair createFileSystem( }; if (allowCache) { - Pair pair = - CACHE.computeIfAbsent( - new CacheKey(options, scheme, authority), key -> supplier.get()); - // cached file systems are never closed, so the reporter may call into them - JindoIOStats.registerNativeMetrics(pair.getKey(), path); - return pair; + return CACHE.computeIfAbsent( + new CacheKey(options, scheme, authority), key -> supplier.get()); } else { return supplier.get(); } } - @Nullable - @Override - protected Duration ioStatsInterval() { - // FileIOs deserialized from older versions have no interval - return ioStatsInterval; - } - @Override public synchronized void close() { if (blobPresigner != null) { diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java new file mode 100644 index 000000000000..640d616c0757 --- /dev/null +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java @@ -0,0 +1,146 @@ +/* + * 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.options.Options; +import org.apache.paimon.utils.SensitiveConfigUtils; + +import com.aliyun.jindodata.oss.auth.SimpleCredentialsProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; + +/** Jindo {@link JindoHadoopOptions}. */ +public class JindoHadoopOptions { + private static final Logger LOG = LoggerFactory.getLogger(JindoHadoopOptions.class); + + private Options hadoopOptions; + private Options hadoopOptionsWithCache; + + /** + * In order to simplify, we make paimon oss configuration keys same with hadoop oss module. So, + * we add all configuration key with prefix `fs.` in paimon conf to hadoop conf. + * + *

Not use fs.oss because this FileIO also access dlf/dls scheme. + */ + private static final String[] CONFIG_PREFIXES = {"fs."}; + + private static final String OSS_ACCESS_KEY_ID = "fs.oss.accessKeyId"; + private static final String OSS_ACCESS_KEY_SECRET = "fs.oss.accessKeySecret"; + private static final String OSS_SECURITY_TOKEN = "fs.oss.securityToken"; + private static final String OSS_SHOW_DIR_TIMESTAMP = "fs.oss.show-dir-timestamp"; + + private static final Map CASE_SENSITIVE_KEYS = + new HashMap() { + { + put(OSS_ACCESS_KEY_ID.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_ID); + put(OSS_ACCESS_KEY_SECRET.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_SECRET); + put(OSS_SECURITY_TOKEN.toLowerCase(Locale.ROOT), OSS_SECURITY_TOKEN); + } + }; + + private boolean isJindoCacheBackend(CatalogContext context) { + return context.options().get("fs.jindocache.namespace.rpc.address") != null; + } + + public JindoHadoopOptions(CatalogContext context) { + hadoopOptions = new Options(); + // read all configuration with prefix 'CONFIG_PREFIXES' + for (String key : context.options().keySet()) { + for (String prefix : CONFIG_PREFIXES) { + if (key.startsWith(prefix)) { + String value = context.options().get(key); + if (CASE_SENSITIVE_KEYS.containsKey(key.toLowerCase(Locale.ROOT))) { + key = CASE_SENSITIVE_KEYS.get(key.toLowerCase(Locale.ROOT)); + } + hadoopOptions.set(key, value); + + LOG.debug( + "Adding config entry for {} as {} to Hadoop config", + key, + SensitiveConfigUtils.redactValue(key, hadoopOptions.get(key))); + } + } + } + // as in rest catalog use could define ak for table so we need first use ak. + if (hadoopOptions.containsKey(OSS_ACCESS_KEY_ID) + && hadoopOptions.containsKey(OSS_ACCESS_KEY_SECRET)) { + LOG.info("Using Ak init Jindo."); + // https://github.com/aliyun/alibabacloud-jindodata/blob/master/docs/user/4.x/4.6.x/4.6.1/oss/hadoop/jindosdk_ide_hadoop.md + hadoopOptions.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem"); + hadoopOptions.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS"); + + // Misalignment can greatly affect performance, so the maximum buffer is set here + hadoopOptions.set("fs.oss.read.position.buffer.size", "8388608"); + hadoopOptions.set("fs.oss.credentials.provider", SimpleCredentialsProvider.NAME); + } else { + LOG.info("Using hadoop conf init Jindo."); + context.hadoopConf() + .iterator() + .forEachRemaining(entry -> hadoopOptions.set(entry.getKey(), entry.getValue())); + } + + // Resolving a timestamp for every listed directory is expensive in Jindo. + if (!hadoopOptions.containsKey(OSS_SHOW_DIR_TIMESTAMP)) { + hadoopOptions.set(OSS_SHOW_DIR_TIMESTAMP, "false"); + } + + JindoUserAgent.apply(context.options(), hadoopOptions); + + if (isJindoCacheBackend(context)) { + initJindoCacheBackend(context); + } else { + initDLFCacheBackend(context); + } + } + + public Options get(boolean enableCache) { + return enableCache ? hadoopOptionsWithCache : hadoopOptions; + } + + private void initJindoCacheBackend(CatalogContext context) { + // another config using jindocache + hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); + hadoopOptionsWithCache.set("fs.xengine", "jindocache"); + if (!hadoopOptionsWithCache.containsKey("fs.jindocache.client.metrics.enable")) { + // enable metrics report by default + hadoopOptionsWithCache.set("fs.jindocache.client.metrics.enable", "true"); + } + // Workaround: following configurations to avoid bug in some JindoSDK versions + hadoopOptionsWithCache.set("fs.oss.read.profile.columnar.use-pread", "false"); + hadoopOptionsWithCache.set( + "fs.jindocache.read.profile.columnar.readahead.pread.enable", "false"); + } + + private void initDLFCacheBackend(CatalogContext context) { + hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); + // DLF cache provide a fallback OSS endpoint for direct access to OSS without cache + if (context.options().get("fs.oss.direct.endpoint") != null) { + hadoopOptions.set("fs.oss.endpoint", context.options().get("fs.oss.direct.endpoint")); + } + LOG.info( + "Using direct access to OSS endpoint: {}, cache endpoint: {}", + hadoopOptions.get("fs.oss.endpoint"), + hadoopOptionsWithCache.get("fs.oss.endpoint")); + } +} From 15207c61fe7fb7be425bcde49a7a910c3a05773e Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Sun, 26 Jul 2026 17:18:24 +0800 Subject: [PATCH 02/21] [jindo] Fix Jindo Hadoop options serialization --- .../paimon/jindo/JindoHadoopOptions.java | 5 +++- .../paimon/jindo/TestJindoCacheEnable.java | 23 +++++++++++++++++-- .../jindo/TestJindoDlfAccessTracking.java | 6 ++--- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java index 640d616c0757..1cc6f374c04b 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java @@ -26,12 +26,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import java.util.Map; /** Jindo {@link JindoHadoopOptions}. */ -public class JindoHadoopOptions { +public class JindoHadoopOptions implements Serializable { + private static final long serialVersionUID = 1L; + private static final Logger LOG = LoggerFactory.getLogger(JindoHadoopOptions.class); private Options hadoopOptions; diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java index 19a3da7bd533..2e002f848be0 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java @@ -21,6 +21,7 @@ import org.apache.paimon.catalog.CatalogContext; import org.apache.paimon.fs.Path; import org.apache.paimon.options.Options; +import org.apache.paimon.utils.InstantiationUtil; import org.junit.jupiter.api.Test; @@ -48,6 +49,9 @@ private CatalogContext createCatalogContext( } if (setRpcAddress) { options.set(JINDO_CACHE_RPC_ADDRESS, "test-rpc-address:8080"); + } else { + options.set("fs.oss.endpoint", "test-dlf-cache-endpoint"); + options.set("fs.oss.direct.endpoint", "test-oss-endpoint"); } if (cacheWhitelist != null) { options.set(IO_CACHE_WHITELIST_PATH, cacheWhitelist); @@ -130,12 +134,12 @@ public void testCacheDisabledWhenPolicyNone() { } @Test - public void testCacheDisabledWhenRpcAddressMissing() { + public void testDlfCacheEnabledWhenRpcAddressMissing() { CatalogContext context = createCatalogContext(true, "meta,read,write", false, null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); - verifyCacheFlags(fileIO, false, false, false); + verifyCacheFlags(fileIO, true, true, true); } @Test @@ -177,4 +181,19 @@ public void testCacheWhitelist() { assertThat(fileIO.shouldCache(new Path("oss://test-bucket/database/table/dir/file"))) .isTrue(); } + + @Test + public void testSerialization() throws Exception { + CatalogContext context = createCatalogContext(true, "read", false, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + JindoFileIO cloned = InstantiationUtil.clone(fileIO); + Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); + + assertThat(cloned.hadoopOptions(path, "read").get("fs.oss.endpoint")) + .isEqualTo("test-dlf-cache-endpoint"); + assertThat(cloned.hadoopOptions(path, "meta").get("fs.oss.endpoint")) + .isEqualTo("test-oss-endpoint"); + } } diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java index 67132a414883..619d45645c4c 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java @@ -36,11 +36,11 @@ public class TestJindoDlfAccessTracking { private Options getHadoopOptions(JindoFileIO fileIO) { try { - Field field = JindoFileIO.class.getDeclaredField("hadoopOptions"); + Field field = JindoFileIO.class.getDeclaredField("jindoHadoopOptions"); field.setAccessible(true); - return (Options) field.get(fileIO); + return ((JindoHadoopOptions) field.get(fileIO)).get(false); } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException("Failed to access hadoopOptions field", e); + throw new RuntimeException("Failed to access Jindo Hadoop options", e); } } From 22cbde4ba2432cc40fc8ab8932da6c724ee02456 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Sun, 26 Jul 2026 17:48:10 +0800 Subject: [PATCH 03/21] Fix cache fs close --- paimon-filesystems/paimon-jindo/pom.xml | 8 ++- .../org/apache/paimon/jindo/JindoFileIO.java | 12 +++- .../apache/paimon/jindo/JindoFileIOTest.java | 62 +++++++++++++++++++ 3 files changed, 79 insertions(+), 3 deletions(-) diff --git a/paimon-filesystems/paimon-jindo/pom.xml b/paimon-filesystems/paimon-jindo/pom.xml index bef3f1854365..9926d6c817b1 100644 --- a/paimon-filesystems/paimon-jindo/pom.xml +++ b/paimon-filesystems/paimon-jindo/pom.xml @@ -154,6 +154,13 @@ test + + org.apache.hadoop + hadoop-annotations + ${hadoop.version} + test + + commons-collections commons-collections @@ -167,7 +174,6 @@ 1.1.3 - diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java index 36954a589fb5..ca984633069d 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java @@ -230,8 +230,8 @@ public synchronized void close() { } } if (!allowCache) { - fsMap.values().stream().map(Pair::getKey).forEach(IOUtils::closeQuietly); - fsMap.clear(); + closeFileSystems(fsMap); + closeFileSystems(jindoCacheFsMap); } } @@ -247,6 +247,14 @@ String create(Path tableRoot, BlobDescriptor descriptor, Duration validity) void close(); } + private static void closeFileSystems(Map> fileSystems) { + if (fileSystems == null) { + return; + } + fileSystems.values().stream().map(Pair::getKey).forEach(IOUtils::closeQuietly); + fileSystems.clear(); + } + private static class CacheKey { private final Options options; diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java index 0c4d98e516e3..ad55c0e7d57a 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java @@ -45,8 +45,12 @@ import java.security.MessageDigest; import java.time.Duration; import java.util.Date; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import static org.apache.paimon.options.CatalogOptions.FILE_IO_ALLOW_CACHE; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -273,6 +277,49 @@ protected Pair getFileSystemPair( } } + @Test + void closeClosesDirectAndCacheFileSystems() { + JindoFileIO fileIO = createNonCachingFileIO(); + TrackingJindoHadoopSystem directFileSystem = new TrackingJindoHadoopSystem(); + TrackingJindoHadoopSystem cacheFileSystem = new TrackingJindoHadoopSystem(); + fileIO.fsMap = new ConcurrentHashMap<>(); + fileIO.fsMap.put("test-bucket", Pair.of(directFileSystem, "test")); + fileIO.jindoCacheFsMap = new ConcurrentHashMap<>(); + fileIO.jindoCacheFsMap.put("test-bucket", Pair.of(cacheFileSystem, "test")); + + fileIO.close(); + + assertThat(directFileSystem.closeCount.get()).isOne(); + assertThat(cacheFileSystem.closeCount.get()).isOne(); + assertThat(fileIO.fsMap).isEmpty(); + assertThat(fileIO.jindoCacheFsMap).isEmpty(); + + assertThatCode(fileIO::close).doesNotThrowAnyException(); + assertThat(directFileSystem.closeCount.get()).isOne(); + assertThat(cacheFileSystem.closeCount.get()).isOne(); + } + + @Test + void closeHandlesCacheOnlyFileSystem() { + JindoFileIO fileIO = createNonCachingFileIO(); + TrackingJindoHadoopSystem cacheFileSystem = new TrackingJindoHadoopSystem(); + fileIO.jindoCacheFsMap = new ConcurrentHashMap<>(); + fileIO.jindoCacheFsMap.put("test-bucket", Pair.of(cacheFileSystem, "test")); + + assertThatCode(fileIO::close).doesNotThrowAnyException(); + + assertThat(cacheFileSystem.closeCount.get()).isOne(); + assertThat(fileIO.jindoCacheFsMap).isEmpty(); + } + + private JindoFileIO createNonCachingFileIO() { + Options options = new Options(); + options.set(FILE_IO_ALLOW_CACHE, false); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(CatalogContext.create(options)); + return fileIO; + } + private static String sha256Hex(byte[] bytes) throws Exception { StringBuilder result = new StringBuilder(); for (byte value : MessageDigest.getInstance("SHA-256").digest(bytes)) { @@ -280,4 +327,19 @@ private static String sha256Hex(byte[] bytes) throws Exception { } return result.toString(); } + + private static class TrackingJindoHadoopSystem extends JindoHadoopSystem { + + private final AtomicInteger closeCount = new AtomicInteger(); + + @Override + public String getScheme() { + return "test"; + } + + @Override + public void close() { + closeCount.incrementAndGet(); + } + } } From ef87e8d3e25fc6e0fabe69d0cc6c0a66c8906c2c Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Tue, 11 Aug 2026 22:06:18 +0800 Subject: [PATCH 04/21] [jindo] Support DLF cache VPC validation --- .../paimon/rest/RESTCatalogOptions.java | 30 ++++- .../apache/paimon/rest/RESTTokenFileIO.java | 7 +- .../apache/paimon/rest/RESTCatalogTest.java | 13 ++- .../paimon/jindo/HadoopCompliantFileIO.java | 38 ++++-- .../paimon/jindo/JindoHadoopOptions.java | 25 +++- .../paimon/jindo/TestJindoCacheEnable.java | 110 +++++++++++++++++- 6 files changed, 193 insertions(+), 30 deletions(-) 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 6fd82f84047a..7a29f97ea7c8 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 @@ -114,12 +114,40 @@ public class RESTCatalogOptions { + "'openapi' (the earlier ROA HMAC-SHA1 scheme). " + "If not set, will be automatically selected based on endpoint host."); + /** @deprecated Cache enablement is controlled by the policy vended by the REST server. */ + @Deprecated public static final ConfigOption IO_CACHE_ENABLED = ConfigOptions.key("io-cache.enabled") .booleanType() .defaultValue(true) .withDescription( - "Enable cache for visiting files using file io (currently only JindoFileIO supports cache)."); + "Deprecated. Cache enablement is controlled by the policy vended by the REST server."); + + public static final ConfigOption IO_CACHE_IGNORE_VPC_VALIDATE = + ConfigOptions.key("io-cache.ignore-vpc-validate") + .booleanType() + .defaultValue(false) + .withDescription( + "Whether to use the cache endpoint even when the REST server cannot validate VPC connectivity."); + + public static final ConfigOption IO_CACHE_VPC_VALIDATED = + ConfigOptions.key("io-cache.vpc-validated") + .booleanType() + .defaultValue(false) + .withDescription( + "Whether the REST server has validated connectivity from the source VPC to the cache endpoint."); + + public static final ConfigOption IO_CACHE_ENDPOINT = + ConfigOptions.key("io-cache.endpoint") + .stringType() + .noDefaultValue() + .withDescription("The cache endpoint vended by the REST server."); + + 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_PATH = ConfigOptions.key("io-cache.whitelist-path") 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..53aece6d9344 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 @@ -53,7 +53,7 @@ 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.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.utils.Preconditions.checkArgument; /** A {@link FileIO} to support getting token from REST Server. */ @@ -349,9 +349,10 @@ private Map mergeTokenWithCatalogOptions(Map tok if (dlfOssEndpoint != null && !dlfOssEndpoint.isEmpty()) { newToken.put("fs.oss.endpoint", dlfOssEndpoint); } - if (catalogOptions.contains(IO_CACHE_ENABLED)) { + if (catalogOptions.contains(IO_CACHE_IGNORE_VPC_VALIDATE)) { newToken.put( - IO_CACHE_ENABLED.key(), String.valueOf(catalogOptions.get(IO_CACHE_ENABLED))); + IO_CACHE_IGNORE_VPC_VALIDATE.key(), + String.valueOf(catalogOptions.get(IO_CACHE_IGNORE_VPC_VALIDATE))); } return ImmutableMap.copyOf(newToken); } 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..da321725538f 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 @@ -172,6 +172,7 @@ 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.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; 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,12 +2173,14 @@ void testValidToken() throws Exception { } @Test - void testValidTokenWithIOCacheEnabled() throws Exception { + void testValidTokenWithIOCacheIgnoreVpcValidate() throws Exception { Map options = new HashMap<>(); - options.put(IO_CACHE_ENABLED.key(), "true"); + options.put(IO_CACHE_ENABLED.key(), "false"); + options.put(IO_CACHE_IGNORE_VPC_VALIDATE.key(), "true"); this.catalog = newRestCatalogWithDataToken(options); Identifier identifier = - Identifier.create("test_data_token", "table_for_testing_io_cache_enabled"); + Identifier.create( + "test_data_token", "table_for_testing_io_cache_ignore_vpc_validate"); RESTToken expiredDataToken = new RESTToken( ImmutableMap.of("akId", "akId", "akSecret", UUID.randomUUID().toString()), @@ -2188,8 +2191,8 @@ void testValidTokenWithIOCacheEnabled() throws Exception { 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("true", fileDataToken.token().get(IO_CACHE_IGNORE_VPC_VALIDATE.key())); + assertThat(fileDataToken.token()).doesNotContainKey(IO_CACHE_ENABLED.key()); } @Test diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java index c514e1be0fcb..d9da0ba8fedd 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java @@ -26,6 +26,7 @@ import org.apache.paimon.fs.RemoteIterator; import org.apache.paimon.fs.SeekableInputStream; import org.apache.paimon.fs.VectoredReadable; +import org.apache.paimon.options.Options; import org.apache.paimon.utils.Pair; import org.apache.paimon.shade.guava30.com.google.common.collect.Lists; @@ -50,8 +51,10 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; /** @@ -95,22 +98,33 @@ boolean shouldCache(Path path) { @Override public void configure(CatalogContext context) { + metaCacheEnabled = false; + readCacheEnabled = false; + writeCacheEnabled = false; + // Process file io cache configuration - if (!context.options().get(IO_CACHE_ENABLED) - || context.options().get(IO_CACHE_POLICY) == null - || context.options().get(IO_CACHE_POLICY).contains(DISABLE_CACHE_TAG)) { + Options options = context.options(); + String cachePolicy = options.get(IO_CACHE_POLICY); + boolean useVpcValidationProtocol = + options.contains(IO_CACHE_ENDPOINT) || options.contains(IO_CACHE_VPC_VALIDATED); + boolean vpcValidated = !useVpcValidationProtocol || options.get(IO_CACHE_VPC_VALIDATED); + boolean ignoreVpcValidate = options.get(IO_CACHE_IGNORE_VPC_VALIDATE); + if (cachePolicy == null + || cachePolicy.contains(DISABLE_CACHE_TAG) + || (!vpcValidated && !ignoreVpcValidate)) { LOG.debug( - "Cache is disabled with io-cache.enabled={}, io-cache.policy={}", - context.options().get(IO_CACHE_ENABLED), - context.options().get(IO_CACHE_POLICY)); + "Cache is disabled with io-cache.policy={}, io-cache.vpc-validated={}, io-cache.ignore-vpc-validate={}, use-vpc-validation-protocol={}", + cachePolicy, + vpcValidated, + ignoreVpcValidate, + useVpcValidationProtocol); return; } // Enable file io cache - metaCacheEnabled = context.options().get(IO_CACHE_POLICY).contains(META_CACHE_ENABLED_TAG); - readCacheEnabled = context.options().get(IO_CACHE_POLICY).contains(READ_CACHE_ENABLED_TAG); - writeCacheEnabled = - context.options().get(IO_CACHE_POLICY).contains(WRITE_CACHE_ENABLED_TAG); - String whitelist = context.options().get(IO_CACHE_WHITELIST_PATH); + metaCacheEnabled = cachePolicy.contains(META_CACHE_ENABLED_TAG); + readCacheEnabled = cachePolicy.contains(READ_CACHE_ENABLED_TAG); + writeCacheEnabled = cachePolicy.contains(WRITE_CACHE_ENABLED_TAG); + String whitelist = options.get(IO_CACHE_WHITELIST_PATH); if (!whitelist.equals("*")) { cacheWhitelistPaths = Lists.newArrayList(whitelist.split(",")); } diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java index 1cc6f374c04b..c62e691ae2dc 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java @@ -21,6 +21,7 @@ import org.apache.paimon.catalog.CatalogContext; import org.apache.paimon.options.Options; import org.apache.paimon.utils.SensitiveConfigUtils; +import org.apache.paimon.utils.StringUtils; import com.aliyun.jindodata.oss.auth.SimpleCredentialsProvider; import org.slf4j.Logger; @@ -31,6 +32,9 @@ import java.util.Locale; import java.util.Map; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; + /** Jindo {@link JindoHadoopOptions}. */ public class JindoHadoopOptions implements Serializable { private static final long serialVersionUID = 1L; @@ -51,6 +55,8 @@ public class JindoHadoopOptions implements Serializable { private static final String OSS_ACCESS_KEY_ID = "fs.oss.accessKeyId"; private static final String OSS_ACCESS_KEY_SECRET = "fs.oss.accessKeySecret"; private static final String OSS_SECURITY_TOKEN = "fs.oss.securityToken"; + private static final String OSS_ENDPOINT = "fs.oss.endpoint"; + private static final String OSS_DIRECT_ENDPOINT = "fs.oss.direct.endpoint"; private static final String OSS_SHOW_DIR_TIMESTAMP = "fs.oss.show-dir-timestamp"; private static final Map CASE_SENSITIVE_KEYS = @@ -137,13 +143,22 @@ private void initJindoCacheBackend(CatalogContext context) { private void initDLFCacheBackend(CatalogContext context) { hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); - // DLF cache provide a fallback OSS endpoint for direct access to OSS without cache - if (context.options().get("fs.oss.direct.endpoint") != null) { - hadoopOptions.set("fs.oss.endpoint", context.options().get("fs.oss.direct.endpoint")); + + String cacheEndpoint = context.options().get(IO_CACHE_ENDPOINT); + if (!StringUtils.isNullOrWhitespaceOnly(cacheEndpoint)) { + hadoopOptionsWithCache.set(OSS_ENDPOINT, cacheEndpoint); + } + + String originEndpoint = context.options().get(IO_CACHE_ORIGIN_ENDPOINT); + if (StringUtils.isNullOrWhitespaceOnly(originEndpoint)) { + originEndpoint = context.options().get(OSS_DIRECT_ENDPOINT); + } + if (!StringUtils.isNullOrWhitespaceOnly(originEndpoint)) { + hadoopOptions.set(OSS_ENDPOINT, originEndpoint); } LOG.info( "Using direct access to OSS endpoint: {}, cache endpoint: {}", - hadoopOptions.get("fs.oss.endpoint"), - hadoopOptionsWithCache.get("fs.oss.endpoint")); + hadoopOptions.get(OSS_ENDPOINT), + hadoopOptionsWithCache.get(OSS_ENDPOINT)); } } diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java index 2e002f848be0..b49e461cbf3e 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java @@ -28,7 +28,11 @@ import java.lang.reflect.Field; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; +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_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; import static org.assertj.core.api.Assertions.assertThat; @@ -51,7 +55,7 @@ private CatalogContext createCatalogContext( options.set(JINDO_CACHE_RPC_ADDRESS, "test-rpc-address:8080"); } else { options.set("fs.oss.endpoint", "test-dlf-cache-endpoint"); - options.set("fs.oss.direct.endpoint", "test-oss-endpoint"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); } if (cacheWhitelist != null) { options.set(IO_CACHE_WHITELIST_PATH, cacheWhitelist); @@ -59,6 +63,26 @@ private CatalogContext createCatalogContext( return CatalogContext.create(options); } + private CatalogContext createDlfCacheContext( + String cachePolicy, Boolean vpcValidated, boolean ignoreVpcValidate) { + Options options = new Options(); + if (cachePolicy != null) { + options.set(IO_CACHE_POLICY, cachePolicy); + } + options.set( + "fs.oss.endpoint", + Boolean.TRUE.equals(vpcValidated) + ? "test-dlf-cache-endpoint" + : "test-oss-endpoint"); + options.set(IO_CACHE_ENDPOINT, "test-dlf-cache-endpoint"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); + if (vpcValidated != null) { + options.set(IO_CACHE_VPC_VALIDATED, vpcValidated); + } + options.set(IO_CACHE_IGNORE_VPC_VALIDATE, ignoreVpcValidate); + return CatalogContext.create(options); + } + private boolean getCacheFlag(HadoopCompliantFileIO fileIO, String fieldName) { try { Field field = HadoopCompliantFileIO.class.getDeclaredField(fieldName); @@ -116,12 +140,12 @@ public void testCacheEnabledWithCombinedPolicy() { } @Test - public void testCacheDisabledWhenEnabledFalse() { + public void testDeprecatedCacheEnabledOptionIsIgnored() { CatalogContext context = createCatalogContext(false, "meta,read,write", true, null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); - verifyCacheFlags(fileIO, false, false, false); + verifyCacheFlags(fileIO, true, true, true); } @Test @@ -134,7 +158,7 @@ public void testCacheDisabledWhenPolicyNone() { } @Test - public void testDlfCacheEnabledWhenRpcAddressMissing() { + public void testOldBennettDlfCacheProtocolRemainsEnabled() { CatalogContext context = createCatalogContext(true, "meta,read,write", false, null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -142,6 +166,84 @@ public void testDlfCacheEnabledWhenRpcAddressMissing() { verifyCacheFlags(fileIO, true, true, true); } + @Test + public void testDlfCacheOriginEndpointCompatibility() { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "read"); + options.set("fs.oss.endpoint", "test-dlf-cache-endpoint"); + options.set("fs.oss.direct.endpoint", "test-legacy-oss-endpoint"); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(CatalogContext.create(options)); + + Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); + assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) + .isEqualTo("test-legacy-oss-endpoint"); + + options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); + fileIO = new JindoFileIO(); + fileIO.configure(CatalogContext.create(options)); + assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) + .isEqualTo("test-oss-endpoint"); + } + + @Test + public void testDlfCacheDisabledWhenVpcNotValidated() { + CatalogContext context = createDlfCacheContext("meta,read,write", false, false); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); + assertThat(fileIO.hadoopOptions(path, "read").get("fs.oss.endpoint")) + .isEqualTo("test-oss-endpoint"); + } + + @Test + public void testDlfCacheEnabledWhenIgnoringVpcValidation() { + CatalogContext context = createDlfCacheContext("read", false, true); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, true, false); + Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); + assertThat(fileIO.hadoopOptions(path, "read").get("fs.oss.endpoint")) + .isEqualTo("test-dlf-cache-endpoint"); + assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) + .isEqualTo("test-oss-endpoint"); + } + + @Test + public void testDlfCacheEnabledWhenVpcValidated() { + CatalogContext context = createDlfCacheContext("read", true, false); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, true, false); + Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); + assertThat(fileIO.hadoopOptions(path, "read").get("fs.oss.endpoint")) + .isEqualTo("test-dlf-cache-endpoint"); + assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) + .isEqualTo("test-oss-endpoint"); + } + + @Test + public void testDlfCacheNewProtocolDefaultsVpcValidationToFalse() { + CatalogContext context = createDlfCacheContext("meta,read,write", null, false); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + } + + @Test + public void testIgnoreVpcValidationDoesNotOverrideDisabledPolicy() { + CatalogContext context = createDlfCacheContext("none", false, true); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + } + @Test public void testCacheDisabledWhenPolicyNull() { CatalogContext context = createCatalogContext(true, null, true, null); From 6ad9471805715a2a7cc45b6aad6d35c1d500e512 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Tue, 11 Aug 2026 22:14:14 +0800 Subject: [PATCH 05/21] [jindo] Support cache file type whitelist --- .../paimon/rest/RESTCatalogOptions.java | 12 +- .../apache/paimon/fs/cache/CachingFileIO.java | 4 +- .../org/apache/paimon/utils/FileType.java | 35 ++++- .../org/apache/paimon/utils/FileTypeTest.java | 17 +++ .../paimon/jindo/HadoopCompliantFileIO.java | 38 ++--- .../paimon/jindo/TestJindoCacheEnable.java | 143 ++++++++++++++---- 6 files changed, 195 insertions(+), 54 deletions(-) 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 7a29f97ea7c8..430a5d4e190a 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 @@ -149,12 +149,22 @@ public class RESTCatalogOptions { .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("meta,global-index") + .withDescription( + "Comma-separated list of file types allowed to use the cache endpoint. " + + "Supported values: meta, global-index, bucket-index, data, file-index."); + + /** @deprecated Use {@link #IO_CACHE_WHITELIST}. Path patterns are no longer supported. */ + @Deprecated public static final ConfigOption IO_CACHE_WHITELIST_PATH = ConfigOptions.key("io-cache.whitelist-path") .stringType() .defaultValue("bucket,manifest,index") .withDescription( - "Cache is only applied to paths which contain the specified pattern, and * means all paths."); + "Deprecated. Use io-cache.whitelist to select cacheable file types."); public static final ConfigOption IO_CACHE_POLICY = ConfigOptions.key("io-cache.policy") diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java index 70ad66cfad04..436d920c1dcc 100644 --- a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java @@ -110,7 +110,9 @@ public static FileIO wrapWithCachingIfNeeded( } Options options = context.options(); Set whitelist = - FileType.parseWhitelist(options.get(CatalogOptions.LOCAL_CACHE_WHITELIST)); + FileType.parseWhitelist( + CatalogOptions.LOCAL_CACHE_WHITELIST.key(), + options.get(CatalogOptions.LOCAL_CACHE_WHITELIST)); if (whitelist.isEmpty()) { return fileIO; } 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..011a9b76cc56 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 @@ -39,10 +39,29 @@ * */ public enum FileType { + /** + * Table metadata files, including snapshots, schemas, manifests, statistics, tags, changelog + * metadata, hint files, success files, consumers, and services. + */ META, + + /** + * Data files, including ORC, Parquet, changelog data, blob and vector files. Unrecognized files + * are also classified as data by default. + */ DATA, + + /** Bucket-level {@code index-*} files, such as hash indexes and deletion-vector indexes. */ BUCKET_INDEX, + + /** + * Table-level {@code global-index-*.index} files, such as BTree, Lumina, and full-text indexes. + */ GLOBAL_INDEX, + + /** + * Non-global data-file-level {@code *.index} files, such as Bloom filter and bitmap indexes. + */ FILE_INDEX; private static final Logger LOG = LoggerFactory.getLogger(FileType.class); @@ -88,7 +107,20 @@ public boolean isIndex() { /** Parse a comma-separated whitelist string into a set of {@link FileType}s. */ public static Set parseWhitelist(String whitelist) { + return parseWhitelist("file type whitelist", whitelist); + } + + /** + * Parse a comma-separated whitelist string into a set of {@link FileType}s. + * + * @param optionKey configuration key used when reporting unsupported values + * @param whitelist comma-separated file type names + */ + public static Set parseWhitelist(String optionKey, String whitelist) { Set result = EnumSet.noneOf(FileType.class); + if (whitelist == null) { + return result; + } for (String name : whitelist.split(",")) { name = name.trim(); switch (name) { @@ -113,9 +145,10 @@ public static Set parseWhitelist(String whitelist) { default: if (!name.isEmpty()) { LOG.warn( - "Unknown local-cache.whitelist value '{}'. " + "Unknown {} value '{}'. " + "Supported values: meta, global-index, bucket-index, data, file-index, " + "or * for all of them.", + optionKey, name); } break; 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..f014a20d4353 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,21 @@ public void testChangelogMetadataIsImmutable() { assertThat(FileType.isMutable(changelog)).isFalse(); } + @Test + public void testParseWhitelist() { + assertThat( + FileType.parseWhitelist( + "test-cache.whitelist", + " meta, global-index, bucket-index, data, file-index ")) + .containsExactlyInAnyOrderElementsOf(EnumSet.allOf(FileType.class)); + assertThat(FileType.parseWhitelist("test-cache.whitelist", "")) + .isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist("test-cache.whitelist", "manifest,unknown")) + .isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist("test-cache.whitelist", null)) + .isEqualTo(Collections.emptySet()); + } + // ===== META files ===== @Test diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java index d9da0ba8fedd..4f0c00a77f13 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java @@ -27,10 +27,9 @@ import org.apache.paimon.fs.SeekableInputStream; import org.apache.paimon.fs.VectoredReadable; import org.apache.paimon.options.Options; +import org.apache.paimon.utils.FileType; import org.apache.paimon.utils.Pair; -import org.apache.paimon.shade.guava30.com.google.common.collect.Lists; - import com.aliyun.jindodata.common.JindoHadoopSystem; import com.aliyun.jindodata.types.JindoHadoopFileStatus; import org.apache.hadoop.fs.FSDataInputStream; @@ -46,8 +45,10 @@ import java.net.URI; import java.time.Duration; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; @@ -55,7 +56,7 @@ import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; /** * Hadoop {@link FileIO}. @@ -67,7 +68,9 @@ public abstract class HadoopCompliantFileIO implements FileIO { private static final long serialVersionUID = 1L; - /// Detailed cache strategies are retrieved from REST server. + // Cache policy values select operation types. In particular, policy "meta" controls metadata + // operations such as getFileStatus and exists. It is independent from whitelist "meta", which + // selects paths classified as FileType.META. private static final String META_CACHE_ENABLED_TAG = "meta"; private static final String READ_CACHE_ENABLED_TAG = "read"; private static final String WRITE_CACHE_ENABLED_TAG = "write"; @@ -80,20 +83,12 @@ public abstract class HadoopCompliantFileIO implements FileIO { protected transient volatile Map> fsMap; protected transient volatile Map> jindoCacheFsMap; - // Only enable cache for path which is generated with uuid - private List cacheWhitelistPaths = new ArrayList<>(); + private Set cacheWhitelist = EnumSet.noneOf(FileType.class); boolean shouldCache(Path path) { - if (cacheWhitelistPaths.isEmpty()) { - return true; - } - String pathStr = path.toUri().getPath(); - for (String pattern : cacheWhitelistPaths) { - if (pathStr.contains(pattern)) { - return true; - } - } - return false; + return cacheWhitelist != null + && !FileType.isMutable(path) + && cacheWhitelist.contains(FileType.classify(path)); } @Override @@ -101,6 +96,7 @@ public void configure(CatalogContext context) { metaCacheEnabled = false; readCacheEnabled = false; writeCacheEnabled = false; + cacheWhitelist = EnumSet.noneOf(FileType.class); // Process file io cache configuration Options options = context.options(); @@ -124,16 +120,14 @@ public void configure(CatalogContext context) { metaCacheEnabled = cachePolicy.contains(META_CACHE_ENABLED_TAG); readCacheEnabled = cachePolicy.contains(READ_CACHE_ENABLED_TAG); writeCacheEnabled = cachePolicy.contains(WRITE_CACHE_ENABLED_TAG); - String whitelist = options.get(IO_CACHE_WHITELIST_PATH); - if (!whitelist.equals("*")) { - cacheWhitelistPaths = Lists.newArrayList(whitelist.split(",")); - } + String whitelist = options.get(IO_CACHE_WHITELIST); + cacheWhitelist = FileType.parseWhitelist(IO_CACHE_WHITELIST.key(), whitelist); LOG.info( - "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist path: {}", + "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist file types: {}", metaCacheEnabled, readCacheEnabled, writeCacheEnabled, - whitelist); + cacheWhitelist); } @Override diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java index b49e461cbf3e..575f105dcfaf 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java @@ -33,6 +33,7 @@ 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_VPC_VALIDATED; +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; @@ -40,6 +41,15 @@ public class TestJindoCacheEnable { private static final String JINDO_CACHE_RPC_ADDRESS = "fs.jindocache.namespace.rpc.address"; + private static final String TABLE_ROOT = "oss://test-bucket/database/table"; + + private static final Path META_PATH = new Path(TABLE_ROOT + "/snapshot/snapshot-1"); + private static final Path GLOBAL_INDEX_PATH = + new Path(TABLE_ROOT + "/index/btree-global-index-a1b2c3d4.index"); + private static final Path BUCKET_INDEX_PATH = new Path(TABLE_ROOT + "/index/index-a1b2c3d4-0"); + private static final Path DATA_PATH = new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc"); + private static final Path FILE_INDEX_PATH = + new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc.index"); private CatalogContext createCatalogContext( boolean cacheEnabled, @@ -58,7 +68,7 @@ private CatalogContext createCatalogContext( options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); } if (cacheWhitelist != null) { - options.set(IO_CACHE_WHITELIST_PATH, cacheWhitelist); + options.set(IO_CACHE_WHITELIST, cacheWhitelist); } return CatalogContext.create(options); } @@ -80,6 +90,7 @@ private CatalogContext createDlfCacheContext( options.set(IO_CACHE_VPC_VALIDATED, vpcValidated); } options.set(IO_CACHE_IGNORE_VPC_VALIDATE, ignoreVpcValidate); + options.set(IO_CACHE_WHITELIST, "data"); return CatalogContext.create(options); } @@ -254,48 +265,122 @@ public void testCacheDisabledWhenPolicyNull() { } @Test - public void testCacheWhitelist() { - // default config + public void testDefaultCacheWhitelist() { CatalogContext context = createCatalogContext(true, "meta,read,write", true, null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); - assertThat( - fileIO.shouldCache( - new Path("oss://test-bucket/database/table/bucket-0/file.orc"))) - .isTrue(); - assertThat( - fileIO.shouldCache( - new Path("oss://test-bucket/database/table/manifest/manifest-111"))) - .isTrue(); - assertThat( - fileIO.shouldCache( - new Path("oss://test-bucket/database/table/snapshot/snapshot-1"))) - .isFalse(); - - // set whitelist config as * - context = createCatalogContext(true, "meta,read,write", true, "*"); - fileIO = new JindoFileIO(); + + assertThat(fileIO.shouldCache(META_PATH)).isTrue(); + assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isTrue(); + assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isFalse(); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); + assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isFalse(); + } + + @Test + public void testAllSupportedCacheWhitelistFileTypes() { + CatalogContext context = + createCatalogContext( + true, + "meta,read,write", + true, + "meta,global-index,bucket-index,data,file-index"); + JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); - assertThat( - fileIO.shouldCache( - new Path("oss://test-bucket/database/table/snapshot/snapshot-1"))) - .isTrue(); - assertThat(fileIO.shouldCache(new Path("oss://test-bucket/database/table/dir/file"))) - .isTrue(); + + assertThat(fileIO.shouldCache(META_PATH)).isTrue(); + assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isTrue(); + assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isTrue(); + assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); + assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isTrue(); + } + + @Test + public void testCustomCacheWhitelist() { + CatalogContext context = + createCatalogContext(true, "meta,read,write", true, "data,file-index"); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); + assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isFalse(); + assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isFalse(); + assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); + assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isTrue(); + } + + @Test + public void testEmptyAndInvalidCacheWhitelistFailClosed() { + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(createCatalogContext(true, "meta,read,write", true, "")); + + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); + + fileIO.configure(createCatalogContext(true, "meta,read,write", true, "manifest,unknown")); + + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); + } + + @SuppressWarnings("deprecation") + @Test + public void testDeprecatedWhitelistPathIsIgnored() { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "meta,read,write"); + options.set(JINDO_CACHE_RPC_ADDRESS, "test-rpc-address:8080"); + options.set(IO_CACHE_WHITELIST_PATH, "*"); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(CatalogContext.create(options)); + + assertThat(fileIO.shouldCache(META_PATH)).isTrue(); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); + } + + @Test + public void testMutableMetaFilesAreNotCached() { + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(createCatalogContext(true, "meta,read,write", true, "meta")); + + assertThat(fileIO.shouldCache(META_PATH)).isTrue(); + assertThat(fileIO.shouldCache(new Path(TABLE_ROOT + "/snapshot/EARLIEST"))).isFalse(); + assertThat(fileIO.shouldCache(new Path(TABLE_ROOT + "/snapshot/LATEST"))).isFalse(); + } + + @Test + public void testConfigureResetsCacheWhitelistAndPolicy() { + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(createCatalogContext(true, "read", true, "data")); + + verifyCacheFlags(fileIO, false, true, false); + assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); + + fileIO.configure(createCatalogContext(true, "read", true, "meta")); + + verifyCacheFlags(fileIO, false, true, false); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); + assertThat(fileIO.shouldCache(META_PATH)).isTrue(); + + fileIO.configure(createCatalogContext(true, "none", true, "data")); + + verifyCacheFlags(fileIO, false, false, false); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); } @Test public void testSerialization() throws Exception { - CatalogContext context = createCatalogContext(true, "read", false, null); + CatalogContext context = createCatalogContext(true, "read", false, "data"); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); JindoFileIO cloned = InstantiationUtil.clone(fileIO); - Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); - assertThat(cloned.hadoopOptions(path, "read").get("fs.oss.endpoint")) + assertThat(cloned.shouldCache(DATA_PATH)).isTrue(); + assertThat(cloned.shouldCache(META_PATH)).isFalse(); + assertThat(cloned.hadoopOptions(DATA_PATH, "read").get("fs.oss.endpoint")) .isEqualTo("test-dlf-cache-endpoint"); - assertThat(cloned.hadoopOptions(path, "meta").get("fs.oss.endpoint")) + assertThat(cloned.hadoopOptions(META_PATH, "read").get("fs.oss.endpoint")) .isEqualTo("test-oss-endpoint"); } } From 7f0ff8dfd6bf26ff31912b0d4561ce68b9764eb7 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Mon, 17 Aug 2026 18:47:11 +0800 Subject: [PATCH 06/21] [jindo] Support combined cache whitelists --- .../paimon/rest/RESTCatalogOptions.java | 13 ++-- .../paimon/jindo/HadoopCompliantFileIO.java | 47 +++++++++++-- .../paimon/jindo/TestJindoCacheEnable.java | 67 ++++++++++++++----- 3 files changed, 101 insertions(+), 26 deletions(-) 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 430a5d4e190a..1643e58bd141 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 @@ -152,19 +152,20 @@ public class RESTCatalogOptions { public static final ConfigOption IO_CACHE_WHITELIST = ConfigOptions.key("io-cache.whitelist") .stringType() - .defaultValue("meta,global-index") + .defaultValue("*") .withDescription( "Comma-separated list of file types allowed to use the cache endpoint. " - + "Supported values: meta, global-index, bucket-index, data, file-index."); + + "Supported values: meta, global-index, bucket-index, data, file-index. " + + "Use * to allow all file types."); - /** @deprecated Use {@link #IO_CACHE_WHITELIST}. Path patterns are no longer supported. */ - @Deprecated public static final ConfigOption IO_CACHE_WHITELIST_PATH = ConfigOptions.key("io-cache.whitelist-path") .stringType() - .defaultValue("bucket,manifest,index") + .defaultValue("*") .withDescription( - "Deprecated. Use io-cache.whitelist to select cacheable file types."); + "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."); public static final ConfigOption IO_CACHE_POLICY = ConfigOptions.key("io-cache.policy") diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java index 4f0c00a77f13..568b5125c03b 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java @@ -57,6 +57,7 @@ import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; /** * Hadoop {@link FileIO}. @@ -84,11 +85,30 @@ public abstract class HadoopCompliantFileIO implements FileIO { protected transient volatile Map> jindoCacheFsMap; private Set cacheWhitelist = EnumSet.noneOf(FileType.class); + private List cacheWhitelistPaths = new ArrayList<>(); + private boolean cacheAllPaths = false; boolean shouldCache(Path path) { return cacheWhitelist != null && !FileType.isMutable(path) - && cacheWhitelist.contains(FileType.classify(path)); + && cacheWhitelist.contains(FileType.classify(path)) + && matchesCacheWhitelistPath(path); + } + + private boolean matchesCacheWhitelistPath(Path path) { + // A null list can occur when deserializing an instance written before path filtering was + // restored. Such instances previously allowed all paths after the file type check. + if (cacheAllPaths || cacheWhitelistPaths == null) { + return true; + } + + String pathString = path.toUri().getPath(); + for (String pattern : cacheWhitelistPaths) { + if (pathString.contains(pattern)) { + return true; + } + } + return false; } @Override @@ -97,6 +117,8 @@ public void configure(CatalogContext context) { readCacheEnabled = false; writeCacheEnabled = false; cacheWhitelist = EnumSet.noneOf(FileType.class); + cacheWhitelistPaths = new ArrayList<>(); + cacheAllPaths = false; // Process file io cache configuration Options options = context.options(); @@ -121,13 +143,30 @@ public void configure(CatalogContext context) { readCacheEnabled = cachePolicy.contains(READ_CACHE_ENABLED_TAG); writeCacheEnabled = cachePolicy.contains(WRITE_CACHE_ENABLED_TAG); String whitelist = options.get(IO_CACHE_WHITELIST); - cacheWhitelist = FileType.parseWhitelist(IO_CACHE_WHITELIST.key(), whitelist); + if (whitelist != null && "*".equals(whitelist.trim())) { + cacheWhitelist = EnumSet.allOf(FileType.class); + } else { + cacheWhitelist = FileType.parseWhitelist(IO_CACHE_WHITELIST.key(), whitelist); + } + + String whitelistPath = options.get(IO_CACHE_WHITELIST_PATH); + if (whitelistPath != null && "*".equals(whitelistPath.trim())) { + cacheAllPaths = true; + } else if (whitelistPath != null) { + for (String pattern : whitelistPath.split(",")) { + pattern = pattern.trim(); + if (!pattern.isEmpty()) { + cacheWhitelistPaths.add(pattern); + } + } + } LOG.info( - "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist file types: {}", + "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist file types: {}, whitelist path: {}", metaCacheEnabled, readCacheEnabled, writeCacheEnabled, - cacheWhitelist); + cacheWhitelist, + whitelistPath); } @Override diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java index 575f105dcfaf..edee9d6f24ed 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java @@ -44,10 +44,14 @@ public class TestJindoCacheEnable { private static final String TABLE_ROOT = "oss://test-bucket/database/table"; private static final Path META_PATH = new Path(TABLE_ROOT + "/snapshot/snapshot-1"); + private static final Path MANIFEST_PATH = + new Path(TABLE_ROOT + "/manifest/manifest-a1b2c3d4-0"); private static final Path GLOBAL_INDEX_PATH = new Path(TABLE_ROOT + "/index/btree-global-index-a1b2c3d4.index"); private static final Path BUCKET_INDEX_PATH = new Path(TABLE_ROOT + "/index/index-a1b2c3d4-0"); private static final Path DATA_PATH = new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc"); + private static final Path OTHER_DATA_PATH = + new Path(TABLE_ROOT + "/bucket-1/data-a1b2c3d4-0.orc"); private static final Path FILE_INDEX_PATH = new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc.index"); @@ -56,6 +60,15 @@ private CatalogContext createCatalogContext( String cachePolicy, boolean setRpcAddress, String cacheWhitelist) { + return createCatalogContext(cacheEnabled, cachePolicy, setRpcAddress, cacheWhitelist, null); + } + + private CatalogContext createCatalogContext( + boolean cacheEnabled, + String cachePolicy, + boolean setRpcAddress, + String cacheWhitelist, + String cacheWhitelistPath) { Options options = new Options(); options.set(IO_CACHE_ENABLED, cacheEnabled); if (cachePolicy != null) { @@ -70,6 +83,9 @@ private CatalogContext createCatalogContext( if (cacheWhitelist != null) { options.set(IO_CACHE_WHITELIST, cacheWhitelist); } + if (cacheWhitelistPath != null) { + options.set(IO_CACHE_WHITELIST_PATH, cacheWhitelistPath); + } return CatalogContext.create(options); } @@ -272,9 +288,9 @@ public void testDefaultCacheWhitelist() { assertThat(fileIO.shouldCache(META_PATH)).isTrue(); assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isTrue(); - assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isFalse(); + assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isTrue(); + assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); + assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isTrue(); } @Test @@ -323,24 +339,42 @@ public void testEmptyAndInvalidCacheWhitelistFailClosed() { assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); } - @SuppressWarnings("deprecation") @Test - public void testDeprecatedWhitelistPathIsIgnored() { - Options options = new Options(); - options.set(IO_CACHE_POLICY, "meta,read,write"); - options.set(JINDO_CACHE_RPC_ADDRESS, "test-rpc-address:8080"); - options.set(IO_CACHE_WHITELIST_PATH, "*"); + public void testCacheWhitelistPath() { + CatalogContext context = + createCatalogContext(true, "meta,read,write", true, "*", "manifest, bucket-0"); JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(CatalogContext.create(options)); + fileIO.configure(context); - assertThat(fileIO.shouldCache(META_PATH)).isTrue(); + assertThat(fileIO.shouldCache(MANIFEST_PATH)).isTrue(); + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); + assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); + assertThat(fileIO.shouldCache(OTHER_DATA_PATH)).isFalse(); + } + + @Test + public void testCacheWhitelistAndPathMustBothMatch() { + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(createCatalogContext(true, "meta,read,write", true, "meta", "manifest")); + + assertThat(fileIO.shouldCache(MANIFEST_PATH)).isTrue(); + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); + assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); + } + + @Test + public void testEmptyCacheWhitelistPathFailsClosed() { + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(createCatalogContext(true, "meta,read,write", true, "*", "")); + + assertThat(fileIO.shouldCache(META_PATH)).isFalse(); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); } @Test public void testMutableMetaFilesAreNotCached() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "meta,read,write", true, "meta")); + fileIO.configure(createCatalogContext(true, "meta,read,write", true, "*")); assertThat(fileIO.shouldCache(META_PATH)).isTrue(); assertThat(fileIO.shouldCache(new Path(TABLE_ROOT + "/snapshot/EARLIEST"))).isFalse(); @@ -350,19 +384,19 @@ public void testMutableMetaFilesAreNotCached() { @Test public void testConfigureResetsCacheWhitelistAndPolicy() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "read", true, "data")); + fileIO.configure(createCatalogContext(true, "read", true, "data", "bucket-0")); verifyCacheFlags(fileIO, false, true, false); assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - fileIO.configure(createCatalogContext(true, "read", true, "meta")); + fileIO.configure(createCatalogContext(true, "read", true, "meta", "*")); verifyCacheFlags(fileIO, false, true, false); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); assertThat(fileIO.shouldCache(META_PATH)).isTrue(); - fileIO.configure(createCatalogContext(true, "none", true, "data")); + fileIO.configure(createCatalogContext(true, "none", true, "data", "bucket-0")); verifyCacheFlags(fileIO, false, false, false); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); @@ -370,13 +404,14 @@ public void testConfigureResetsCacheWhitelistAndPolicy() { @Test public void testSerialization() throws Exception { - CatalogContext context = createCatalogContext(true, "read", false, "data"); + CatalogContext context = createCatalogContext(true, "read", false, "data", "bucket-0"); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); JindoFileIO cloned = InstantiationUtil.clone(fileIO); assertThat(cloned.shouldCache(DATA_PATH)).isTrue(); + assertThat(cloned.shouldCache(OTHER_DATA_PATH)).isFalse(); assertThat(cloned.shouldCache(META_PATH)).isFalse(); assertThat(cloned.hadoopOptions(DATA_PATH, "read").get("fs.oss.endpoint")) .isEqualTo("test-dlf-cache-endpoint"); From a2ca0798b7a3d31ed55fc90206b605e08ad0a2b6 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Tue, 18 Aug 2026 17:45:17 +0800 Subject: [PATCH 07/21] [jindo] Address DLF cache review comments --- .../paimon/rest/RESTCatalogOptions.java | 9 -- .../apache/paimon/fs/cache/CachingFileIO.java | 4 +- .../org/apache/paimon/utils/FileType.java | 32 +---- .../org/apache/paimon/utils/FileTypeTest.java | 14 +- .../apache/paimon/rest/RESTCatalogTest.java | 3 - paimon-filesystems/paimon-jindo/pom.xml | 7 - .../paimon/jindo/HadoopCompliantFileIO.java | 33 ++--- .../org/apache/paimon/jindo/JindoFileIO.java | 2 +- .../paimon/jindo/JindoHadoopOptions.java | 41 ++---- .../apache/paimon/jindo/JindoFileIOTest.java | 41 ++---- ...cheEnable.java => TestDlfCacheEnable.java} | 120 +++++------------- 11 files changed, 68 insertions(+), 238 deletions(-) rename paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/{TestJindoCacheEnable.java => TestDlfCacheEnable.java} (73%) 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 1643e58bd141..f5802b47b96b 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 @@ -114,15 +114,6 @@ public class RESTCatalogOptions { + "'openapi' (the earlier ROA HMAC-SHA1 scheme). " + "If not set, will be automatically selected based on endpoint host."); - /** @deprecated Cache enablement is controlled by the policy vended by the REST server. */ - @Deprecated - public static final ConfigOption IO_CACHE_ENABLED = - ConfigOptions.key("io-cache.enabled") - .booleanType() - .defaultValue(true) - .withDescription( - "Deprecated. Cache enablement is controlled by the policy vended by the REST server."); - public static final ConfigOption IO_CACHE_IGNORE_VPC_VALIDATE = ConfigOptions.key("io-cache.ignore-vpc-validate") .booleanType() diff --git a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java index 436d920c1dcc..70ad66cfad04 100644 --- a/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachingFileIO.java @@ -110,9 +110,7 @@ public static FileIO wrapWithCachingIfNeeded( } Options options = context.options(); Set whitelist = - FileType.parseWhitelist( - CatalogOptions.LOCAL_CACHE_WHITELIST.key(), - options.get(CatalogOptions.LOCAL_CACHE_WHITELIST)); + FileType.parseWhitelist(options.get(CatalogOptions.LOCAL_CACHE_WHITELIST)); if (whitelist.isEmpty()) { return fileIO; } 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 011a9b76cc56..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 @@ -39,29 +39,10 @@ * */ public enum FileType { - /** - * Table metadata files, including snapshots, schemas, manifests, statistics, tags, changelog - * metadata, hint files, success files, consumers, and services. - */ META, - - /** - * Data files, including ORC, Parquet, changelog data, blob and vector files. Unrecognized files - * are also classified as data by default. - */ DATA, - - /** Bucket-level {@code index-*} files, such as hash indexes and deletion-vector indexes. */ BUCKET_INDEX, - - /** - * Table-level {@code global-index-*.index} files, such as BTree, Lumina, and full-text indexes. - */ GLOBAL_INDEX, - - /** - * Non-global data-file-level {@code *.index} files, such as Bloom filter and bitmap indexes. - */ FILE_INDEX; private static final Logger LOG = LoggerFactory.getLogger(FileType.class); @@ -107,16 +88,6 @@ public boolean isIndex() { /** Parse a comma-separated whitelist string into a set of {@link FileType}s. */ public static Set parseWhitelist(String whitelist) { - return parseWhitelist("file type whitelist", whitelist); - } - - /** - * Parse a comma-separated whitelist string into a set of {@link FileType}s. - * - * @param optionKey configuration key used when reporting unsupported values - * @param whitelist comma-separated file type names - */ - public static Set parseWhitelist(String optionKey, String whitelist) { Set result = EnumSet.noneOf(FileType.class); if (whitelist == null) { return result; @@ -145,10 +116,9 @@ public static Set parseWhitelist(String optionKey, String whitelist) { default: if (!name.isEmpty()) { LOG.warn( - "Unknown {} value '{}'. " + "Unknown whitelist value '{}'. " + "Supported values: meta, global-index, bucket-index, data, file-index, " + "or * for all of them.", - optionKey, name); } break; 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 f014a20d4353..35f0ee5d43f2 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 @@ -109,17 +109,11 @@ public void testChangelogMetadataIsImmutable() { @Test public void testParseWhitelist() { - assertThat( - FileType.parseWhitelist( - "test-cache.whitelist", - " meta, global-index, bucket-index, data, file-index ")) + assertThat(FileType.parseWhitelist(" meta, global-index, bucket-index, data, file-index ")) .containsExactlyInAnyOrderElementsOf(EnumSet.allOf(FileType.class)); - assertThat(FileType.parseWhitelist("test-cache.whitelist", "")) - .isEqualTo(Collections.emptySet()); - assertThat(FileType.parseWhitelist("test-cache.whitelist", "manifest,unknown")) - .isEqualTo(Collections.emptySet()); - assertThat(FileType.parseWhitelist("test-cache.whitelist", null)) - .isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist("")).isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist("manifest,unknown")).isEqualTo(Collections.emptySet()); + assertThat(FileType.parseWhitelist(null)).isEqualTo(Collections.emptySet()); } // ===== META files ===== 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 da321725538f..a542a48476ef 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.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.auth.DLFToken.TOKEN_DATE_FORMATTER; import static org.apache.paimon.utils.SnapshotManagerTest.createSnapshotWithMillis; @@ -2175,7 +2174,6 @@ void testValidToken() throws Exception { @Test void testValidTokenWithIOCacheIgnoreVpcValidate() throws Exception { Map options = new HashMap<>(); - options.put(IO_CACHE_ENABLED.key(), "false"); options.put(IO_CACHE_IGNORE_VPC_VALIDATE.key(), "true"); this.catalog = newRestCatalogWithDataToken(options); Identifier identifier = @@ -2192,7 +2190,6 @@ void testValidTokenWithIOCacheIgnoreVpcValidate() throws Exception { RESTToken fileDataToken = fileIO.validToken(); assertEquals("true", fileDataToken.token().get(IO_CACHE_IGNORE_VPC_VALIDATE.key())); - assertThat(fileDataToken.token()).doesNotContainKey(IO_CACHE_ENABLED.key()); } @Test diff --git a/paimon-filesystems/paimon-jindo/pom.xml b/paimon-filesystems/paimon-jindo/pom.xml index 9926d6c817b1..e33cedc79f85 100644 --- a/paimon-filesystems/paimon-jindo/pom.xml +++ b/paimon-filesystems/paimon-jindo/pom.xml @@ -154,13 +154,6 @@ test - - org.apache.hadoop - hadoop-annotations - ${hadoop.version} - test - - commons-collections commons-collections diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java index 568b5125c03b..50d3256af8ae 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java @@ -52,7 +52,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; @@ -69,9 +68,7 @@ public abstract class HadoopCompliantFileIO implements FileIO { private static final long serialVersionUID = 1L; - // Cache policy values select operation types. In particular, policy "meta" controls metadata - // operations such as getFileStatus and exists. It is independent from whitelist "meta", which - // selects paths classified as FileType.META. + // Cache policy tags select the operation types that use cache. private static final String META_CACHE_ENABLED_TAG = "meta"; private static final String READ_CACHE_ENABLED_TAG = "read"; private static final String WRITE_CACHE_ENABLED_TAG = "write"; @@ -82,23 +79,20 @@ public abstract class HadoopCompliantFileIO implements FileIO { protected boolean writeCacheEnabled = false; protected transient volatile Map> fsMap; - protected transient volatile Map> jindoCacheFsMap; + protected transient volatile Map> cacheFsMap; private Set cacheWhitelist = EnumSet.noneOf(FileType.class); private List cacheWhitelistPaths = new ArrayList<>(); private boolean cacheAllPaths = false; boolean shouldCache(Path path) { - return cacheWhitelist != null - && !FileType.isMutable(path) + return !FileType.isMutable(path) && cacheWhitelist.contains(FileType.classify(path)) && matchesCacheWhitelistPath(path); } private boolean matchesCacheWhitelistPath(Path path) { - // A null list can occur when deserializing an instance written before path filtering was - // restored. Such instances previously allowed all paths after the file type check. - if (cacheAllPaths || cacheWhitelistPaths == null) { + if (cacheAllPaths) { return true; } @@ -123,19 +117,16 @@ public void configure(CatalogContext context) { // Process file io cache configuration Options options = context.options(); String cachePolicy = options.get(IO_CACHE_POLICY); - boolean useVpcValidationProtocol = - options.contains(IO_CACHE_ENDPOINT) || options.contains(IO_CACHE_VPC_VALIDATED); - boolean vpcValidated = !useVpcValidationProtocol || options.get(IO_CACHE_VPC_VALIDATED); + boolean vpcValidated = options.get(IO_CACHE_VPC_VALIDATED); boolean ignoreVpcValidate = options.get(IO_CACHE_IGNORE_VPC_VALIDATE); if (cachePolicy == null || cachePolicy.contains(DISABLE_CACHE_TAG) || (!vpcValidated && !ignoreVpcValidate)) { LOG.debug( - "Cache is disabled with io-cache.policy={}, io-cache.vpc-validated={}, io-cache.ignore-vpc-validate={}, use-vpc-validation-protocol={}", + "Cache is disabled with io-cache.policy={}, io-cache.vpc-validated={}, io-cache.ignore-vpc-validate={}", cachePolicy, vpcValidated, - ignoreVpcValidate, - useVpcValidationProtocol); + ignoreVpcValidate); return; } // Enable file io cache @@ -146,7 +137,7 @@ public void configure(CatalogContext context) { if (whitelist != null && "*".equals(whitelist.trim())) { cacheWhitelist = EnumSet.allOf(FileType.class); } else { - cacheWhitelist = FileType.parseWhitelist(IO_CACHE_WHITELIST.key(), whitelist); + cacheWhitelist = FileType.parseWhitelist(whitelist); } String whitelistPath = options.get(IO_CACHE_WHITELIST_PATH); @@ -327,14 +318,14 @@ protected Pair getFileSystemPair( org.apache.hadoop.fs.Path path, boolean enableCache) throws IOException { Map> map; if (enableCache) { - if (jindoCacheFsMap == null) { + if (cacheFsMap == null) { synchronized (this) { - if (jindoCacheFsMap == null) { - jindoCacheFsMap = new ConcurrentHashMap<>(); + if (cacheFsMap == null) { + cacheFsMap = new ConcurrentHashMap<>(); } } } - map = jindoCacheFsMap; + map = cacheFsMap; } else { if (fsMap == null) { synchronized (this) { diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java index ca984633069d..b77c3ea66a68 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java @@ -231,7 +231,7 @@ public synchronized void close() { } if (!allowCache) { closeFileSystems(fsMap); - closeFileSystems(jindoCacheFsMap); + closeFileSystems(cacheFsMap); } } diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java index c62e691ae2dc..00c905c4df8f 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java @@ -31,6 +31,7 @@ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import java.util.Objects; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; @@ -56,7 +57,6 @@ public class JindoHadoopOptions implements Serializable { private static final String OSS_ACCESS_KEY_SECRET = "fs.oss.accessKeySecret"; private static final String OSS_SECURITY_TOKEN = "fs.oss.securityToken"; private static final String OSS_ENDPOINT = "fs.oss.endpoint"; - private static final String OSS_DIRECT_ENDPOINT = "fs.oss.direct.endpoint"; private static final String OSS_SHOW_DIR_TIMESTAMP = "fs.oss.show-dir-timestamp"; private static final Map CASE_SENSITIVE_KEYS = @@ -68,10 +68,6 @@ public class JindoHadoopOptions implements Serializable { } }; - private boolean isJindoCacheBackend(CatalogContext context) { - return context.options().get("fs.jindocache.namespace.rpc.address") != null; - } - public JindoHadoopOptions(CatalogContext context) { hadoopOptions = new Options(); // read all configuration with prefix 'CONFIG_PREFIXES' @@ -116,31 +112,13 @@ public JindoHadoopOptions(CatalogContext context) { JindoUserAgent.apply(context.options(), hadoopOptions); - if (isJindoCacheBackend(context)) { - initJindoCacheBackend(context); - } else { - initDLFCacheBackend(context); - } + initDLFCacheBackend(context); } public Options get(boolean enableCache) { return enableCache ? hadoopOptionsWithCache : hadoopOptions; } - private void initJindoCacheBackend(CatalogContext context) { - // another config using jindocache - hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); - hadoopOptionsWithCache.set("fs.xengine", "jindocache"); - if (!hadoopOptionsWithCache.containsKey("fs.jindocache.client.metrics.enable")) { - // enable metrics report by default - hadoopOptionsWithCache.set("fs.jindocache.client.metrics.enable", "true"); - } - // Workaround: following configurations to avoid bug in some JindoSDK versions - hadoopOptionsWithCache.set("fs.oss.read.profile.columnar.use-pread", "false"); - hadoopOptionsWithCache.set( - "fs.jindocache.read.profile.columnar.readahead.pread.enable", "false"); - } - private void initDLFCacheBackend(CatalogContext context) { hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); @@ -150,15 +128,16 @@ private void initDLFCacheBackend(CatalogContext context) { } String originEndpoint = context.options().get(IO_CACHE_ORIGIN_ENDPOINT); - if (StringUtils.isNullOrWhitespaceOnly(originEndpoint)) { - originEndpoint = context.options().get(OSS_DIRECT_ENDPOINT); - } if (!StringUtils.isNullOrWhitespaceOnly(originEndpoint)) { hadoopOptions.set(OSS_ENDPOINT, originEndpoint); } - LOG.info( - "Using direct access to OSS endpoint: {}, cache endpoint: {}", - hadoopOptions.get(OSS_ENDPOINT), - hadoopOptionsWithCache.get(OSS_ENDPOINT)); + String directEndpoint = hadoopOptions.get(OSS_ENDPOINT); + String configuredCacheEndpoint = hadoopOptionsWithCache.get(OSS_ENDPOINT); + if (!Objects.equals(directEndpoint, configuredCacheEndpoint)) { + LOG.info( + "Using direct access to OSS endpoint: {}, cache endpoint: {}", + directEndpoint, + configuredCacheEndpoint); + } } } diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java index ad55c0e7d57a..b44caaf43139 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java @@ -29,6 +29,7 @@ import org.apache.paimon.utils.Pair; import com.aliyun.jindodata.common.JindoHadoopSystem; +import com.aliyun.jindodata.oss.JindoOssFileSystem; import com.aliyun.jindodata.types.JindoHadoopFileStatus; import com.aliyun.oss.ClientConfiguration; import com.aliyun.oss.HttpMethod; @@ -46,7 +47,6 @@ import java.time.Duration; import java.util.Date; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; import static org.apache.paimon.options.CatalogOptions.FILE_IO_ALLOW_CACHE; import static org.assertj.core.api.Assertions.assertThat; @@ -278,38 +278,30 @@ protected Pair getFileSystemPair( } @Test - void closeClosesDirectAndCacheFileSystems() { + void closeClearsDirectAndCacheFileSystems() { JindoFileIO fileIO = createNonCachingFileIO(); - TrackingJindoHadoopSystem directFileSystem = new TrackingJindoHadoopSystem(); - TrackingJindoHadoopSystem cacheFileSystem = new TrackingJindoHadoopSystem(); fileIO.fsMap = new ConcurrentHashMap<>(); - fileIO.fsMap.put("test-bucket", Pair.of(directFileSystem, "test")); - fileIO.jindoCacheFsMap = new ConcurrentHashMap<>(); - fileIO.jindoCacheFsMap.put("test-bucket", Pair.of(cacheFileSystem, "test")); + fileIO.fsMap.put("test-bucket", Pair.of(new JindoOssFileSystem(), "test")); + fileIO.cacheFsMap = new ConcurrentHashMap<>(); + fileIO.cacheFsMap.put("test-bucket", Pair.of(new JindoOssFileSystem(), "test")); fileIO.close(); - assertThat(directFileSystem.closeCount.get()).isOne(); - assertThat(cacheFileSystem.closeCount.get()).isOne(); assertThat(fileIO.fsMap).isEmpty(); - assertThat(fileIO.jindoCacheFsMap).isEmpty(); + assertThat(fileIO.cacheFsMap).isEmpty(); assertThatCode(fileIO::close).doesNotThrowAnyException(); - assertThat(directFileSystem.closeCount.get()).isOne(); - assertThat(cacheFileSystem.closeCount.get()).isOne(); } @Test void closeHandlesCacheOnlyFileSystem() { JindoFileIO fileIO = createNonCachingFileIO(); - TrackingJindoHadoopSystem cacheFileSystem = new TrackingJindoHadoopSystem(); - fileIO.jindoCacheFsMap = new ConcurrentHashMap<>(); - fileIO.jindoCacheFsMap.put("test-bucket", Pair.of(cacheFileSystem, "test")); + fileIO.cacheFsMap = new ConcurrentHashMap<>(); + fileIO.cacheFsMap.put("test-bucket", Pair.of(new JindoOssFileSystem(), "test")); assertThatCode(fileIO::close).doesNotThrowAnyException(); - assertThat(cacheFileSystem.closeCount.get()).isOne(); - assertThat(fileIO.jindoCacheFsMap).isEmpty(); + assertThat(fileIO.cacheFsMap).isEmpty(); } private JindoFileIO createNonCachingFileIO() { @@ -327,19 +319,4 @@ private static String sha256Hex(byte[] bytes) throws Exception { } return result.toString(); } - - private static class TrackingJindoHadoopSystem extends JindoHadoopSystem { - - private final AtomicInteger closeCount = new AtomicInteger(); - - @Override - public String getScheme() { - return "test"; - } - - @Override - public void close() { - closeCount.incrementAndGet(); - } - } } diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java similarity index 73% rename from paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java rename to paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java index edee9d6f24ed..416e97a150ca 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java @@ -27,7 +27,6 @@ import java.lang.reflect.Field; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; @@ -37,10 +36,9 @@ import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; import static org.assertj.core.api.Assertions.assertThat; -/** Test for Jindo cache enable configuration. */ -public class TestJindoCacheEnable { +/** Test for DLF cache enable configuration. */ +public class TestDlfCacheEnable { - private static final String JINDO_CACHE_RPC_ADDRESS = "fs.jindocache.namespace.rpc.address"; private static final String TABLE_ROOT = "oss://test-bucket/database/table"; private static final Path META_PATH = new Path(TABLE_ROOT + "/snapshot/snapshot-1"); @@ -55,31 +53,20 @@ public class TestJindoCacheEnable { private static final Path FILE_INDEX_PATH = new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc.index"); - private CatalogContext createCatalogContext( - boolean cacheEnabled, - String cachePolicy, - boolean setRpcAddress, - String cacheWhitelist) { - return createCatalogContext(cacheEnabled, cachePolicy, setRpcAddress, cacheWhitelist, null); + private CatalogContext createCatalogContext(String cachePolicy, String cacheWhitelist) { + return createCatalogContext(cachePolicy, cacheWhitelist, null); } private CatalogContext createCatalogContext( - boolean cacheEnabled, - String cachePolicy, - boolean setRpcAddress, - String cacheWhitelist, - String cacheWhitelistPath) { + String cachePolicy, String cacheWhitelist, String cacheWhitelistPath) { Options options = new Options(); - options.set(IO_CACHE_ENABLED, cacheEnabled); if (cachePolicy != null) { options.set(IO_CACHE_POLICY, cachePolicy); } - if (setRpcAddress) { - options.set(JINDO_CACHE_RPC_ADDRESS, "test-rpc-address:8080"); - } else { - options.set("fs.oss.endpoint", "test-dlf-cache-endpoint"); - options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); - } + options.set("fs.oss.endpoint", "test-oss-endpoint"); + options.set(IO_CACHE_ENDPOINT, "test-dlf-cache-endpoint"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); + options.set(IO_CACHE_VPC_VALIDATED, true); if (cacheWhitelist != null) { options.set(IO_CACHE_WHITELIST, cacheWhitelist); } @@ -95,11 +82,7 @@ private CatalogContext createDlfCacheContext( if (cachePolicy != null) { options.set(IO_CACHE_POLICY, cachePolicy); } - options.set( - "fs.oss.endpoint", - Boolean.TRUE.equals(vpcValidated) - ? "test-dlf-cache-endpoint" - : "test-oss-endpoint"); + options.set("fs.oss.endpoint", "test-oss-endpoint"); options.set(IO_CACHE_ENDPOINT, "test-dlf-cache-endpoint"); options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); if (vpcValidated != null) { @@ -132,7 +115,7 @@ private void verifyCacheFlags( @Test public void testCacheEnabledWithMetaPolicy() { - CatalogContext context = createCatalogContext(true, "meta", true, null); + CatalogContext context = createCatalogContext("meta", null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -141,7 +124,7 @@ public void testCacheEnabledWithMetaPolicy() { @Test public void testCacheEnabledWithReadPolicy() { - CatalogContext context = createCatalogContext(true, "read", true, null); + CatalogContext context = createCatalogContext("read", null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -150,7 +133,7 @@ public void testCacheEnabledWithReadPolicy() { @Test public void testCacheEnabledWithWritePolicy() { - CatalogContext context = createCatalogContext(true, "write", true, null); + CatalogContext context = createCatalogContext("write", null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -159,16 +142,7 @@ public void testCacheEnabledWithWritePolicy() { @Test public void testCacheEnabledWithCombinedPolicy() { - CatalogContext context = createCatalogContext(true, "meta,read,write", true, null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, true, true, true); - } - - @Test - public void testDeprecatedCacheEnabledOptionIsIgnored() { - CatalogContext context = createCatalogContext(false, "meta,read,write", true, null); + CatalogContext context = createCatalogContext("meta,read,write", null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -177,42 +151,13 @@ public void testDeprecatedCacheEnabledOptionIsIgnored() { @Test public void testCacheDisabledWhenPolicyNone() { - CatalogContext context = createCatalogContext(true, "none", true, null); + CatalogContext context = createCatalogContext("none", null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); verifyCacheFlags(fileIO, false, false, false); } - @Test - public void testOldBennettDlfCacheProtocolRemainsEnabled() { - CatalogContext context = createCatalogContext(true, "meta,read,write", false, null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, true, true, true); - } - - @Test - public void testDlfCacheOriginEndpointCompatibility() { - Options options = new Options(); - options.set(IO_CACHE_POLICY, "read"); - options.set("fs.oss.endpoint", "test-dlf-cache-endpoint"); - options.set("fs.oss.direct.endpoint", "test-legacy-oss-endpoint"); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(CatalogContext.create(options)); - - Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); - assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) - .isEqualTo("test-legacy-oss-endpoint"); - - options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); - fileIO = new JindoFileIO(); - fileIO.configure(CatalogContext.create(options)); - assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) - .isEqualTo("test-oss-endpoint"); - } - @Test public void testDlfCacheDisabledWhenVpcNotValidated() { CatalogContext context = createDlfCacheContext("meta,read,write", false, false); @@ -254,7 +199,7 @@ public void testDlfCacheEnabledWhenVpcValidated() { } @Test - public void testDlfCacheNewProtocolDefaultsVpcValidationToFalse() { + public void testDlfCacheDefaultsVpcValidationToFalse() { CatalogContext context = createDlfCacheContext("meta,read,write", null, false); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -273,7 +218,7 @@ public void testIgnoreVpcValidationDoesNotOverrideDisabledPolicy() { @Test public void testCacheDisabledWhenPolicyNull() { - CatalogContext context = createCatalogContext(true, null, true, null); + CatalogContext context = createCatalogContext(null, null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -282,7 +227,7 @@ public void testCacheDisabledWhenPolicyNull() { @Test public void testDefaultCacheWhitelist() { - CatalogContext context = createCatalogContext(true, "meta,read,write", true, null); + CatalogContext context = createCatalogContext("meta,read,write", null); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -297,10 +242,7 @@ public void testDefaultCacheWhitelist() { public void testAllSupportedCacheWhitelistFileTypes() { CatalogContext context = createCatalogContext( - true, - "meta,read,write", - true, - "meta,global-index,bucket-index,data,file-index"); + "meta,read,write", "meta,global-index,bucket-index,data,file-index"); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -313,8 +255,7 @@ public void testAllSupportedCacheWhitelistFileTypes() { @Test public void testCustomCacheWhitelist() { - CatalogContext context = - createCatalogContext(true, "meta,read,write", true, "data,file-index"); + CatalogContext context = createCatalogContext("meta,read,write", "data,file-index"); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -328,12 +269,12 @@ public void testCustomCacheWhitelist() { @Test public void testEmptyAndInvalidCacheWhitelistFailClosed() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "meta,read,write", true, "")); + fileIO.configure(createCatalogContext("meta,read,write", "")); assertThat(fileIO.shouldCache(META_PATH)).isFalse(); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - fileIO.configure(createCatalogContext(true, "meta,read,write", true, "manifest,unknown")); + fileIO.configure(createCatalogContext("meta,read,write", "manifest,unknown")); assertThat(fileIO.shouldCache(META_PATH)).isFalse(); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); @@ -341,8 +282,7 @@ public void testEmptyAndInvalidCacheWhitelistFailClosed() { @Test public void testCacheWhitelistPath() { - CatalogContext context = - createCatalogContext(true, "meta,read,write", true, "*", "manifest, bucket-0"); + CatalogContext context = createCatalogContext("meta,read,write", "*", "manifest, bucket-0"); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); @@ -355,7 +295,7 @@ public void testCacheWhitelistPath() { @Test public void testCacheWhitelistAndPathMustBothMatch() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "meta,read,write", true, "meta", "manifest")); + fileIO.configure(createCatalogContext("meta,read,write", "meta", "manifest")); assertThat(fileIO.shouldCache(MANIFEST_PATH)).isTrue(); assertThat(fileIO.shouldCache(META_PATH)).isFalse(); @@ -365,7 +305,7 @@ public void testCacheWhitelistAndPathMustBothMatch() { @Test public void testEmptyCacheWhitelistPathFailsClosed() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "meta,read,write", true, "*", "")); + fileIO.configure(createCatalogContext("meta,read,write", "*", "")); assertThat(fileIO.shouldCache(META_PATH)).isFalse(); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); @@ -374,7 +314,7 @@ public void testEmptyCacheWhitelistPathFailsClosed() { @Test public void testMutableMetaFilesAreNotCached() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "meta,read,write", true, "*")); + fileIO.configure(createCatalogContext("meta,read,write", "*")); assertThat(fileIO.shouldCache(META_PATH)).isTrue(); assertThat(fileIO.shouldCache(new Path(TABLE_ROOT + "/snapshot/EARLIEST"))).isFalse(); @@ -384,19 +324,19 @@ public void testMutableMetaFilesAreNotCached() { @Test public void testConfigureResetsCacheWhitelistAndPolicy() { JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext(true, "read", true, "data", "bucket-0")); + fileIO.configure(createCatalogContext("read", "data", "bucket-0")); verifyCacheFlags(fileIO, false, true, false); assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - fileIO.configure(createCatalogContext(true, "read", true, "meta", "*")); + fileIO.configure(createCatalogContext("read", "meta", "*")); verifyCacheFlags(fileIO, false, true, false); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); assertThat(fileIO.shouldCache(META_PATH)).isTrue(); - fileIO.configure(createCatalogContext(true, "none", true, "data", "bucket-0")); + fileIO.configure(createCatalogContext("none", "data", "bucket-0")); verifyCacheFlags(fileIO, false, false, false); assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); @@ -404,7 +344,7 @@ public void testConfigureResetsCacheWhitelistAndPolicy() { @Test public void testSerialization() throws Exception { - CatalogContext context = createCatalogContext(true, "read", false, "data", "bucket-0"); + CatalogContext context = createCatalogContext("read", "data", "bucket-0"); JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(context); From 991a46128d1c2132652b29c5e07c509985093f3d Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Sun, 8 Nov 2026 17:10:08 +0800 Subject: [PATCH 08/21] Support cache policy for pypaimon --- .../catalog/rest/rest_token_file_io.py | 8 +- .../pypaimon/common/options/config.py | 60 +++ .../filesystem/cache_policy_file_io.py | 421 +++++++++++++++++ .../tests/cache_policy_file_io_test.py | 446 ++++++++++++++++++ .../pypaimon/tests/file_type_test.py | 9 + .../tests/rest/rest_token_file_io_test.py | 50 ++ paimon-python/pypaimon/utils/file_type.py | 4 +- 7 files changed, 996 insertions(+), 2 deletions(-) create mode 100644 paimon-python/pypaimon/filesystem/cache_policy_file_io.py create mode 100644 paimon-python/pypaimon/tests/cache_policy_file_io_test.py 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..3796eef9afde 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): @@ -151,7 +152,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 @@ -216,6 +218,10 @@ def _merge_token_with_catalog_options(self, token: dict) -> dict: 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 + if self.catalog_options.contains(CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE): + merged_token[CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key()] = str( + self.catalog_options.get( + CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE)).lower() return merged_token def new_input_stream(self, path: str): diff --git a/paimon-python/pypaimon/common/options/config.py b/paimon-python/pypaimon/common/options/config.py index 0d38bd58ef9a..573007581234 100644 --- a/paimon-python/pypaimon/common/options/config.py +++ b/paimon-python/pypaimon/common/options/config.py @@ -149,6 +149,66 @@ 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_IGNORE_VPC_VALIDATE = ( + ConfigOptions.key("io-cache.ignore-vpc-validate") + .boolean_type() + .default_value(False) + .with_description( + "Whether to use the cache endpoint even when the REST server cannot " + "validate VPC connectivity." + ) + ) + IO_CACHE_VPC_VALIDATED = ( + ConfigOptions.key("io-cache.vpc-validated") + .boolean_type() + .default_value(False) + .with_description( + "Whether the REST server has validated connectivity from the source " + "VPC to the cache endpoint." + ) + ) + IO_CACHE_ENDPOINT = ( + ConfigOptions.key("io-cache.endpoint") + .string_type() + .no_default_value() + .with_description("The cache endpoint vended by the REST server.") + ) + 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 table-level cache policy provided by the REST server, 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..e082cb4cb876 --- /dev/null +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -0,0 +1,421 @@ +# 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 logging +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__) + + +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. + """ + + 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._options_with_endpoint( + catalog_options, CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT) + origin_file_io = file_io_factory(path, origin_options) + if not cls._cache_enabled(catalog_options): + return origin_file_io + + cache_options = cls._options_with_endpoint( + catalog_options, CatalogOptions.IO_CACHE_ENDPOINT) + return cls( + path, + catalog_options, + origin_file_io, + cache_options, + file_io_factory, + ) + + @staticmethod + def _options_with_endpoint(options: Options, endpoint_option) -> Options: + result = options.copy() + endpoint = options.get(endpoint_option) + 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 + and ( + options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED) + or options.get(CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE) + ) + ) + + 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_file_io = origin_file_io + self._cache_options = cache_options + self._file_io_factory = file_io_factory + self._cache_file_io = None + self._cache_file_io_lock = threading.Lock() + 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._cache_file_io_lock = threading.Lock() + self._initialize_filesystem() + + def _get_cache_file_io(self) -> FileIO: + if self._cache_file_io is None: + with self._cache_file_io_lock: + if self._cache_file_io is None: + self._cache_file_io = self._file_io_factory( + self._path, self._cache_options) + return self._cache_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 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: + use_cache = self._should_use_cache(path, operation) + self._log_route(path, operation, use_cache) + if use_cache: + return self._get_cache_file_io() + 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._file_io_for(path, "read").new_input_stream(path) + + def new_output_stream(self, path: str): + return self._file_io_for(path, "write").new_output_stream(path) + + def get_file_status(self, path: str): + return self._file_io_for(path, "meta").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._file_io_for(path, "meta").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(): + file_io = ( + self._get_cache_file_io() + if use_cache else self._origin_file_io) + result.update(file_io.exists_batch(grouped_paths)) + 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._file_io_for(path, "meta").get_file_size(path) + + def is_dir(self, path: str) -> bool: + return self._file_io_for(path, "meta").is_dir(path) + + def to_filesystem_path(self, path: str) -> str: + return self._origin_file_io.to_filesystem_path(path) + + 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._file_io_for(path, "write").write_parquet(path, *args, **kwargs) + + def write_orc(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_orc(path, *args, **kwargs) + + def write_avro(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_avro(path, *args, **kwargs) + + def write_lance(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_lance(path, *args, **kwargs) + + def write_blob(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_blob(path, *args, **kwargs) + + def write_mosaic(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_mosaic(path, *args, **kwargs) + + def write_vortex(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_vortex(path, *args, **kwargs) + + def write_row(self, path: str, *args, **kwargs): + return self._file_io_for(path, "write").write_row(path, *args, **kwargs) + + 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 _filesystem_for(self, path: str, operation: str): + return self._file_io._file_io_for(path, operation).filesystem + + @property + def _origin_filesystem(self): + return self._file_io._origin_file_io.filesystem + + def _origin_filesystem_for(self, path: str, operation: str): + self._file_io._log_route(path, operation, False) + return self._origin_filesystem + + def get_type_name(self) -> str: + return "cache-policy" + + def normalize_path(self, path: str) -> str: + return self._origin_filesystem.normalize_path(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) + grouped.setdefault(use_cache, []).append((index, path)) + + for use_cache, indexed_paths in grouped.items(): + filesystem = ( + self._file_io._get_cache_file_io().filesystem + if use_cache else self._origin_filesystem) + infos = filesystem.get_file_info( + [path for _, path in indexed_paths]) + for (index, _), info in zip(indexed_paths, infos): + result[index] = info + return result + + def get_file_info_selector(self, selector: pafs.FileSelector) -> list: + return self._origin_filesystem_for( + selector.base_dir, "list").get_file_info(selector) + + def create_dir(self, path: str, recursive: bool): + return self._origin_filesystem_for( + path, "mkdirs").create_dir(path, recursive=recursive) + + def delete_dir(self, path: str): + return self._origin_filesystem_for(path, "delete").delete_dir(path) + + def delete_dir_contents(self, path: str, missing_dir_ok: bool = False): + return self._origin_filesystem_for(path, "delete").delete_dir_contents( + path, missing_dir_ok=missing_dir_ok) + + def delete_root_dir_contents(self): + return self._origin_filesystem_for( + "/", "delete").delete_dir_contents( + "/", accept_root_dir=True) + + def delete_file(self, path: str): + return self._origin_filesystem_for(path, "delete").delete_file(path) + + def move(self, src: str, dest: str): + return self._origin_filesystem_for(src, "rename").move(src, dest) + + def copy_file(self, src: str, dest: str): + return self._origin_filesystem_for(src, "copy").copy_file(src, dest) + + def open_input_stream(self, path: str): + return self._filesystem_for(path, "read").open_input_stream(path) + + def open_input_file(self, path: str): + return self._filesystem_for(path, "read").open_input_file(path) + + def open_output_stream(self, path: str, metadata): + filesystem = self._filesystem_for(path, "write") + if metadata is None: + return filesystem.open_output_stream(path) + return filesystem.open_output_stream(path, metadata=metadata) + + def open_append_stream(self, path: str, metadata): + filesystem = self._filesystem_for(path, "write") + if metadata is None: + return filesystem.open_append_stream(path) + return filesystem.open_append_stream(path, metadata=metadata) 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..a4e14b28e09c --- /dev/null +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -0,0 +1,446 @@ +# 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 tempfile +import unittest +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 + + +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_VPC_VALIDATED.key(): True, + CatalogOptions.IO_CACHE_ENDPOINT.key(): "cache-endpoint", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "origin-endpoint", + CatalogOptions.IO_CACHE_WHITELIST.key(): "*", + CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "*", + OssOptions.OSS_ENDPOINT.key(): "token-endpoint", + OssOptions.OSS_IMPL.key(): "jindo", + } + values.update(overrides) + return Options(values) + + +class CachePolicyFileIOTest(unittest.TestCase): + + 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=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_vpc_validation_and_none_policy_disable_wrapper(self): + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): False}), + factory, + ) + self.assertNotIsInstance(file_io, CachePolicyFileIO) + self.assertEqual(1, len(factory.calls)) + self.assertEqual( + "origin-endpoint", + factory.calls[0][1].get(OssOptions.OSS_ENDPOINT), + ) + + factory = _RecordingFactory() + options = _options() + options.to_map().pop(CatalogOptions.IO_CACHE_VPC_VALIDATED.key()) + file_io = CachePolicyFileIO.create(TABLE_ROOT, options, factory) + self.assertNotIsInstance(file_io, CachePolicyFileIO) + + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{ + CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): False, + CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key(): True, + }), + factory, + ) + self.assertIsInstance(file_io, CachePolicyFileIO) + + factory = _RecordingFactory() + file_io = CachePolicyFileIO.create( + TABLE_ROOT, + _options(**{CatalogOptions.IO_CACHE_POLICY.key(): "none"}), + factory, + ) + self.assertNotIsInstance(file_io, CachePolicyFileIO) + + 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..e3a999fe6220 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 @@ -708,6 +709,55 @@ def test_dlf_oss_endpoint_overrides_token_endpoint(self): "Other token properties should be preserved" ) + def test_ignore_vpc_validation_is_merged_into_token(self): + catalog_options = Options({ + CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key(): True, + }) + file_io = RESTTokenFileIO( + self.identifier, self.warehouse_path, catalog_options) + + merged_token = file_io._merge_token_with_catalog_options({ + CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key(): "false", + }) + + self.assertEqual( + "true", + merged_token[CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key()], + ) + + 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", + CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): "true", + CatalogOptions.IO_CACHE_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.assertTrue(options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED)) + 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, From 456662d7a95b40ef3f03426cc1174600593ce9a1 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Mon, 9 Nov 2026 01:05:45 +0800 Subject: [PATCH 09/21] Adapt cache policy tests to current master --- .../src/test/java/org/apache/paimon/utils/FileTypeTest.java | 2 +- .../test/java/org/apache/paimon/jindo/TestJindoUserAgent.java | 4 ++-- paimon-python/pypaimon/tests/cache_policy_file_io_test.py | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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 35f0ee5d43f2..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 @@ -108,7 +108,7 @@ public void testChangelogMetadataIsImmutable() { } @Test - public void testParseWhitelist() { + 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()); diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java index 99e0e123b3fb..600def188bb9 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java @@ -103,9 +103,9 @@ private static Options configure(Options options) { JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(CatalogContext.create(options)); try { - Field field = JindoFileIO.class.getDeclaredField("hadoopOptions"); + Field field = JindoFileIO.class.getDeclaredField("jindoHadoopOptions"); field.setAccessible(true); - return (Options) field.get(fileIO); + return ((JindoHadoopOptions) field.get(fileIO)).get(false); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index a4e14b28e09c..7bb59ce94a29 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -249,7 +249,7 @@ def test_debug_log_contains_path_route_and_endpoint(self): 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=DATA", 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) From 67ff004c152adbf14147d11a625f4f84a8126235 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Mon, 16 Nov 2026 21:30:57 +0800 Subject: [PATCH 10/21] [cache] Move REST cache policy above FileIO and preserve legacy JindoCache --- .../paimon/rest/RESTCatalogOptions.java | 21 +- .../fs/BaseMultiPartUploadCommitter.java | 20 +- .../apache/paimon/fs/cache/CachePolicy.java | 103 ++++ .../paimon/fs/cache/CachePolicyFileIO.java | 321 ++++++++++++ .../apache/paimon/rest/RESTTokenFileIO.java | 42 +- .../fs/BaseMultiPartUploadCommitterTest.java | 25 + .../fs/cache/CachePolicyFileIOTest.java | 480 ++++++++++++++++++ .../paimon/fs/cache/CachePolicyTest.java | 177 +++++++ .../paimon/rest/RESTTokenFileIOTest.java | 75 +++ paimon-filesystems/paimon-jindo/pom.xml | 1 + .../paimon/jindo/HadoopCompliantFileIO.java | 105 ++-- .../org/apache/paimon/jindo/JindoFileIO.java | 144 +++++- .../paimon/jindo/JindoHadoopOptions.java | 143 ------ .../jindo/CachePolicyJindoFileIOTest.java | 182 +++++++ .../apache/paimon/jindo/JindoFileIOTest.java | 39 -- .../paimon/jindo/TestDlfCacheEnable.java | 361 ------------- .../paimon/jindo/TestJindoCacheEnable.java | 180 +++++++ .../jindo/TestJindoDlfAccessTracking.java | 6 +- .../paimon/jindo/TestJindoUserAgent.java | 4 +- 19 files changed, 1780 insertions(+), 649 deletions(-) create mode 100644 paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java create mode 100644 paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java create mode 100644 paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyFileIOTest.java create mode 100644 paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyTest.java delete mode 100644 paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java create mode 100644 paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/CachePolicyJindoFileIOTest.java delete mode 100644 paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java create mode 100644 paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java 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 f5802b47b96b..f73d8a6ae11c 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 @@ -114,6 +114,21 @@ public class RESTCatalogOptions { + "'openapi' (the earlier ROA HMAC-SHA1 scheme). " + "If not set, will be automatically selected based on endpoint host."); + /** + * Legacy JindoCache switch, retained for compatibility. Remote cache endpoint routing does not + * use this option. + * + * @deprecated The JindoCache integration is deprecated. Use the REST cache policy instead. + */ + @Deprecated + public static final ConfigOption IO_CACHE_ENABLED = + ConfigOptions.key("io-cache.enabled") + .booleanType() + .defaultValue(false) + .withDescription( + "Deprecated: enables only the legacy JindoCache integration in JindoFileIO. " + + "This option does not control REST cache endpoint routing."); + public static final ConfigOption IO_CACHE_IGNORE_VPC_VALIDATE = ConfigOptions.key("io-cache.ignore-vpc-validate") .booleanType() @@ -152,11 +167,13 @@ public class RESTCatalogOptions { public static final ConfigOption IO_CACHE_WHITELIST_PATH = ConfigOptions.key("io-cache.whitelist-path") .stringType() - .defaultValue("*") + .defaultValue("bucket,manifest,index") .withDescription( "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."); + + "and io-cache.whitelist-path to use the cache endpoint. " + + "REST cache endpoint routing defaults to * when this option is absent; " + + "the deprecated JindoCache integration retains its original default."); public static final ConfigOption IO_CACHE_POLICY = ConfigOptions.key("io-cache.policy") 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/CachePolicy.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java new file mode 100644 index 000000000000..fc000442d894 --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java @@ -0,0 +1,103 @@ +/* + * 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_IGNORE_VPC_VALIDATE; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; +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") + && (options.get(IO_CACHE_VPC_VALIDATED) + || options.get(IO_CACHE_IGNORE_VPC_VALIDATE)); + 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..529998191c0f --- /dev/null +++ b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java @@ -0,0 +1,321 @@ +/* + * 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.ConfigOption; +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.Optional; + +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; +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. */ +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 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, IO_CACHE_ORIGIN_ENDPOINT); + FileIO origin = FileIO.get(path, originContext); + if (!policy.enabled()) { + return origin; + } + return new CachePolicyFileIO( + path, policy, origin, originContext, withEndpoint(context, IO_CACHE_ENDPOINT)); + } + + private static CatalogContext withEndpoint( + CatalogContext context, ConfigOption endpointOption) { + Options options = new Options(context.options().toMap()); + Configuration hadoopConf = new Configuration(context.hadoopConf()); + String endpoint = options.get(endpointOption); + 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 = 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(); + current = cache; + if (current == null) { + current = FileIO.get(tablePath, cacheContext); + try { + current.setRuntimeContext(new HashMap<>(runtimeOptions)); + } catch (RuntimeException | Error e) { + try { + current.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw e; + } + cache = current; + } + } + } + return current; + } + + @Override + public SeekableInputStream newInputStream(Path path) throws IOException { + return fileIO(path, "read").newInputStream(path); + } + + @Override + public PositionOutputStream newOutputStream(Path path, boolean overwrite) throws IOException { + return fileIO(path, "write").newOutputStream(path, overwrite); + } + + @Override + public FileStatus getFileStatus(Path path) throws IOException { + return fileIO(path, "meta").getFileStatus(path); + } + + @Override + public boolean exists(Path path) throws IOException { + return fileIO(path, "meta").exists(path); + } + + @Override + public long getFileSize(Path path) throws IOException { + return fileIO(path, "meta").getFileSize(path); + } + + @Override + public boolean isDir(Path path) throws IOException { + return fileIO(path, "meta").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); + while (delegate instanceof ResolvingFileIO) { + delegate = ((ResolvingFileIO) delegate).fileIO(path); + } + if (delegate instanceof HadoopOptionsProvider) { + return ((HadoopOptionsProvider) delegate).hadoopOptions(path, opType); + } + Options options = + new Options( + (policy.shouldCache(path, opType) ? 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 53aece6d9344..7f2c3e642927 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,6 +28,7 @@ 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; @@ -47,6 +48,7 @@ import java.io.IOException; import java.time.Duration; import java.util.Map; +import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -67,7 +69,7 @@ public class RESTTokenFileIO implements FileIO { .defaultValue(false) .withDescription("Whether to support data token provided by the REST server."); - private static final Cache FILE_IO_CACHE = + private static final Cache FILE_IO_CACHE = Caffeine.newBuilder() .maximumSize(1000) .expireAfterAccess(10, TimeUnit.HOURS) @@ -250,13 +252,14 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc + "REST credential lifetime after refresh."); } - FileIO fileIO = FILE_IO_CACHE.getIfPresent(currentToken); + FileIOCacheKey cacheKey = new FileIOCacheKey(currentToken, path, catalogContext); + FileIO fileIO = FILE_IO_CACHE.getIfPresent(cacheKey); if (fileIO != null) { return new FileIOWithToken(fileIO, currentToken); } synchronized (FILE_IO_CACHE) { - fileIO = FILE_IO_CACHE.getIfPresent(currentToken); + fileIO = FILE_IO_CACHE.getIfPresent(cacheKey); if (fileIO != null) { return new FileIOWithToken(fileIO, currentToken); } @@ -270,8 +273,8 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc catalogContext.hadoopConf(), catalogContext.preferIO(), catalogContext.fallbackIO()); - fileIO = FileIO.get(path, context); - FILE_IO_CACHE.put(currentToken, fileIO); + fileIO = CachePolicyFileIO.create(path, context); + FILE_IO_CACHE.put(cacheKey, fileIO); return new FileIOWithToken(fileIO, currentToken); } } @@ -305,6 +308,35 @@ private boolean shouldRefresh(long minimumValidityMillis) { < Math.max(TOKEN_EXPIRATION_SAFE_TIME_MILLIS, minimumValidityMillis); } + private static class FileIOCacheKey { + + private final RESTToken token; + private final Path path; + // A token can be shared by tables using different loaders, Hadoop settings or policies. + // Only wrappers built from the same catalog context may share a delegate. + private final CatalogContext context; + + private FileIOCacheKey(RESTToken token, Path path, CatalogContext context) { + this.token = token; + this.path = path; + this.context = context; + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof FileIOCacheKey)) { + return false; + } + FileIOCacheKey that = (FileIOCacheKey) other; + return token.equals(that.token) && path.equals(that.path) && context == that.context; + } + + @Override + public int hashCode() { + return Objects.hash(token, path, System.identityHashCode(context)); + } + } + private static class FileIOWithToken { private final FileIO fileIO; 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..6f9b2c48ee94 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,9 @@ 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.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -73,6 +78,26 @@ 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(IO_CACHE_VPC_VALIDATED, true); + 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/CachePolicyFileIOTest.java b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyFileIOTest.java new file mode 100644 index 000000000000..60128c9965d3 --- /dev/null +++ b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyFileIOTest.java @@ -0,0 +1,480 @@ +/* + * 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.junit.jupiter.api.Test; + +import java.io.IOException; +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_ENDPOINT; +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_VPC_VALIDATED; +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 (boolean vpcValidated : new boolean[] {true, false}) { + Options options = options(); + options.set(IO_CACHE_VPC_VALIDATED, vpcValidated); + if (vpcValidated) { + options.set(IO_CACHE_POLICY, "none"); + } + 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("configured"); + assertThat(loader.delegate("origin").options.keySet()) + .doesNotContain(IO_CACHE_ENDPOINT.key(), IO_CACHE_ORIGIN_ENDPOINT.key()); + } + } + } + + @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 testMissingEndpointRetainsConfiguredEndpoint() throws Exception { + Options options = options(); + options.set(IO_CACHE_ENDPOINT, " "); + options.remove(IO_CACHE_ORIGIN_ENDPOINT); + try (FileIO fileIO = create(options, new RecordingLoader())) { + assertThat( + ((HadoopOptionsProvider) fileIO) + .hadoopOptions(DATA, "read") + .get("fs.oss.endpoint")) + .isEqualTo("configured"); + } + } + + @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"); + } + } + + private static Options options() { + Options options = new Options(); + options.set(IO_CACHE_POLICY, "meta,read,write"); + options.set(IO_CACHE_VPC_VALIDATED, true); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); + options.set(IO_CACHE_ENDPOINT, "cache"); + options.set("fs.oss.endpoint", "configured"); + 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<>(); + + @Override + public String getScheme() { + return "oss"; + } + + @Override + public FileIO load(Path path) { + RecordingFileIO fileIO = new RecordingFileIO(); + 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; + + @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 (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) { + calls.add("exists"); + 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..3e61bb601ffa --- /dev/null +++ b/paimon-common/src/test/java/org/apache/paimon/fs/cache/CachePolicyTest.java @@ -0,0 +1,177 @@ +/* + * 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_IGNORE_VPC_VALIDATE; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; +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); + options.set(IO_CACHE_IGNORE_VPC_VALIDATE, true); + CachePolicy policy = new CachePolicy(options); + assertThat(policy.enabled()).isFalse(); + assertThat(policy.shouldCache(DATA, "read")).isFalse(); + } + } + + @Test + void testVpcValidationAndOverride() { + Options options = options("read"); + options.remove(IO_CACHE_VPC_VALIDATED); + assertThat(new CachePolicy(options).enabled()).isFalse(); + options.set(IO_CACHE_VPC_VALIDATED, false); + assertThat(new CachePolicy(options).enabled()).isFalse(); + options.set(IO_CACHE_IGNORE_VPC_VALIDATE, true); + assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isTrue(); + options.set(IO_CACHE_IGNORE_VPC_VALIDATE, false); + options.set(IO_CACHE_VPC_VALIDATED, true); + 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); + } + options.set(IO_CACHE_VPC_VALIDATED, true); + 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..3ab389b15f6f 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,15 @@ 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.IO_CACHE_ENDPOINT; +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_VPC_VALIDATED; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; @@ -49,6 +57,73 @@ /** Tests for {@link RESTTokenFileIO}. */ class RESTTokenFileIOTest { + @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(IO_CACHE_VPC_VALIDATED.key(), "true"); + tokenOptions.put(IO_CACHE_ENDPOINT.key(), "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 testIdenticalTokensDoNotShareDifferentPathsOrCatalogContexts() throws IOException { + Path root = new Path("oss://bucket/table"); + RESTApi api = mock(RESTApi.class); + Identifier identifier = Identifier.create("db", "table"); + when(api.loadTableToken(identifier)) + .thenReturn(new GetTableTokenResponse(Collections.emptyMap(), Long.MAX_VALUE)); + FileIOLoader firstLoader = mock(FileIOLoader.class); + FileIOLoader secondLoader = mock(FileIOLoader.class); + when(firstLoader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); + when(secondLoader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); + CatalogContext firstContext = CatalogContext.create(new Options(), firstLoader, null); + CatalogContext secondContext = CatalogContext.create(new Options(), secondLoader, null); + FileIO first = new RESTTokenFileIO(firstContext, api, identifier, root).fileIO(); + assertThat(new RESTTokenFileIO(firstContext, api, identifier, root).fileIO()) + .isSameAs(first); + assertThat(new RESTTokenFileIO(secondContext, api, identifier, root).fileIO()) + .isNotSameAs(first); + assertThat( + new RESTTokenFileIO(firstContext, api, identifier, new Path(root, "other")) + .fileIO()) + .isNotSameAs(first); + } + @Test void testSetFileIOCacheMaximumSize() { long originalMaximumSize = RESTTokenFileIO.fileIOCacheMaximumSize(); diff --git a/paimon-filesystems/paimon-jindo/pom.xml b/paimon-filesystems/paimon-jindo/pom.xml index e33cedc79f85..bef3f1854365 100644 --- a/paimon-filesystems/paimon-jindo/pom.xml +++ b/paimon-filesystems/paimon-jindo/pom.xml @@ -167,6 +167,7 @@ 1.1.3 + diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java index 50d3256af8ae..f52e1d8c16dc 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/HadoopCompliantFileIO.java @@ -26,10 +26,10 @@ import org.apache.paimon.fs.RemoteIterator; import org.apache.paimon.fs.SeekableInputStream; import org.apache.paimon.fs.VectoredReadable; -import org.apache.paimon.options.Options; -import org.apache.paimon.utils.FileType; import org.apache.paimon.utils.Pair; +import org.apache.paimon.shade.guava30.com.google.common.collect.Lists; + import com.aliyun.jindodata.common.JindoHadoopSystem; import com.aliyun.jindodata.types.JindoHadoopFileStatus; import org.apache.hadoop.fs.FSDataInputStream; @@ -45,17 +45,13 @@ import java.net.URI; import java.time.Duration; import java.util.ArrayList; -import java.util.EnumSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; /** @@ -68,7 +64,7 @@ public abstract class HadoopCompliantFileIO implements FileIO { private static final long serialVersionUID = 1L; - // Cache policy tags select the operation types that use cache. + /// Detailed cache strategies are retrieved from REST server. private static final String META_CACHE_ENABLED_TAG = "meta"; private static final String READ_CACHE_ENABLED_TAG = "read"; private static final String WRITE_CACHE_ENABLED_TAG = "write"; @@ -79,26 +75,18 @@ public abstract class HadoopCompliantFileIO implements FileIO { protected boolean writeCacheEnabled = false; protected transient volatile Map> fsMap; - protected transient volatile Map> cacheFsMap; + protected transient volatile Map> jindoCacheFsMap; - private Set cacheWhitelist = EnumSet.noneOf(FileType.class); + // Only enable cache for path which is generated with uuid private List cacheWhitelistPaths = new ArrayList<>(); - private boolean cacheAllPaths = false; boolean shouldCache(Path path) { - return !FileType.isMutable(path) - && cacheWhitelist.contains(FileType.classify(path)) - && matchesCacheWhitelistPath(path); - } - - private boolean matchesCacheWhitelistPath(Path path) { - if (cacheAllPaths) { + if (cacheWhitelistPaths.isEmpty()) { return true; } - - String pathString = path.toUri().getPath(); + String pathStr = path.toUri().getPath(); for (String pattern : cacheWhitelistPaths) { - if (pathString.contains(pattern)) { + if (pathStr.contains(pattern)) { return true; } } @@ -107,57 +95,38 @@ private boolean matchesCacheWhitelistPath(Path path) { @Override public void configure(CatalogContext context) { - metaCacheEnabled = false; - readCacheEnabled = false; - writeCacheEnabled = false; - cacheWhitelist = EnumSet.noneOf(FileType.class); - cacheWhitelistPaths = new ArrayList<>(); - cacheAllPaths = false; - // Process file io cache configuration - Options options = context.options(); - String cachePolicy = options.get(IO_CACHE_POLICY); - boolean vpcValidated = options.get(IO_CACHE_VPC_VALIDATED); - boolean ignoreVpcValidate = options.get(IO_CACHE_IGNORE_VPC_VALIDATE); - if (cachePolicy == null - || cachePolicy.contains(DISABLE_CACHE_TAG) - || (!vpcValidated && !ignoreVpcValidate)) { + if (!context.options().get(IO_CACHE_ENABLED) + || context.options().get(IO_CACHE_POLICY) == null + || context.options().get(IO_CACHE_POLICY).contains(DISABLE_CACHE_TAG)) { LOG.debug( - "Cache is disabled with io-cache.policy={}, io-cache.vpc-validated={}, io-cache.ignore-vpc-validate={}", - cachePolicy, - vpcValidated, - ignoreVpcValidate); + "Cache is disabled with io-cache.enabled={}, io-cache.policy={}", + context.options().get(IO_CACHE_ENABLED), + context.options().get(IO_CACHE_POLICY)); return; } // Enable file io cache - metaCacheEnabled = cachePolicy.contains(META_CACHE_ENABLED_TAG); - readCacheEnabled = cachePolicy.contains(READ_CACHE_ENABLED_TAG); - writeCacheEnabled = cachePolicy.contains(WRITE_CACHE_ENABLED_TAG); - String whitelist = options.get(IO_CACHE_WHITELIST); - if (whitelist != null && "*".equals(whitelist.trim())) { - cacheWhitelist = EnumSet.allOf(FileType.class); + if (context.options().get("fs.jindocache.namespace.rpc.address") == null) { + LOG.info( + "FileIO cache is enabled but JindoCache RPC address is not set, fallback to no-cache"); } else { - cacheWhitelist = FileType.parseWhitelist(whitelist); - } - - String whitelistPath = options.get(IO_CACHE_WHITELIST_PATH); - if (whitelistPath != null && "*".equals(whitelistPath.trim())) { - cacheAllPaths = true; - } else if (whitelistPath != null) { - for (String pattern : whitelistPath.split(",")) { - pattern = pattern.trim(); - if (!pattern.isEmpty()) { - cacheWhitelistPaths.add(pattern); - } + metaCacheEnabled = + context.options().get(IO_CACHE_POLICY).contains(META_CACHE_ENABLED_TAG); + readCacheEnabled = + context.options().get(IO_CACHE_POLICY).contains(READ_CACHE_ENABLED_TAG); + writeCacheEnabled = + context.options().get(IO_CACHE_POLICY).contains(WRITE_CACHE_ENABLED_TAG); + String whitelist = context.options().get(IO_CACHE_WHITELIST_PATH); + if (!whitelist.equals("*")) { + cacheWhitelistPaths = Lists.newArrayList(whitelist.split(",")); } + LOG.info( + "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist path: {}", + metaCacheEnabled, + readCacheEnabled, + writeCacheEnabled, + whitelist); } - LOG.info( - "Cache enabled with cache policy: meta cache enabled {}, read cache enabled {}, write cache enabled {}, whitelist file types: {}, whitelist path: {}", - metaCacheEnabled, - readCacheEnabled, - writeCacheEnabled, - cacheWhitelist, - whitelistPath); } @Override @@ -318,14 +287,14 @@ protected Pair getFileSystemPair( org.apache.hadoop.fs.Path path, boolean enableCache) throws IOException { Map> map; if (enableCache) { - if (cacheFsMap == null) { + if (jindoCacheFsMap == null) { synchronized (this) { - if (cacheFsMap == null) { - cacheFsMap = new ConcurrentHashMap<>(); + if (jindoCacheFsMap == null) { + jindoCacheFsMap = new ConcurrentHashMap<>(); } } } - map = cacheFsMap; + map = jindoCacheFsMap; } else { if (fsMap == null) { synchronized (this) { diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java index b77c3ea66a68..5afb528a6234 100644 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java +++ b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoFileIO.java @@ -24,24 +24,32 @@ import org.apache.paimon.fs.HadoopOptionsProvider; import org.apache.paimon.fs.Path; import org.apache.paimon.fs.TwoPhaseOutputStream; +import org.apache.paimon.options.ConfigOption; +import org.apache.paimon.options.ConfigOptions; import org.apache.paimon.options.Options; import org.apache.paimon.plugin.PluginLoader; import org.apache.paimon.utils.IOUtils; import org.apache.paimon.utils.Pair; +import org.apache.paimon.utils.SensitiveConfigUtils; import com.aliyun.jindodata.common.JindoHadoopSystem; import com.aliyun.jindodata.dls.JindoDlsFileSystem; import com.aliyun.jindodata.oss.JindoOssFileSystem; +import com.aliyun.jindodata.oss.auth.SimpleCredentialsProvider; import com.aliyun.jindodata.store.JindoMpuStore; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.annotation.Nullable; + import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; +import java.util.HashMap; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; @@ -56,6 +64,40 @@ public class JindoFileIO extends HadoopCompliantFileIO implements HadoopOptionsP private static final Logger LOG = LoggerFactory.getLogger(JindoFileIO.class); + /** + * In order to simplify, we make paimon oss configuration keys same with hadoop oss module. So, + * we add all configuration key with prefix `fs.` in paimon conf to hadoop conf. + * + *

Not use fs.oss because this FileIO also access dlf/dls scheme. + */ + private static final String[] CONFIG_PREFIXES = {"fs."}; + + private static final String OSS_ACCESS_KEY_ID = "fs.oss.accessKeyId"; + private static final String OSS_ACCESS_KEY_SECRET = "fs.oss.accessKeySecret"; + private static final String OSS_SECURITY_TOKEN = "fs.oss.securityToken"; + private static final String OSS_SHOW_DIR_TIMESTAMP = "fs.oss.show-dir-timestamp"; + + private static final ConfigOption IO_STATS_INTERVAL = + ConfigOptions.key("jindo.io-stats.interval") + .durationType() + .defaultValue(Duration.ZERO) + .withDescription( + "Interval of logging Jindo stream and memory statistics while Jindo " + + "streams are in use, e.g. 1 min. Stream counts cover the " + + "class loader of paimon-jindo, which is the whole JVM unless " + + "jobs bundle their own copy. The shortest interval set in " + + "it is used. 0 (the default) disables it, and streams of " + + "this FileIO are not counted."); + + private static final Map CASE_SENSITIVE_KEYS = + new HashMap() { + { + put(OSS_ACCESS_KEY_ID.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_ID); + put(OSS_ACCESS_KEY_SECRET.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_SECRET); + put(OSS_SECURITY_TOKEN.toLowerCase(Locale.ROOT), OSS_SECURITY_TOKEN); + } + }; + /** * Cache JindoOssFileSystem, at present, there is no good mechanism to ensure that the file * system will be shut down, so here the fs cache is used to avoid resource leakage. @@ -63,8 +105,10 @@ public class JindoFileIO extends HadoopCompliantFileIO implements HadoopOptionsP private static final Map> CACHE = new ConcurrentHashMap<>(); - private JindoHadoopOptions jindoHadoopOptions; + private Options hadoopOptions; + private Options hadoopOptionsWithCache; private boolean allowCache = true; + private Duration ioStatsInterval = IO_STATS_INTERVAL.defaultValue(); private transient BlobPresigner blobPresigner; public JindoFileIO() {} @@ -82,7 +126,61 @@ public boolean isObjectStore() { public void configure(CatalogContext context) { super.configure(context); allowCache = context.options().get(FILE_IO_ALLOW_CACHE); - jindoHadoopOptions = new JindoHadoopOptions(context); + ioStatsInterval = context.options().get(IO_STATS_INTERVAL); + hadoopOptions = new Options(); + // read all configuration with prefix 'CONFIG_PREFIXES' + for (String key : context.options().keySet()) { + for (String prefix : CONFIG_PREFIXES) { + if (key.startsWith(prefix)) { + String value = context.options().get(key); + if (CASE_SENSITIVE_KEYS.containsKey(key.toLowerCase(Locale.ROOT))) { + key = CASE_SENSITIVE_KEYS.get(key.toLowerCase(Locale.ROOT)); + } + hadoopOptions.set(key, value); + + LOG.debug( + "Adding config entry for {} as {} to Hadoop config", + key, + SensitiveConfigUtils.redactValue(key, hadoopOptions.get(key))); + } + } + } + // as in rest catalog use could define ak for table so we need first use ak. + if (hadoopOptions.containsKey(OSS_ACCESS_KEY_ID) + && hadoopOptions.containsKey(OSS_ACCESS_KEY_SECRET)) { + LOG.info("Using Ak init Jindo."); + // https://github.com/aliyun/alibabacloud-jindodata/blob/master/docs/user/4.x/4.6.x/4.6.1/oss/hadoop/jindosdk_ide_hadoop.md + hadoopOptions.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem"); + hadoopOptions.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS"); + + // Misalignment can greatly affect performance, so the maximum buffer is set here + hadoopOptions.set("fs.oss.read.position.buffer.size", "8388608"); + hadoopOptions.set("fs.oss.credentials.provider", SimpleCredentialsProvider.NAME); + } else { + LOG.info("Using hadoop conf init Jindo."); + context.hadoopConf() + .iterator() + .forEachRemaining(entry -> hadoopOptions.set(entry.getKey(), entry.getValue())); + } + + // Resolving a timestamp for every listed directory is expensive in Jindo. + if (!hadoopOptions.containsKey(OSS_SHOW_DIR_TIMESTAMP)) { + hadoopOptions.set(OSS_SHOW_DIR_TIMESTAMP, "false"); + } + + JindoUserAgent.apply(context.options(), hadoopOptions); + + // another config when enable cache + hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); + hadoopOptionsWithCache.set("fs.xengine", "jindocache"); + if (!hadoopOptionsWithCache.containsKey("fs.jindocache.client.metrics.enable")) { + // enable metrics report by default + hadoopOptionsWithCache.set("fs.jindocache.client.metrics.enable", "true"); + } + // Workaround: following configurations to avoid bug in some JindoSDK versions + hadoopOptionsWithCache.set("fs.oss.read.profile.columnar.use-pread", "false"); + hadoopOptionsWithCache.set( + "fs.jindocache.read.profile.columnar.readahead.pread.enable", "false"); } /** @@ -102,7 +200,11 @@ public Options hadoopOptions(Path path, String opType) { } else if (opType.equalsIgnoreCase("meta")) { shouldCache = metaCacheEnabled && shouldCache(path); } - return jindoHadoopOptions.get(shouldCache); + if (shouldCache) { + return hadoopOptionsWithCache; + } else { + return hadoopOptions; + } } @Override @@ -122,7 +224,10 @@ public TwoPhaseOutputStream newTwoPhaseOutputStream(Path path, boolean overwrite return super.newTwoPhaseOutputStream(path, overwrite); } return new JindoTwoPhaseOutputStream( - new JindoMultiPartUpload(mpuStore, fs.getWorkingDirectory()), hadoopPath, path); + new JindoMultiPartUpload(mpuStore, fs.getWorkingDirectory()), + hadoopPath, + path, + ioStatsInterval()); } @Override @@ -148,7 +253,7 @@ private synchronized BlobPresigner blobPresigner() { thread.setContextClassLoader(loader.submoduleClassLoader()); BlobPresigner presigner = loader.newInstance("org.apache.paimon.jindo.JindoBlobPresigner"); - presigner.configure(jindoHadoopOptions.get(false)); + presigner.configure(hadoopOptions); blobPresigner = presigner; } finally { thread.setContextClassLoader(previous); @@ -174,7 +279,7 @@ protected Pair createFileSystem( org.apache.hadoop.fs.Path path, boolean enableCache) { final String scheme = path.toUri().getScheme(); final String authority = path.toUri().getAuthority(); - Options options = jindoHadoopOptions.get(enableCache); + Options options = enableCache ? hadoopOptionsWithCache : hadoopOptions; Supplier> supplier = () -> { Configuration hadoopConf = new Configuration(false); @@ -209,13 +314,24 @@ protected Pair createFileSystem( }; if (allowCache) { - return CACHE.computeIfAbsent( - new CacheKey(options, scheme, authority), key -> supplier.get()); + Pair pair = + CACHE.computeIfAbsent( + new CacheKey(options, scheme, authority), key -> supplier.get()); + // cached file systems are never closed, so the reporter may call into them + JindoIOStats.registerNativeMetrics(pair.getKey(), path); + return pair; } else { return supplier.get(); } } + @Nullable + @Override + protected Duration ioStatsInterval() { + // FileIOs deserialized from older versions have no interval + return ioStatsInterval; + } + @Override public synchronized void close() { if (blobPresigner != null) { @@ -230,8 +346,8 @@ public synchronized void close() { } } if (!allowCache) { - closeFileSystems(fsMap); - closeFileSystems(cacheFsMap); + fsMap.values().stream().map(Pair::getKey).forEach(IOUtils::closeQuietly); + fsMap.clear(); } } @@ -247,14 +363,6 @@ String create(Path tableRoot, BlobDescriptor descriptor, Duration validity) void close(); } - private static void closeFileSystems(Map> fileSystems) { - if (fileSystems == null) { - return; - } - fileSystems.values().stream().map(Pair::getKey).forEach(IOUtils::closeQuietly); - fileSystems.clear(); - } - private static class CacheKey { private final Options options; diff --git a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java b/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java deleted file mode 100644 index 00c905c4df8f..000000000000 --- a/paimon-filesystems/paimon-jindo/src/main/java/org/apache/paimon/jindo/JindoHadoopOptions.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * 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.options.Options; -import org.apache.paimon.utils.SensitiveConfigUtils; -import org.apache.paimon.utils.StringUtils; - -import com.aliyun.jindodata.oss.auth.SimpleCredentialsProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; - -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ORIGIN_ENDPOINT; - -/** Jindo {@link JindoHadoopOptions}. */ -public class JindoHadoopOptions implements Serializable { - private static final long serialVersionUID = 1L; - - private static final Logger LOG = LoggerFactory.getLogger(JindoHadoopOptions.class); - - private Options hadoopOptions; - private Options hadoopOptionsWithCache; - - /** - * In order to simplify, we make paimon oss configuration keys same with hadoop oss module. So, - * we add all configuration key with prefix `fs.` in paimon conf to hadoop conf. - * - *

Not use fs.oss because this FileIO also access dlf/dls scheme. - */ - private static final String[] CONFIG_PREFIXES = {"fs."}; - - private static final String OSS_ACCESS_KEY_ID = "fs.oss.accessKeyId"; - private static final String OSS_ACCESS_KEY_SECRET = "fs.oss.accessKeySecret"; - private static final String OSS_SECURITY_TOKEN = "fs.oss.securityToken"; - private static final String OSS_ENDPOINT = "fs.oss.endpoint"; - private static final String OSS_SHOW_DIR_TIMESTAMP = "fs.oss.show-dir-timestamp"; - - private static final Map CASE_SENSITIVE_KEYS = - new HashMap() { - { - put(OSS_ACCESS_KEY_ID.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_ID); - put(OSS_ACCESS_KEY_SECRET.toLowerCase(Locale.ROOT), OSS_ACCESS_KEY_SECRET); - put(OSS_SECURITY_TOKEN.toLowerCase(Locale.ROOT), OSS_SECURITY_TOKEN); - } - }; - - public JindoHadoopOptions(CatalogContext context) { - hadoopOptions = new Options(); - // read all configuration with prefix 'CONFIG_PREFIXES' - for (String key : context.options().keySet()) { - for (String prefix : CONFIG_PREFIXES) { - if (key.startsWith(prefix)) { - String value = context.options().get(key); - if (CASE_SENSITIVE_KEYS.containsKey(key.toLowerCase(Locale.ROOT))) { - key = CASE_SENSITIVE_KEYS.get(key.toLowerCase(Locale.ROOT)); - } - hadoopOptions.set(key, value); - - LOG.debug( - "Adding config entry for {} as {} to Hadoop config", - key, - SensitiveConfigUtils.redactValue(key, hadoopOptions.get(key))); - } - } - } - // as in rest catalog use could define ak for table so we need first use ak. - if (hadoopOptions.containsKey(OSS_ACCESS_KEY_ID) - && hadoopOptions.containsKey(OSS_ACCESS_KEY_SECRET)) { - LOG.info("Using Ak init Jindo."); - // https://github.com/aliyun/alibabacloud-jindodata/blob/master/docs/user/4.x/4.6.x/4.6.1/oss/hadoop/jindosdk_ide_hadoop.md - hadoopOptions.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem"); - hadoopOptions.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS"); - - // Misalignment can greatly affect performance, so the maximum buffer is set here - hadoopOptions.set("fs.oss.read.position.buffer.size", "8388608"); - hadoopOptions.set("fs.oss.credentials.provider", SimpleCredentialsProvider.NAME); - } else { - LOG.info("Using hadoop conf init Jindo."); - context.hadoopConf() - .iterator() - .forEachRemaining(entry -> hadoopOptions.set(entry.getKey(), entry.getValue())); - } - - // Resolving a timestamp for every listed directory is expensive in Jindo. - if (!hadoopOptions.containsKey(OSS_SHOW_DIR_TIMESTAMP)) { - hadoopOptions.set(OSS_SHOW_DIR_TIMESTAMP, "false"); - } - - JindoUserAgent.apply(context.options(), hadoopOptions); - - initDLFCacheBackend(context); - } - - public Options get(boolean enableCache) { - return enableCache ? hadoopOptionsWithCache : hadoopOptions; - } - - private void initDLFCacheBackend(CatalogContext context) { - hadoopOptionsWithCache = new Options(hadoopOptions.toMap()); - - String cacheEndpoint = context.options().get(IO_CACHE_ENDPOINT); - if (!StringUtils.isNullOrWhitespaceOnly(cacheEndpoint)) { - hadoopOptionsWithCache.set(OSS_ENDPOINT, cacheEndpoint); - } - - String originEndpoint = context.options().get(IO_CACHE_ORIGIN_ENDPOINT); - if (!StringUtils.isNullOrWhitespaceOnly(originEndpoint)) { - hadoopOptions.set(OSS_ENDPOINT, originEndpoint); - } - String directEndpoint = hadoopOptions.get(OSS_ENDPOINT); - String configuredCacheEndpoint = hadoopOptionsWithCache.get(OSS_ENDPOINT); - if (!Objects.equals(directEndpoint, configuredCacheEndpoint)) { - LOG.info( - "Using direct access to OSS endpoint: {}, cache endpoint: {}", - directEndpoint, - configuredCacheEndpoint); - } - } -} 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..2217c397e6f8 --- /dev/null +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/CachePolicyJindoFileIOTest.java @@ -0,0 +1,182 @@ +/* + * 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_ENDPOINT; +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_VPC_VALIDATED; +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("configured"); + } + } + + @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_VPC_VALIDATED, true); + options.set(IO_CACHE_ENDPOINT, "cache"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); + options.set("fs.oss.endpoint", "configured"); + 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-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java index b44caaf43139..0c4d98e516e3 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/JindoFileIOTest.java @@ -29,7 +29,6 @@ import org.apache.paimon.utils.Pair; import com.aliyun.jindodata.common.JindoHadoopSystem; -import com.aliyun.jindodata.oss.JindoOssFileSystem; import com.aliyun.jindodata.types.JindoHadoopFileStatus; import com.aliyun.oss.ClientConfiguration; import com.aliyun.oss.HttpMethod; @@ -46,11 +45,8 @@ import java.security.MessageDigest; import java.time.Duration; import java.util.Date; -import java.util.concurrent.ConcurrentHashMap; -import static org.apache.paimon.options.CatalogOptions.FILE_IO_ALLOW_CACHE; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -277,41 +273,6 @@ protected Pair getFileSystemPair( } } - @Test - void closeClearsDirectAndCacheFileSystems() { - JindoFileIO fileIO = createNonCachingFileIO(); - fileIO.fsMap = new ConcurrentHashMap<>(); - fileIO.fsMap.put("test-bucket", Pair.of(new JindoOssFileSystem(), "test")); - fileIO.cacheFsMap = new ConcurrentHashMap<>(); - fileIO.cacheFsMap.put("test-bucket", Pair.of(new JindoOssFileSystem(), "test")); - - fileIO.close(); - - assertThat(fileIO.fsMap).isEmpty(); - assertThat(fileIO.cacheFsMap).isEmpty(); - - assertThatCode(fileIO::close).doesNotThrowAnyException(); - } - - @Test - void closeHandlesCacheOnlyFileSystem() { - JindoFileIO fileIO = createNonCachingFileIO(); - fileIO.cacheFsMap = new ConcurrentHashMap<>(); - fileIO.cacheFsMap.put("test-bucket", Pair.of(new JindoOssFileSystem(), "test")); - - assertThatCode(fileIO::close).doesNotThrowAnyException(); - - assertThat(fileIO.cacheFsMap).isEmpty(); - } - - private JindoFileIO createNonCachingFileIO() { - Options options = new Options(); - options.set(FILE_IO_ALLOW_CACHE, false); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(CatalogContext.create(options)); - return fileIO; - } - private static String sha256Hex(byte[] bytes) throws Exception { StringBuilder result = new StringBuilder(); for (byte value : MessageDigest.getInstance("SHA-256").digest(bytes)) { diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java deleted file mode 100644 index 416e97a150ca..000000000000 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestDlfCacheEnable.java +++ /dev/null @@ -1,361 +0,0 @@ -/* - * 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.Path; -import org.apache.paimon.options.Options; -import org.apache.paimon.utils.InstantiationUtil; - -import org.junit.jupiter.api.Test; - -import java.lang.reflect.Field; - -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; -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_VPC_VALIDATED; -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; - -/** Test for DLF cache enable configuration. */ -public class TestDlfCacheEnable { - - private static final String TABLE_ROOT = "oss://test-bucket/database/table"; - - private static final Path META_PATH = new Path(TABLE_ROOT + "/snapshot/snapshot-1"); - private static final Path MANIFEST_PATH = - new Path(TABLE_ROOT + "/manifest/manifest-a1b2c3d4-0"); - private static final Path GLOBAL_INDEX_PATH = - new Path(TABLE_ROOT + "/index/btree-global-index-a1b2c3d4.index"); - private static final Path BUCKET_INDEX_PATH = new Path(TABLE_ROOT + "/index/index-a1b2c3d4-0"); - private static final Path DATA_PATH = new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc"); - private static final Path OTHER_DATA_PATH = - new Path(TABLE_ROOT + "/bucket-1/data-a1b2c3d4-0.orc"); - private static final Path FILE_INDEX_PATH = - new Path(TABLE_ROOT + "/bucket-0/data-a1b2c3d4-0.orc.index"); - - private CatalogContext createCatalogContext(String cachePolicy, String cacheWhitelist) { - return createCatalogContext(cachePolicy, cacheWhitelist, null); - } - - private CatalogContext createCatalogContext( - String cachePolicy, String cacheWhitelist, String cacheWhitelistPath) { - Options options = new Options(); - if (cachePolicy != null) { - options.set(IO_CACHE_POLICY, cachePolicy); - } - options.set("fs.oss.endpoint", "test-oss-endpoint"); - options.set(IO_CACHE_ENDPOINT, "test-dlf-cache-endpoint"); - options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); - options.set(IO_CACHE_VPC_VALIDATED, true); - if (cacheWhitelist != null) { - options.set(IO_CACHE_WHITELIST, cacheWhitelist); - } - if (cacheWhitelistPath != null) { - options.set(IO_CACHE_WHITELIST_PATH, cacheWhitelistPath); - } - return CatalogContext.create(options); - } - - private CatalogContext createDlfCacheContext( - String cachePolicy, Boolean vpcValidated, boolean ignoreVpcValidate) { - Options options = new Options(); - if (cachePolicy != null) { - options.set(IO_CACHE_POLICY, cachePolicy); - } - options.set("fs.oss.endpoint", "test-oss-endpoint"); - options.set(IO_CACHE_ENDPOINT, "test-dlf-cache-endpoint"); - options.set(IO_CACHE_ORIGIN_ENDPOINT, "test-oss-endpoint"); - if (vpcValidated != null) { - options.set(IO_CACHE_VPC_VALIDATED, vpcValidated); - } - options.set(IO_CACHE_IGNORE_VPC_VALIDATE, ignoreVpcValidate); - options.set(IO_CACHE_WHITELIST, "data"); - return CatalogContext.create(options); - } - - private boolean getCacheFlag(HadoopCompliantFileIO fileIO, String fieldName) { - try { - Field field = HadoopCompliantFileIO.class.getDeclaredField(fieldName); - field.setAccessible(true); - return field.getBoolean(fileIO); - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException("Failed to access field: " + fieldName, e); - } - } - - private void verifyCacheFlags( - HadoopCompliantFileIO fileIO, - boolean expectedMeta, - boolean expectedRead, - boolean expectedWrite) { - assertThat(getCacheFlag(fileIO, "metaCacheEnabled")).isEqualTo(expectedMeta); - assertThat(getCacheFlag(fileIO, "readCacheEnabled")).isEqualTo(expectedRead); - assertThat(getCacheFlag(fileIO, "writeCacheEnabled")).isEqualTo(expectedWrite); - } - - @Test - public void testCacheEnabledWithMetaPolicy() { - CatalogContext context = createCatalogContext("meta", null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, true, false, false); - } - - @Test - public void testCacheEnabledWithReadPolicy() { - CatalogContext context = createCatalogContext("read", null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, true, false); - } - - @Test - public void testCacheEnabledWithWritePolicy() { - CatalogContext context = createCatalogContext("write", null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, false, true); - } - - @Test - public void testCacheEnabledWithCombinedPolicy() { - CatalogContext context = createCatalogContext("meta,read,write", null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, true, true, true); - } - - @Test - public void testCacheDisabledWhenPolicyNone() { - CatalogContext context = createCatalogContext("none", null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, false, false); - } - - @Test - public void testDlfCacheDisabledWhenVpcNotValidated() { - CatalogContext context = createDlfCacheContext("meta,read,write", false, false); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, false, false); - Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); - assertThat(fileIO.hadoopOptions(path, "read").get("fs.oss.endpoint")) - .isEqualTo("test-oss-endpoint"); - } - - @Test - public void testDlfCacheEnabledWhenIgnoringVpcValidation() { - CatalogContext context = createDlfCacheContext("read", false, true); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, true, false); - Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); - assertThat(fileIO.hadoopOptions(path, "read").get("fs.oss.endpoint")) - .isEqualTo("test-dlf-cache-endpoint"); - assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) - .isEqualTo("test-oss-endpoint"); - } - - @Test - public void testDlfCacheEnabledWhenVpcValidated() { - CatalogContext context = createDlfCacheContext("read", true, false); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, true, false); - Path path = new Path("oss://test-bucket/database/table/bucket-0/file.orc"); - assertThat(fileIO.hadoopOptions(path, "read").get("fs.oss.endpoint")) - .isEqualTo("test-dlf-cache-endpoint"); - assertThat(fileIO.hadoopOptions(path, "meta").get("fs.oss.endpoint")) - .isEqualTo("test-oss-endpoint"); - } - - @Test - public void testDlfCacheDefaultsVpcValidationToFalse() { - CatalogContext context = createDlfCacheContext("meta,read,write", null, false); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, false, false); - } - - @Test - public void testIgnoreVpcValidationDoesNotOverrideDisabledPolicy() { - CatalogContext context = createDlfCacheContext("none", false, true); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, false, false); - } - - @Test - public void testCacheDisabledWhenPolicyNull() { - CatalogContext context = createCatalogContext(null, null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - verifyCacheFlags(fileIO, false, false, false); - } - - @Test - public void testDefaultCacheWhitelist() { - CatalogContext context = createCatalogContext("meta,read,write", null); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - assertThat(fileIO.shouldCache(META_PATH)).isTrue(); - assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isTrue(); - assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isTrue(); - assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); - assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isTrue(); - } - - @Test - public void testAllSupportedCacheWhitelistFileTypes() { - CatalogContext context = - createCatalogContext( - "meta,read,write", "meta,global-index,bucket-index,data,file-index"); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - assertThat(fileIO.shouldCache(META_PATH)).isTrue(); - assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isTrue(); - assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isTrue(); - assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); - assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isTrue(); - } - - @Test - public void testCustomCacheWhitelist() { - CatalogContext context = createCatalogContext("meta,read,write", "data,file-index"); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - assertThat(fileIO.shouldCache(GLOBAL_INDEX_PATH)).isFalse(); - assertThat(fileIO.shouldCache(BUCKET_INDEX_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); - assertThat(fileIO.shouldCache(FILE_INDEX_PATH)).isTrue(); - } - - @Test - public void testEmptyAndInvalidCacheWhitelistFailClosed() { - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext("meta,read,write", "")); - - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - - fileIO.configure(createCatalogContext("meta,read,write", "manifest,unknown")); - - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - } - - @Test - public void testCacheWhitelistPath() { - CatalogContext context = createCatalogContext("meta,read,write", "*", "manifest, bucket-0"); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - assertThat(fileIO.shouldCache(MANIFEST_PATH)).isTrue(); - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); - assertThat(fileIO.shouldCache(OTHER_DATA_PATH)).isFalse(); - } - - @Test - public void testCacheWhitelistAndPathMustBothMatch() { - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext("meta,read,write", "meta", "manifest")); - - assertThat(fileIO.shouldCache(MANIFEST_PATH)).isTrue(); - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - } - - @Test - public void testEmptyCacheWhitelistPathFailsClosed() { - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext("meta,read,write", "*", "")); - - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - } - - @Test - public void testMutableMetaFilesAreNotCached() { - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext("meta,read,write", "*")); - - assertThat(fileIO.shouldCache(META_PATH)).isTrue(); - assertThat(fileIO.shouldCache(new Path(TABLE_ROOT + "/snapshot/EARLIEST"))).isFalse(); - assertThat(fileIO.shouldCache(new Path(TABLE_ROOT + "/snapshot/LATEST"))).isFalse(); - } - - @Test - public void testConfigureResetsCacheWhitelistAndPolicy() { - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(createCatalogContext("read", "data", "bucket-0")); - - verifyCacheFlags(fileIO, false, true, false); - assertThat(fileIO.shouldCache(DATA_PATH)).isTrue(); - assertThat(fileIO.shouldCache(META_PATH)).isFalse(); - - fileIO.configure(createCatalogContext("read", "meta", "*")); - - verifyCacheFlags(fileIO, false, true, false); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - assertThat(fileIO.shouldCache(META_PATH)).isTrue(); - - fileIO.configure(createCatalogContext("none", "data", "bucket-0")); - - verifyCacheFlags(fileIO, false, false, false); - assertThat(fileIO.shouldCache(DATA_PATH)).isFalse(); - } - - @Test - public void testSerialization() throws Exception { - CatalogContext context = createCatalogContext("read", "data", "bucket-0"); - JindoFileIO fileIO = new JindoFileIO(); - fileIO.configure(context); - - JindoFileIO cloned = InstantiationUtil.clone(fileIO); - - assertThat(cloned.shouldCache(DATA_PATH)).isTrue(); - assertThat(cloned.shouldCache(OTHER_DATA_PATH)).isFalse(); - assertThat(cloned.shouldCache(META_PATH)).isFalse(); - assertThat(cloned.hadoopOptions(DATA_PATH, "read").get("fs.oss.endpoint")) - .isEqualTo("test-dlf-cache-endpoint"); - assertThat(cloned.hadoopOptions(META_PATH, "read").get("fs.oss.endpoint")) - .isEqualTo("test-oss-endpoint"); - } -} diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java new file mode 100644 index 000000000000..19a3da7bd533 --- /dev/null +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoCacheEnable.java @@ -0,0 +1,180 @@ +/* + * 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.Path; +import org.apache.paimon.options.Options; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Field; + +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; +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; + +/** Test for Jindo cache enable configuration. */ +public class TestJindoCacheEnable { + + private static final String JINDO_CACHE_RPC_ADDRESS = "fs.jindocache.namespace.rpc.address"; + + private CatalogContext createCatalogContext( + boolean cacheEnabled, + String cachePolicy, + boolean setRpcAddress, + String cacheWhitelist) { + Options options = new Options(); + options.set(IO_CACHE_ENABLED, cacheEnabled); + if (cachePolicy != null) { + options.set(IO_CACHE_POLICY, cachePolicy); + } + if (setRpcAddress) { + options.set(JINDO_CACHE_RPC_ADDRESS, "test-rpc-address:8080"); + } + if (cacheWhitelist != null) { + options.set(IO_CACHE_WHITELIST_PATH, cacheWhitelist); + } + return CatalogContext.create(options); + } + + private boolean getCacheFlag(HadoopCompliantFileIO fileIO, String fieldName) { + try { + Field field = HadoopCompliantFileIO.class.getDeclaredField(fieldName); + field.setAccessible(true); + return field.getBoolean(fileIO); + } catch (NoSuchFieldException | IllegalAccessException e) { + throw new RuntimeException("Failed to access field: " + fieldName, e); + } + } + + private void verifyCacheFlags( + HadoopCompliantFileIO fileIO, + boolean expectedMeta, + boolean expectedRead, + boolean expectedWrite) { + assertThat(getCacheFlag(fileIO, "metaCacheEnabled")).isEqualTo(expectedMeta); + assertThat(getCacheFlag(fileIO, "readCacheEnabled")).isEqualTo(expectedRead); + assertThat(getCacheFlag(fileIO, "writeCacheEnabled")).isEqualTo(expectedWrite); + } + + @Test + public void testCacheEnabledWithMetaPolicy() { + CatalogContext context = createCatalogContext(true, "meta", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, true, false, false); + } + + @Test + public void testCacheEnabledWithReadPolicy() { + CatalogContext context = createCatalogContext(true, "read", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, true, false); + } + + @Test + public void testCacheEnabledWithWritePolicy() { + CatalogContext context = createCatalogContext(true, "write", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, true); + } + + @Test + public void testCacheEnabledWithCombinedPolicy() { + CatalogContext context = createCatalogContext(true, "meta,read,write", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, true, true, true); + } + + @Test + public void testCacheDisabledWhenEnabledFalse() { + CatalogContext context = createCatalogContext(false, "meta,read,write", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + } + + @Test + public void testCacheDisabledWhenPolicyNone() { + CatalogContext context = createCatalogContext(true, "none", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + } + + @Test + public void testCacheDisabledWhenRpcAddressMissing() { + CatalogContext context = createCatalogContext(true, "meta,read,write", false, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + } + + @Test + public void testCacheDisabledWhenPolicyNull() { + CatalogContext context = createCatalogContext(true, null, true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + + verifyCacheFlags(fileIO, false, false, false); + } + + @Test + public void testCacheWhitelist() { + // default config + CatalogContext context = createCatalogContext(true, "meta,read,write", true, null); + JindoFileIO fileIO = new JindoFileIO(); + fileIO.configure(context); + assertThat( + fileIO.shouldCache( + new Path("oss://test-bucket/database/table/bucket-0/file.orc"))) + .isTrue(); + assertThat( + fileIO.shouldCache( + new Path("oss://test-bucket/database/table/manifest/manifest-111"))) + .isTrue(); + assertThat( + fileIO.shouldCache( + new Path("oss://test-bucket/database/table/snapshot/snapshot-1"))) + .isFalse(); + + // set whitelist config as * + context = createCatalogContext(true, "meta,read,write", true, "*"); + fileIO = new JindoFileIO(); + fileIO.configure(context); + assertThat( + fileIO.shouldCache( + new Path("oss://test-bucket/database/table/snapshot/snapshot-1"))) + .isTrue(); + assertThat(fileIO.shouldCache(new Path("oss://test-bucket/database/table/dir/file"))) + .isTrue(); + } +} diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java index 619d45645c4c..67132a414883 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoDlfAccessTracking.java @@ -36,11 +36,11 @@ public class TestJindoDlfAccessTracking { private Options getHadoopOptions(JindoFileIO fileIO) { try { - Field field = JindoFileIO.class.getDeclaredField("jindoHadoopOptions"); + Field field = JindoFileIO.class.getDeclaredField("hadoopOptions"); field.setAccessible(true); - return ((JindoHadoopOptions) field.get(fileIO)).get(false); + return (Options) field.get(fileIO); } catch (NoSuchFieldException | IllegalAccessException e) { - throw new RuntimeException("Failed to access Jindo Hadoop options", e); + throw new RuntimeException("Failed to access hadoopOptions field", e); } } diff --git a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java index 600def188bb9..99e0e123b3fb 100644 --- a/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java +++ b/paimon-filesystems/paimon-jindo/src/test/java/org/apache/paimon/jindo/TestJindoUserAgent.java @@ -103,9 +103,9 @@ private static Options configure(Options options) { JindoFileIO fileIO = new JindoFileIO(); fileIO.configure(CatalogContext.create(options)); try { - Field field = JindoFileIO.class.getDeclaredField("jindoHadoopOptions"); + Field field = JindoFileIO.class.getDeclaredField("hadoopOptions"); field.setAccessible(true); - return ((JindoHadoopOptions) field.get(fileIO)).get(false); + return (Options) field.get(fileIO); } catch (ReflectiveOperationException e) { throw new RuntimeException(e); } From 8e8e8779d2c85c6ef5863d3e80b66b7cd31dfed1 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Thu, 19 Nov 2026 12:39:25 +0800 Subject: [PATCH 11/21] [cache] Preserve token-based FileIO reuse across tables --- .../apache/paimon/rest/RESTTokenFileIO.java | 39 +------ .../paimon/rest/RESTTokenFileIOTest.java | 100 +++++++++++++++--- 2 files changed, 89 insertions(+), 50 deletions(-) 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 7f2c3e642927..f35b4ae715ec 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 @@ -48,7 +48,6 @@ import java.io.IOException; import java.time.Duration; import java.util.Map; -import java.util.Objects; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -69,7 +68,7 @@ public class RESTTokenFileIO implements FileIO { .defaultValue(false) .withDescription("Whether to support data token provided by the REST server."); - private static final Cache FILE_IO_CACHE = + private static final Cache FILE_IO_CACHE = Caffeine.newBuilder() .maximumSize(1000) .expireAfterAccess(10, TimeUnit.HOURS) @@ -252,14 +251,13 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc + "REST credential lifetime after refresh."); } - FileIOCacheKey cacheKey = new FileIOCacheKey(currentToken, path, catalogContext); - FileIO fileIO = FILE_IO_CACHE.getIfPresent(cacheKey); + FileIO fileIO = FILE_IO_CACHE.getIfPresent(currentToken); if (fileIO != null) { return new FileIOWithToken(fileIO, currentToken); } synchronized (FILE_IO_CACHE) { - fileIO = FILE_IO_CACHE.getIfPresent(cacheKey); + fileIO = FILE_IO_CACHE.getIfPresent(currentToken); if (fileIO != null) { return new FileIOWithToken(fileIO, currentToken); } @@ -274,7 +272,7 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc catalogContext.preferIO(), catalogContext.fallbackIO()); fileIO = CachePolicyFileIO.create(path, context); - FILE_IO_CACHE.put(cacheKey, fileIO); + FILE_IO_CACHE.put(currentToken, fileIO); return new FileIOWithToken(fileIO, currentToken); } } @@ -308,35 +306,6 @@ private boolean shouldRefresh(long minimumValidityMillis) { < Math.max(TOKEN_EXPIRATION_SAFE_TIME_MILLIS, minimumValidityMillis); } - private static class FileIOCacheKey { - - private final RESTToken token; - private final Path path; - // A token can be shared by tables using different loaders, Hadoop settings or policies. - // Only wrappers built from the same catalog context may share a delegate. - private final CatalogContext context; - - private FileIOCacheKey(RESTToken token, Path path, CatalogContext context) { - this.token = token; - this.path = path; - this.context = context; - } - - @Override - public boolean equals(Object other) { - if (!(other instanceof FileIOCacheKey)) { - return false; - } - FileIOCacheKey that = (FileIOCacheKey) other; - return token.equals(that.token) && path.equals(that.path) && context == that.context; - } - - @Override - public int hashCode() { - return Objects.hash(token, path, System.identityHashCode(context)); - } - } - private static class FileIOWithToken { private final FileIO fileIO; 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 3ab389b15f6f..b56860357ce4 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 @@ -45,6 +45,7 @@ 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_VPC_VALIDATED; +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; @@ -101,27 +102,96 @@ long currentTimeMillis() { } @Test - void testIdenticalTokensDoNotShareDifferentPathsOrCatalogContexts() throws IOException { - Path root = new Path("oss://bucket/table"); + 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); - Identifier identifier = Identifier.create("db", "table"); - when(api.loadTableToken(identifier)) - .thenReturn(new GetTableTokenResponse(Collections.emptyMap(), Long.MAX_VALUE)); + Map tokenOptions = new HashMap<>(); + tokenOptions.put("test.token", UUID.randomUUID().toString()); + tokenOptions.put(IO_CACHE_POLICY.key(), "read"); + tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); + tokenOptions.put(IO_CACHE_ENDPOINT.key(), "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); - when(firstLoader.load(any())).thenAnswer(ignored -> mock(FileIO.class)); - when(secondLoader.load(any())).thenAnswer(ignored -> mock(FileIO.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); - FileIO first = new RESTTokenFileIO(firstContext, api, identifier, root).fileIO(); - assertThat(new RESTTokenFileIO(firstContext, api, identifier, root).fileIO()) - .isSameAs(first); - assertThat(new RESTTokenFileIO(secondContext, api, identifier, root).fileIO()) - .isNotSameAs(first); + 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(IO_CACHE_VPC_VALIDATED.key(), "true"); + tokenOptions.put(IO_CACHE_ENDPOINT.key(), "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(IO_CACHE_ENDPOINT.key(), "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( - new RESTTokenFileIO(firstContext, api, identifier, new Path(root, "other")) - .fileIO()) - .isNotSameAs(first); + ((HadoopOptionsProvider) otherEndpoint) + .hadoopOptions(data, "read") + .get("fs.oss.endpoint")) + .isEqualTo("other-cache"); } @Test From 3d7a8c26529422b2035fb4d0d71af5ffc6d198f2 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Thu, 19 Nov 2026 17:19:11 +0800 Subject: [PATCH 12/21] [cache] Honor server validation and use the standard OSS cache endpoint --- .../paimon/rest/RESTCatalogOptions.java | 13 ----- .../apache/paimon/fs/cache/CachePolicy.java | 7 +-- .../paimon/fs/cache/CachePolicyFileIO.java | 22 +++++--- .../apache/paimon/rest/RESTTokenFileIO.java | 17 ++++--- .../fs/cache/CachePolicyFileIOTest.java | 35 ++++++++----- .../paimon/fs/cache/CachePolicyTest.java | 7 +-- .../paimon/rest/RESTTokenFileIOTest.java | 50 +++++++++++++++++-- .../apache/paimon/rest/RESTCatalogTest.java | 28 +++++++---- .../jindo/CachePolicyJindoFileIOTest.java | 6 +-- .../catalog/rest/rest_token_file_io.py | 13 +++-- .../pypaimon/common/options/config.py | 15 ------ .../filesystem/cache_policy_file_io.py | 17 +++---- .../tests/cache_policy_file_io_test.py | 19 +++++-- .../tests/rest/rest_token_file_io_test.py | 48 ++++++++++++------ 14 files changed, 174 insertions(+), 123 deletions(-) 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 f73d8a6ae11c..1cdbd71ab5fb 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 @@ -129,13 +129,6 @@ public class RESTCatalogOptions { "Deprecated: enables only the legacy JindoCache integration in JindoFileIO. " + "This option does not control REST cache endpoint routing."); - public static final ConfigOption IO_CACHE_IGNORE_VPC_VALIDATE = - ConfigOptions.key("io-cache.ignore-vpc-validate") - .booleanType() - .defaultValue(false) - .withDescription( - "Whether to use the cache endpoint even when the REST server cannot validate VPC connectivity."); - public static final ConfigOption IO_CACHE_VPC_VALIDATED = ConfigOptions.key("io-cache.vpc-validated") .booleanType() @@ -143,12 +136,6 @@ public class RESTCatalogOptions { .withDescription( "Whether the REST server has validated connectivity from the source VPC to the cache endpoint."); - public static final ConfigOption IO_CACHE_ENDPOINT = - ConfigOptions.key("io-cache.endpoint") - .stringType() - .noDefaultValue() - .withDescription("The cache endpoint vended by the REST server."); - public static final ConfigOption IO_CACHE_ORIGIN_ENDPOINT = ConfigOptions.key("io-cache.origin.endpoint") .stringType() 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 index fc000442d894..8a3807bcd718 100644 --- 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 @@ -27,7 +27,6 @@ import java.util.List; import java.util.Set; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; @@ -48,11 +47,7 @@ public final class CachePolicy implements Serializable { public CachePolicy(Options options) { String policy = options.get(IO_CACHE_POLICY); - enabled = - policy != null - && !policy.contains("none") - && (options.get(IO_CACHE_VPC_VALIDATED) - || options.get(IO_CACHE_IGNORE_VPC_VALIDATE)); + enabled = policy != null && !policy.contains("none") && options.get(IO_CACHE_VPC_VALIDATED); metaEnabled = enabled && policy.contains("meta"); readEnabled = enabled && policy.contains("read"); writeEnabled = enabled && policy.contains("write"); 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 index 529998191c0f..edc4bb1c5bf0 100644 --- 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 @@ -30,7 +30,6 @@ import org.apache.paimon.fs.SeekableInputStream; import org.apache.paimon.fs.StorageType; import org.apache.paimon.fs.TwoPhaseOutputStream; -import org.apache.paimon.options.ConfigOption; import org.apache.paimon.options.Options; import org.apache.paimon.utils.FileType; import org.apache.paimon.utils.StringUtils; @@ -47,12 +46,16 @@ import java.util.Optional; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENABLED; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; 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. */ +/** + * 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; @@ -84,20 +87,23 @@ private CachePolicyFileIO( /** 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, IO_CACHE_ORIGIN_ENDPOINT); + CatalogContext originContext = + withEndpoint(context, context.options().get(IO_CACHE_ORIGIN_ENDPOINT)); FileIO origin = FileIO.get(path, originContext); if (!policy.enabled()) { return origin; } return new CachePolicyFileIO( - path, policy, origin, originContext, withEndpoint(context, IO_CACHE_ENDPOINT)); + path, + policy, + origin, + originContext, + withEndpoint(context, context.options().get("fs.oss.endpoint"))); } - private static CatalogContext withEndpoint( - CatalogContext context, ConfigOption endpointOption) { + private static CatalogContext withEndpoint(CatalogContext context, String endpoint) { Options options = new Options(context.options().toMap()); Configuration hadoopConf = new Configuration(context.hadoopConf()); - String endpoint = options.get(endpointOption); if (!StringUtils.isNullOrWhitespaceOnly(endpoint)) { options.set("fs.oss.endpoint", endpoint); hadoopConf.set("fs.oss.endpoint", endpoint); 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 f35b4ae715ec..a8582a2154be 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 @@ -54,7 +54,7 @@ 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_IGNORE_VPC_VALIDATE; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.apache.paimon.utils.Preconditions.checkArgument; /** A {@link FileIO} to support getting token from REST Server. */ @@ -264,6 +264,10 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc Options options = catalogContext.options(); options = new Options(RESTUtil.merge(options.toMap(), currentToken.token())); + // Connectivity validation can only come from the REST server. + options.set( + IO_CACHE_VPC_VALIDATED, + Boolean.parseBoolean(currentToken.token().get(IO_CACHE_VPC_VALIDATED.key()))); options.set(FILE_IO_ALLOW_CACHE, false); CatalogContext context = CatalogContext.create( @@ -345,16 +349,13 @@ 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. + // Preserve the server endpoint; use the client endpoint only when the server omits it. String dlfOssEndpoint = catalogOptions.get(DLF_OSS_ENDPOINT.key()); - if (dlfOssEndpoint != null && !dlfOssEndpoint.isEmpty()) { + if (!newToken.containsKey("fs.oss.endpoint") + && dlfOssEndpoint != null + && !dlfOssEndpoint.isEmpty()) { newToken.put("fs.oss.endpoint", dlfOssEndpoint); } - if (catalogOptions.contains(IO_CACHE_IGNORE_VPC_VALIDATE)) { - newToken.put( - IO_CACHE_IGNORE_VPC_VALIDATE.key(), - String.valueOf(catalogOptions.get(IO_CACHE_IGNORE_VPC_VALIDATE))); - } return ImmutableMap.copyOf(newToken); } 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 index 60128c9965d3..8a10fed7293e 100644 --- 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 @@ -51,7 +51,6 @@ 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_ENDPOINT; 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_VPC_VALIDATED; @@ -142,9 +141,9 @@ void testDisabledPolicyStillAppliesOriginEndpoint() throws Exception { .hadoopOptions(DATA, "read") .get("fs.oss.endpoint")) .isEqualTo("origin"); - assertThat(options.get("fs.oss.endpoint")).isEqualTo("configured"); + assertThat(options.get("fs.oss.endpoint")).isEqualTo("cache"); assertThat(loader.delegate("origin").options.keySet()) - .doesNotContain(IO_CACHE_ENDPOINT.key(), IO_CACHE_ORIGIN_ENDPOINT.key()); + .doesNotContain(IO_CACHE_ORIGIN_ENDPOINT.key()); } } } @@ -193,16 +192,29 @@ void testNativeOptionsUseTheSamePolicyWithResolvingFileIO() throws Exception { } @Test - void testMissingEndpointRetainsConfiguredEndpoint() throws Exception { + void testMissingOriginEndpointRetainsCacheEndpoint() throws Exception { Options options = options(); - options.set(IO_CACHE_ENDPOINT, " "); options.remove(IO_CACHE_ORIGIN_ENDPOINT); try (FileIO fileIO = create(options, new RecordingLoader())) { - assertThat( - ((HadoopOptionsProvider) fileIO) - .hadoopOptions(DATA, "read") - .get("fs.oss.endpoint")) - .isEqualTo("configured"); + 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"); } } @@ -307,8 +319,7 @@ private static Options options() { options.set(IO_CACHE_POLICY, "meta,read,write"); options.set(IO_CACHE_VPC_VALIDATED, true); options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); - options.set(IO_CACHE_ENDPOINT, "cache"); - options.set("fs.oss.endpoint", "configured"); + options.set("fs.oss.endpoint", "cache"); options.set("fs.oss.securityToken", "test-token"); return options; } 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 index 3e61bb601ffa..c129ee9badf3 100644 --- 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 @@ -24,7 +24,6 @@ import org.junit.jupiter.api.Test; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; @@ -57,7 +56,6 @@ void testOperationTagsAndCombinations() { void testDisabledPolicies() { for (String tags : new String[] {null, "none", "none,read"}) { Options options = options(tags); - options.set(IO_CACHE_IGNORE_VPC_VALIDATE, true); CachePolicy policy = new CachePolicy(options); assertThat(policy.enabled()).isFalse(); assertThat(policy.shouldCache(DATA, "read")).isFalse(); @@ -65,15 +63,12 @@ void testDisabledPolicies() { } @Test - void testVpcValidationAndOverride() { + void testServerVpcValidationIsRequired() { Options options = options("read"); options.remove(IO_CACHE_VPC_VALIDATED); assertThat(new CachePolicy(options).enabled()).isFalse(); options.set(IO_CACHE_VPC_VALIDATED, false); assertThat(new CachePolicy(options).enabled()).isFalse(); - options.set(IO_CACHE_IGNORE_VPC_VALIDATE, true); - assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isTrue(); - options.set(IO_CACHE_IGNORE_VPC_VALIDATE, false); options.set(IO_CACHE_VPC_VALIDATED, true); assertThat(new CachePolicy(options).shouldCache(DATA, "read")).isTrue(); } 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 b56860357ce4..6b3829b09d65 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 @@ -32,6 +32,7 @@ import org.apache.paimon.rest.responses.GetTableTokenResponse; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import java.io.IOException; import java.time.Duration; @@ -41,7 +42,7 @@ import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_ENDPOINT; +import static org.apache.paimon.rest.RESTCatalogOptions.DLF_OSS_ENDPOINT; 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_VPC_VALIDATED; @@ -58,6 +59,45 @@ /** Tests for {@link RESTTokenFileIO}. */ class RESTTokenFileIOTest { + @Test + void testServerCacheSettingsCannotBeOverriddenByCatalogOptions() throws IOException { + for (String validation : new String[] {null, "false"}) { + Options options = new Options(); + options.set(IO_CACHE_VPC_VALIDATED, true); + options.set("io-cache.ignore-vpc-validate", "true"); + options.set("fs.oss.endpoint", "client-endpoint"); + options.set(DLF_OSS_ENDPOINT, "client-dlf-endpoint"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "client-origin"); + Map tokenOptions = new HashMap<>(); + tokenOptions.put("test.token", UUID.randomUUID().toString()); + tokenOptions.put(IO_CACHE_POLICY.key(), "read"); + tokenOptions.put("fs.oss.endpoint", "server-cache"); + tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "server-origin"); + if (validation != null) { + tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), validation); + } + 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)); + RESTTokenFileIO rest = + new RESTTokenFileIO( + CatalogContext.create(options, loader, null), + api, + identifier, + new Path("oss://bucket/table")); + FileIO delegate = rest.fileIO(); + assertThat(delegate).isNotInstanceOf(CachePolicyFileIO.class); + ArgumentCaptor context = ArgumentCaptor.forClass(CatalogContext.class); + verify(delegate).configure(context.capture()); + assertThat(context.getValue().options().get("fs.oss.endpoint")) + .isEqualTo("server-origin"); + assertThat(rest.validToken().token().get("fs.oss.endpoint")).isEqualTo("server-cache"); + } + } + @Test void testTokenRefreshRebuildsPolicyWrapper() throws IOException { Path root = new Path("oss://bucket/table"); @@ -69,7 +109,7 @@ void testTokenRefreshRebuildsPolicyWrapper() throws IOException { Map tokenOptions = new HashMap<>(); tokenOptions.put(IO_CACHE_POLICY.key(), "read"); tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); - tokenOptions.put(IO_CACHE_ENDPOINT.key(), "cache"); + 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"); @@ -112,7 +152,7 @@ void testIdenticalTokensSharePolicyWrapperAcrossTablesAndContexts() throws IOExc tokenOptions.put("test.token", UUID.randomUUID().toString()); tokenOptions.put(IO_CACHE_POLICY.key(), "read"); tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); - tokenOptions.put(IO_CACHE_ENDPOINT.key(), "cache"); + 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())) @@ -160,12 +200,12 @@ void testIdenticalCredentialsWithDifferentCacheOptionsDoNotShareFileIO() throws tokenOptions.put("fs.oss.securityToken", UUID.randomUUID().toString()); tokenOptions.put(IO_CACHE_POLICY.key(), "read"); tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); - tokenOptions.put(IO_CACHE_ENDPOINT.key(), "cache"); + 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(IO_CACHE_ENDPOINT.key(), "other-cache"); + otherEndpointOptions.put("fs.oss.endpoint", "other-cache"); RESTApi api = mock(RESTApi.class); Identifier identifier = Identifier.create("db", "table"); when(api.loadTableToken(identifier)) 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 a542a48476ef..b16c4f320b9c 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,7 @@ 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_IGNORE_VPC_VALIDATE; +import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; 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 +2172,34 @@ void testValidToken() throws Exception { } @Test - void testValidTokenWithIOCacheIgnoreVpcValidate() throws Exception { + void testValidTokenPreservesServerCacheSettings() throws Exception { Map options = new HashMap<>(); - options.put(IO_CACHE_IGNORE_VPC_VALIDATE.key(), "true"); + options.put(IO_CACHE_VPC_VALIDATED.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_ignore_vpc_validate"); - 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_VPC_VALIDATED.key(), + "false", + "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(); - assertEquals("true", fileDataToken.token().get(IO_CACHE_IGNORE_VPC_VALIDATE.key())); + assertEquals("false", fileDataToken.token().get(IO_CACHE_VPC_VALIDATED.key())); + 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 index 2217c397e6f8..e2fd71be916b 100644 --- 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 @@ -31,7 +31,6 @@ 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_ENDPOINT; 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_VPC_VALIDATED; @@ -115,7 +114,7 @@ options, hadoopConf, new TestingJindoLoader(), null))) { .isEqualTo("hadoop-token"); } assertThat(hadoopConf.get("fs.oss.endpoint")).isEqualTo("hadoop-configured"); - assertThat(options.get("fs.oss.endpoint")).isEqualTo("configured"); + assertThat(options.get("fs.oss.endpoint")).isEqualTo("cache"); } } @@ -149,9 +148,8 @@ private static Options options() { Options options = new Options(); options.set(IO_CACHE_POLICY, "read"); options.set(IO_CACHE_VPC_VALIDATED, true); - options.set(IO_CACHE_ENDPOINT, "cache"); options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); - options.set("fs.oss.endpoint", "configured"); + 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"); 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 3796eef9afde..c8b3d14582e1 100644 --- a/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py +++ b/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py @@ -205,23 +205,22 @@ def _merged_options(self, token: RESTToken) -> Options: self.catalog_options.to_map() if self.catalog_options else {}, token.token ) - if self.catalog_options: + # Connectivity validation can only come from the REST server. + merged_properties[CatalogOptions.IO_CACHE_VPC_VALIDATED.key()] = token.token.get( + CatalogOptions.IO_CACHE_VPC_VALIDATED.key(), False) + if self.catalog_options and OssOptions.OSS_ENDPOINT.key() not in token.token: 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.""" + """Keep the server endpoint, falling back to the client endpoint when absent.""" merged_token = dict(token) - if self.catalog_options: + if self.catalog_options and OssOptions.OSS_ENDPOINT.key() not in merged_token: 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 - if self.catalog_options.contains(CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE): - merged_token[CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key()] = str( - self.catalog_options.get( - CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE)).lower() return merged_token def new_input_stream(self, path: str): diff --git a/paimon-python/pypaimon/common/options/config.py b/paimon-python/pypaimon/common/options/config.py index 573007581234..c9083a2cb3bd 100644 --- a/paimon-python/pypaimon/common/options/config.py +++ b/paimon-python/pypaimon/common/options/config.py @@ -149,15 +149,6 @@ 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_IGNORE_VPC_VALIDATE = ( - ConfigOptions.key("io-cache.ignore-vpc-validate") - .boolean_type() - .default_value(False) - .with_description( - "Whether to use the cache endpoint even when the REST server cannot " - "validate VPC connectivity." - ) - ) IO_CACHE_VPC_VALIDATED = ( ConfigOptions.key("io-cache.vpc-validated") .boolean_type() @@ -167,12 +158,6 @@ class CatalogOptions: "VPC to the cache endpoint." ) ) - IO_CACHE_ENDPOINT = ( - ConfigOptions.key("io-cache.endpoint") - .string_type() - .no_default_value() - .with_description("The cache endpoint vended by the REST server.") - ) IO_CACHE_ORIGIN_ENDPOINT = ( ConfigOptions.key("io-cache.origin.endpoint") .string_type() diff --git a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py index e082cb4cb876..536a6374a400 100644 --- a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -37,6 +37,8 @@ class CachePolicyFileIO(FileIO): 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" @@ -50,14 +52,12 @@ def create(cls, path: str, catalog_options: Options, file_io_factory=None) -> Fi if file_io_factory is None: file_io_factory = FileIO.get - origin_options = cls._options_with_endpoint( - catalog_options, CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT) + origin_options = cls._origin_options(catalog_options) origin_file_io = file_io_factory(path, origin_options) if not cls._cache_enabled(catalog_options): return origin_file_io - cache_options = cls._options_with_endpoint( - catalog_options, CatalogOptions.IO_CACHE_ENDPOINT) + cache_options = catalog_options.copy() return cls( path, catalog_options, @@ -67,9 +67,9 @@ def create(cls, path: str, catalog_options: Options, file_io_factory=None) -> Fi ) @staticmethod - def _options_with_endpoint(options: Options, endpoint_option) -> Options: + def _origin_options(options: Options) -> Options: result = options.copy() - endpoint = options.get(endpoint_option) + endpoint = options.get(CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT) if endpoint is not None and endpoint.strip(): result.set(OssOptions.OSS_ENDPOINT, endpoint) return result @@ -80,10 +80,7 @@ def _cache_enabled(cls, options: Options) -> bool: return ( policy is not None and cls.DISABLE_CACHE_TAG not in policy - and ( - options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED) - or options.get(CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE) - ) + and options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED) ) def __init__( diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index 7bb59ce94a29..e19aec26db12 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -181,11 +181,10 @@ def _options(**overrides): values = { CatalogOptions.IO_CACHE_POLICY.key(): "meta,read,write", CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): True, - CatalogOptions.IO_CACHE_ENDPOINT.key(): "cache-endpoint", CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "origin-endpoint", CatalogOptions.IO_CACHE_WHITELIST.key(): "*", CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "*", - OssOptions.OSS_ENDPOINT.key(): "token-endpoint", + OssOptions.OSS_ENDPOINT.key(): "cache-endpoint", OssOptions.OSS_IMPL.key(): "jindo", } values.update(overrides) @@ -194,6 +193,18 @@ def _options(**overrides): class CachePolicyFileIOTest(unittest.TestCase): + 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): @@ -415,11 +426,11 @@ def test_vpc_validation_and_none_policy_disable_wrapper(self): TABLE_ROOT, _options(**{ CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): False, - CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key(): True, + "io-cache.ignore-vpc-validate": True, }), factory, ) - self.assertIsInstance(file_io, CachePolicyFileIO) + self.assertNotIsInstance(file_io, CachePolicyFileIO) factory = _RecordingFactory() file_io = CachePolicyFileIO.create( 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 e3a999fe6220..a4e79305c27c 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 @@ -667,8 +667,8 @@ 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_server_endpoint_takes_precedence_over_dlf_endpoint(self): + """Use the DLF endpoint only when the server omits the standard endpoint.""" dlf_oss_endpoint = "https://dlf-custom-endpoint.oss-cn-hangzhou.aliyuncs.com" catalog_options = { CatalogOptions.DLF_OSS_ENDPOINT.key(): dlf_oss_endpoint @@ -691,11 +691,14 @@ 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 + # Preserve the server endpoint even when a client DLF endpoint is configured. self.assertEqual( merged_token[OssOptions.OSS_ENDPOINT.key()], - dlf_oss_endpoint, - "DLF OSS endpoint should override the standard OSS endpoint in token" + token[OssOptions.OSS_ENDPOINT.key()], + ) + self.assertEqual( + token[OssOptions.OSS_ENDPOINT.key()], + file_io._merged_options(RESTToken(merged_token, 0)).get(OssOptions.OSS_ENDPOINT), ) # Verify other token properties are preserved self.assertEqual( @@ -703,27 +706,40 @@ 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_ignore_vpc_validation_is_merged_into_token(self): + def test_server_cache_settings_take_precedence(self): catalog_options = Options({ - CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key(): True, + CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): True, + OssOptions.OSS_ENDPOINT.key(): "client-endpoint", + CatalogOptions.DLF_OSS_ENDPOINT.key(): "client-dlf-endpoint", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "client-origin", }) file_io = RESTTokenFileIO( self.identifier, self.warehouse_path, catalog_options) - - merged_token = file_io._merge_token_with_catalog_options({ - CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key(): "false", - }) - + server_options = { + CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): "false", + OssOptions.OSS_ENDPOINT.key(): "server-cache", + CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "server-origin", + } + merged_token = file_io._merge_token_with_catalog_options(server_options) + self.assertEqual(server_options, merged_token) + options = file_io._merged_options(RESTToken(merged_token, 0)) + self.assertFalse(options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED)) + self.assertEqual("server-cache", options.get(OssOptions.OSS_ENDPOINT)) self.assertEqual( - "true", - merged_token[CatalogOptions.IO_CACHE_IGNORE_VPC_VALIDATE.key()], - ) + "server-origin", options.get(CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT)) + server_options.pop(CatalogOptions.IO_CACHE_VPC_VALIDATED.key()) + options = file_io._merged_options(RESTToken(server_options, 0)) + self.assertFalse(options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED)) def test_token_file_io_uses_cache_policy_factory(self): file_io = RESTTokenFileIO( @@ -735,7 +751,7 @@ def test_token_file_io_uses_cache_policy_factory(self): { CatalogOptions.IO_CACHE_POLICY.key(): "read", CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): "true", - CatalogOptions.IO_CACHE_ENDPOINT.key(): "cache-endpoint", + OssOptions.OSS_ENDPOINT.key(): "cache-endpoint", }, int(time.time() * 1000) + 7_200_000, ) From 82cfca9f58606452069d4eb38b77a9aade0e2692 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Thu, 19 Nov 2026 17:30:04 +0800 Subject: [PATCH 13/21] [cache] Remove VPC validation and document cache policy --- doc/cache-policy.md | 197 ++++++++++++++++++ .../paimon/rest/RESTCatalogOptions.java | 7 - .../apache/paimon/fs/cache/CachePolicy.java | 3 +- .../apache/paimon/rest/RESTTokenFileIO.java | 5 - .../fs/BaseMultiPartUploadCommitterTest.java | 2 - .../fs/cache/CachePolicyFileIOTest.java | 11 +- .../paimon/fs/cache/CachePolicyTest.java | 12 +- .../paimon/rest/RESTTokenFileIOTest.java | 72 +++---- .../apache/paimon/rest/RESTCatalogTest.java | 8 +- .../jindo/CachePolicyJindoFileIOTest.java | 2 - .../catalog/rest/rest_token_file_io.py | 3 - .../pypaimon/common/options/config.py | 9 - .../filesystem/cache_policy_file_io.py | 1 - .../tests/cache_policy_file_io_test.py | 53 ++--- .../tests/rest/rest_token_file_io_test.py | 9 +- 15 files changed, 262 insertions(+), 132 deletions(-) create mode 100644 doc/cache-policy.md diff --git a/doc/cache-policy.md b/doc/cache-policy.md new file mode 100644 index 000000000000..fb9db0d7964d --- /dev/null +++ b/doc/cache-policy.md @@ -0,0 +1,197 @@ + + +# Cache Policy 参数与路由说明 + +Cache policy 控制 Paimon 文件操作访问缓存端点还是 origin 端点。Java 和 PyPaimon +在通用 `CachePolicyFileIO` 包装层中执行相同的路由规则,底层 FileIO 负责实际读写。 +它独立于客户端本地 block cache,也不改变表本身的存储和读取语义。 + +REST Catalog 通过 table token 下发凭证、端点和 `io-cache.*` 策略。 +`RESTTokenFileIO` 合并配置并创建包装层;策略刷新随 token 刷新生效。 +也可以显式调用 `CachePolicyFileIO.create`,传入相同的配置。 +普通 `FileIO.get` 调用不会自动装配远端 cache policy。 + +## 有效参数 + +下表中的默认值指新的 cache policy 层,Java 与 PyPaimon 一致。 + +| 参数 | 类型 | 默认值 | 含义 | +| --- | --- | --- | --- | +| `fs.oss.endpoint` | 字符串 | 无,由下发配置或底层 FileIO 配置提供 | 缓存操作使用的端点。包装层始终保留这个值作为 cache endpoint。 | +| `io-cache.origin.endpoint` | 字符串 | 未设置时保留 `fs.oss.endpoint` | 不走缓存的操作使用的 origin endpoint。非空时,仅覆盖 origin delegate 的 `fs.oss.endpoint`。 | +| `io-cache.policy` | 字符串 | 未设置,没有缓存操作 | 启用哪些操作类型,可组合 `meta`、`read`、`write`;`none` 关闭全部缓存操作。 | +| `io-cache.whitelist` | 字符串 | `*` | 允许缓存的文件类型,多个类型用逗号分隔。 | +| `io-cache.whitelist-path` | 字符串 | `*` | 允许缓存的 URI path 子串,多个子串用逗号分隔。类型与路径白名单必须同时命中。 | + +协议不再包含 VPC validate 步骤。`io-cache.vpc-validated` 和 +`io-cache.ignore-vpc-validate` 均已移除,不参与策略判断。 +也没有独立的 `io-cache.endpoint` 参数;缓存端点统一使用 `fs.oss.endpoint`。 +新的 policy 层不需要 `io-cache.enabled` 客户端开关。 + +### 端点规则 + +cache 与 origin 使用原始文件路径和相同的对象存储命名空间,仅访问端点不同。 +两个端点使用下发的同一组凭证。 + +- 命中缓存策略:使用 `fs.oss.endpoint`。 +- 未命中、可变文件或固定走 origin 的操作:使用 `io-cache.origin.endpoint`。 +- 没有策略或策略为 `none`:直接返回 origin FileIO,origin 配置仍生效。 +- origin 参数缺失、为空或仅含空白:保留原来的 `fs.oss.endpoint`,不自动推导真实 OSS 端点。 + 需要绕过缓存访问真实 OSS 时,服务端应明确下发 origin 参数。 + +REST token 中已有的 `fs.oss.endpoint` 优先于客户端端点设置。 +客户端 `dlf.oss-endpoint` 仅在服务端未提供 `fs.oss.endpoint` 时作为兼容回退。 +Java 同时把选定端点写入 delegate 的 options 和复制后的 Hadoop configuration, +保证 Hadoop 配置回退与原生 reader 取得相同的端点;不会修改原始配置对象。 + +### policy 标签 + +| 标签 | 控制的操作 | 示例 | +| --- | --- | --- | +| `read` | 文件内容读取 | `newInputStream`、Python `new_input_stream`、Arrow 文件读取 | +| `write` | 普通文件内容写入 | `newOutputStream`、Python 普通格式写入、Arrow 文件写入 | +| `meta` | 文件属性查询 | `getFileStatus`、`exists`、`getFileSize`、`isDir`;Python 对应接口及批量属性查询 | +| `none` | 关闭全部缓存操作,优先于其他标签 | `none,read` 仍全部走 origin | + +例如,`read` 只允许读取内容走缓存;`meta,read` 允许属性查询和内容读取; +`meta,read,write` 允许三类操作。即使标签已开启,仍需满足文件类型、路径和不可变性条件。 + +`meta` 标签表示**操作类型**,不等同于文件类型白名单中的 `meta`。 +例如 `io-cache.policy=meta` 且 `io-cache.whitelist=data` 时, +数据文件的属性查询可以走缓存,但数据内容读取仍走 origin。 + +参数使用小写标签和逗号分隔的规范写法。当前实现沿用标签子串包含判断, +并未引入新的策略表达式或大小写转换。未设置策略或策略为空时,所有操作都走 origin。 + +## 文件类型与路径白名单 + +| 文件类型值 | 覆盖范围与示例 | +| --- | --- | +| `meta` | snapshot、schema、manifest、manifest list、manifest sidecar、statistics 等元数据文件。可变元数据仍会被不可变性规则排除。 | +| `global-index` | 表级全局索引,例如 `btree-global-index-.index`。 | +| `bucket-index` | bucket 级索引,例如 `index--0`。 | +| `file-index` | 数据文件附属索引,例如 `data--0.orc.index`。 | +| `data` | 数据文件,以及未匹配其他分类规则的文件。PyPaimon 同时包含其 `STRUCTURED_DATA` 分类。 | +| `*` | 所有文件类型,仍受不可变性和路径白名单约束。 | + +PyPaimon 另支持 `structured-data`,只匹配其 Parquet、ORC、Avro、ROW、Mosaic +结构化数据分类。Java 没有单独的该分类;需要跨 Java/Python 使用相同配置时采用 `data`。 + +白名单规则如下: + +- 同一白名单内部为 OR,不同白名单之间为 AND。 + `io-cache.whitelist=data,file-index` 表示两类文件都允许; + 它们还必须命中 `io-cache.whitelist-path` 才能走缓存。 +- 路径匹配的是 URI 的 path 部分,不匹配 scheme、bucket authority、query 或 fragment。 + 例如 `oss://bucket/db/table/bucket-0/data.orc` 使用 `/db/table/bucket-0/data.orc` 匹配。 +- 路径采用区分大小写的子串匹配,不是 glob 或正则;`bucket-0,bucket-1` 表示任一子串命中。 + 单独的 `*` 才表示所有路径,`bucket-*` 是普通字面子串。 +- 文件类型和路径条目会去掉两侧空白;显式空串或只有逗号、空白时,没有匹配项。 + 未知文件类型会被忽略并记录告警。例如 `manifest` 不是类型值,应使用 `meta`。 + +新 policy 层在未显式设置路径白名单时默认允许全部路径。 +Java 的共享配置常量仍保留旧 JindoCache 的 `bucket,manifest,index` 默认值, +新的 `CachePolicy` 解析逻辑会区分“未设置”与“显式设置”,按本节的 `*` 默认值执行。 + +## 路由条件与固定回退 + +一次操作只有同时满足以下条件才会访问缓存端点: + +```text +policy 未包含 none +AND 当前操作的 meta/read/write 标签已开启 +AND 文件不是可变文件 +AND 命中文件类型白名单 +AND 命中 URI path 白名单 +``` + +可变文件始终绕过缓存,即使两个白名单都是 `*`。当前规则包含 `LATEST`、`EARLIEST`、 +`_SUCCESS` 及以 `_SUCCESS` 结尾的文件、`consumer-*`、`service-*`、`tag-*`、 +Paimon 生成的临时文件,以及会被覆盖的 Iceberg 兼容元数据:`version-hint.text`、 +`retire-pending`、`*.metadata.json`。 + +以下操作始终使用 origin,以保留目录、命名空间和提交语义: + +| 操作 | 行为 | +| --- | --- | +| 目录列表、递归列表 | 走 origin,目录可能同时包含多种文件类型。 | +| `delete`、`rename`、`mkdirs` | 走 origin。 | +| 原子写 `tryToWriteAtomic` 及 Python 对应接口 | 直接转发 origin 的实现。 | +| Java `newTwoPhaseOutputStream`、multipart 提交和清理 | 走 origin,上传与提交使用同一类端点;提交时沿现有 REST token 链路取得有效凭证。 | +| Blob presign、Java archive/restore/unarchive | 走 origin,保留底层签名和存储管理能力。 | + +cache delegate 在第一次命中缓存操作时惰性创建。缓存端点访问失败时,错误直接上抛, +客户端不会自动重试到 origin;这里的“回退”表示策略路由,不是失败重试。 +Java `HadoopOptionsProvider` 与 Python Arrow filesystem adapter 使用同一套路径和操作规则。 + +## 服务端下发示例 + +只缓存指定表的两个 bucket 中的数据和文件索引读取,其余操作使用 origin: + +```json +{ + "fs.oss.endpoint": "cache.example.internal", + "io-cache.origin.endpoint": "oss-cn-hangzhou-internal.aliyuncs.com", + "io-cache.policy": "read", + "io-cache.whitelist": "data,file-index", + "io-cache.whitelist-path": "/db/table/bucket-0/,/db/table/bucket-1/" +} +``` + +以 `oss://bucket/db/table` 为表路径,上述配置的结果如下: + +| 操作和路径 | 访问端点 | 原因 | +| --- | --- | --- | +| 读取 `bucket-0/data--0.orc` | cache | `read`、类型和路径均命中。 | +| 读取 `bucket-1/data--0.orc.index` | cache | `file-index` 和路径命中。 | +| 读取 `bucket-2/data--0.orc` | origin | 路径未命中。 | +| 读取 `manifest/manifest--0` | origin | `meta` 文件类型未被允许。 | +| 读取 `snapshot/LATEST` | origin | 可变文件始终绕过。 | +| 查询数据文件大小或是否存在 | origin | 未启用 `meta` 操作标签。 | +| 写入数据文件 | origin | 未启用 `write` 操作标签。 | +| 列目录、删除文件、Java 两阶段上传 | origin | 固定走 origin。 | + +允许所有不可变文件的读取与属性查询时,可以省略两个白名单: + +```json +{ + "fs.oss.endpoint": "cache.example.internal", + "io-cache.origin.endpoint": "oss-cn-hangzhou-internal.aliyuncs.com", + "io-cache.policy": "meta,read" +} +``` + +停用缓存时,服务端将 `io-cache.policy` 下发为 `none` 或不下发该参数, +并提供期望使用的 origin endpoint;不需要额外的客户端关闭开关。 + +## 旧 JindoCache 兼容边界 + +Java `io-cache.enabled` 仍保留为旧 JindoCache 的客户端开关,默认 `false`,已标记废弃。 +旧实现还依赖其 RPC 地址、policy 和路径白名单;其原有实现继续保留。 +该开关只控制旧 JindoCache,不决定新的 endpoint policy 是否生效, +也不增加 VPC 校验要求。使用新的远端 cache policy 无需开启它。 + +相关实现: + +- [Java CachePolicy](../paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java) +- [Java CachePolicyFileIO](../paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java) +- [Java 参数定义](../paimon-api/src/main/java/org/apache/paimon/rest/RESTCatalogOptions.java) +- [PyPaimon CachePolicyFileIO](../paimon-python/pypaimon/filesystem/cache_policy_file_io.py) +- [PyPaimon 参数定义](../paimon-python/pypaimon/common/options/config.py) 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 1cdbd71ab5fb..7b484cf52647 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 @@ -129,13 +129,6 @@ public class RESTCatalogOptions { "Deprecated: enables only the legacy JindoCache integration in JindoFileIO. " + "This option does not control REST cache endpoint routing."); - public static final ConfigOption IO_CACHE_VPC_VALIDATED = - ConfigOptions.key("io-cache.vpc-validated") - .booleanType() - .defaultValue(false) - .withDescription( - "Whether the REST server has validated connectivity from the source VPC to the cache endpoint."); - public static final ConfigOption IO_CACHE_ORIGIN_ENDPOINT = ConfigOptions.key("io-cache.origin.endpoint") .stringType() 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 index 8a3807bcd718..7bcde2d3d74c 100644 --- 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 @@ -28,7 +28,6 @@ import java.util.Set; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; @@ -47,7 +46,7 @@ public final class CachePolicy implements Serializable { public CachePolicy(Options options) { String policy = options.get(IO_CACHE_POLICY); - enabled = policy != null && !policy.contains("none") && options.get(IO_CACHE_VPC_VALIDATED); + enabled = policy != null && !policy.contains("none"); metaEnabled = enabled && policy.contains("meta"); readEnabled = enabled && policy.contains("read"); writeEnabled = enabled && policy.contains("write"); 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 a8582a2154be..c0ab7ebfd667 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 @@ -54,7 +54,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_VPC_VALIDATED; import static org.apache.paimon.utils.Preconditions.checkArgument; /** A {@link FileIO} to support getting token from REST Server. */ @@ -264,10 +263,6 @@ private FileIOWithToken fileIOWithToken(long minimumValidityMillis) throws IOExc Options options = catalogContext.options(); options = new Options(RESTUtil.merge(options.toMap(), currentToken.token())); - // Connectivity validation can only come from the REST server. - options.set( - IO_CACHE_VPC_VALIDATED, - Boolean.parseBoolean(currentToken.token().get(IO_CACHE_VPC_VALIDATED.key()))); options.set(FILE_IO_ALLOW_CACHE, false); CatalogContext context = CatalogContext.create( 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 6f9b2c48ee94..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 @@ -31,7 +31,6 @@ import static org.apache.paimon.options.CatalogOptions.RESOLVING_FILE_IO_ENABLED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_POLICY; -import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_VPC_VALIDATED; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -82,7 +81,6 @@ public void testConcreteFileIOIsPassedThroughUnchanged() throws IOException { public void testCommitAndDiscardResolveRestPolicyAndResolverWrappers() throws IOException { Options options = new Options(); options.set(IO_CACHE_POLICY, "write"); - options.set(IO_CACHE_VPC_VALIDATED, true); options.set(RESOLVING_FILE_IO_ENABLED, true); FileIOLoader loader = mock(FileIOLoader.class); when(loader.load(any())).thenReturn(resolved); 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 index 8a10fed7293e..2d62acc3e5d0 100644 --- 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 @@ -53,7 +53,6 @@ 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_VPC_VALIDATED; 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; @@ -127,11 +126,12 @@ void testOriginOnlyOperationsPreserveDelegateOverrides() throws Exception { @Test void testDisabledPolicyStillAppliesOriginEndpoint() throws Exception { - for (boolean vpcValidated : new boolean[] {true, false}) { + for (String policy : new String[] {null, "none"}) { Options options = options(); - options.set(IO_CACHE_VPC_VALIDATED, vpcValidated); - if (vpcValidated) { - options.set(IO_CACHE_POLICY, "none"); + 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)) { @@ -317,7 +317,6 @@ void testCacheReadFailuresAreNotRetriedOnOrigin() throws Exception { private static Options options() { Options options = new Options(); options.set(IO_CACHE_POLICY, "meta,read,write"); - options.set(IO_CACHE_VPC_VALIDATED, true); options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); options.set("fs.oss.endpoint", "cache"); options.set("fs.oss.securityToken", "test-token"); 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 index c129ee9badf3..2cec9f6289c6 100644 --- 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 @@ -25,7 +25,6 @@ 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_VPC_VALIDATED; 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; @@ -63,13 +62,11 @@ void testDisabledPolicies() { } @Test - void testServerVpcValidationIsRequired() { + void testPolicyDoesNotRequireVpcValidation() { Options options = options("read"); - options.remove(IO_CACHE_VPC_VALIDATED); - assertThat(new CachePolicy(options).enabled()).isFalse(); - options.set(IO_CACHE_VPC_VALIDATED, false); - assertThat(new CachePolicy(options).enabled()).isFalse(); - options.set(IO_CACHE_VPC_VALIDATED, true); + 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(); } @@ -166,7 +163,6 @@ private static Options options(String tags) { if (tags != null) { options.set(IO_CACHE_POLICY, tags); } - options.set(IO_CACHE_VPC_VALIDATED, true); 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 6b3829b09d65..d6d6a6b4b556 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 @@ -32,7 +32,6 @@ import org.apache.paimon.rest.responses.GetTableTokenResponse; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; import java.io.IOException; import java.time.Duration; @@ -45,7 +44,6 @@ import static org.apache.paimon.rest.RESTCatalogOptions.DLF_OSS_ENDPOINT; 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_VPC_VALIDATED; 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; @@ -60,42 +58,37 @@ class RESTTokenFileIOTest { @Test - void testServerCacheSettingsCannotBeOverriddenByCatalogOptions() throws IOException { - for (String validation : new String[] {null, "false"}) { - Options options = new Options(); - options.set(IO_CACHE_VPC_VALIDATED, true); - options.set("io-cache.ignore-vpc-validate", "true"); - options.set("fs.oss.endpoint", "client-endpoint"); - options.set(DLF_OSS_ENDPOINT, "client-dlf-endpoint"); - options.set(IO_CACHE_ORIGIN_ENDPOINT, "client-origin"); - Map tokenOptions = new HashMap<>(); - tokenOptions.put("test.token", UUID.randomUUID().toString()); - tokenOptions.put(IO_CACHE_POLICY.key(), "read"); - tokenOptions.put("fs.oss.endpoint", "server-cache"); - tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "server-origin"); - if (validation != null) { - tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), validation); - } - 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)); - RESTTokenFileIO rest = - new RESTTokenFileIO( - CatalogContext.create(options, loader, null), - api, - identifier, - new Path("oss://bucket/table")); - FileIO delegate = rest.fileIO(); - assertThat(delegate).isNotInstanceOf(CachePolicyFileIO.class); - ArgumentCaptor context = ArgumentCaptor.forClass(CatalogContext.class); - verify(delegate).configure(context.capture()); - assertThat(context.getValue().options().get("fs.oss.endpoint")) - .isEqualTo("server-origin"); - assertThat(rest.validToken().token().get("fs.oss.endpoint")).isEqualTo("server-cache"); - } + void testServerEndpointsCannotBeOverriddenByCatalogOptions() throws IOException { + Options options = new Options(); + options.set("fs.oss.endpoint", "client-endpoint"); + options.set(DLF_OSS_ENDPOINT, "client-dlf-endpoint"); + options.set(IO_CACHE_ORIGIN_ENDPOINT, "client-origin"); + Map tokenOptions = new HashMap<>(); + tokenOptions.put("test.token", UUID.randomUUID().toString()); + tokenOptions.put(IO_CACHE_POLICY.key(), "read"); + tokenOptions.put("fs.oss.endpoint", "server-cache"); + tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "server-origin"); + 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)); + RESTTokenFileIO rest = + new RESTTokenFileIO( + CatalogContext.create(options, loader, null), + api, + identifier, + new Path("oss://bucket/table")); + 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("server-cache"); + assertThat(provider.hadoopOptions(data, "write").get("fs.oss.endpoint")) + .isEqualTo("server-origin"); + assertThat(rest.validToken().token().get("fs.oss.endpoint")).isEqualTo("server-cache"); } @Test @@ -108,7 +101,6 @@ void testTokenRefreshRebuildsPolicyWrapper() throws IOException { Identifier identifier = Identifier.create("db", "table"); Map tokenOptions = new HashMap<>(); tokenOptions.put(IO_CACHE_POLICY.key(), "read"); - tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); tokenOptions.put("fs.oss.endpoint", "cache"); tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "origin"); Map disabledOptions = new HashMap<>(tokenOptions); @@ -151,7 +143,6 @@ void testIdenticalTokensSharePolicyWrapperAcrossTablesAndContexts() throws IOExc Map tokenOptions = new HashMap<>(); tokenOptions.put("test.token", UUID.randomUUID().toString()); tokenOptions.put(IO_CACHE_POLICY.key(), "read"); - tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); tokenOptions.put("fs.oss.endpoint", "cache"); tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "origin"); tokenOptions.put(IO_CACHE_WHITELIST_PATH.key(), "table-two"); @@ -199,7 +190,6 @@ void testIdenticalCredentialsWithDifferentCacheOptionsDoNotShareFileIO() throws Map tokenOptions = new HashMap<>(); tokenOptions.put("fs.oss.securityToken", UUID.randomUUID().toString()); tokenOptions.put(IO_CACHE_POLICY.key(), "read"); - tokenOptions.put(IO_CACHE_VPC_VALIDATED.key(), "true"); tokenOptions.put("fs.oss.endpoint", "cache"); tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "origin"); Map disabledOptions = new HashMap<>(tokenOptions); 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 b16c4f320b9c..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_VPC_VALIDATED; 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; @@ -2174,7 +2173,6 @@ void testValidToken() throws Exception { @Test void testValidTokenPreservesServerCacheSettings() throws Exception { Map options = new HashMap<>(); - options.put(IO_CACHE_VPC_VALIDATED.key(), "true"); options.put("fs.oss.endpoint", "client-endpoint"); options.put(DLF_OSS_ENDPOINT.key(), "client-dlf-endpoint"); this.catalog = newRestCatalogWithDataToken(options); @@ -2187,8 +2185,8 @@ void testValidTokenPreservesServerCacheSettings() throws Exception { "akId", "akSecret", UUID.randomUUID().toString(), - IO_CACHE_VPC_VALIDATED.key(), - "false", + "io-cache.origin.endpoint", + "server-origin", "fs.oss.endpoint", "server-cache"), System.currentTimeMillis() + 3600_000L); @@ -2198,7 +2196,7 @@ void testValidTokenPreservesServerCacheSettings() throws Exception { RESTTokenFileIO fileIO = (RESTTokenFileIO) fileStoreTable.fileIO(); RESTToken fileDataToken = fileIO.validToken(); - assertEquals("false", fileDataToken.token().get(IO_CACHE_VPC_VALIDATED.key())); + assertEquals("server-origin", fileDataToken.token().get("io-cache.origin.endpoint")); assertEquals("server-cache", fileDataToken.token().get("fs.oss.endpoint")); } 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 index e2fd71be916b..66554dbf8ea2 100644 --- 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 @@ -33,7 +33,6 @@ 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_VPC_VALIDATED; import static org.apache.paimon.rest.RESTCatalogOptions.IO_CACHE_WHITELIST_PATH; import static org.assertj.core.api.Assertions.assertThat; @@ -147,7 +146,6 @@ private static FileIO create(Options options) throws Exception { private static Options options() { Options options = new Options(); options.set(IO_CACHE_POLICY, "read"); - options.set(IO_CACHE_VPC_VALIDATED, true); options.set(IO_CACHE_ORIGIN_ENDPOINT, "origin"); options.set("fs.oss.endpoint", "cache"); options.set("fs.oss.accessKeyId", "test-ak"); 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 c8b3d14582e1..39d893d01cc1 100644 --- a/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py +++ b/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py @@ -205,9 +205,6 @@ def _merged_options(self, token: RESTToken) -> Options: self.catalog_options.to_map() if self.catalog_options else {}, token.token ) - # Connectivity validation can only come from the REST server. - merged_properties[CatalogOptions.IO_CACHE_VPC_VALIDATED.key()] = token.token.get( - CatalogOptions.IO_CACHE_VPC_VALIDATED.key(), False) if self.catalog_options and OssOptions.OSS_ENDPOINT.key() not in token.token: dlf_oss_endpoint = self.catalog_options.get(CatalogOptions.DLF_OSS_ENDPOINT) if dlf_oss_endpoint and dlf_oss_endpoint.strip(): diff --git a/paimon-python/pypaimon/common/options/config.py b/paimon-python/pypaimon/common/options/config.py index c9083a2cb3bd..f89c7078d732 100644 --- a/paimon-python/pypaimon/common/options/config.py +++ b/paimon-python/pypaimon/common/options/config.py @@ -149,15 +149,6 @@ 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_VPC_VALIDATED = ( - ConfigOptions.key("io-cache.vpc-validated") - .boolean_type() - .default_value(False) - .with_description( - "Whether the REST server has validated connectivity from the source " - "VPC to the cache endpoint." - ) - ) IO_CACHE_ORIGIN_ENDPOINT = ( ConfigOptions.key("io-cache.origin.endpoint") .string_type() diff --git a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py index 536a6374a400..079520933e80 100644 --- a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -80,7 +80,6 @@ def _cache_enabled(cls, options: Options) -> bool: return ( policy is not None and cls.DISABLE_CACHE_TAG not in policy - and options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED) ) def __init__( diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index e19aec26db12..25893f4c1758 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -180,7 +180,6 @@ def to_filesystem_path(self, path: str) -> str: def _options(**overrides): values = { CatalogOptions.IO_CACHE_POLICY.key(): "meta,read,write", - CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): True, CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "origin-endpoint", CatalogOptions.IO_CACHE_WHITELIST.key(): "*", CatalogOptions.IO_CACHE_WHITELIST_PATH.key(): "*", @@ -401,44 +400,32 @@ def test_pyarrow_filesystem_invokes_policy_handler(self): with file_io.filesystem.open_input_file(relative_path) as input_file: self.assertEqual(b"cache", input_file.read()) - def test_vpc_validation_and_none_policy_disable_wrapper(self): - factory = _RecordingFactory() - file_io = CachePolicyFileIO.create( - TABLE_ROOT, - _options(**{CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): False}), - factory, - ) - self.assertNotIsInstance(file_io, CachePolicyFileIO) - self.assertEqual(1, len(factory.calls)) - self.assertEqual( - "origin-endpoint", - factory.calls[0][1].get(OssOptions.OSS_ENDPOINT), - ) - - factory = _RecordingFactory() - options = _options() - options.to_map().pop(CatalogOptions.IO_CACHE_VPC_VALIDATED.key()) - file_io = CachePolicyFileIO.create(TABLE_ROOT, options, factory) - self.assertNotIsInstance(file_io, CachePolicyFileIO) + 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)) - factory = _RecordingFactory() + 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(**{ - CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): False, - "io-cache.ignore-vpc-validate": True, + "io-cache.vpc-validated": False, + "io-cache.ignore-vpc-validate": False, }), - factory, - ) - self.assertNotIsInstance(file_io, CachePolicyFileIO) - - factory = _RecordingFactory() - file_io = CachePolicyFileIO.create( - TABLE_ROOT, - _options(**{CatalogOptions.IO_CACHE_POLICY.key(): "none"}), - factory, + _RecordingFactory(), ) - self.assertNotIsInstance(file_io, CachePolicyFileIO) + self.assertIn("cache-endpoint", file_io.new_input_stream(DATA_PATH)[0]) def test_serialization_restores_policy_filesystem(self): file_io = CachePolicyFileIO.create( 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 a4e79305c27c..1837dfcd940b 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 @@ -718,7 +718,6 @@ def test_server_endpoint_takes_precedence_over_dlf_endpoint(self): def test_server_cache_settings_take_precedence(self): catalog_options = Options({ - CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): True, OssOptions.OSS_ENDPOINT.key(): "client-endpoint", CatalogOptions.DLF_OSS_ENDPOINT.key(): "client-dlf-endpoint", CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "client-origin", @@ -726,20 +725,15 @@ def test_server_cache_settings_take_precedence(self): file_io = RESTTokenFileIO( self.identifier, self.warehouse_path, catalog_options) server_options = { - CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): "false", OssOptions.OSS_ENDPOINT.key(): "server-cache", CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT.key(): "server-origin", } merged_token = file_io._merge_token_with_catalog_options(server_options) self.assertEqual(server_options, merged_token) options = file_io._merged_options(RESTToken(merged_token, 0)) - self.assertFalse(options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED)) self.assertEqual("server-cache", options.get(OssOptions.OSS_ENDPOINT)) self.assertEqual( "server-origin", options.get(CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT)) - server_options.pop(CatalogOptions.IO_CACHE_VPC_VALIDATED.key()) - options = file_io._merged_options(RESTToken(server_options, 0)) - self.assertFalse(options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED)) def test_token_file_io_uses_cache_policy_factory(self): file_io = RESTTokenFileIO( @@ -750,7 +744,6 @@ def test_token_file_io_uses_cache_policy_factory(self): file_io.token = RESTToken( { CatalogOptions.IO_CACHE_POLICY.key(): "read", - CatalogOptions.IO_CACHE_VPC_VALIDATED.key(): "true", OssOptions.OSS_ENDPOINT.key(): "cache-endpoint", }, int(time.time() * 1000) + 7_200_000, @@ -772,7 +765,7 @@ def test_token_file_io_uses_cache_policy_factory(self): 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.assertTrue(options.get(CatalogOptions.IO_CACHE_VPC_VALIDATED)) + self.assertEqual("cache-endpoint", options.get(OssOptions.OSS_ENDPOINT)) def test_catalog_options_not_modified(self): from pypaimon.api.rest_util import RESTUtil From 0e2ac3dc6f6729d06cf4d1c853e439de619a56e6 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Thu, 19 Nov 2026 21:45:58 +0800 Subject: [PATCH 14/21] Fall back to origin when cache policy endpoint is unreachable --- doc/cache-policy.md | 22 ++- .../fs/cache/CacheConnectionFailure.java | 101 +++++++++++ .../paimon/fs/cache/CachePolicyFileIO.java | 85 +++++++-- .../fs/cache/CacheConnectionFailureTest.java | 75 ++++++++ .../fs/cache/CachePolicyFileIOTest.java | 113 +++++++++++- .../filesystem/cache_policy_file_io.py | 162 +++++++++++++----- .../tests/cache_policy_file_io_test.py | 131 +++++++++++++- 7 files changed, 626 insertions(+), 63 deletions(-) create mode 100644 paimon-common/src/main/java/org/apache/paimon/fs/cache/CacheConnectionFailure.java create mode 100644 paimon-common/src/test/java/org/apache/paimon/fs/cache/CacheConnectionFailureTest.java diff --git a/doc/cache-policy.md b/doc/cache-policy.md index fb9db0d7964d..24e96435ca36 100644 --- a/doc/cache-policy.md +++ b/doc/cache-policy.md @@ -137,8 +137,26 @@ Paimon 生成的临时文件,以及会被覆盖的 Iceberg 兼容元数据:` | Java `newTwoPhaseOutputStream`、multipart 提交和清理 | 走 origin,上传与提交使用同一类端点;提交时沿现有 REST token 链路取得有效凭证。 | | Blob presign、Java archive/restore/unarchive | 走 origin,保留底层签名和存储管理能力。 | -cache delegate 在第一次命中缓存操作时惰性创建。缓存端点访问失败时,错误直接上抛, -客户端不会自动重试到 origin;这里的“回退”表示策略路由,不是失败重试。 +cache delegate 在第一次命中缓存操作时惰性创建,并对该操作的文件路径执行一次 +`exists` 连通性探测(文件尚不存在是有效结果)。这是为了在 Jindo 等后端延迟到 +输出流关闭时才建立网络连接的情况下,仍能在开始写入前发现不可达端点。 + +初始化、探测或打开文件/查询元数据遇到可识别的连接错误时,该操作改用 origin, +并输出一次 `WARN CACHE_POLICY_FALLBACK` 日志,包含操作、路径、两端 endpoint 和 +异常类型。此后同一个 FileIO 实例持续屏蔽 cache endpoint,所有操作使用 origin, +序列化也保留这一状态;新建 FileIO 实例才会重新尝试缓存。并发中已经开始的请求可能 +仍在使用 cache delegate,delegate 保留至 FileIO 关闭时统一清理。 + +可回退的错误包括连接拒绝/断开、DNS 解析失败、socket 连接/读取超时,以及 Jindo +原生 `Failed to connect Http service:` 和 Arrow `NETWORK_CONNECTION` 诊断。 +文件不存在、文件已存在、权限/鉴权失败、取消/中断以及无法确认是连接故障的一般 IO +错误均直接上抛,不触发回退或屏蔽。若 origin 重试也失败,最终抛出 origin 异常。 + +回退发生在 FileIO API 调用及 Arrow filesystem adapter 调用的边界,已返回的原生 +输入/输出流不做透明重放。特别是已经开始写入后失败,不能安全地将部分写入或已消费 +的迭代器重放到 origin;Python 格式写入接口仅在开始写入前探测失败时自动改用 origin, +写入途中失败仍报错,并在确认是连接故障时屏蔽后续缓存操作。调用方仍需处理这种写入 +失败。此机制不新增客户端参数,仍按服务端下发的 policy 和 origin endpoint 工作。 Java `HadoopOptionsProvider` 与 Python Arrow filesystem adapter 使用同一套路径和操作规则。 ## 服务端下发示例 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/CachePolicyFileIO.java b/paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java index edc4bb1c5bf0..3e6c31b222b8 100644 --- 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 @@ -69,6 +69,7 @@ public class CachePolicyFileIO implements FileIO, HadoopOptionsProvider { private final Map runtimeOptions = new HashMap<>(); private transient volatile FileIO cache; + private volatile boolean cacheUnavailable; private volatile boolean closed; private CachePolicyFileIO( @@ -135,7 +136,7 @@ private void ensureOpen() throws IOException { private FileIO fileIO(Path path, String operation) throws IOException { ensureOpen(); - boolean useCache = policy.shouldCache(path, operation); + boolean useCache = !cacheUnavailable && policy.shouldCache(path, operation); LOG.debug( "CACHE_POLICY_ROUTE operation={} route={} endpoint={} file_type={} path={}", operation, @@ -150,16 +151,29 @@ private FileIO fileIO(Path path, String operation) throws IOException { if (current == null) { synchronized (this) { ensureOpen(); + if (cacheUnavailable) { + return origin; + } current = cache; if (current == null) { - current = FileIO.get(tablePath, cacheContext); try { + current = FileIO.get(tablePath, cacheContext); current.setRuntimeContext(new HashMap<>(runtimeOptions)); - } catch (RuntimeException | Error e) { - try { - current.close(); - } catch (Exception closeFailure) { - e.addSuppressed(closeFailure); + // 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; } @@ -170,34 +184,73 @@ private FileIO fileIO(Path path, String operation) throws IOException { 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()); + } + } + + 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 fileIO(path, "read").newInputStream(path); + return execute(path, "read", io -> io.newInputStream(path)); } @Override public PositionOutputStream newOutputStream(Path path, boolean overwrite) throws IOException { - return fileIO(path, "write").newOutputStream(path, overwrite); + return execute(path, "write", io -> io.newOutputStream(path, overwrite)); } @Override public FileStatus getFileStatus(Path path) throws IOException { - return fileIO(path, "meta").getFileStatus(path); + return execute(path, "meta", io -> io.getFileStatus(path)); } @Override public boolean exists(Path path) throws IOException { - return fileIO(path, "meta").exists(path); + return execute(path, "meta", io -> io.exists(path)); } @Override public long getFileSize(Path path) throws IOException { - return fileIO(path, "meta").getFileSize(path); + return execute(path, "meta", io -> io.getFileSize(path)); } @Override public boolean isDir(Path path) throws IOException { - return fileIO(path, "meta").isDir(path); + return execute(path, "meta", io -> io.isDir(path)); } @Override @@ -267,6 +320,7 @@ public Optional unarchive(Path path, StorageType type) throws IOException 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); } @@ -274,10 +328,7 @@ public Options hadoopOptions(Path path, String opType) { return ((HadoopOptionsProvider) delegate).hadoopOptions(path, opType); } Options options = - new Options( - (policy.shouldCache(path, opType) ? cacheContext : originContext) - .options() - .toMap()); + new Options((useCache ? cacheContext : originContext).options().toMap()); synchronized (this) { runtimeOptions.forEach(options::set); } 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 index 2d62acc3e5d0..8a20821991f6 100644 --- 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 @@ -36,7 +36,9 @@ 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; @@ -314,6 +316,103 @@ void testCacheReadFailuresAreNotRetriedOnOrigin() throws Exception { } } + @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"); @@ -330,6 +429,7 @@ private static FileIO create(Options options, RecordingLoader loader) throws IOE private static class RecordingLoader implements FileIOLoader { private final List created = new ArrayList<>(); + private IOException cacheProbeFailure; @Override public String getScheme() { @@ -339,6 +439,7 @@ public String getScheme() { @Override public FileIO load(Path path) { RecordingFileIO fileIO = new RecordingFileIO(); + fileIO.probeFailure = cacheProbeFailure; created.add(fileIO); return fileIO; } @@ -362,6 +463,8 @@ private static class RecordingFileIO extends LocalFileIO implements HadoopOption private int closeCount; private boolean failClose; private boolean failRead; + private IOException readFailure; + private IOException probeFailure; @Override public void configure(CatalogContext context) { @@ -378,6 +481,9 @@ public Options hadoopOptions(Path path, String opType) { @Override public SeekableInputStream newInputStream(Path path) throws IOException { calls.add("read"); + if (readFailure != null) { + throw readFailure; + } if (failRead) { throw new IOException("cache read failed"); } @@ -397,8 +503,13 @@ public FileStatus getFileStatus(Path path) { } @Override - public boolean exists(Path path) { + 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; } diff --git a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py index 079520933e80..7f101bf3af9c 100644 --- a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -15,7 +15,9 @@ # specific language governing permissions and limitations # under the License. +import errno import logging +import socket import threading from typing import Dict, List from urllib.parse import urlparse @@ -32,6 +34,38 @@ _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. @@ -95,7 +129,8 @@ def __init__( self._cache_options = cache_options self._file_io_factory = file_io_factory self._cache_file_io = None - self._cache_file_io_lock = threading.Lock() + 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 "" @@ -145,17 +180,61 @@ def __getstate__(self): def __setstate__(self, state): self.__dict__.update(state) - self._cache_file_io_lock = threading.Lock() + self._cache_file_io_lock = threading.RLock() self._initialize_filesystem() - def _get_cache_file_io(self) -> FileIO: + def _get_cache_file_io(self, path, operation) -> FileIO: 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: - self._cache_file_io = self._file_io_factory( - self._path, self._cache_options) + 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): + 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__) + + 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) @@ -202,7 +281,7 @@ def _should_use_cache(self, path: str, operation: str) -> bool: or (operation == "read" and self.read_cache_enabled) or (operation == "write" and self.write_cache_enabled) ) - return enabled and self.should_cache(path) + return not self._cache_unavailable and enabled and self.should_cache(path) def _log_route(self, path: str, operation: str, use_cache: bool): options = ( @@ -224,7 +303,7 @@ def _file_io_for(self, path: str, operation: str) -> FileIO: use_cache = self._should_use_cache(path, operation) self._log_route(path, operation, use_cache) if use_cache: - return self._get_cache_file_io() + return self._get_cache_file_io(path, operation) return self._origin_file_io def _origin_file_io_for(self, path: str, operation: str) -> FileIO: @@ -232,19 +311,19 @@ def _origin_file_io_for(self, path: str, operation: str) -> FileIO: return self._origin_file_io def new_input_stream(self, path: str): - return self._file_io_for(path, "read").new_input_stream(path) + return self._execute(path, "read", lambda io: io.new_input_stream(path)) def new_output_stream(self, path: str): - return self._file_io_for(path, "write").new_output_stream(path) + return self._execute(path, "write", lambda io: io.new_output_stream(path)) def get_file_status(self, path: str): - return self._file_io_for(path, "meta").get_file_status(path) + 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._file_io_for(path, "meta").exists(path) + return self._execute(path, "meta", lambda io: io.exists(path)) def exists_batch(self, paths: List[str]) -> Dict[str, bool]: grouped = {} @@ -255,10 +334,12 @@ def exists_batch(self, paths: List[str]) -> Dict[str, bool]: result = {} for use_cache, grouped_paths in grouped.items(): - file_io = ( - self._get_cache_file_io() - if use_cache else self._origin_file_io) - result.update(file_io.exists_batch(grouped_paths)) + 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: @@ -271,10 +352,10 @@ 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._file_io_for(path, "meta").get_file_size(path) + return self._execute(path, "meta", lambda io: io.get_file_size(path)) def is_dir(self, path: str) -> bool: - return self._file_io_for(path, "meta").is_dir(path) + return self._execute(path, "meta", lambda io: io.is_dir(path)) def to_filesystem_path(self, path: str) -> str: return self._origin_file_io.to_filesystem_path(path) @@ -293,28 +374,28 @@ def uri_reader_factory(self): return UriReaderFactory.from_file_io(self) def write_parquet(self, path: str, *args, **kwargs): - return self._file_io_for(path, "write").write_parquet(path, *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._file_io_for(path, "write").write_orc(path, *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._file_io_for(path, "write").write_avro(path, *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._file_io_for(path, "write").write_lance(path, *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._file_io_for(path, "write").write_blob(path, *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._file_io_for(path, "write").write_mosaic(path, *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._file_io_for(path, "write").write_vortex(path, *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._file_io_for(path, "write").write_row(path, *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) @@ -333,8 +414,8 @@ class _CachePolicyFileSystemHandler(FileSystemHandler): def __init__(self, file_io: CachePolicyFileIO): self._file_io = file_io - def _filesystem_for(self, path: str, operation: str): - return self._file_io._file_io_for(path, operation).filesystem + def _execute(self, path, operation, action): + return self._file_io._execute(path, operation, lambda io: action(io.filesystem)) @property def _origin_filesystem(self): @@ -360,11 +441,12 @@ def get_file_info(self, paths) -> list: grouped.setdefault(use_cache, []).append((index, path)) for use_cache, indexed_paths in grouped.items(): - filesystem = ( - self._file_io._get_cache_file_io().filesystem - if use_cache else self._origin_filesystem) - infos = filesystem.get_file_info( - [path for _, path in indexed_paths]) + grouped_paths = [path for _, path in indexed_paths] + if use_cache: + infos = self._execute( + grouped_paths[0], "meta", lambda fs: fs.get_file_info(grouped_paths)) + else: + infos = self._origin_filesystem.get_file_info(grouped_paths) for (index, _), info in zip(indexed_paths, infos): result[index] = info return result @@ -399,19 +481,15 @@ def copy_file(self, src: str, dest: str): return self._origin_filesystem_for(src, "copy").copy_file(src, dest) def open_input_stream(self, path: str): - return self._filesystem_for(path, "read").open_input_stream(path) + return self._execute(path, "read", lambda fs: fs.open_input_stream(path)) def open_input_file(self, path: str): - return self._filesystem_for(path, "read").open_input_file(path) + return self._execute(path, "read", lambda fs: fs.open_input_file(path)) def open_output_stream(self, path: str, metadata): - filesystem = self._filesystem_for(path, "write") - if metadata is None: - return filesystem.open_output_stream(path) - return filesystem.open_output_stream(path, metadata=metadata) + kwargs = {} if metadata is None else {"metadata": metadata} + return self._execute(path, "write", lambda fs: fs.open_output_stream(path, **kwargs)) def open_append_stream(self, path: str, metadata): - filesystem = self._filesystem_for(path, "write") - if metadata is None: - return filesystem.open_append_stream(path) - return filesystem.open_append_stream(path, metadata=metadata) + kwargs = {} if metadata is None else {"metadata": metadata} + return self._execute(path, "write", lambda fs: fs.open_append_stream(path, **kwargs)) diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index 25893f4c1758..05ce8a4cb83a 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -17,8 +17,11 @@ import os import pickle +import socket import tempfile import unittest +from concurrent.futures import ThreadPoolExecutor +from unittest.mock import patch from urllib.parse import urlparse import pyarrow.fs as pafs @@ -26,7 +29,7 @@ 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 +from pypaimon.filesystem.cache_policy_file_io import CachePolicyFileIO, _is_connection_failure TABLE_ROOT = "oss://test-bucket/database/table" @@ -192,6 +195,132 @@ def _options(**overrides): class CachePolicyFileIOTest(unittest.TestCase): + 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"}) From 6b3b9ac5875fb89640439b6a9d5304b781acb639 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Fri, 20 Nov 2026 16:57:33 +0800 Subject: [PATCH 15/21] Log full exception when cache policy falls back to origin --- doc/cache-policy.md | 3 ++- .../java/org/apache/paimon/fs/cache/CachePolicyFileIO.java | 3 ++- paimon-python/pypaimon/filesystem/cache_policy_file_io.py | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/doc/cache-policy.md b/doc/cache-policy.md index 24e96435ca36..fd2808a2d282 100644 --- a/doc/cache-policy.md +++ b/doc/cache-policy.md @@ -143,7 +143,8 @@ cache delegate 在第一次命中缓存操作时惰性创建,并对该操作 初始化、探测或打开文件/查询元数据遇到可识别的连接错误时,该操作改用 origin, 并输出一次 `WARN CACHE_POLICY_FALLBACK` 日志,包含操作、路径、两端 endpoint 和 -异常类型。此后同一个 FileIO 实例持续屏蔽 cache endpoint,所有操作使用 origin, +异常类型,并完整打印异常堆栈及原因链。此后同一个 FileIO 实例持续屏蔽 cache endpoint, +所有操作使用 origin, 序列化也保留这一状态;新建 FileIO 实例才会重新尝试缓存。并发中已经开始的请求可能 仍在使用 cache delegate,delegate 保留至 FileIO 关闭时统一清理。 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 index 3e6c31b222b8..a43b317db9cd 100644 --- 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 @@ -194,7 +194,8 @@ private synchronized void disableCache(Path path, String operation, Throwable fa cacheContext.options().get("fs.oss.endpoint"), originContext.options().get("fs.oss.endpoint"), path, - failure.getClass().getName()); + failure.getClass().getName(), + failure); } } diff --git a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py index 7f101bf3af9c..d5c5444fca2b 100644 --- a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -219,7 +219,8 @@ def _disable_cache(self, path, operation, error): "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__) + 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) From 5b5c7cdc2c555405e139a7644a71306ae6b8bde6 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Fri, 20 Nov 2026 20:57:27 +0800 Subject: [PATCH 16/21] Fix native format routing and fork lifecycle in cache policy FileIO --- doc/cache-policy.md | 5 + .../catalog/rest/rest_token_file_io.py | 3 + paimon-python/pypaimon/common/file_io.py | 4 + .../filesystem/cache_policy_file_io.py | 114 +++++++++++----- .../pypaimon/filesystem/resolving_file_io.py | 3 + .../pypaimon/filesystem/vortex_utils.py | 6 +- .../tests/cache_policy_file_io_test.py | 124 ++++++++++++++++++ 7 files changed, 223 insertions(+), 36 deletions(-) diff --git a/doc/cache-policy.md b/doc/cache-policy.md index fd2808a2d282..edcbd3377c7f 100644 --- a/doc/cache-policy.md +++ b/doc/cache-policy.md @@ -159,6 +159,11 @@ cache delegate 在第一次命中缓存操作时惰性创建,并对该操作 写入途中失败仍报错,并在确认是连接故障时屏蔽后续缓存操作。调用方仍需处理这种写入 失败。此机制不新增客户端参数,仍按服务端下发的 policy 和 origin endpoint 工作。 Java `HadoopOptionsProvider` 与 Python Arrow filesystem adapter 使用同一套路径和操作规则。 +Python 的 Vortex reader/writer 通过 `FileIO.for_path(path, operation)` 获取具体后端的 +原生存储参数,同样遵守操作、路径白名单及缓存故障屏蔽状态。Arrow adapter 保留逻辑 URI, +每次操作先解析 `ResolvingFileIO`,再按选中的具体后端转换物理路径。 +fork 后首次使用包装层时会重建锁及两个端点的进程内后端,避免继承其他线程持有的锁; +已经屏蔽缓存的状态继续保留。 ## 服务端下发示例 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 39d893d01cc1..03cd96c90a0e 100644 --- a/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py +++ b/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py @@ -130,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: 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/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py index d5c5444fca2b..18b4db35eb3a 100644 --- a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -17,6 +17,7 @@ import errno import logging +import os import socket import threading from typing import Dict, List @@ -125,7 +126,8 @@ def __init__( file_io_factory): self._path = path self.properties = catalog_options - self._origin_file_io = origin_file_io + 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 @@ -180,10 +182,31 @@ def __getstate__(self): 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: @@ -210,6 +233,7 @@ def _get_cache_file_io(self, path, operation) -> FileIO: 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 @@ -301,6 +325,7 @@ def _log_route(self, path: str, operation: str, use_cache: bool): ) 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: @@ -359,7 +384,12 @@ 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: - return self._origin_file_io.to_filesystem_path(path) + # 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( @@ -416,21 +446,26 @@ def __init__(self, file_io: CachePolicyFileIO): self._file_io = file_io def _execute(self, path, operation, action): - return self._file_io._execute(path, operation, lambda io: action(io.filesystem)) + 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) - @property - def _origin_filesystem(self): - return self._file_io._origin_file_io.filesystem + 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)) - def _origin_filesystem_for(self, path: str, operation: str): - self._file_io._log_route(path, operation, False) - return self._origin_filesystem + @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 self._origin_filesystem.normalize_path(path) + return path def get_file_info(self, paths) -> list: paths = list(paths) @@ -439,58 +474,69 @@ def get_file_info(self, paths) -> list: 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) - grouped.setdefault(use_cache, []).append((index, path)) + parsed = urlparse(path) + grouped.setdefault((use_cache, parsed.scheme, parsed.netloc), []).append((index, path)) - for use_cache, indexed_paths in grouped.items(): + 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._execute( - grouped_paths[0], "meta", lambda fs: fs.get_file_info(grouped_paths)) + infos = self._file_io._execute(grouped_paths[0], "meta", get_infos) else: - infos = self._origin_filesystem.get_file_info(grouped_paths) - for (index, _), info in zip(indexed_paths, infos): - result[index] = info + 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: - return self._origin_filesystem_for( - selector.base_dir, "list").get_file_info(selector) + 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_filesystem_for( - path, "mkdirs").create_dir(path, recursive=recursive) + return self._origin_execute(path, "mkdirs", lambda fs, p: fs.create_dir(p, recursive=recursive)) def delete_dir(self, path: str): - return self._origin_filesystem_for(path, "delete").delete_dir(path) + 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_filesystem_for(path, "delete").delete_dir_contents( - path, missing_dir_ok=missing_dir_ok) + 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_filesystem_for( - "/", "delete").delete_dir_contents( - "/", accept_root_dir=True) + 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_filesystem_for(path, "delete").delete_file(path) + return self._origin_execute(path, "delete", lambda fs, p: fs.delete_file(p)) def move(self, src: str, dest: str): - return self._origin_filesystem_for(src, "rename").move(src, dest) + 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): - return self._origin_filesystem_for(src, "copy").copy_file(src, dest) + 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: fs.open_input_stream(path)) + 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: fs.open_input_file(path)) + 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: fs.open_output_stream(path, **kwargs)) + 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: fs.open_append_stream(path, **kwargs)) + return self._execute(path, "write", lambda fs, p: fs.open_append_stream(p, **kwargs)) 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 index 05ce8a4cb83a..587a2cdc1328 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -17,8 +17,11 @@ 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 @@ -195,6 +198,127 @@ def _options(**overrides): class CachePolicyFileIOTest(unittest.TestCase): + 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 + + fake = types.ModuleType("vortex") + fake.array = MagicMock(return_value="array") + fake.store = types.SimpleNamespace(from_url=MagicMock()) + io = CachePolicyFileIO.create( + TABLE_ROOT, _options(**{"io-cache.policy": "read"}), _RecordingFactory()) + with patch.dict("sys.modules", {"vortex": fake}): + write_vortex_file(io, TABLE_ROOT + "/bucket-0/data-a.vortex", []) + self.assertIn("origin-endpoint", fake.store.from_url.call_args.kwargs["endpoint"]) + fake.store.from_url.return_value.write.assert_called_once_with("array") + + 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"), From 1d88e5d3ce68fe794c493baf233339841e4bab27 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Fri, 20 Nov 2026 21:14:04 +0800 Subject: [PATCH 17/21] Preserve native cache policy routing through local block cache --- paimon-python/pypaimon/filesystem/caching_file_io.py | 3 +++ .../pypaimon/tests/cache_policy_file_io_test.py | 10 ++++++++++ 2 files changed, 13 insertions(+) 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/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index 587a2cdc1328..9ed07f05a93f 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -240,6 +240,16 @@ def test_vortex_writer_selects_write_options(self): self.assertIn("origin-endpoint", fake.store.from_url.call_args.kwargs["endpoint"]) fake.store.from_url.return_value.write.assert_called_once_with("array") + 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 From d7b135d971c084915994359d78685d2b1da6bf5f Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Sun, 22 Nov 2026 21:26:17 +0800 Subject: [PATCH 18/21] Honor client cache routing overrides and bypass identical endpoints --- doc/cache-policy.md | 357 +++++++++--------- .../paimon/rest/RESTCatalogOptions.java | 7 +- .../paimon/fs/cache/CachePolicyFileIO.java | 14 +- .../apache/paimon/rest/RESTTokenFileIO.java | 15 +- .../fs/cache/CachePolicyFileIOTest.java | 42 +++ .../paimon/rest/RESTTokenFileIOTest.java | 192 +++++++++- .../catalog/rest/rest_token_file_io.py | 27 +- .../pypaimon/common/options/config.py | 5 +- .../filesystem/cache_policy_file_io.py | 3 +- .../tests/cache_policy_file_io_test.py | 19 + .../tests/rest/rest_token_file_io_test.py | 128 ++++++- 11 files changed, 581 insertions(+), 228 deletions(-) diff --git a/doc/cache-policy.md b/doc/cache-policy.md index edcbd3377c7f..de8ee8e0b502 100644 --- a/doc/cache-policy.md +++ b/doc/cache-policy.md @@ -17,205 +17,220 @@ specific language governing permissions and limitations under the License. --> -# Cache Policy 参数与路由说明 +# Cache policy -Cache policy 控制 Paimon 文件操作访问缓存端点还是 origin 端点。Java 和 PyPaimon -在通用 `CachePolicyFileIO` 包装层中执行相同的路由规则,底层 FileIO 负责实际读写。 -它独立于客户端本地 block cache,也不改变表本身的存储和读取语义。 +Cache policy routes object-storage operations through a cache endpoint or directly +to the origin endpoint. Java and PyPaimon use the same operation, file-type and +path selection rules. It is independent of the local block cache and does not +change table storage or read semantics. -REST Catalog 通过 table token 下发凭证、端点和 `io-cache.*` 策略。 -`RESTTokenFileIO` 合并配置并创建包装层;策略刷新随 token 刷新生效。 -也可以显式调用 `CachePolicyFileIO.create`,传入相同的配置。 -普通 `FileIO.get` 调用不会自动装配远端 cache policy。 +REST Catalog can provide credentials, endpoints and cache settings in a table +token. Applications can override endpoint and cache settings in their catalog +configuration. -## 有效参数 +## Configuration -下表中的默认值指新的 cache policy 层,Java 与 PyPaimon 一致。 +| Option | Default | Description | +| --- | --- | --- | +| `fs.oss.endpoint` | Supplied by the storage configuration or REST token | Endpoint used for operations selected by the cache policy. | +| `dlf.oss-endpoint` | Unset | REST Catalog client override for `fs.oss.endpoint`. A nonblank value has the highest endpoint priority. | +| `io-cache.origin.endpoint` | The effective `fs.oss.endpoint` | Origin endpoint for operations that bypass the cache. An unset, empty or whitespace-only value uses `fs.oss.endpoint`. | +| `io-cache.policy` | Unset; no operations use the cache | Comma-separated operation labels: `meta`, `read`, `write`, or `none`. | +| `io-cache.whitelist` | `*` | Comma-separated file types allowed to use the cache. | +| `io-cache.whitelist-path` | `*` | Comma-separated URI path substrings allowed to use the cache. | -| 参数 | 类型 | 默认值 | 含义 | -| --- | --- | --- | --- | -| `fs.oss.endpoint` | 字符串 | 无,由下发配置或底层 FileIO 配置提供 | 缓存操作使用的端点。包装层始终保留这个值作为 cache endpoint。 | -| `io-cache.origin.endpoint` | 字符串 | 未设置时保留 `fs.oss.endpoint` | 不走缓存的操作使用的 origin endpoint。非空时,仅覆盖 origin delegate 的 `fs.oss.endpoint`。 | -| `io-cache.policy` | 字符串 | 未设置,没有缓存操作 | 启用哪些操作类型,可组合 `meta`、`read`、`write`;`none` 关闭全部缓存操作。 | -| `io-cache.whitelist` | 字符串 | `*` | 允许缓存的文件类型,多个类型用逗号分隔。 | -| `io-cache.whitelist-path` | 字符串 | `*` | 允许缓存的 URI path 子串,多个子串用逗号分隔。类型与路径白名单必须同时命中。 | +### Client overrides -协议不再包含 VPC validate 步骤。`io-cache.vpc-validated` 和 -`io-cache.ignore-vpc-validate` 均已移除,不参与策略判断。 -也没有独立的 `io-cache.endpoint` 参数;缓存端点统一使用 `fs.oss.endpoint`。 -新的 policy 层不需要 `io-cache.enabled` 客户端开关。 +For REST token configuration, endpoint priority is: -### 端点规则 +1. A nonblank client `dlf.oss-endpoint`. +2. An explicitly configured client `fs.oss.endpoint`. +3. The token's `fs.oss.endpoint`. +4. The underlying storage configuration when no endpoint is provided above. -cache 与 origin 使用原始文件路径和相同的对象存储命名空间,仅访问端点不同。 -两个端点使用下发的同一组凭证。 +Every explicitly configured client `io-cache.*` option takes precedence over the +same option in the token, including `io-cache.origin.endpoint`, policy and both +whitelists. Unspecified options retain the token's values. Explicit empty values +are preserved: an empty policy or whitelist does not fall back to the token's +value. -- 命中缓存策略:使用 `fs.oss.endpoint`。 -- 未命中、可变文件或固定走 origin 的操作:使用 `io-cache.origin.endpoint`。 -- 没有策略或策略为 `none`:直接返回 origin FileIO,origin 配置仍生效。 -- origin 参数缺失、为空或仅含空白:保留原来的 `fs.oss.endpoint`,不自动推导真实 OSS 端点。 - 需要绕过缓存访问真实 OSS 时,服务端应明确下发 origin 参数。 +These overrides apply to both FileIO operations and routing settings exposed to +native readers. They continue to apply after token refresh. Object-storage +credentials are supplied by the REST token. -REST token 中已有的 `fs.oss.endpoint` 优先于客户端端点设置。 -客户端 `dlf.oss-endpoint` 仅在服务端未提供 `fs.oss.endpoint` 时作为兼容回退。 -Java 同时把选定端点写入 delegate 的 options 和复制后的 Hadoop configuration, -保证 Hadoop 配置回退与原生 reader 取得相同的端点;不会修改原始配置对象。 +Cache and origin settings have separate roles. Overriding `fs.oss.endpoint` +selects the endpoint for cache-eligible operations; it does not replace an +explicit `io-cache.origin.endpoint`. -### policy 标签 +After configuration is merged, if cache and origin use the same endpoint, Paimon +initializes a regular FileIO directly. No cache-policy wrapper or cache +connectivity probe is needed. This also applies when the origin endpoint is +omitted and therefore inherits the cache endpoint. -| 标签 | 控制的操作 | 示例 | -| --- | --- | --- | -| `read` | 文件内容读取 | `newInputStream`、Python `new_input_stream`、Arrow 文件读取 | -| `write` | 普通文件内容写入 | `newOutputStream`、Python 普通格式写入、Arrow 文件写入 | -| `meta` | 文件属性查询 | `getFileStatus`、`exists`、`getFileSize`、`isDir`;Python 对应接口及批量属性查询 | -| `none` | 关闭全部缓存操作,优先于其他标签 | `none,read` 仍全部走 origin | +### Operation labels -例如,`read` 只允许读取内容走缓存;`meta,read` 允许属性查询和内容读取; -`meta,read,write` 允许三类操作。即使标签已开启,仍需满足文件类型、路径和不可变性条件。 +| Label | Operations | +| --- | --- | +| `read` | File-content reads. | +| `write` | File-content writes supported by the cache endpoint. | +| `meta` | File attributes, existence, length and directory-status queries, including corresponding batch operations. | +| `none` | Disable all cache operations, even when combined with other labels. | -`meta` 标签表示**操作类型**,不等同于文件类型白名单中的 `meta`。 -例如 `io-cache.policy=meta` 且 `io-cache.whitelist=data` 时, -数据文件的属性查询可以走缓存,但数据内容读取仍走 origin。 +Use lowercase labels separated by commas. For example, `meta,read` enables +attribute queries and content reads. An unset or empty policy sends all operations +to origin. Enabling an operation does not bypass file-type, path or immutability +requirements. -参数使用小写标签和逗号分隔的规范写法。当前实现沿用标签子串包含判断, -并未引入新的策略表达式或大小写转换。未设置策略或策略为空时,所有操作都走 origin。 +The `meta` operation label and `meta` file type serve different purposes. With +`io-cache.policy=meta` and `io-cache.whitelist=data`, data-file attribute queries +can use the cache, while data-file content reads use origin. -## 文件类型与路径白名单 +### File types and paths -| 文件类型值 | 覆盖范围与示例 | +| File-type value | Files | +| --- | --- | +| `meta` | Immutable snapshot, schema, manifest, statistics and other table metadata files. | +| `global-index` | Table-level global index files. | +| `bucket-index` | Bucket-level index files. | +| `file-index` | Index files associated with individual data files. | +| `data` | Data files and files not assigned to another category. | +| `*` | All file types, subject to the path and immutability rules. | + +PyPaimon also supports `structured-data` for its structured data-file category, +including Parquet, ORC, Avro, ROW and Mosaic. Use `data` for a shared +Java/Python configuration; it includes this category in PyPaimon. + +Whitelist rules: + +- Entries within one whitelist are alternatives. The file-type and path + whitelists must both match. +- Path matching uses the URI path, excluding its scheme, bucket authority, query + and fragment. For `oss://bucket/db/table/bucket-0/data.orc`, the matched path is + `/db/table/bucket-0/data.orc`. +- Path entries are case-sensitive substrings, not glob patterns or regular + expressions. A standalone `*` matches all paths; `bucket-*` is a literal + substring. +- Leading and trailing whitespace around entries is ignored. An explicit empty + whitelist, or a list containing only commas and whitespace, matches nothing. + Unknown file types are ignored with a warning. + +## Routing behavior + +An operation uses the cache only when all of the following are true: + +- Its operation label is enabled and the policy does not contain `none`. +- The file is immutable. +- Its file type matches `io-cache.whitelist`. +- Its URI path matches `io-cache.whitelist-path`. + +Mutable files always use origin. Examples include snapshot pointers such as +`LATEST` and `EARLIEST`, success markers, consumer/service/tag state, Paimon +temporary files, and mutable Iceberg-compatible metadata such as +`version-hint.text` and `*.metadata.json`. + +The following operations always use origin: + +| Operation | Routing | | --- | --- | -| `meta` | snapshot、schema、manifest、manifest list、manifest sidecar、statistics 等元数据文件。可变元数据仍会被不可变性规则排除。 | -| `global-index` | 表级全局索引,例如 `btree-global-index-.index`。 | -| `bucket-index` | bucket 级索引,例如 `index--0`。 | -| `file-index` | 数据文件附属索引,例如 `data--0.orc.index`。 | -| `data` | 数据文件,以及未匹配其他分类规则的文件。PyPaimon 同时包含其 `STRUCTURED_DATA` 分类。 | -| `*` | 所有文件类型,仍受不可变性和路径白名单约束。 | - -PyPaimon 另支持 `structured-data`,只匹配其 Parquet、ORC、Avro、ROW、Mosaic -结构化数据分类。Java 没有单独的该分类;需要跨 Java/Python 使用相同配置时采用 `data`。 - -白名单规则如下: - -- 同一白名单内部为 OR,不同白名单之间为 AND。 - `io-cache.whitelist=data,file-index` 表示两类文件都允许; - 它们还必须命中 `io-cache.whitelist-path` 才能走缓存。 -- 路径匹配的是 URI 的 path 部分,不匹配 scheme、bucket authority、query 或 fragment。 - 例如 `oss://bucket/db/table/bucket-0/data.orc` 使用 `/db/table/bucket-0/data.orc` 匹配。 -- 路径采用区分大小写的子串匹配,不是 glob 或正则;`bucket-0,bucket-1` 表示任一子串命中。 - 单独的 `*` 才表示所有路径,`bucket-*` 是普通字面子串。 -- 文件类型和路径条目会去掉两侧空白;显式空串或只有逗号、空白时,没有匹配项。 - 未知文件类型会被忽略并记录告警。例如 `manifest` 不是类型值,应使用 `meta`。 - -新 policy 层在未显式设置路径白名单时默认允许全部路径。 -Java 的共享配置常量仍保留旧 JindoCache 的 `bucket,manifest,index` 默认值, -新的 `CachePolicy` 解析逻辑会区分“未设置”与“显式设置”,按本节的 `*` 默认值执行。 - -## 路由条件与固定回退 - -一次操作只有同时满足以下条件才会访问缓存端点: - -```text -policy 未包含 none -AND 当前操作的 meta/read/write 标签已开启 -AND 文件不是可变文件 -AND 命中文件类型白名单 -AND 命中 URI path 白名单 +| Directory listing and recursive listing | Origin | +| Directory creation, deletion and rename | Origin | +| Atomic writes and two-phase or multipart upload/commit operations | Origin | +| Presigned URLs and archive/restore operations | Origin | + +Cache and origin endpoints must refer to the same object-storage namespace and +accept the credentials used by the application. The cache endpoint must support +the operations enabled by its policy. + +### Connection failures + +When a selected cache operation first initializes its backend, Paimon checks +connectivity before returning a stream. A missing object is a valid probe result. + +A recognized connection failure, such as connection refusal, DNS failure or +connection timeout, causes the operation to retry against origin. Paimon emits a +`WARN` log containing `CACHE_POLICY_FALLBACK`, the endpoints, path and full +exception. Subsequent operations on that FileIO instance use origin; a new +instance may try the cache again. + +Missing files, existing files, permission or authentication failures, cancellation, +and errors that cannot be identified as connection failures do not trigger this +fallback. + +Already-open streams are not transparently replayed. A write that fails after +consuming input or persisting partial data may still fail; applications must +handle such failures. When that failure is identified as a connection problem, +subsequent operations on the same FileIO bypass the cache. + +## Examples + +### Cache metadata reads + +A REST token or explicit cache-policy configuration can select immutable metadata +reads and attribute queries: + +```properties +fs.oss.endpoint=cache.example.com +io-cache.origin.endpoint=oss-region.example.com +io-cache.policy=meta,read +io-cache.whitelist=meta ``` -可变文件始终绕过缓存,即使两个白名单都是 `*`。当前规则包含 `LATEST`、`EARLIEST`、 -`_SUCCESS` 及以 `_SUCCESS` 结尾的文件、`consumer-*`、`service-*`、`tag-*`、 -Paimon 生成的临时文件,以及会被覆盖的 Iceberg 兼容元数据:`version-hint.text`、 -`retire-pending`、`*.metadata.json`。 +Data-file reads and all writes use origin. Metadata reads use the cache; mutable +metadata and directory listings still use origin. -以下操作始终使用 origin,以保留目录、命名空间和提交语义: +### Restrict caching to selected data paths -| 操作 | 行为 | -| --- | --- | -| 目录列表、递归列表 | 走 origin,目录可能同时包含多种文件类型。 | -| `delete`、`rename`、`mkdirs` | 走 origin。 | -| 原子写 `tryToWriteAtomic` 及 Python 对应接口 | 直接转发 origin 的实现。 | -| Java `newTwoPhaseOutputStream`、multipart 提交和清理 | 走 origin,上传与提交使用同一类端点;提交时沿现有 REST token 链路取得有效凭证。 | -| Blob presign、Java archive/restore/unarchive | 走 origin,保留底层签名和存储管理能力。 | - -cache delegate 在第一次命中缓存操作时惰性创建,并对该操作的文件路径执行一次 -`exists` 连通性探测(文件尚不存在是有效结果)。这是为了在 Jindo 等后端延迟到 -输出流关闭时才建立网络连接的情况下,仍能在开始写入前发现不可达端点。 - -初始化、探测或打开文件/查询元数据遇到可识别的连接错误时,该操作改用 origin, -并输出一次 `WARN CACHE_POLICY_FALLBACK` 日志,包含操作、路径、两端 endpoint 和 -异常类型,并完整打印异常堆栈及原因链。此后同一个 FileIO 实例持续屏蔽 cache endpoint, -所有操作使用 origin, -序列化也保留这一状态;新建 FileIO 实例才会重新尝试缓存。并发中已经开始的请求可能 -仍在使用 cache delegate,delegate 保留至 FileIO 关闭时统一清理。 - -可回退的错误包括连接拒绝/断开、DNS 解析失败、socket 连接/读取超时,以及 Jindo -原生 `Failed to connect Http service:` 和 Arrow `NETWORK_CONNECTION` 诊断。 -文件不存在、文件已存在、权限/鉴权失败、取消/中断以及无法确认是连接故障的一般 IO -错误均直接上抛,不触发回退或屏蔽。若 origin 重试也失败,最终抛出 origin 异常。 - -回退发生在 FileIO API 调用及 Arrow filesystem adapter 调用的边界,已返回的原生 -输入/输出流不做透明重放。特别是已经开始写入后失败,不能安全地将部分写入或已消费 -的迭代器重放到 origin;Python 格式写入接口仅在开始写入前探测失败时自动改用 origin, -写入途中失败仍报错,并在确认是连接故障时屏蔽后续缓存操作。调用方仍需处理这种写入 -失败。此机制不新增客户端参数,仍按服务端下发的 policy 和 origin endpoint 工作。 -Java `HadoopOptionsProvider` 与 Python Arrow filesystem adapter 使用同一套路径和操作规则。 -Python 的 Vortex reader/writer 通过 `FileIO.for_path(path, operation)` 获取具体后端的 -原生存储参数,同样遵守操作、路径白名单及缓存故障屏蔽状态。Arrow adapter 保留逻辑 URI, -每次操作先解析 `ResolvingFileIO`,再按选中的具体后端转换物理路径。 -fork 后首次使用包装层时会重建锁及两个端点的进程内后端,避免继承其他线程持有的锁; -已经屏蔽缓存的状态继续保留。 - -## 服务端下发示例 - -只缓存指定表的两个 bucket 中的数据和文件索引读取,其余操作使用 origin: - -```json -{ - "fs.oss.endpoint": "cache.example.internal", - "io-cache.origin.endpoint": "oss-cn-hangzhou-internal.aliyuncs.com", - "io-cache.policy": "read", - "io-cache.whitelist": "data,file-index", - "io-cache.whitelist-path": "/db/table/bucket-0/,/db/table/bucket-1/" -} +```properties +fs.oss.endpoint=cache.example.com +io-cache.origin.endpoint=oss-region.example.com +io-cache.policy=read +io-cache.whitelist=data,file-index +io-cache.whitelist-path=/db/table/bucket-0/,/db/table/bucket-1/ ``` -以 `oss://bucket/db/table` 为表路径,上述配置的结果如下: +With table path `oss://bucket/db/table`, this caches data and file-index content +reads under the two listed buckets. Reads in other paths, attribute queries and +writes use origin. -| 操作和路径 | 访问端点 | 原因 | -| --- | --- | --- | -| 读取 `bucket-0/data--0.orc` | cache | `read`、类型和路径均命中。 | -| 读取 `bucket-1/data--0.orc.index` | cache | `file-index` 和路径命中。 | -| 读取 `bucket-2/data--0.orc` | origin | 路径未命中。 | -| 读取 `manifest/manifest--0` | origin | `meta` 文件类型未被允许。 | -| 读取 `snapshot/LATEST` | origin | 可变文件始终绕过。 | -| 查询数据文件大小或是否存在 | origin | 未启用 `meta` 操作标签。 | -| 写入数据文件 | origin | 未启用 `write` 操作标签。 | -| 列目录、删除文件、Java 两阶段上传 | origin | 固定走 origin。 | - -允许所有不可变文件的读取与属性查询时,可以省略两个白名单: - -```json -{ - "fs.oss.endpoint": "cache.example.internal", - "io-cache.origin.endpoint": "oss-cn-hangzhou-internal.aliyuncs.com", - "io-cache.policy": "meta,read" -} +### Override a server policy from the client + +These catalog options override the corresponding token settings: + +```properties +io-cache.policy=meta,read +io-cache.whitelist=meta +io-cache.whitelist-path=* +``` + +To disable cache routing, set this client catalog option: + +```properties +io-cache.policy=none +``` + +Operations then use the effective origin endpoint. + +To force every operation to a particular endpoint, set both endpoint roles to +the same value: + +```properties +dlf.oss-endpoint=oss-region.example.com +io-cache.origin.endpoint=oss-region.example.com ``` -停用缓存时,服务端将 `io-cache.policy` 下发为 `none` 或不下发该参数, -并提供期望使用的 origin endpoint;不需要额外的客户端关闭开关。 +The client endpoint overrides the token endpoint, and Paimon creates a regular +FileIO because the effective cache and origin endpoints are identical. -## 旧 JindoCache 兼容边界 +### Explicit FileIO construction -Java `io-cache.enabled` 仍保留为旧 JindoCache 的客户端开关,默认 `false`,已标记废弃。 -旧实现还依赖其 RPC 地址、policy 和路径白名单;其原有实现继续保留。 -该开关只控制旧 JindoCache,不决定新的 endpoint policy 是否生效, -也不增加 VPC 校验要求。使用新的远端 cache policy 无需开启它。 +REST Catalog automatically applies cache policy when it constructs a +token-backed FileIO. Applications that create FileIO instances directly can use +`CachePolicyFileIO.create` in Java or PyPaimon and supply `fs.oss.endpoint`, +`io-cache.origin.endpoint` and the policy options above. A plain `FileIO.get` +call does not automatically enable endpoint routing. -相关实现: +## Legacy JindoCache configuration -- [Java CachePolicy](../paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicy.java) -- [Java CachePolicyFileIO](../paimon-common/src/main/java/org/apache/paimon/fs/cache/CachePolicyFileIO.java) -- [Java 参数定义](../paimon-api/src/main/java/org/apache/paimon/rest/RESTCatalogOptions.java) -- [PyPaimon CachePolicyFileIO](../paimon-python/pypaimon/filesystem/cache_policy_file_io.py) -- [PyPaimon 参数定义](../paimon-python/pypaimon/common/options/config.py) +Java's deprecated `io-cache.enabled` option controls the legacy JindoCache +integration only. It is not required to enable cache-policy endpoint routing. +Use `io-cache.policy=none` to disable endpoint routing. 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 7b484cf52647..697c0af72075 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 @@ -102,7 +102,9 @@ public class RESTCatalogOptions { ConfigOptions.key("dlf.oss-endpoint") .stringType() .noDefaultValue() - .withDescription("REST Catalog DLF OSS endpoint."); + .withDescription( + "REST Catalog client override for fs.oss.endpoint, taking precedence " + + "over both client and REST token endpoint settings."); public static final ConfigOption DLF_SIGNING_ALGORITHM = ConfigOptions.key("dlf.signing-algorithm") @@ -160,7 +162,8 @@ public class RESTCatalogOptions { .stringType() .noDefaultValue() .withDescription( - "The table-level cache policy provided by the REST server, combined with: meta,read,write." + "The file I/O cache policy. Explicit client settings override the REST token policy. " + + "Combined with: meta,read,write. " + "`meta`: meta cache is enabled for visiting files; " + "`read`: cache is enabled when reading files; " + "`write`: data is also cached when writing files; " 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 index a43b317db9cd..5e36b925adbf 100644 --- 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 @@ -43,6 +43,7 @@ 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; @@ -91,15 +92,16 @@ public static FileIO create(Path path, CatalogContext context) throws IOExceptio CatalogContext originContext = withEndpoint(context, context.options().get(IO_CACHE_ORIGIN_ENDPOINT)); FileIO origin = FileIO.get(path, originContext); - if (!policy.enabled()) { + if (!policy.enabled() || Objects.equals(endpoint(context), endpoint(originContext))) { return origin; } return new CachePolicyFileIO( - path, - policy, - origin, - originContext, - withEndpoint(context, context.options().get("fs.oss.endpoint"))); + 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) { 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 c0ab7ebfd667..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 @@ -34,6 +34,7 @@ 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; @@ -344,11 +345,17 @@ private void refreshToken() { private Map mergeTokenWithCatalogOptions(Map token) { Map newToken = Maps.newLinkedHashMap(token); Options catalogOptions = catalogContext.options(); - // Preserve the server endpoint; use the client endpoint only when the server omits it. + // 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 (!newToken.containsKey("fs.oss.endpoint") - && dlfOssEndpoint != null - && !dlfOssEndpoint.isEmpty()) { + if (!StringUtils.isNullOrWhitespaceOnly(dlfOssEndpoint)) { newToken.put("fs.oss.endpoint", dlfOssEndpoint); } return ImmutableMap.copyOf(newToken); 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 index 8a20821991f6..69ba8e92329c 100644 --- 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 @@ -34,6 +34,7 @@ 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; @@ -150,6 +151,47 @@ void testDisabledPolicyStillAppliesOriginEndpoint() throws Exception { } } + @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}) { 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 d6d6a6b4b556..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 @@ -42,8 +42,10 @@ 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; @@ -58,37 +60,191 @@ class RESTTokenFileIOTest { @Test - void testServerEndpointsCannotBeOverriddenByCatalogOptions() throws IOException { + 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("fs.oss.endpoint", "client-endpoint"); - options.set(DLF_OSS_ENDPOINT, "client-dlf-endpoint"); + 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"); - Map tokenOptions = new HashMap<>(); - tokenOptions.put("test.token", UUID.randomUUID().toString()); - tokenOptions.put(IO_CACHE_POLICY.key(), "read"); - tokenOptions.put("fs.oss.endpoint", "server-cache"); - tokenOptions.put(IO_CACHE_ORIGIN_ENDPOINT.key(), "server-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")); - 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("server-cache"); - assertThat(provider.hadoopOptions(data, "write").get("fs.oss.endpoint")) - .isEqualTo("server-origin"); - assertThat(rest.validToken().token().get("fs.oss.endpoint")).isEqualTo("server-cache"); + 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 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 03cd96c90a0e..7e9b3e6dc6c6 100644 --- a/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py +++ b/paimon-python/pypaimon/catalog/rest/rest_token_file_io.py @@ -206,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 and OssOptions.OSS_ENDPOINT.key() not in token.token: - 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: - """Keep the server endpoint, falling back to the client endpoint when absent.""" + """Apply this client's routing overrides without changing shared credentials.""" merged_token = dict(token) - if self.catalog_options and OssOptions.OSS_ENDPOINT.key() not in merged_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) @@ -418,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) @@ -441,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/options/config.py b/paimon-python/pypaimon/common/options/config.py index f89c7078d732..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( @@ -180,7 +181,7 @@ class CatalogOptions: .string_type() .no_default_value() .with_description( - "The table-level cache policy provided by the REST server, combined with: " + "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." ) diff --git a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py index 18b4db35eb3a..572b205a6471 100644 --- a/paimon-python/pypaimon/filesystem/cache_policy_file_io.py +++ b/paimon-python/pypaimon/filesystem/cache_policy_file_io.py @@ -89,7 +89,8 @@ def create(cls, path: str, catalog_options: Options, file_io_factory=None) -> Fi origin_options = cls._origin_options(catalog_options) origin_file_io = file_io_factory(path, origin_options) - if not cls._cache_enabled(catalog_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() diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index 9ed07f05a93f..d99dd4e478ea 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -198,6 +198,25 @@ def _options(**overrides): 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 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 1837dfcd940b..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 @@ -667,11 +667,12 @@ def test_pickle_serialization(self): with open(expected_path, 'rb') as f: self.assertEqual(f.read(), test_content) - def test_server_endpoint_takes_precedence_over_dlf_endpoint(self): - """Use the DLF endpoint only when the server omits the standard endpoint.""" + 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'): @@ -691,14 +692,13 @@ def test_server_endpoint_takes_precedence_over_dlf_endpoint(self): # Merge token with catalog options merged_token = file_io._merge_token_with_catalog_options(token) - # Preserve the server endpoint even when a client DLF endpoint is configured. self.assertEqual( merged_token[OssOptions.OSS_ENDPOINT.key()], - token[OssOptions.OSS_ENDPOINT.key()], + dlf_oss_endpoint, ) self.assertEqual( - token[OssOptions.OSS_ENDPOINT.key()], - file_io._merged_options(RESTToken(merged_token, 0)).get(OssOptions.OSS_ENDPOINT), + dlf_oss_endpoint, + file_io._merged_options(RESTToken(token, 0)).get(OssOptions.OSS_ENDPOINT), ) # Verify other token properties are preserved self.assertEqual( @@ -716,24 +716,126 @@ def test_server_endpoint_takes_precedence_over_dlf_endpoint(self): "Other token properties should be preserved" ) - def test_server_cache_settings_take_precedence(self): + 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) - self.assertEqual(server_options, merged_token) - options = file_io._merged_options(RESTToken(merged_token, 0)) - self.assertEqual("server-cache", options.get(OssOptions.OSS_ENDPOINT)) - self.assertEqual( - "server-origin", options.get(CatalogOptions.IO_CACHE_ORIGIN_ENDPOINT)) + 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( From 2388f41cfe582fac1bfe88e6dad5d97932f78413 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Sun, 22 Nov 2026 23:02:15 +0800 Subject: [PATCH 19/21] Remove cache policy guide from the source repository --- doc/cache-policy.md | 236 -------------------------------------------- 1 file changed, 236 deletions(-) delete mode 100644 doc/cache-policy.md diff --git a/doc/cache-policy.md b/doc/cache-policy.md deleted file mode 100644 index de8ee8e0b502..000000000000 --- a/doc/cache-policy.md +++ /dev/null @@ -1,236 +0,0 @@ - - -# Cache policy - -Cache policy routes object-storage operations through a cache endpoint or directly -to the origin endpoint. Java and PyPaimon use the same operation, file-type and -path selection rules. It is independent of the local block cache and does not -change table storage or read semantics. - -REST Catalog can provide credentials, endpoints and cache settings in a table -token. Applications can override endpoint and cache settings in their catalog -configuration. - -## Configuration - -| Option | Default | Description | -| --- | --- | --- | -| `fs.oss.endpoint` | Supplied by the storage configuration or REST token | Endpoint used for operations selected by the cache policy. | -| `dlf.oss-endpoint` | Unset | REST Catalog client override for `fs.oss.endpoint`. A nonblank value has the highest endpoint priority. | -| `io-cache.origin.endpoint` | The effective `fs.oss.endpoint` | Origin endpoint for operations that bypass the cache. An unset, empty or whitespace-only value uses `fs.oss.endpoint`. | -| `io-cache.policy` | Unset; no operations use the cache | Comma-separated operation labels: `meta`, `read`, `write`, or `none`. | -| `io-cache.whitelist` | `*` | Comma-separated file types allowed to use the cache. | -| `io-cache.whitelist-path` | `*` | Comma-separated URI path substrings allowed to use the cache. | - -### Client overrides - -For REST token configuration, endpoint priority is: - -1. A nonblank client `dlf.oss-endpoint`. -2. An explicitly configured client `fs.oss.endpoint`. -3. The token's `fs.oss.endpoint`. -4. The underlying storage configuration when no endpoint is provided above. - -Every explicitly configured client `io-cache.*` option takes precedence over the -same option in the token, including `io-cache.origin.endpoint`, policy and both -whitelists. Unspecified options retain the token's values. Explicit empty values -are preserved: an empty policy or whitelist does not fall back to the token's -value. - -These overrides apply to both FileIO operations and routing settings exposed to -native readers. They continue to apply after token refresh. Object-storage -credentials are supplied by the REST token. - -Cache and origin settings have separate roles. Overriding `fs.oss.endpoint` -selects the endpoint for cache-eligible operations; it does not replace an -explicit `io-cache.origin.endpoint`. - -After configuration is merged, if cache and origin use the same endpoint, Paimon -initializes a regular FileIO directly. No cache-policy wrapper or cache -connectivity probe is needed. This also applies when the origin endpoint is -omitted and therefore inherits the cache endpoint. - -### Operation labels - -| Label | Operations | -| --- | --- | -| `read` | File-content reads. | -| `write` | File-content writes supported by the cache endpoint. | -| `meta` | File attributes, existence, length and directory-status queries, including corresponding batch operations. | -| `none` | Disable all cache operations, even when combined with other labels. | - -Use lowercase labels separated by commas. For example, `meta,read` enables -attribute queries and content reads. An unset or empty policy sends all operations -to origin. Enabling an operation does not bypass file-type, path or immutability -requirements. - -The `meta` operation label and `meta` file type serve different purposes. With -`io-cache.policy=meta` and `io-cache.whitelist=data`, data-file attribute queries -can use the cache, while data-file content reads use origin. - -### File types and paths - -| File-type value | Files | -| --- | --- | -| `meta` | Immutable snapshot, schema, manifest, statistics and other table metadata files. | -| `global-index` | Table-level global index files. | -| `bucket-index` | Bucket-level index files. | -| `file-index` | Index files associated with individual data files. | -| `data` | Data files and files not assigned to another category. | -| `*` | All file types, subject to the path and immutability rules. | - -PyPaimon also supports `structured-data` for its structured data-file category, -including Parquet, ORC, Avro, ROW and Mosaic. Use `data` for a shared -Java/Python configuration; it includes this category in PyPaimon. - -Whitelist rules: - -- Entries within one whitelist are alternatives. The file-type and path - whitelists must both match. -- Path matching uses the URI path, excluding its scheme, bucket authority, query - and fragment. For `oss://bucket/db/table/bucket-0/data.orc`, the matched path is - `/db/table/bucket-0/data.orc`. -- Path entries are case-sensitive substrings, not glob patterns or regular - expressions. A standalone `*` matches all paths; `bucket-*` is a literal - substring. -- Leading and trailing whitespace around entries is ignored. An explicit empty - whitelist, or a list containing only commas and whitespace, matches nothing. - Unknown file types are ignored with a warning. - -## Routing behavior - -An operation uses the cache only when all of the following are true: - -- Its operation label is enabled and the policy does not contain `none`. -- The file is immutable. -- Its file type matches `io-cache.whitelist`. -- Its URI path matches `io-cache.whitelist-path`. - -Mutable files always use origin. Examples include snapshot pointers such as -`LATEST` and `EARLIEST`, success markers, consumer/service/tag state, Paimon -temporary files, and mutable Iceberg-compatible metadata such as -`version-hint.text` and `*.metadata.json`. - -The following operations always use origin: - -| Operation | Routing | -| --- | --- | -| Directory listing and recursive listing | Origin | -| Directory creation, deletion and rename | Origin | -| Atomic writes and two-phase or multipart upload/commit operations | Origin | -| Presigned URLs and archive/restore operations | Origin | - -Cache and origin endpoints must refer to the same object-storage namespace and -accept the credentials used by the application. The cache endpoint must support -the operations enabled by its policy. - -### Connection failures - -When a selected cache operation first initializes its backend, Paimon checks -connectivity before returning a stream. A missing object is a valid probe result. - -A recognized connection failure, such as connection refusal, DNS failure or -connection timeout, causes the operation to retry against origin. Paimon emits a -`WARN` log containing `CACHE_POLICY_FALLBACK`, the endpoints, path and full -exception. Subsequent operations on that FileIO instance use origin; a new -instance may try the cache again. - -Missing files, existing files, permission or authentication failures, cancellation, -and errors that cannot be identified as connection failures do not trigger this -fallback. - -Already-open streams are not transparently replayed. A write that fails after -consuming input or persisting partial data may still fail; applications must -handle such failures. When that failure is identified as a connection problem, -subsequent operations on the same FileIO bypass the cache. - -## Examples - -### Cache metadata reads - -A REST token or explicit cache-policy configuration can select immutable metadata -reads and attribute queries: - -```properties -fs.oss.endpoint=cache.example.com -io-cache.origin.endpoint=oss-region.example.com -io-cache.policy=meta,read -io-cache.whitelist=meta -``` - -Data-file reads and all writes use origin. Metadata reads use the cache; mutable -metadata and directory listings still use origin. - -### Restrict caching to selected data paths - -```properties -fs.oss.endpoint=cache.example.com -io-cache.origin.endpoint=oss-region.example.com -io-cache.policy=read -io-cache.whitelist=data,file-index -io-cache.whitelist-path=/db/table/bucket-0/,/db/table/bucket-1/ -``` - -With table path `oss://bucket/db/table`, this caches data and file-index content -reads under the two listed buckets. Reads in other paths, attribute queries and -writes use origin. - -### Override a server policy from the client - -These catalog options override the corresponding token settings: - -```properties -io-cache.policy=meta,read -io-cache.whitelist=meta -io-cache.whitelist-path=* -``` - -To disable cache routing, set this client catalog option: - -```properties -io-cache.policy=none -``` - -Operations then use the effective origin endpoint. - -To force every operation to a particular endpoint, set both endpoint roles to -the same value: - -```properties -dlf.oss-endpoint=oss-region.example.com -io-cache.origin.endpoint=oss-region.example.com -``` - -The client endpoint overrides the token endpoint, and Paimon creates a regular -FileIO because the effective cache and origin endpoints are identical. - -### Explicit FileIO construction - -REST Catalog automatically applies cache policy when it constructs a -token-backed FileIO. Applications that create FileIO instances directly can use -`CachePolicyFileIO.create` in Java or PyPaimon and supply `fs.oss.endpoint`, -`io-cache.origin.endpoint` and the policy options above. A plain `FileIO.get` -call does not automatically enable endpoint routing. - -## Legacy JindoCache configuration - -Java's deprecated `io-cache.enabled` option controls the legacy JindoCache -integration only. It is not required to enable cache-policy endpoint routing. -Use `io-cache.policy=none` to disable endpoint routing. From 0f98c40eef8baaed4f1b1e2924014c0e3f0145f1 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Mon, 23 Nov 2026 11:45:34 +0800 Subject: [PATCH 20/21] Preserve existing REST catalog option descriptions and annotations --- .../paimon/rest/RESTCatalogOptions.java | 23 ++++--------------- 1 file changed, 4 insertions(+), 19 deletions(-) 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 697c0af72075..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 @@ -102,9 +102,7 @@ public class RESTCatalogOptions { ConfigOptions.key("dlf.oss-endpoint") .stringType() .noDefaultValue() - .withDescription( - "REST Catalog client override for fs.oss.endpoint, taking precedence " - + "over both client and REST token endpoint settings."); + .withDescription("REST Catalog DLF OSS endpoint."); public static final ConfigOption DLF_SIGNING_ALGORITHM = ConfigOptions.key("dlf.signing-algorithm") @@ -116,20 +114,12 @@ public class RESTCatalogOptions { + "'openapi' (the earlier ROA HMAC-SHA1 scheme). " + "If not set, will be automatically selected based on endpoint host."); - /** - * Legacy JindoCache switch, retained for compatibility. Remote cache endpoint routing does not - * use this option. - * - * @deprecated The JindoCache integration is deprecated. Use the REST cache policy instead. - */ - @Deprecated public static final ConfigOption IO_CACHE_ENABLED = ConfigOptions.key("io-cache.enabled") .booleanType() .defaultValue(false) .withDescription( - "Deprecated: enables only the legacy JindoCache integration in JindoFileIO. " - + "This option does not control REST cache endpoint routing."); + "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") @@ -151,19 +141,14 @@ public class RESTCatalogOptions { .stringType() .defaultValue("bucket,manifest,index") .withDescription( - "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. " - + "REST cache endpoint routing defaults to * when this option is absent; " - + "the deprecated JindoCache integration retains its original default."); + "Cache is only applied to paths which contain the specified pattern, and * means all paths."); public static final ConfigOption IO_CACHE_POLICY = ConfigOptions.key("io-cache.policy") .stringType() .noDefaultValue() .withDescription( - "The file I/O cache policy. Explicit client settings override the REST token policy. " - + "Combined with: meta,read,write. " + "The table-level cache policy provided by the REST server, combined with: meta,read,write." + "`meta`: meta cache is enabled for visiting files; " + "`read`: cache is enabled when reading files; " + "`write`: data is also cached when writing files; " From e7ffe6ed29560d713f80cee104db60942f27d712 Mon Sep 17 00:00:00 2001 From: "shunyang.ysy" Date: Mon, 23 Nov 2026 20:00:50 +0800 Subject: [PATCH 21/21] Adapt cache policy writer regression to current Vortex API --- .../tests/cache_policy_file_io_test.py | 41 +++++++++++++++---- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py index d99dd4e478ea..b05a7b1b907e 100644 --- a/paimon-python/pypaimon/tests/cache_policy_file_io_test.py +++ b/paimon-python/pypaimon/tests/cache_policy_file_io_test.py @@ -248,16 +248,39 @@ def test_vortex_native_options_follow_operation_path_and_disabled_state(self): 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 - fake = types.ModuleType("vortex") - fake.array = MagicMock(return_value="array") - fake.store = types.SimpleNamespace(from_url=MagicMock()) - io = CachePolicyFileIO.create( - TABLE_ROOT, _options(**{"io-cache.policy": "read"}), _RecordingFactory()) - with patch.dict("sys.modules", {"vortex": fake}): - write_vortex_file(io, TABLE_ROOT + "/bucket-0/data-a.vortex", []) - self.assertIn("origin-endpoint", fake.store.from_url.call_args.kwargs["endpoint"]) - fake.store.from_url.return_value.write.assert_called_once_with("array") + 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