ivandika3 commented on code in PR #10941: URL: https://github.com/apache/ozone/pull/10941#discussion_r4333663719
########## hadoop-ozone/mini-cluster/src/main/java/org/apache/hadoop/ozone/MetricsLeakAssertion.java: ########## @@ -0,0 +1,241 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.hadoop.ozone; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import org.apache.hadoop.metrics2.MetricsSource; +import org.apache.hadoop.metrics2.MetricsSystem; +import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem; + +/** + * Asserts that no metrics sources remain registered in the + * {@link DefaultMetricsSystem} after a mini cluster is shut down. + * + * <p>Hadoop's {@code MetricsSystemImpl} does not remove registered sources on + * {@code stop()} or {@code shutdown()}; a metrics class that forgets to call + * {@code unregisterSource(...)} leaks its registration silently. This helper + * inspects the private {@code allSources} map via reflection and fails the + * test if anything is still registered. + */ +public final class MetricsLeakAssertion { + + private static final String ALL_SOURCES_FIELD = "allSources"; + + /** + * Metrics sources that are registered once per JVM (or once per service) + * and intentionally never unregistered, so they are expected to still be + * present after a mini cluster shuts down. These are JVM-level singletons + * with no per-service owner; do not add per-service metrics here. + * + * <p>For the matching rules see {@link #isExpectedLeftover(String)}. + */ + private static final List<String> EXPECTED_LEFTOVER_SOURCES = Arrays.asList( + "JvmMetrics*", // per service, via HddsServerUtil.initializeMetrics + "JvmMetricsCpu", + "UgiMetrics", // Hadoop security UGI metrics + "ManagedRocksObjectMetrics", + "ContainerCacheMetrics" // ContainerCache singleton, created once per JVM + ); + + /** + * Metrics sources that leak: they should be unregistered when the mini + * cluster shuts down but currently are not. This is a transitional list to + * keep the integration suite green while the leaks are being fixed. Each + * entry should be removed once the corresponding source unregisters + * properly; do not add new entries, fix the leak instead. + * + * <p>For the matching rules see {@link #isExpectedLeftover(String)}. + */ + private static final List<String> TODO_LEFTOVER_SOURCES = Arrays.asList( + // RPC / HTTP server metrics (name embeds the listening port). + "RpcActivityForPort*", + "RpcDetailedActivityForPort*", + "HttpServer2*", + "LocalJobRunnerMetrics*", + + // Datanode per-instance metrics. + "StorageContainerMetrics", + "ContainerDataScannerMetrics*", // name embeds the volume path + "ContainerMetadataScannerMetrics", + "On-demand container scanner metrics", + "BackgroundVolumeScannerMetrics", + "VolumeHealthMetrics-*", + "VolumeIOStats-*", // name embeds the volume path + // Name embeds the volume path. Also intentionally kept registered for + // failed volumes (HDDS-7086), so only the healthy-volume case is a leak. + "VolumeInfoMetrics-*", + "CommandHandlerMetrics", + "HddsDispatcher", + "ECReconstructionMetrics", + "ReplicationSupervisorMetrics", + "ContainerReplicator/push", + "BlockDeletingService", + "GrpcMetrics", + + // SCM metrics. + "SCMNodeMetrics", + "SCMContainerManagerMetrics", + "SafeModeMetrics", + "ContainerBalancerMetrics", + "NodeDecommissionMetrics", + "SCMDatanodeProtocol", + "ScmBlockLocationProtocol", + "ScmContainerLocationProtocol", + "ScmSecurityProtocol", + "EventQueue*", // per event/handler pair, registered by SCM EventQueue + + // OM metrics. + "OMMetrics", + "OMPerformanceMetrics", + "OMLockMetrics", + "OMHAMetrics", + "OMSnapshotDirectoryMetrics", + "OmSnapshotMetrics", + "OmClientProtocol", + "DeletingServiceMetrics", + "KeyLifecycleServiceMetrics", + "BucketUtilizationMetrics", + "DelegationTokenSecretManagerMetrics", + + // OM / SCM RocksDB table cache and DB metrics (name embeds path/uuid). + "Rocksdb_*", + "SSTFilePruningMetrics-*", + "DBCheckpointMetrics", + "*TableCache", + + // Ratis / third-party infrastructure metrics. + "CSMMetricsgroup-*", // Ratis container state machine, embeds a random id + "CacheMetrics-*", // Hadoop cache metrics (XceiverClientManager, etc.) + "NettyMetrics*", + "ContainerClientMetrics1", + "ReconTaskMetrics", + "ReconTaskControllerMetrics" + ); + + private MetricsLeakAssertion() { + } + + /** + * Throws an {@link AssertionError} if any metrics sources are still + * registered with the default metrics system, or if the expected + * {@code allSources} field cannot be found or read (e.g. a Hadoop version + * change restructured {@code MetricsSystemImpl}), so that a broken or + * missing check fails loudly instead of going unnoticed. + */ + public static void assertNoLeaks() { + try { + MetricsSystem ms = DefaultMetricsSystem.instance(); + Field field = findAllSourcesField(ms.getClass()); + if (field == null) { + throw new AssertionError("Cannot check for metrics leaks: '" + ALL_SOURCES_FIELD + + "' field not found on " + ms.getClass().getName() + + ". The metrics system implementation may have changed."); + } + field.setAccessible(true); + Object value = field.get(ms); + if (!(value instanceof Map)) { + throw new AssertionError("Cannot check for metrics leaks: '" + ALL_SOURCES_FIELD + + "' on " + ms.getClass().getName() + " is not a Map."); + } + @SuppressWarnings("unchecked") + Map<String, MetricsSource> sources = (Map<String, MetricsSource>) value; + Set<String> leaked = new TreeSet<>(sources.keySet()); + leaked.removeIf(MetricsLeakAssertion::isExpectedLeftover); + if (!leaked.isEmpty()) { + throw new AssertionError("Found " + leaked.size() + Review Comment: Good idea, updated. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
