Izeren commented on code in PR #28427: URL: https://github.com/apache/flink/pull/28427#discussion_r3587649240
########## docs/content/docs/deployment/filesystems/s3.md: ########## @@ -172,6 +172,12 @@ In addition to the [common configuration](#common-configuration) options (`s3.ac View the detailed configuration at [native-s3-fs](https://github.com/apache/flink/tree/master/flink-filesystems/flink-s3-fs-native#configuration-options) +#### Metrics + +The Native S3 FileSystem can publish AWS SDK operation metrics into Flink's process-level metric group on the JobManager and TaskManager. Metrics are enabled by default with `s3.metrics.enabled: true` and are scoped under `filesystem.filesystem_type.s3` or `filesystem.filesystem_type.s3a`. Review Comment: Are we planning Chinese docs for a follow up PR? ########## flink-core/src/main/java/org/apache/flink/core/plugin/MetricsAware.java: ########## @@ -0,0 +1,49 @@ +/* + * 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.flink.core.plugin; + +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.metrics.MetricGroup; + +/** + * Opt-in capability marker for {@link Plugin}s that register Flink metrics. Plugins that do not + * implement it emit no metrics; the hook is reusable by any plugin family, not only file systems. Review Comment: > the hook is reusable by any plugin family, not only file systems Do we have examples to call out? ########## flink-core/src/main/java/org/apache/flink/core/plugin/MetricsAware.java: ########## @@ -0,0 +1,49 @@ +/* + * 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.flink.core.plugin; + +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.metrics.MetricGroup; + +/** + * Opt-in capability marker for {@link Plugin}s that register Flink metrics. Plugins that do not Review Comment: > Plugins that do not implement it emit no metrics Is that true? I would remove this unless it is a part of the class contract ########## flink-core/src/main/java/org/apache/flink/core/plugin/MetricsAware.java: ########## @@ -0,0 +1,49 @@ +/* + * 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.flink.core.plugin; + +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.metrics.MetricGroup; + +/** + * Opt-in capability marker for {@link Plugin}s that register Flink metrics. Plugins that do not + * implement it emit no metrics; the hook is reusable by any plugin family, not only file systems. + * + * <p><b>Two-phase init.</b> The runtime calls {@link #setMetricGroup(MetricGroup)} after {@link + * Plugin#configure(org.apache.flink.configuration.Configuration)} and before any metric is emitted, + * only from entrypoints that own a process-level {@link MetricGroup} (TaskManager, JobManager) via + * {@link org.apache.flink.core.fs.FileSystem#attachMetrics(MetricGroup)}. Other contexts (CLI, Review Comment: > Other contexts (CLI, HistoryServer, YARN client) never call it, and the plugin must keep working without metrics. It is unclear to me. Is it a contract of MetricsAware? Javadocs for MetricsAware should focus on "what" implementing this interface gives and how to implement it correctly. For non-obvious parts it can also contain justification of "why" it was done this way referring to implementation examples. ########## flink-core/src/test/java/org/apache/flink/core/fs/FileSystemAttachMetricsTest.java: ########## @@ -0,0 +1,243 @@ +/* + * 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.flink.core.fs; + +import org.apache.flink.configuration.Configuration; +import org.apache.flink.configuration.CoreOptions; +import org.apache.flink.core.plugin.MetricsAware; +import org.apache.flink.core.plugin.TestingPluginManager; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.metrics.groups.UnregisteredMetricsGroup; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +/** + * Tests for {@link FileSystem#attachMetrics(MetricGroup)} and the {@link MetricsAware} contract. + */ +class FileSystemAttachMetricsTest { + + @AfterEach + void resetFileSystems() { + // Restore the default, plugin-less factory registry so other tests are unaffected. + FileSystem.initialize(new Configuration(), null); + } + + @Test + void attachMetricsReachesPluginLoadedMetricsAwareFactory() { + // Headline case: plugin file systems are registered behind wrappers such as + // PluginFileSystemFactory. attachMetrics must still reach the real factory, otherwise the + // metric group is silently never delivered and no metrics are ever emitted. + TestingFileSystemFactory factory = new TestingFileSystemFactory("metrics-test-fs"); + initializeWithPlugins(factory); + + RecordingMetricGroup processGroup = new RecordingMetricGroup(); + FileSystem.attachMetrics(processGroup); + + // Unwrapped through PluginFileSystemFactory and invoked exactly once. + assertThat(factory.setMetricGroupCalls).hasValue(1); + // The group handed to the factory is the "filesystem" child of the process group, not the + // process group itself. + assertThat(processGroup.childGroupNames).containsExactly("filesystem"); + assertThat(factory.receivedGroup.get()).isNotNull().isNotSameAs(processGroup); + } + + @Test + void attachMetricsReachesMetricsAwareFactoryBehindConnectionLimiter() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("limited-test-fs"); + Configuration config = new Configuration(); + config.set(CoreOptions.fileSystemConnectionLimit(factory.getScheme()), 1); + initializeWithPlugins(config, factory); + + FileSystem.attachMetrics(new UnregisteredMetricsGroup()); + + assertThat(factory.setMetricGroupCalls).hasValue(1); + } + + @Test + void attachMetricsSkipsFactoriesThatAreNotMetricsAware() { + // A factory that does not implement MetricsAware is filtered out by the instanceof check in + // attachMetrics, so it simply receives no group. One representative factory is enough. + initializeWithPlugins(new PlainFileSystemFactory("plain-test-fs")); + + assertThatCode(() -> FileSystem.attachMetrics(new UnregisteredMetricsGroup())) + .doesNotThrowAnyException(); + } + + @Test + void attachMetricsIsResilientToAFactoryThatThrows() { + TestingFileSystemFactory ok = new TestingFileSystemFactory("ok-test-fs"); + initializeWithPlugins( + new TestingFileSystemFactory( + "throwing-test-fs", + group -> { + throw new RuntimeException( + "intentional failure from a misbehaving plugin"); + }), + ok); + + // A misbehaving plugin must never break process startup, and well-behaved factories must + // still receive their group regardless of iteration order. + assertThatCode(() -> FileSystem.attachMetrics(new UnregisteredMetricsGroup())) + .doesNotThrowAnyException(); + assertThat(ok.setMetricGroupCalls).hasValue(1); + } + + @Test + void attachMetricsForwardsToFactoryOnEveryInvocation() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("idem-test-fs"); + initializeWithPlugins(factory); + + MetricGroup group = new UnregisteredMetricsGroup(); + FileSystem.attachMetrics(group); + FileSystem.attachMetrics(group); + + // The hook forwards on every call; collapsing duplicate registrations is the factory's + // responsibility, verified end-to-end in NativeS3FileSystemFactoryMetricsTest + // #repeatedAttachmentWithSameGroupDoesNotCreateNewFilesystemTypeGroup. + assertThat(factory.setMetricGroupCalls).hasValue(2); + } + + @Test + void setMetricGroupIsNotInvokedWhenAttachMetricsIsNeverCalled() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("never-test-fs"); + initializeWithPlugins(factory); + + assertThat(factory.setMetricGroupCalls).hasValue(0); + } + + @Test + void pluginFileSystemFactoryForwardsMetricGroupToInner() { + TestingFileSystemFactory inner = new TestingFileSystemFactory("wrapped-fs"); + FileSystemFactory wrapper = PluginFileSystemFactory.of(inner); + + // The wrapper must itself be MetricsAware so attachMetrics reaches it without unwrapping. + assertThat(wrapper).isInstanceOf(MetricsAware.class); + + MetricGroup group = new UnregisteredMetricsGroup(); + ((MetricsAware) wrapper).setMetricGroup(group); + + assertThat(inner.setMetricGroupCalls).hasValue(1); + assertThat(inner.receivedGroup.get()).isSameAs(group); + } + + private static void initializeWithPlugins(FileSystemFactory... factories) { + initializeWithPlugins(new Configuration(), factories); + } + + private static void initializeWithPlugins( + Configuration config, FileSystemFactory... factories) { + Map<Class<?>, Iterator<?>> plugins = new HashMap<>(); + plugins.put(FileSystemFactory.class, Arrays.asList(factories).iterator()); + FileSystem.initialize(config, new TestingPluginManager(plugins)); + } + + // ------------------------------------------------------------------------ + // test factories + // ------------------------------------------------------------------------ + + private static class PlainFileSystemFactory implements FileSystemFactory { + private final String scheme; + + PlainFileSystemFactory(String scheme) { + this.scheme = scheme; + } + + @Override + public void configure(Configuration config) {} + + @Override + public String getScheme() { + return scheme; + } + + @Override + public FileSystem create(URI fsUri) throws IOException { + throw new UnsupportedOperationException("not needed for this test"); + } + } + + /** + * A metrics-aware factory that records how it was called. An optional hook runs inside {@link Review Comment: > An optional hook runs inside {@link #setMetricGroup}, so one class models both the well-behaved and the throwing cases. That would be better placed next to the hook and/or `setMetricGroup` ########## flink-core/src/test/java/org/apache/flink/core/fs/FileSystemAttachMetricsTest.java: ########## @@ -0,0 +1,243 @@ +/* + * 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.flink.core.fs; + +import org.apache.flink.configuration.Configuration; +import org.apache.flink.configuration.CoreOptions; +import org.apache.flink.core.plugin.MetricsAware; +import org.apache.flink.core.plugin.TestingPluginManager; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.metrics.groups.UnregisteredMetricsGroup; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +/** + * Tests for {@link FileSystem#attachMetrics(MetricGroup)} and the {@link MetricsAware} contract. + */ +class FileSystemAttachMetricsTest { + + @AfterEach + void resetFileSystems() { + // Restore the default, plugin-less factory registry so other tests are unaffected. + FileSystem.initialize(new Configuration(), null); + } + + @Test + void attachMetricsReachesPluginLoadedMetricsAwareFactory() { + // Headline case: plugin file systems are registered behind wrappers such as + // PluginFileSystemFactory. attachMetrics must still reach the real factory, otherwise the + // metric group is silently never delivered and no metrics are ever emitted. + TestingFileSystemFactory factory = new TestingFileSystemFactory("metrics-test-fs"); + initializeWithPlugins(factory); + + RecordingMetricGroup processGroup = new RecordingMetricGroup(); + FileSystem.attachMetrics(processGroup); + + // Unwrapped through PluginFileSystemFactory and invoked exactly once. + assertThat(factory.setMetricGroupCalls).hasValue(1); + // The group handed to the factory is the "filesystem" child of the process group, not the + // process group itself. + assertThat(processGroup.childGroupNames).containsExactly("filesystem"); + assertThat(factory.receivedGroup.get()).isNotNull().isNotSameAs(processGroup); + } + + @Test + void attachMetricsReachesMetricsAwareFactoryBehindConnectionLimiter() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("limited-test-fs"); + Configuration config = new Configuration(); + config.set(CoreOptions.fileSystemConnectionLimit(factory.getScheme()), 1); + initializeWithPlugins(config, factory); + + FileSystem.attachMetrics(new UnregisteredMetricsGroup()); + + assertThat(factory.setMetricGroupCalls).hasValue(1); + } + + @Test + void attachMetricsSkipsFactoriesThatAreNotMetricsAware() { + // A factory that does not implement MetricsAware is filtered out by the instanceof check in + // attachMetrics, so it simply receives no group. One representative factory is enough. + initializeWithPlugins(new PlainFileSystemFactory("plain-test-fs")); + + assertThatCode(() -> FileSystem.attachMetrics(new UnregisteredMetricsGroup())) + .doesNotThrowAnyException(); + } + + @Test + void attachMetricsIsResilientToAFactoryThatThrows() { + TestingFileSystemFactory ok = new TestingFileSystemFactory("ok-test-fs"); + initializeWithPlugins( + new TestingFileSystemFactory( + "throwing-test-fs", + group -> { + throw new RuntimeException( + "intentional failure from a misbehaving plugin"); + }), + ok); + + // A misbehaving plugin must never break process startup, and well-behaved factories must + // still receive their group regardless of iteration order. + assertThatCode(() -> FileSystem.attachMetrics(new UnregisteredMetricsGroup())) + .doesNotThrowAnyException(); + assertThat(ok.setMetricGroupCalls).hasValue(1); + } + + @Test + void attachMetricsForwardsToFactoryOnEveryInvocation() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("idem-test-fs"); + initializeWithPlugins(factory); + + MetricGroup group = new UnregisteredMetricsGroup(); + FileSystem.attachMetrics(group); + FileSystem.attachMetrics(group); + + // The hook forwards on every call; collapsing duplicate registrations is the factory's + // responsibility, verified end-to-end in NativeS3FileSystemFactoryMetricsTest + // #repeatedAttachmentWithSameGroupDoesNotCreateNewFilesystemTypeGroup. + assertThat(factory.setMetricGroupCalls).hasValue(2); + } + + @Test + void setMetricGroupIsNotInvokedWhenAttachMetricsIsNeverCalled() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("never-test-fs"); + initializeWithPlugins(factory); + + assertThat(factory.setMetricGroupCalls).hasValue(0); + } + + @Test + void pluginFileSystemFactoryForwardsMetricGroupToInner() { + TestingFileSystemFactory inner = new TestingFileSystemFactory("wrapped-fs"); + FileSystemFactory wrapper = PluginFileSystemFactory.of(inner); + + // The wrapper must itself be MetricsAware so attachMetrics reaches it without unwrapping. + assertThat(wrapper).isInstanceOf(MetricsAware.class); + + MetricGroup group = new UnregisteredMetricsGroup(); + ((MetricsAware) wrapper).setMetricGroup(group); + + assertThat(inner.setMetricGroupCalls).hasValue(1); + assertThat(inner.receivedGroup.get()).isSameAs(group); + } + + private static void initializeWithPlugins(FileSystemFactory... factories) { + initializeWithPlugins(new Configuration(), factories); + } + + private static void initializeWithPlugins( + Configuration config, FileSystemFactory... factories) { + Map<Class<?>, Iterator<?>> plugins = new HashMap<>(); + plugins.put(FileSystemFactory.class, Arrays.asList(factories).iterator()); + FileSystem.initialize(config, new TestingPluginManager(plugins)); + } + + // ------------------------------------------------------------------------ + // test factories + // ------------------------------------------------------------------------ + + private static class PlainFileSystemFactory implements FileSystemFactory { + private final String scheme; + + PlainFileSystemFactory(String scheme) { + this.scheme = scheme; + } + + @Override + public void configure(Configuration config) {} + + @Override + public String getScheme() { + return scheme; + } + + @Override + public FileSystem create(URI fsUri) throws IOException { + throw new UnsupportedOperationException("not needed for this test"); + } + } + + /** + * A metrics-aware factory that records how it was called. An optional hook runs inside {@link + * #setMetricGroup}, so one class models both the well-behaved and the throwing cases. + */ + private static class TestingFileSystemFactory extends PlainFileSystemFactory + implements MetricsAware { + final AtomicInteger setMetricGroupCalls = new AtomicInteger(); + final AtomicReference<MetricGroup> receivedGroup = new AtomicReference<>(); + @Nullable private final Consumer<MetricGroup> onSetMetricGroup; + + TestingFileSystemFactory(String scheme) { + this(scheme, null); + } + + TestingFileSystemFactory(String scheme, @Nullable Consumer<MetricGroup> onSetMetricGroup) { + super(scheme); + this.onSetMetricGroup = onSetMetricGroup; + } + + @Override + public void setMetricGroup(MetricGroup metricGroup) { + setMetricGroupCalls.incrementAndGet(); + receivedGroup.set(metricGroup); + if (onSetMetricGroup != null) { Review Comment: Is it legit for the hook to be null? Do we need to do anything if no hook is provided? Or is silence the expected behaviour? ########## flink-core/src/main/java/org/apache/flink/core/plugin/MetricsAware.java: ########## @@ -0,0 +1,49 @@ +/* + * 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.flink.core.plugin; + +import org.apache.flink.annotation.PublicEvolving; +import org.apache.flink.metrics.MetricGroup; + +/** + * Opt-in capability marker for {@link Plugin}s that register Flink metrics. Plugins that do not + * implement it emit no metrics; the hook is reusable by any plugin family, not only file systems. + * + * <p><b>Two-phase init.</b> The runtime calls {@link #setMetricGroup(MetricGroup)} after {@link + * Plugin#configure(org.apache.flink.configuration.Configuration)} and before any metric is emitted, + * only from entrypoints that own a process-level {@link MetricGroup} (TaskManager, JobManager) via + * {@link org.apache.flink.core.fs.FileSystem#attachMetrics(MetricGroup)}. Other contexts (CLI, + * HistoryServer, YARN client) never call it, and the plugin must keep working without metrics. + * + * <p><b>Idempotency.</b> {@code setMetricGroup} may be called more than once: the same {@link + * MetricGroup} must not register duplicate metrics, and a different group re-scopes metrics created Review Comment: Would it produce log noise on attempts to register duplicate groups? Can we maybe give a simple example of why it can be called more than once? ########## flink-core/src/main/java/org/apache/flink/core/fs/ConnectionLimitingFactory.java: ########## @@ -59,6 +61,13 @@ public void configure(Configuration config) { factory.configure(config); } + @Override + public void setMetricGroup(MetricGroup metricGroup) { Review Comment: Missing Javadoc on public method ########## flink-core/src/test/java/org/apache/flink/core/fs/FileSystemAttachMetricsTest.java: ########## @@ -0,0 +1,243 @@ +/* + * 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.flink.core.fs; + +import org.apache.flink.configuration.Configuration; +import org.apache.flink.configuration.CoreOptions; +import org.apache.flink.core.plugin.MetricsAware; +import org.apache.flink.core.plugin.TestingPluginManager; +import org.apache.flink.metrics.MetricGroup; +import org.apache.flink.metrics.groups.UnregisteredMetricsGroup; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import javax.annotation.Nullable; + +import java.io.IOException; +import java.net.URI; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +/** + * Tests for {@link FileSystem#attachMetrics(MetricGroup)} and the {@link MetricsAware} contract. + */ +class FileSystemAttachMetricsTest { + + @AfterEach + void resetFileSystems() { + // Restore the default, plugin-less factory registry so other tests are unaffected. + FileSystem.initialize(new Configuration(), null); + } + + @Test + void attachMetricsReachesPluginLoadedMetricsAwareFactory() { + // Headline case: plugin file systems are registered behind wrappers such as + // PluginFileSystemFactory. attachMetrics must still reach the real factory, otherwise the + // metric group is silently never delivered and no metrics are ever emitted. + TestingFileSystemFactory factory = new TestingFileSystemFactory("metrics-test-fs"); + initializeWithPlugins(factory); + + RecordingMetricGroup processGroup = new RecordingMetricGroup(); + FileSystem.attachMetrics(processGroup); + + // Unwrapped through PluginFileSystemFactory and invoked exactly once. + assertThat(factory.setMetricGroupCalls).hasValue(1); + // The group handed to the factory is the "filesystem" child of the process group, not the + // process group itself. + assertThat(processGroup.childGroupNames).containsExactly("filesystem"); + assertThat(factory.receivedGroup.get()).isNotNull().isNotSameAs(processGroup); + } + + @Test + void attachMetricsReachesMetricsAwareFactoryBehindConnectionLimiter() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("limited-test-fs"); + Configuration config = new Configuration(); + config.set(CoreOptions.fileSystemConnectionLimit(factory.getScheme()), 1); + initializeWithPlugins(config, factory); + + FileSystem.attachMetrics(new UnregisteredMetricsGroup()); + + assertThat(factory.setMetricGroupCalls).hasValue(1); + } + + @Test + void attachMetricsSkipsFactoriesThatAreNotMetricsAware() { + // A factory that does not implement MetricsAware is filtered out by the instanceof check in + // attachMetrics, so it simply receives no group. One representative factory is enough. + initializeWithPlugins(new PlainFileSystemFactory("plain-test-fs")); + + assertThatCode(() -> FileSystem.attachMetrics(new UnregisteredMetricsGroup())) + .doesNotThrowAnyException(); + } + + @Test + void attachMetricsIsResilientToAFactoryThatThrows() { + TestingFileSystemFactory ok = new TestingFileSystemFactory("ok-test-fs"); + initializeWithPlugins( + new TestingFileSystemFactory( + "throwing-test-fs", + group -> { + throw new RuntimeException( + "intentional failure from a misbehaving plugin"); + }), + ok); + + // A misbehaving plugin must never break process startup, and well-behaved factories must + // still receive their group regardless of iteration order. + assertThatCode(() -> FileSystem.attachMetrics(new UnregisteredMetricsGroup())) + .doesNotThrowAnyException(); + assertThat(ok.setMetricGroupCalls).hasValue(1); + } + + @Test + void attachMetricsForwardsToFactoryOnEveryInvocation() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("idem-test-fs"); + initializeWithPlugins(factory); + + MetricGroup group = new UnregisteredMetricsGroup(); + FileSystem.attachMetrics(group); + FileSystem.attachMetrics(group); + + // The hook forwards on every call; collapsing duplicate registrations is the factory's + // responsibility, verified end-to-end in NativeS3FileSystemFactoryMetricsTest + // #repeatedAttachmentWithSameGroupDoesNotCreateNewFilesystemTypeGroup. + assertThat(factory.setMetricGroupCalls).hasValue(2); + } + + @Test + void setMetricGroupIsNotInvokedWhenAttachMetricsIsNeverCalled() { + TestingFileSystemFactory factory = new TestingFileSystemFactory("never-test-fs"); + initializeWithPlugins(factory); + + assertThat(factory.setMetricGroupCalls).hasValue(0); + } + + @Test + void pluginFileSystemFactoryForwardsMetricGroupToInner() { + TestingFileSystemFactory inner = new TestingFileSystemFactory("wrapped-fs"); + FileSystemFactory wrapper = PluginFileSystemFactory.of(inner); + + // The wrapper must itself be MetricsAware so attachMetrics reaches it without unwrapping. + assertThat(wrapper).isInstanceOf(MetricsAware.class); + + MetricGroup group = new UnregisteredMetricsGroup(); + ((MetricsAware) wrapper).setMetricGroup(group); + + assertThat(inner.setMetricGroupCalls).hasValue(1); + assertThat(inner.receivedGroup.get()).isSameAs(group); + } + + private static void initializeWithPlugins(FileSystemFactory... factories) { + initializeWithPlugins(new Configuration(), factories); + } + + private static void initializeWithPlugins( + Configuration config, FileSystemFactory... factories) { + Map<Class<?>, Iterator<?>> plugins = new HashMap<>(); + plugins.put(FileSystemFactory.class, Arrays.asList(factories).iterator()); + FileSystem.initialize(config, new TestingPluginManager(plugins)); + } + + // ------------------------------------------------------------------------ + // test factories + // ------------------------------------------------------------------------ + + private static class PlainFileSystemFactory implements FileSystemFactory { + private final String scheme; + + PlainFileSystemFactory(String scheme) { + this.scheme = scheme; + } + + @Override + public void configure(Configuration config) {} + + @Override + public String getScheme() { + return scheme; + } + + @Override + public FileSystem create(URI fsUri) throws IOException { + throw new UnsupportedOperationException("not needed for this test"); Review Comment: Exception should be actionable. If someone adds new test that invokes this method the test would fail with a contradicting exception. -- 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]
