mchades commented on code in PR #14407:
URL: https://github.com/apache/gravitino/pull/14407#discussion_r4676017314
##########
catalogs/catalog-fileset/src/main/java/org/apache/gravitino/catalog/fileset/FilesetCatalogOperations.java:
##########
@@ -1481,17 +1790,183 @@ FileSystem getFileSystemWithCache(Path path,
Map<String, String> conf) {
FileSystemProvider provider = fileSystemProvidersMap.get(scheme);
String authority =
provider != null ? provider.getFullAuthority(path, conf) :
path.toUri().getAuthority();
- return fileSystemCache.get(
- new FileSystemCacheKey(scheme, authority),
- cacheKey -> {
- try {
+ // Resolving the settings and creating the file system share one
connection timeout.
+ long deadlineNanos =
+ System.nanoTime() +
TimeUnit.SECONDS.toNanos(connectionTimeoutSeconds(conf));
+ // Only an HDFS file system logs in with the settings of the
configuration, see
+ // createFileSystem.
+ String fsScheme = scheme != null ? scheme :
defaultFileSystemProvider.scheme();
+ if (!SCHEME_HDFS.equals(fsScheme)) {
+ return cachedFileSystem(
+ path,
+ conf,
+ new FileSystemCacheKey(scheme, authority, Collections.emptyMap()),
+ null,
+ deadlineNanos);
+ }
+
+ FileSystem fs = getHdfsFileSystemWithCache(path, conf, scheme, authority,
deadlineNanos);
+ if (fs == null) {
+ // The config.resources files changed after their login settings were
cached.
+
sharedHdfsLoginSettingsCache.synchronous().invalidate(ConfKey.withoutIdentifier(conf));
+ hdfsLoginSettingsCache.synchronous().invalidate(ConfKey.of(conf));
+ fs = getHdfsFileSystemWithCache(path, conf, scheme, authority,
deadlineNanos);
+ }
+ if (fs == null) {
+ throw new GravitinoRuntimeException(
+ "The login settings in config.resources changed while getting
FileSystem for fileset:"
+ + " path: %s",
+ path);
+ }
+ return fs;
+ }
+
+ // Returns null if the config.resources files no longer resolve to the
cached login settings: a
+ // file system is cached only under the settings of the configuration it is
created with.
+ @Nullable
+ private FileSystem getHdfsFileSystemWithCache(
+ Path path,
+ Map<String, String> conf,
+ @Nullable String scheme,
+ @Nullable String authority,
+ long deadlineNanos) {
+ Map<String, String> settings = hdfsLoginSettings(path, conf,
deadlineNanos);
+ return cachedFileSystem(
+ path, conf, new FileSystemCacheKey(scheme, authority, settings),
settings, deadlineNanos);
+ }
+
+ // A miss creates the file system on the pool, under the deadline of this
caller. Callers that
+ // find it being created wait for it until their own deadlines.
+ @Nullable
+ private FileSystem cachedFileSystem(
+ Path path,
+ Map<String, String> conf,
+ FileSystemCacheKey key,
+ @Nullable Map<String, String> expectedSettings,
+ long deadlineNanos) {
+ // A null result caches nothing; the cache statistics count it as a failed
load.
+ try {
+ return TimedTask.awaitEntry(
+ fileSystemCache,
+ key,
+ (cacheKey, executor) -> {
+ fileSystemProvider(path);
+ // The creation may outlive this caller, whose configuration is
not copied on a hit.
+ Map<String, String> keptConf = new HashMap<>(conf);
// Create the file system for the user it is cached under.
- return getFileSystem(path, conf, cacheKey.currentUser);
- } catch (IOException e) {
- throw new GravitinoRuntimeException(
- e, "Failed to get FileSystem for fileset: path: %s", path);
- }
- });
+ return TimedTask.start(
+ fileSystemExecutor,
+ () -> getFileSystem(path, keptConf, cacheKey.currentUser,
expectedSettings),
+ deadlineNanos);
+ },
+ deadlineNanos);
+ } catch (TimeoutException
+ | InterruptedException
+ | RejectedExecutionException
+ | ExecutionException e) {
+ throw new GravitinoRuntimeException(
+ fileSystemFailure(path, conf, e), "Failed to get FileSystem for
fileset: path: %s", path);
+ }
+ }
+
+ private Map<String, String> hdfsLoginSettings(
+ Path path, Map<String, String> conf, long deadlineNanos) {
+ // Settings resolved for the shared entry that expand variables, cached
for this configuration
+ // after the shared entry is loaded.
+ AtomicReference<Map<String, String>> resolved = new AtomicReference<>();
+ Optional<Map<String, String>> shared =
+ awaitLoginSettings(
+ path,
+ conf,
+ sharedHdfsLoginSettingsCache,
+ ConfKey.withoutIdentifier(conf),
+ keptConf -> {
+ HdfsLogin login = resolveHdfsLogin(keptConf);
+ if (login.expandsVariables) {
+ resolved.set(login.settings);
+ return Optional.empty();
+ }
+ return Optional.of(login.settings);
+ },
+ deadlineNanos);
+ if (shared.isPresent()) {
+ return shared.get();
+ }
+ if (resolved.get() != null) {
+ hdfsLoginSettingsCache.put(
+ ConfKey.of(conf).copy(),
CompletableFuture.completedFuture(resolved.get()));
Review Comment:
**[P2] Preserve a newer login-settings cache entry**
This `put()` can overwrite settings that a concurrent lookup has already
resolved for the same full key. If `config.resources` changed after the shared
load read it, this gives the older settings a fresh TTL. A warm filesystem hit
then skips the creation-time consistency check. Can this populate only an
absent entry and use the value that wins publication?
##########
catalogs/hadoop-common/src/main/java/org/apache/gravitino/catalog/hadoop/fs/HDFSFileSystemProxy.java:
##########
@@ -195,15 +480,23 @@ private UserGroupInformation initKerberosUgi(
.checkIntervalSec(kerberosConfig.getCheckIntervalSec())
.krb5Conf(Constants.HADOOP_KRB5_CONF,
Constants.SECURITY_KRB5_ENV)
.build();
- String keytabPath =
- String.format(GRAVITINO_KEYTAB_FORMAT,
properties.getOrDefault(GRAVITINO_ID_KEY, ""));
- File keytabFile =
- KerberosAuthUtils.saveKeytabFromUri(
- kerberosConfig.getKeytab(),
- new File(keytabPath),
- kerberosConfig.getFetchTimeoutSec(),
- false,
- configuration);
+ // One file for each open proxy: another proxy for the same entity would
rewrite a shared
+ // file while this one still renews its ticket from it. close() deletes
it.
+ String identifier = properties.getOrDefault(GRAVITINO_ID_KEY, "");
+ // The JDK never reads the file fetched into, so its name is not reused.
It is recorded
+ // before the fetch, so that close() also deletes what a failed fetch
leaves behind.
+ File destination =
+ new File(
+ String.format(
+ GRAVITINO_KEYTAB_FORMAT,
+ identifier + "-" + KeytabNames.token() + "-fetch-" +
UUID.randomUUID()));
Review Comment:
**[P2] Handle stale staged keytabs after an unclean restart**
`saveKeytabFromUri()` replaced the old stable destination on the next login.
The new per-JVM names leave downloaded copies behind if the process exits
before cleanup. On a persistent working directory, repeated unclean restarts
can accumulate copies for the same fileset. What will reclaim those copies
while preserving files owned by running processes?
##########
catalogs/catalog-fileset/src/test/java/org/apache/gravitino/catalog/fileset/TestFilesetCatalogOperations.java:
##########
@@ -2815,6 +2930,1423 @@ private static void
startPoolThreadsAs(FilesetCatalogOperations ops, String user
new UserPrincipal(user), () ->
ops.fileSystemExecutor.prestartAllCoreThreads());
}
+ @ParameterizedTest
+ @ValueSource(strings = {BUILTIN_HDFS_FS_PROVIDER, BUILTIN_LOCAL_FS_PROVIDER})
+ public void testFileSystemCacheSeparatesAuthenticationSettings(String
defaultProvider)
+ throws Exception {
+ File resourceA = new File(UNFORMALIZED_TEST_ROOT_PATH,
"cache_key/a-site.xml");
+ File resourceB = new File(UNFORMALIZED_TEST_ROOT_PATH,
"cache_key/b-site.xml");
+ FileUtils.writeStringToFile(resourceA, "<configuration/>",
StandardCharsets.UTF_8);
+ FileUtils.writeStringToFile(resourceB, "<configuration/>",
StandardCharsets.UTF_8);
+ // Listed here, not read from the code under test, so that dropping a
setting there fails this
+ // test.
+ Map<String, String[]> settings =
+ ImmutableMap.<String, String[]>builder()
+ .put(AuthenticationConfig.AUTH_TYPE_KEY, new String[] {"simple",
"kerberos"})
+ .put(HADOOP_SECURITY_AUTHENTICATION, new String[] {"simple",
"kerberos"})
+ .put(
+ GRAVITINO_BYPASS + HADOOP_SECURITY_AUTHENTICATION,
+ new String[] {"simple", "kerberos"})
+ .put(AuthenticationConfig.IMPERSONATION_ENABLE_KEY, new String[]
{"false", "true"})
+ .put(
+ CONFIG_RESOURCES,
+ new String[] {resourceA.getAbsolutePath(),
resourceB.getAbsolutePath()})
+ .build();
+ Map<String, String[]> kerberosSettings = kerberosOnlySettings();
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(defaultProvider)) {
+ for (Path path : hdfsCacheKeyPaths(defaultProvider)) {
+ assertSettingsSeparateFileSystems(ops, path, ImmutableMap.of(),
settings);
+ assertSettingsSeparateFileSystems(
+ ops,
+ path,
+ ImmutableMap.of(AuthenticationConfig.AUTH_TYPE_KEY, "kerberos"),
+ kerberosSettings);
+ }
+ }
+ }
+
+ @Test
+ public void
testFileSystemCacheIgnoresKerberosSettingsWithSimpleAuthentication()
+ throws Exception {
+ Map<String, String> simple =
ImmutableMap.of(AuthenticationConfig.AUTH_TYPE_KEY, "simple");
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ for (Map.Entry<String, String[]> setting :
kerberosOnlySettings().entrySet()) {
+ Assertions.assertSame(
+ ops.getFileSystemWithCache(
+ path, withSetting(simple, setting.getKey(),
setting.getValue()[0])),
+ ops.getFileSystemWithCache(
+ path, withSetting(simple, setting.getKey(),
setting.getValue()[1])),
+ setting.getKey());
+ }
+ }
+ }
+
+ // These decide the login only with Kerberos authentication.
+ private static Map<String, String[]> kerberosOnlySettings() {
+ return ImmutableMap.<String, String[]>builder()
+ .put(KerberosConfig.PRINCIPAL_KEY, new String[] {"[email protected]",
"[email protected]"})
+ .put(KerberosConfig.KEY_TAB_URI_KEY, new String[] {"file:///a.keytab",
"file:///b.keytab"})
+ .put(HADOOP_SECURITY_PRINCIPAL, new String[] {"[email protected]",
"[email protected]"})
+ .put(GRAVITINO_BYPASS + HADOOP_SECURITY_PRINCIPAL, new String[]
{"[email protected]", "[email protected]"})
+ .put(HADOOP_SECURITY_KEYTAB, new String[] {"/a.keytab", "/b.keytab"})
+ .put(GRAVITINO_BYPASS + HADOOP_SECURITY_KEYTAB, new String[]
{"/a.keytab", "/b.keytab"})
+ .put(HADOOP_KRB5_CONF, new String[] {"/a-krb5.conf", "/b-krb5.conf"})
+ .put(GRAVITINO_BYPASS + HADOOP_KRB5_CONF, new String[]
{"/a-krb5.conf", "/b-krb5.conf"})
+ .build();
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {BUILTIN_HDFS_FS_PROVIDER, BUILTIN_LOCAL_FS_PROVIDER})
+ public void testFileSystemCacheSeparatesResolvedLoginSettings(String
defaultProvider)
+ throws Exception {
+ File resource = new File(UNFORMALIZED_TEST_ROOT_PATH,
"cache_key/shared-site.xml");
+ FileUtils.writeStringToFile(
+ resource,
+ "<configuration><property><name>"
+ + HADOOP_SECURITY_PRINCIPAL
+ +
"</name><value>svc@${tenant.realm}</value></property></configuration>",
+ StandardCharsets.UTF_8);
+ Map<String, String> first =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ CONFIG_RESOURCES,
+ resource.getAbsolutePath(),
+ GRAVITINO_BYPASS + "tenant.realm",
+ "A.COM");
+ Map<String, String> second =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ CONFIG_RESOURCES,
+ resource.getAbsolutePath(),
+ GRAVITINO_BYPASS + "tenant.realm",
+ "B.COM");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(defaultProvider)) {
+ for (Path path : hdfsCacheKeyPaths(defaultProvider)) {
+ Assertions.assertNotSame(
+ ops.getFileSystemWithCache(path, first),
ops.getFileSystemWithCache(path, second));
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {BUILTIN_HDFS_FS_PROVIDER, BUILTIN_LOCAL_FS_PROVIDER})
+ public void
testFileSystemCacheResolvesPrincipalWithKerberosAuthentication(String
defaultProvider)
+ throws Exception {
+ // The proxy switches Hadoop to Kerberos authentication before it expands
the principal.
+ Map<String, String> first =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ HADOOP_SECURITY_PRINCIPAL,
+ "svc-${" + HADOOP_SECURITY_AUTHENTICATION + "}@EXAMPLE.COM");
+ Map<String, String> second =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ HADOOP_SECURITY_PRINCIPAL,
+ "[email protected]");
+ // What the first principal expands to.
+ Map<String, String> expanded =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ HADOOP_SECURITY_PRINCIPAL,
+ "[email protected]");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(defaultProvider)) {
+ for (Path path : hdfsCacheKeyPaths(defaultProvider)) {
+ FileSystem fs = ops.getFileSystemWithCache(path, first);
+ Assertions.assertNotSame(fs, ops.getFileSystemWithCache(path, second));
+ Assertions.assertSame(fs, ops.getFileSystemWithCache(path, expanded));
+ }
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheIgnoresAuthenticationSettingsOfNonHdfsPaths()
throws Exception {
+ Map<String, String> simple =
ImmutableMap.of(AuthenticationConfig.AUTH_TYPE_KEY, "simple");
+ Map<String, String> kerberos =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ KerberosConfig.PRINCIPAL_KEY,
+ "[email protected]");
+
+ // Only HDFS file systems log in with these settings. The default provider
here is local.
+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store,
secretManager)) {
+ ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"),
FILESET_PROPERTIES_METADATA);
+ for (Path path :
+ new Path[] {new Path(TEST_ROOT_PATH, "cache_key"), new
Path("/tmp/cache_key")}) {
+ Assertions.assertSame(
+ ops.getFileSystemWithCache(path, simple),
ops.getFileSystemWithCache(path, kerberos));
+ }
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheResolvesLoginSettingsOncePerConfiguration()
throws Exception {
+ Map<String, String> conf =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ KerberosConfig.PRINCIPAL_KEY,
+ "[email protected]");
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // Each request merges its own copy of the configuration.
+ FileSystem fs = ops.getFileSystemWithCache(path, new HashMap<>(conf));
+ // Once for the settings, and once for the configuration the new file
system logs in with.
+ Mockito.verify(ops, Mockito.times(2)).resolveHdfsLogin(any());
+ Mockito.clearInvocations(ops);
+ Assertions.assertSame(fs, ops.getFileSystemWithCache(path, new
HashMap<>(conf)));
+ // Resolving parses XML, so the second lookup must not do it again.
+ Mockito.verify(ops, never()).resolveHdfsLogin(any());
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheSharesLoginSettingsAcrossFilesets() throws
Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ FileSystem fs = ops.getFileSystemWithCache(path,
filesetConf("[email protected]", "1"));
+ Mockito.clearInvocations(ops);
+ // The configurations of filesets that inherit the same settings differ
in the identifier.
+ Assertions.assertSame(
+ fs, ops.getFileSystemWithCache(path, filesetConf("[email protected]",
"2")));
+ Mockito.verify(ops, never()).resolveHdfsLogin(any());
+ }
+ }
+
+ @Test
+ public void
testFileSystemCacheResolvesLoginSettingsOfEachFilesetThatExpandsVariables()
+ throws Exception {
+ String principal = "svc-${" + StringIdentifier.ID_KEY + "}@EXAMPLE.COM";
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ FileSystem first = ops.getFileSystemWithCache(path,
filesetConf(principal, "1"));
+ // Once for the settings, and once for the configuration the new file
system logs in with.
+ Mockito.verify(ops, Mockito.times(2)).resolveHdfsLogin(any());
+ FileSystem second = ops.getFileSystemWithCache(path,
filesetConf(principal, "2"));
+ Assertions.assertNotSame(first, second);
+ ArgumentCaptor<Configuration> loginConf =
ArgumentCaptor.forClass(Configuration.class);
+ Mockito.verify(ops, Mockito.times(2))
+ .createFileSystem(any(), any(), any(), any(), any(),
loginConf.capture());
+ Assertions.assertEquals(
+ "[email protected]",
loginConf.getValue().get(HADOOP_SECURITY_PRINCIPAL));
+
+ // The settings of each fileset are cached under its whole configuration.
+ Mockito.clearInvocations(ops);
+ Assertions.assertSame(first, ops.getFileSystemWithCache(path,
filesetConf(principal, "1")));
+ Assertions.assertSame(second, ops.getFileSystemWithCache(path,
filesetConf(principal, "2")));
+ Mockito.verify(ops, never()).resolveHdfsLogin(any());
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"kerberos", "KERBEROS"})
+ void
testFileSystemCacheResolvesAuthenticationOfEachFilesetThatExpandsIt(String
kerberosType)
+ throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // The authentication type of each fileset is its identifier.
+ FileSystem kerberos =
+ ops.getFileSystemWithCache(path,
identifierAuthenticationConf(kerberosType));
+ Assertions.assertNotSame(
+ kerberos, ops.getFileSystemWithCache(path,
identifierAuthenticationConf("simple")));
+ }
+ }
+
+ @Test
+ public void
testFileSystemCacheResolvesLoginSettingsUnderTheConnectionTimeout() throws
Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ Map<String, String> conf =
+ withSetting(
+ filesetConf("[email protected]", "1"),
FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "1");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // As if reading the config.resources files hung while the settings were
resolved.
+ AtomicInteger resolutions = new AtomicInteger();
+ Mockito.doAnswer(
+ invocation -> {
+ if (resolutions.getAndIncrement() == 0) {
+ Thread.sleep(10_000);
+ }
+ return invocation.callRealMethod();
+ })
+ .when(ops)
+ .resolveHdfsLogin(any());
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class, () ->
ops.getFileSystemWithCache(path, conf));
+ // The settings step timed out, not the file system step after it.
+ Assertions.assertTrue(
+ e.getMessage().contains("Failed to resolve the login settings"),
e.getMessage());
+ Assertions.assertInstanceOf(TimeoutException.class, e.getCause());
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheGivesALookupOneConnectionTimeout() throws
Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ Map<String, String> conf =
+ withSetting(
+ filesetConf("[email protected]", "1"),
FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "2");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // Resolving the settings takes half the timeout, and creating the file
system takes more
+ // than the other half, though less than a whole timeout.
+ AtomicInteger resolutions = new AtomicInteger();
+ Mockito.doAnswer(
+ invocation -> {
+ if (resolutions.getAndIncrement() == 0) {
+ Thread.sleep(1_000);
+ }
+ return invocation.callRealMethod();
+ })
+ .when(ops)
+ .resolveHdfsLogin(any());
+ Mockito.doAnswer(
+ invocation -> {
+ Thread.sleep(1_500);
+ return Mockito.mock(FileSystem.class);
+ })
+ .when(ops)
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class, () ->
ops.getFileSystemWithCache(path, conf));
+ // Creating the file system timed out, with the time left after
resolving the settings.
+ Assertions.assertFalse(
+ e.getMessage().contains("Failed to resolve the login settings"),
e.getMessage());
+ Assertions.assertTrue(
+
Throwables.getCausalChain(e).stream().anyMatch(TimeoutException.class::isInstance));
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheWrapsAnErrorFromResolvingLoginSettings()
throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ NoClassDefFoundError error = new
NoClassDefFoundError("org/example/Missing");
+ Mockito.doThrow(error).when(ops).resolveHdfsLogin(any());
+ // As when creating the file system, so that callers that catch
exceptions handle it.
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> ops.getFileSystemWithCache(path,
filesetConf("[email protected]", "1")));
+ Assertions.assertSame(error, e.getCause());
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void
testFileSystemCacheReportsItsOwnPathWhenSharedLoginSettingsFail() throws
Exception {
+ Path first = new Path("hdfs://localhost:8020/fileset_1");
+ Path second = new Path("hdfs://localhost:8020/fileset_2");
+ IllegalArgumentException failure = new IllegalArgumentException("bad
principal");
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService callers = Executors.newFixedThreadPool(2);
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ Mockito.doAnswer(
+ invocation -> {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ throw failure;
+ })
+ .when(ops)
+ .resolveHdfsLogin(any());
+ try {
+ // The two filesets share the settings, and the second waits for the
first to resolve them.
+ Future<GravitinoRuntimeException> firstFailure =
+ callers.submit(
+ () ->
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> ops.getFileSystemWithCache(first,
filesetConf("[email protected]", "1"))));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ AtomicReference<Thread> secondCaller = new AtomicReference<>();
+ Future<GravitinoRuntimeException> secondFailure =
+ callers.submit(
+ () -> {
+ secondCaller.set(Thread.currentThread());
+ return Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> ops.getFileSystemWithCache(second,
filesetConf("[email protected]", "2")));
+ });
+ awaitTimedWaiting(secondCaller);
+ release.countDown();
+ GravitinoRuntimeException e = secondFailure.get(10, TimeUnit.SECONDS);
+ GravitinoRuntimeException other = firstFailure.get(10,
TimeUnit.SECONDS);
+ // The second fileset resolves them once more with its own
configuration.
+ Mockito.verify(ops, Mockito.times(2)).resolveHdfsLogin(any());
+ Assertions.assertTrue(e.getMessage().contains(second.toString()),
e.getMessage());
+ Assertions.assertFalse(e.getMessage().contains(first.toString()),
e.getMessage());
+ Assertions.assertSame(failure, e.getCause());
+ Assertions.assertTrue(other.getMessage().contains(first.toString()),
other.getMessage());
+ Assertions.assertNotSame(e, other);
+ } finally {
+ release.countDown();
+ callers.shutdownNow();
+ }
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheReportsPathWhenItsPoolsRejectTasks() throws
Exception {
+ Path hdfsPath = new Path("hdfs://localhost:8020/cache_key");
+ Path localPath = new Path(TEST_ROOT_PATH, "rejected");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // As after the catalog is closed.
+ ops.loginSettingsExecutor.shutdownNow();
+ ops.fileSystemExecutor.shutdownNow();
+ for (Path path : new Path[] {hdfsPath, localPath}) {
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> ops.getFileSystemWithCache(path,
filesetConf("[email protected]", "1")));
+ Assertions.assertTrue(e.getMessage().contains(path.toString()),
e.getMessage());
+ Assertions.assertTrue(
+ Throwables.getCausalChain(e).stream()
+ .anyMatch(RejectedExecutionException.class::isInstance));
+ }
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheFindsCachedFileSystemWhileCreationsHang()
throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ Map<String, String> conf =
+ withSetting(
+ filesetConf("[email protected]", "1"),
FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "10");
+ CountDownLatch release = new CountDownLatch(1);
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ FileSystem fs = ops.getFileSystemWithCache(path, conf);
+ // As if logins to a KDC that does not answer held every thread that
creates file systems.
+ int threads = ops.fileSystemExecutor.getCorePoolSize();
+ CountDownLatch started = new CountDownLatch(threads);
+ try {
+ for (int i = 0; i < threads; i++) {
+ ops.fileSystemExecutor.execute(
+ () -> {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ });
+ }
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ // As if the settings of the configuration expired.
+ ops.sharedHdfsLoginSettingsCache.synchronous().invalidateAll();
+ ops.hdfsLoginSettingsCache.synchronous().invalidateAll();
+ Assertions.assertSame(fs, ops.getFileSystemWithCache(path, conf));
+ } finally {
+ release.countDown();
+ }
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void
testFileSystemCacheWaitsForAFileSystemBeingCreatedUntilItsOwnDeadline()
+ throws Exception {
+ Path path = new Path(TEST_ROOT_PATH, "being_created");
+ FileSystem created = Mockito.mock(FileSystem.class);
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService caller = Executors.newSingleThreadExecutor();
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ Mockito.doAnswer(
+ invocation -> {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ return created;
+ })
+ .when(ops)
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ try {
+ // A lookup with a longer timeout creates the file system that the
next lookup waits for.
+ Future<FileSystem> first =
+ caller.submit(
+ () ->
+ ops.getFileSystemWithCache(
+ path,
ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "10")));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ long start = System.nanoTime();
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () ->
+ ops.getFileSystemWithCache(
+ path,
ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "1")));
+ long waitedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() -
start);
+ Assertions.assertTrue(
+ waitedMillis >= 900 && waitedMillis < 5_000, "waited " +
waitedMillis + " ms");
+ Assertions.assertTrue(
+
Throwables.getCausalChain(e).stream().anyMatch(TimeoutException.class::isInstance));
+
+ // The first lookup still gets the file system, and it is cached.
+ release.countDown();
+ Assertions.assertSame(created, first.get(10, TimeUnit.SECONDS));
+ Assertions.assertSame(created, ops.getFileSystemWithCache(path,
ImmutableMap.of()));
+ Mockito.verify(ops, Mockito.times(1))
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ } finally {
+ release.countDown();
+ caller.shutdownNow();
+ }
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void testFileSystemCacheCreatesAgainWhenALookupWithLessTimeGivesUp()
throws Exception {
+ Path path = new Path(TEST_ROOT_PATH, "created_again");
+ FileSystem late = Mockito.mock(FileSystem.class);
+ FileSystem created = Mockito.mock(FileSystem.class);
+ AtomicInteger creations = new AtomicInteger();
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService caller = Executors.newSingleThreadExecutor();
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ Mockito.doAnswer(
+ invocation -> {
+ if (creations.getAndIncrement() > 0) {
+ return created;
+ }
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ return late;
+ })
+ .when(ops)
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ try {
+ Future<FileSystem> first =
+ caller.submit(
+ () ->
+ ops.getFileSystemWithCache(
+ path,
ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "1")));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ // This lookup waits for the creation that the first one started, and
creates the file
+ // system itself once the first one gives up.
+ Assertions.assertSame(
+ created,
+ ops.getFileSystemWithCache(
+ path, ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS,
"10")));
+ ExecutionException e =
+ Assertions.assertThrows(
+ ExecutionException.class, () -> first.get(10,
TimeUnit.SECONDS));
+ Assertions.assertTrue(
+
Throwables.getCausalChain(e).stream().anyMatch(TimeoutException.class::isInstance));
+ } finally {
+ release.countDown();
+ caller.shutdownNow();
+ }
+ Mockito.verify(late, Mockito.timeout(10_000)).close();
+ Mockito.verify(created, never()).close();
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void
testFileSystemCacheCreatesItsOwnFileSystemWhenAJoinedCreationFails()
+ throws Exception {
+ Path path = new Path(TEST_ROOT_PATH, "joined_failure");
+ FileSystem created = Mockito.mock(FileSystem.class);
+ AtomicInteger creations = new AtomicInteger();
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService callers = Executors.newFixedThreadPool(2);
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // The first creation fails, as with a transient error, or a property
that the key leaves out.
+ Mockito.doAnswer(
+ invocation -> {
+ if (creations.getAndIncrement() > 0) {
+ return created;
+ }
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ throw new IOException("Connection refused");
+ })
+ .when(ops)
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ try {
+ Future<FileSystem> first =
+ callers.submit(
+ () ->
+ ops.getFileSystemWithCache(
+ path,
ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "10")));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ AtomicReference<Thread> secondCaller = new AtomicReference<>();
+ Future<FileSystem> second =
+ callers.submit(
+ () -> {
+ secondCaller.set(Thread.currentThread());
+ return ops.getFileSystemWithCache(
+ path,
ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "10"));
+ });
+ awaitTimedWaiting(secondCaller);
+ release.countDown();
+ // The lookup that joined the failed creation creates the file system
itself, as each
+ // lookup did before.
+ Assertions.assertSame(created, second.get(10, TimeUnit.SECONDS));
+ ExecutionException e =
+ Assertions.assertThrows(
+ ExecutionException.class, () -> first.get(10,
TimeUnit.SECONDS));
+ Assertions.assertTrue(
+ Throwables.getCausalChain(e).stream()
+ .anyMatch(t -> "Connection refused".equals(t.getMessage())));
+ Mockito.verify(ops, Mockito.times(2))
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ } finally {
+ release.countDown();
+ callers.shutdownNow();
+ }
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void testRetryingLookupKeepsTheEntryOfALaterLoad() throws Exception {
+ List<String> removed = new CopyOnWriteArrayList<>();
+ AsyncCache<String, String> cache =
+ Caffeine.newBuilder()
+ .executor(Runnable::run)
+ .removalListener((key, value, cause) -> removed.add(value + ":" +
cause))
+ .buildAsync();
+ List<CompletableFuture<String>> loads = new CopyOnWriteArrayList<>();
+ BiFunction<String, Executor, CompletableFuture<String>> load =
+ (key, executor) -> {
+ CompletableFuture<String> future = new CompletableFuture<>();
+ loads.add(future);
+ return future;
+ };
+ CompletableFuture<String> failing = cache.get("key", load);
+ // The cache itself waits for each entry it holds.
+ int cacheDependents = failing.getNumberOfDependents();
+ ExecutorService caller = Executors.newSingleThreadExecutor();
+ try {
+ Future<String> lookup =
+ caller.submit(
+ () ->
+ FilesetCatalogOperations.TimedTask.awaitEntry(
+ cache, "key", load, System.nanoTime() +
TimeUnit.SECONDS.toNanos(30)));
+ awaitDependents(failing, cacheDependents + 1);
+ // The configuration changed, and another lookup started a new load
before the first failed.
+ cache.synchronous().invalidate("key");
+ CompletableFuture<String> later = cache.get("key", load);
+ failing.completeExceptionally(new TimeoutException());
+ // The waiting lookup retries and joins the later load rather than
replacing it.
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ while (later.getNumberOfDependents() <= cacheDependents && loads.size()
== 2) {
+ Assertions.assertTrue(System.nanoTime() < deadline, "the lookup never
retried");
+ Thread.sleep(10);
+ }
+ loads.forEach(future -> future.complete(future == later ? "later" :
"replaced"));
+ Assertions.assertEquals("later", lookup.get(10, TimeUnit.SECONDS));
+ Assertions.assertEquals(2, loads.size());
+ Assertions.assertEquals("later",
cache.synchronous().getIfPresent("key"));
+ // For the file system cache, a removed value is closed while its caller
uses it.
+ Assertions.assertEquals(Collections.emptyList(), removed);
+ } finally {
+ loads.forEach(future -> future.complete("released"));
+ caller.shutdownNow();
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void testRetryingLookupLoadsItselfAfterEveryJoinedLoadFails() throws
Exception {
+ AsyncCache<String, String> cache =
Caffeine.newBuilder().executor(Runnable::run).buildAsync();
+ List<CompletableFuture<String>> loads = new CopyOnWriteArrayList<>();
+ BiFunction<String, Executor, CompletableFuture<String>> load =
+ (key, executor) -> {
+ CompletableFuture<String> future = new CompletableFuture<>();
+ loads.add(future);
+ return future;
+ };
+ CompletableFuture<String> joined = cache.get("key", load);
+ // The cache itself waits for each entry it holds.
+ int cacheDependents = joined.getNumberOfDependents();
+ ExecutorService caller = Executors.newSingleThreadExecutor();
+ try {
+ Future<String> lookup =
+ caller.submit(
+ () ->
+ FilesetCatalogOperations.TimedTask.awaitEntry(
+ cache, "key", load, System.nanoTime() +
TimeUnit.SECONDS.toNanos(30)));
+ // Three loads that other lookups started fail one after the other while
the lookup waits.
+ for (int i = 0; i < 2; i++) {
+ awaitDependents(joined, cacheDependents + 1);
+ cache.synchronous().invalidate("key");
+ CompletableFuture<String> next = cache.get("key", load);
+ joined.completeExceptionally(new IOException("Connection refused"));
+ joined = next;
+ }
+ awaitDependents(joined, cacheDependents + 1);
+ joined.completeExceptionally(new IOException("Connection refused"));
+ // Then the lookup loads with its own configuration.
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ while (loads.size() < 4) {
+ Assertions.assertTrue(System.nanoTime() < deadline, "the lookup never
loaded itself");
+ Thread.sleep(10);
+ }
+ loads.get(3).complete("own");
+ Assertions.assertEquals("own", lookup.get(10, TimeUnit.SECONDS));
+ Assertions.assertEquals(4, loads.size());
+ } finally {
+ loads.forEach(future -> future.complete("released"));
+ caller.shutdownNow();
+ }
+ }
+
+ // Waits until the future has the given number of dependents, as when a
thread waits for it.
+ private static void awaitDependents(CompletableFuture<?> future, int
dependents)
+ throws InterruptedException {
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ while (future.getNumberOfDependents() < dependents) {
+ Assertions.assertTrue(System.nanoTime() < deadline, "nothing waited for
the future");
+ Thread.sleep(10);
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void
testFileSystemCacheResolvesSharedLoginSettingsAgainWhenTheirLookupGivesUp()
+ throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ Map<String, String> first =
+ withSetting(filesetConf("[email protected]", "1"),
FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "3");
+ Map<String, String> second =
+ withSetting(filesetConf("[email protected]", "2"),
FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "3");
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService callers = Executors.newFixedThreadPool(2);
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ AtomicInteger resolutions = new AtomicInteger();
+ Mockito.doAnswer(
+ invocation -> {
+ if (resolutions.getAndIncrement() == 0) {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ }
+ return invocation.callRealMethod();
+ })
+ .when(ops)
+ .resolveHdfsLogin(any());
+ try {
+ Future<FileSystem> firstLookup =
+ callers.submit(() -> ops.getFileSystemWithCache(path, first));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ // The second fileset waits for the settings that the first one is
resolving, and has time
+ // left when the first one gives up.
+ Thread.sleep(1_500);
+ Future<FileSystem> secondLookup =
+ callers.submit(() -> ops.getFileSystemWithCache(path, second));
+ Assertions.assertNotNull(secondLookup.get(10, TimeUnit.SECONDS));
+ ExecutionException e =
+ Assertions.assertThrows(
+ ExecutionException.class, () -> firstLookup.get(10,
TimeUnit.SECONDS));
+ Assertions.assertTrue(
+ e.getCause().getMessage().contains("Failed to resolve the login
settings"),
+ e.getCause().getMessage());
+ } finally {
+ release.countDown();
+ callers.shutdownNow();
+ }
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void testInterruptedLookupLeavesTheSharedLoginSettingsToTheOthers()
throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService callers = Executors.newSingleThreadExecutor();
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ AtomicInteger resolutions = new AtomicInteger();
+ Mockito.doAnswer(
+ invocation -> {
+ if (resolutions.getAndIncrement() == 0) {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ }
+ return invocation.callRealMethod();
+ })
+ .when(ops)
+ .resolveHdfsLogin(any());
+ AtomicReference<Throwable> failure = new AtomicReference<>();
+ try {
+ Future<FileSystem> firstLookup =
+ callers.submit(() -> ops.getFileSystemWithCache(path,
filesetConf("[email protected]", "1")));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ // The second fileset waits for the same settings and is interrupted.
+ Thread second =
+ new Thread(
+ () -> {
+ try {
+ ops.getFileSystemWithCache(path, filesetConf("[email protected]",
"2"));
+ } catch (Throwable t) {
+ failure.set(t);
+ }
+ });
+ second.start();
+ Thread.sleep(500);
+ second.interrupt();
+ second.join(10_000);
+ Assertions.assertFalse(second.isAlive(), "the caller kept waiting
after the interrupt");
+ Assertions.assertNotNull(failure.get(), "the caller returned without
an exception");
+ Assertions.assertInstanceOf(
+ InterruptedException.class,
Throwables.getRootCause(failure.get()));
+
+ release.countDown();
+ Assertions.assertNotNull(firstLookup.get(10, TimeUnit.SECONDS));
+ // Once for the shared settings, and once for the configuration the
file system logs in
+ // with.
+ Mockito.verify(ops, Mockito.times(2)).resolveHdfsLogin(any());
+ } finally {
+ release.countDown();
+ callers.shutdownNow();
+ }
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void
testFileSystemCacheResolvesLoginSettingsBesideAHangingResolution() throws
Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ Map<String, String> base =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY, "kerberos",
HADOOP_SECURITY_PRINCIPAL, "[email protected]");
+ Map<String, String> hanging = withSetting(base,
FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "10");
+ // Another configuration with the same hash code, which the settings cache
keeps in the same
+ // bucket. Its lookup would wait 10 seconds behind the hanging one.
+ int padding =
+ (FILESYSTEM_CONNECTION_TIMEOUT_SECONDS.hashCode() ^ "10".hashCode())
+ - (FILESYSTEM_CONNECTION_TIMEOUT_SECONDS.hashCode() ^
"4".hashCode());
+ Map<String, String> waiting =
+ withSetting(
+ withSetting(base, FILESYSTEM_CONNECTION_TIMEOUT_SECONDS, "4"),
+ "padding",
+ withHashCode("padding".hashCode() ^ padding));
+ Assertions.assertEquals(hanging.hashCode(), waiting.hashCode());
+ CountDownLatch started = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ ExecutorService caller = Executors.newSingleThreadExecutor();
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ AtomicInteger resolutions = new AtomicInteger();
+ Mockito.doAnswer(
+ invocation -> {
+ if (resolutions.getAndIncrement() == 0) {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(release);
+ }
+ return invocation.callRealMethod();
+ })
+ .when(ops)
+ .resolveHdfsLogin(any());
+ try {
+ caller.submit(() -> ops.getFileSystemWithCache(path, hanging));
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ long start = System.nanoTime();
+ Assertions.assertNotNull(ops.getFileSystemWithCache(path, waiting));
+ long waitedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() -
start);
+ Assertions.assertTrue(waitedMillis < 5_000, "waited " + waitedMillis +
" ms");
+ } finally {
+ release.countDown();
+ caller.shutdownNow();
+ }
+ }
+ }
+
+ // A string whose hash code is the given one.
+ private static String withHashCode(int hashCode) {
+ // The hash code of 'A' + d[0], ..., 'A' + d[6] is that of "AAAAAAA" plus
the sum of
+ // d[i] * 31^(6 - i), so d holds the digits of the difference in base 31.
+ long rest = Integer.toUnsignedLong(hashCode - "AAAAAAA".hashCode());
+ char[] chars = new char[7];
+ for (int i = 6; i >= 0; i--) {
+ chars[i] = (char) ('A' + rest % 31);
+ rest /= 31;
+ }
+ return new String(chars);
+ }
+
+ @Test
+ @Timeout(60)
+ public void testFileSystemCacheQueuesABurstOfLoginSettingsResolutions()
throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ CountDownLatch blocked = new CountDownLatch(1);
+ ExecutorService callers = Executors.newFixedThreadPool(120);
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // As if config.resources reads were slow, holding every thread that
resolves settings.
+ int threads = ops.loginSettingsExecutor.getCorePoolSize();
+ CountDownLatch started = new CountDownLatch(threads);
+ for (int i = 0; i < threads; i++) {
+ ops.loginSettingsExecutor.execute(
+ () -> {
+ started.countDown();
+ Uninterruptibles.awaitUninterruptibly(blocked);
+ });
+ }
+ try {
+ Assertions.assertTrue(started.await(10, TimeUnit.SECONDS));
+ // A resolution that its lookup gave up on leaves the queue.
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () ->
+ ops.getFileSystemWithCache(
+ path,
+ withSetting(
+ filesetConf("[email protected]", "1"),
+ FILESYSTEM_CONNECTION_TIMEOUT_SECONDS,
+ "1")));
+ long removed = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ while (!ops.loginSettingsExecutor.getQueue().isEmpty()) {
+ Assertions.assertTrue(System.nanoTime() < removed, "the resolution
stayed queued");
+ Thread.sleep(10);
+ }
+
+ // A burst of cold lookups of different settings, as after a restart,
waits in the queue.
+ List<Future<FileSystem>> lookups = new ArrayList<>();
+ for (int i = 0; i < 120; i++) {
+ Map<String, String> conf =
+ withSetting(
+ filesetConf("svc-" + i + "@A.COM", "1"),
+ FILESYSTEM_CONNECTION_TIMEOUT_SECONDS,
+ "30");
+ lookups.add(callers.submit(() -> ops.getFileSystemWithCache(path,
conf)));
+ }
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10);
+ while (ops.loginSettingsExecutor.getQueue().size() < 120) {
+ for (Future<FileSystem> lookup : lookups) {
+ if (lookup.isDone()) {
+ lookup.get();
+ }
+ }
+ Assertions.assertTrue(System.nanoTime() < deadline, "the lookups
never queued");
+ Thread.sleep(10);
+ }
+ blocked.countDown();
+ for (Future<FileSystem> lookup : lookups) {
+ Assertions.assertNotNull(lookup.get(30, TimeUnit.SECONDS));
+ }
+ } finally {
+ blocked.countDown();
+ callers.shutdownNow();
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"[email protected]",
"svc-${gravitino.identifier}@EXAMPLE.COM"})
+ public void
testFileSystemCacheKeepsLoginSettingsWhenTheCallerChangesItsConfiguration(
+ String principal) throws Exception {
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // Settings without variables are in the shared cache, the others in the
cache by the whole
+ // configuration.
+ Map<String, String> conf = new HashMap<>(filesetConf(principal, "1"));
+ FileSystem fs = ops.getFileSystemWithCache(path, conf);
+ // A lookup does not copy the configuration on a hit, so the caches keep
their own copy.
+ conf.put(HADOOP_SECURITY_PRINCIPAL, "[email protected]");
+ Mockito.clearInvocations(ops);
+ Assertions.assertSame(fs, ops.getFileSystemWithCache(path,
filesetConf(principal, "1")));
+ Mockito.verify(ops, never()).resolveHdfsLogin(any());
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheReportsPathOfUnreadableLoginSettings() throws
Exception {
+ File resource = new File(UNFORMALIZED_TEST_ROOT_PATH,
"cache_key/malformed-site.xml");
+ FileUtils.writeStringToFile(resource, "<configuration>",
StandardCharsets.UTF_8);
+ Map<String, String> conf = ImmutableMap.of(CONFIG_RESOURCES,
resource.getAbsolutePath());
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class, () ->
ops.getFileSystemWithCache(path, conf));
+ Assertions.assertTrue(e.getMessage().contains(path.toString()),
e.getMessage());
+ // The cause carries the parse error.
+ Assertions.assertNotNull(e.getCause());
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheKeyHoldsLoginSettingsOfNewFileSystem() throws
Exception {
+ File resource = new File(UNFORMALIZED_TEST_ROOT_PATH,
"cache_key/edited-site.xml");
+ writePrincipal(resource, "[email protected]");
+ Map<String, String> conf =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ CONFIG_RESOURCES,
+ resource.getAbsolutePath());
+ // A plain key overrides the resource file, so this configuration still
logs in as svc-v1.
+ Map<String, String> svcV1 = withSetting(conf, HADOOP_SECURITY_PRINCIPAL,
"[email protected]");
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ ops.getFileSystemWithCache(path, conf);
+ writePrincipal(resource, "[email protected]");
+
+ // Bob's file system is new, so it logs in as svc-v2 while the settings
of conf are cached.
+ UserPrincipal bob = new UserPrincipal("bob");
+ FileSystem edited = PrincipalUtils.doAs(bob, () ->
ops.getFileSystemWithCache(path, conf));
+ ArgumentCaptor<Configuration> loginConf =
ArgumentCaptor.forClass(Configuration.class);
+ Mockito.verify(ops, Mockito.times(2))
+ .createFileSystem(any(), any(), any(), any(), any(),
loginConf.capture());
+ Assertions.assertEquals(
+ "[email protected]",
loginConf.getValue().get(HADOOP_SECURITY_PRINCIPAL));
+ Assertions.assertSame(
+ edited, PrincipalUtils.doAs(bob, () ->
ops.getFileSystemWithCache(path, conf)));
+ Assertions.assertNotSame(
+ edited, PrincipalUtils.doAs(bob, () ->
ops.getFileSystemWithCache(path, svcV1)));
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheFailsWhenLoginSettingsKeepChanging() throws
Exception {
+ Map<String, String> conf =
+ ImmutableMap.of(
+ AuthenticationConfig.AUTH_TYPE_KEY,
+ "kerberos",
+ KerberosConfig.PRINCIPAL_KEY,
+ "[email protected]");
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ // As if the config.resources files changed again before each file
system was created.
+ doReturn(null).when(ops).getFileSystem(any(), any(), any(), any());
+
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class, () ->
ops.getFileSystemWithCache(path, conf));
+ Assertions.assertTrue(e.getMessage().contains(path.toString()),
e.getMessage());
+ // The retry resolves the settings again before it gives up.
+ Mockito.verify(ops, Mockito.times(2)).getFileSystem(any(), any(), any(),
any());
+ Mockito.verify(ops, Mockito.times(2)).resolveHdfsLogin(any());
+ }
+ }
+
+ @Test
+ public void testFileSystemCacheReportsPathOfUnresolvableLoginSettings()
throws Exception {
+ // Hadoop fails a lookup that needs 20 or more variable substitutions.
+ ImmutableMap.Builder<String, String> conf =
+ ImmutableMap.<String, String>builder()
+ .put(AuthenticationConfig.AUTH_TYPE_KEY, "kerberos")
+ .put(HADOOP_SECURITY_PRINCIPAL, "${v0}")
+ .put("v21", "[email protected]");
+ for (int i = 0; i < 21; i++) {
+ conf.put("v" + i, "${v" + (i + 1) + "}");
+ }
+ Path path = new Path("hdfs://localhost:8020/cache_key");
+
+ try (FilesetCatalogOperations ops =
newOpsWithStubbedHdfs(BUILTIN_HDFS_FS_PROVIDER)) {
+ GravitinoRuntimeException e =
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () -> ops.getFileSystemWithCache(path, conf.build()));
+ Assertions.assertTrue(e.getMessage().contains(path.toString()),
e.getMessage());
+ }
+ }
+
+ @Test
+ public void testHdfsFileSystemLogsInWithTheGivenConfiguration() throws
Exception {
+ Configuration hadoopConf =
HDFSFileSystemProxy.hadoopConfiguration(ImmutableMap.of());
+ try (FilesetCatalogOperations ops = new FilesetCatalogOperations(store,
secretManager)) {
+ ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"),
FILESET_PROPERTIES_METADATA);
+ // The scheme selects the HDFS proxy, and the local path needs no
NameNode.
+ try (FileSystem fs =
+ ops.createFileSystem(
+ new Path(TEST_ROOT_PATH), ImmutableMap.of(), "hdfs", null,
"bob", hadoopConf)) {
+ Assertions.assertSame(hadoopConf, fs.getConf());
+ }
+ }
+ }
+
+ @Test
+ @Timeout(60)
+ public void testFileSystemCreatedAfterTimeoutIsClosed() throws Exception {
+ FileSystem late = Mockito.mock(FileSystem.class);
+ CountDownLatch timedOut = new CountDownLatch(1);
+ try (FilesetCatalogOperations ops =
+ Mockito.spy(new FilesetCatalogOperations(store, secretManager))) {
+ ops.initialize(ImmutableMap.of(), randomCatalogInfo("m1", "c1"),
FILESET_PROPERTIES_METADATA);
+ // Like a Kerberos login that swallows the interrupt of the timeout.
+ Mockito.doAnswer(
+ invocation -> {
+ Uninterruptibles.awaitUninterruptibly(timedOut);
+ Thread.interrupted();
+ return late;
+ })
+ .when(ops)
+ .createFileSystem(any(), any(), any(), any(), any(), any());
+ // Holds the thread that runs CompletableFuture timeouts, so that only
the lookup's own wait
+ // fails the creation, as when the creation ends right after the lookup
gave up.
+ CountDownLatch timerHeld = new CountDownLatch(1);
+ CountDownLatch releaseTimer = new CountDownLatch(1);
+ CompletableFuture.delayedExecutor(0, TimeUnit.NANOSECONDS, Runnable::run)
+ .execute(
+ () -> {
+ timerHeld.countDown();
+ Uninterruptibles.awaitUninterruptibly(releaseTimer);
+ });
+
+ try {
+ Assertions.assertTrue(timerHeld.await(10, TimeUnit.SECONDS));
+ try {
+ Assertions.assertThrows(
+ GravitinoRuntimeException.class,
+ () ->
+ ops.getFileSystemWithCache(
+ new Path(TEST_ROOT_PATH, "late"),
+ ImmutableMap.of(FILESYSTEM_CONNECTION_TIMEOUT_SECONDS,
"1")));
+ } finally {
+ timedOut.countDown();
+ }
+ Mockito.verify(late, Mockito.timeout(10_000)).close();
Review Comment:
**[P3] Synchronize worker startup in the timeout tests**
The timer latch covers the timer thread. On a slow CI runner the one-second
deadline can cancel creation before the worker enters the mock, and this
verification then fails because no filesystem was created.
`testFileSystemCreationIsInterruptedAtTheDeadlineOfItsLookup` has the same
startup assumption. Can these tests wait for the worker to start before driving
the timeout?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]