apoorvmittal10 commented on code in PR #14724: URL: https://github.com/apache/kafka/pull/14724#discussion_r1391698213
########## clients/src/main/java/org/apache/kafka/clients/ClientTelemetryUtils.java: ########## @@ -0,0 +1,202 @@ +/* + * 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.kafka.clients; + +import io.opentelemetry.proto.metrics.v1.MetricsData; + +import org.apache.kafka.common.KafkaException; +import org.apache.kafka.common.Uuid; +import org.apache.kafka.common.metrics.MetricsContext; +import org.apache.kafka.common.protocol.Errors; +import org.apache.kafka.common.record.CompressionType; +import org.apache.kafka.common.telemetry.internals.MetricKeyable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + +import static org.apache.kafka.clients.ClientTelemetryReporter.DEFAULT_PUSH_INTERVAL_MS; + +public class ClientTelemetryUtils { + + private final static Logger log = LoggerFactory.getLogger(ClientTelemetryUtils.class); + + public final static Predicate<? super MetricKeyable> SELECTOR_NO_METRICS = k -> false; + + public final static Predicate<? super MetricKeyable> SELECTOR_ALL_METRICS = k -> true; + + /** + * Examine the response data and handle different error code accordingly: + * + * <ul> + * <li>Invalid Request: Disable Telemetry</li> + * <li>Invalid Record: Disable Telemetry</li> + * <li>UnknownSubscription or Unsupported Compression: Retry immediately</li> + * <li>TelemetryTooLarge or ThrottlingQuotaExceeded: Retry as per next interval</li> + * </ul> + * + * @param errorCode response body error code + * @param intervalMs current push interval in milliseconds + * + * @return Optional of push interval in milliseconds + */ + public static Optional<Integer> maybeFetchErrorIntervalMs(short errorCode, int intervalMs) { + if (errorCode == Errors.NONE.code()) + return Optional.empty(); + + int pushIntervalMs; + String reason; + + switch (Errors.forCode(errorCode)) { + case INVALID_REQUEST: + case INVALID_RECORD: { + pushIntervalMs = Integer.MAX_VALUE; + reason = "The broker response indicates the client sent an request that cannot be resolved" + + " by re-trying, hence disable telemetry"; + break; + } + case UNKNOWN_SUBSCRIPTION_ID: + case UNSUPPORTED_COMPRESSION_TYPE: { + pushIntervalMs = 0; + reason = Errors.forCode(errorCode).message(); + break; + } + case TELEMETRY_TOO_LARGE: + case THROTTLING_QUOTA_EXCEEDED: { + reason = Errors.forCode(errorCode).message(); + pushIntervalMs = (intervalMs != -1) ? intervalMs : DEFAULT_PUSH_INTERVAL_MS; + break; + } + default: { + reason = "Unwrapped error code"; + log.error("Error code: {}, reason: {}. Unmapped error for telemetry, disable telemetry.", + errorCode, Errors.forCode(errorCode).message()); + pushIntervalMs = Integer.MAX_VALUE; + } + } + + log.debug("Error code: {}, reason: {}. Retry automatically in {} ms.", errorCode, reason, pushIntervalMs); + return Optional.of(pushIntervalMs); + } + + public static Predicate<? super MetricKeyable> getSelectorFromRequestedMetrics(List<String> requestedMetrics) { + if (requestedMetrics == null || requestedMetrics.isEmpty()) { + log.debug("Telemetry subscription has specified no metric names; telemetry will record no metrics"); + return SELECTOR_NO_METRICS; + } else if (requestedMetrics.size() == 1 && requestedMetrics.get(0) != null && requestedMetrics.get(0).isEmpty()) { + log.debug("Telemetry subscription has specified a single empty metric name; using all metrics"); + return SELECTOR_ALL_METRICS; + } else { + log.debug("Telemetry subscription has specified to include only metrics that are prefixed with the following strings: {}", requestedMetrics); + return k -> requestedMetrics.stream().anyMatch(f -> k.key().name().startsWith(f)); + } + } + + public static List<CompressionType> getCompressionTypesFromAcceptedList(List<Byte> acceptedCompressionTypes) { + if (acceptedCompressionTypes == null || acceptedCompressionTypes.isEmpty()) { + return Collections.emptyList(); + } + + List<CompressionType> result = new ArrayList<>(); + for (Byte compressionByte : acceptedCompressionTypes) { + int compressionId = compressionByte.intValue(); + try { + CompressionType compressionType = CompressionType.forId(compressionId); + result.add(compressionType); + } catch (IllegalArgumentException e) { + log.warn("Accepted compressionByte type with ID {} is not a known compressionByte type; ignoring", compressionId, e); + } + } + return result; + } + + public static Uuid validateClientInstanceId(Uuid clientInstanceId) { + if (clientInstanceId == null || clientInstanceId == Uuid.ZERO_UUID) { + throw new IllegalArgumentException("clientInstanceId is not valid"); + } + + return clientInstanceId; + } + + public static int validateIntervalMs(int intervalMs) { + if (intervalMs <= 0) { + log.warn("Telemetry subscription push interval value from broker was invalid ({})," + + " substituting with default value of {}", intervalMs, DEFAULT_PUSH_INTERVAL_MS); + return DEFAULT_PUSH_INTERVAL_MS; + } + + log.debug("Telemetry subscription push interval value from broker: {}", intervalMs); + return intervalMs; + } + + public static boolean validateRequiredResourceLabels(Map<String, String> metadata) { + return notEmptyString(metadata, MetricsContext.NAMESPACE); + } + + public static boolean notEmptyString(Map<String, ?> m, String key) { Review Comment: Done. -- 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: jira-unsubscr...@kafka.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org