Copilot commented on code in PR #65694: URL: https://github.com/apache/doris/pull/65694#discussion_r3593486481
########## fe/fe-common/src/main/java/org/apache/doris/common/MetaServiceRpcRateLimitConfigValidator.java: ########## @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.common; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public final class MetaServiceRpcRateLimitConfigValidator { + private MetaServiceRpcRateLimitConfigValidator() { + } + + public static Map<String, Integer> parseQpsPerCoreConfig(String config) throws ConfigException { + if (config == null || config.trim().isEmpty()) { + return Collections.emptyMap(); + } + + Map<String, Integer> qpsPerCore = new HashMap<>(); + Set<String> methods = new HashSet<>(); + for (String item : config.split(";")) { + String trimmedItem = item.trim(); + if (trimmedItem.isEmpty()) { + continue; + } + int separatorIndex = trimmedItem.indexOf(':'); + if (separatorIndex <= 0 || separatorIndex != trimmedItem.lastIndexOf(':') + || separatorIndex == trimmedItem.length() - 1) { + throw new ConfigException("Invalid format, expected method1:qps1;method2:qps2"); + } + + String methodName = trimmedItem.substring(0, separatorIndex).trim(); + String qpsText = trimmedItem.substring(separatorIndex + 1).trim(); + if (methodName.isEmpty() || qpsText.isEmpty()) { + throw new ConfigException("Invalid format, expected method1:qps1;method2:qps2"); + } + if (!methods.add(methodName)) { + throw new ConfigException("Duplicate method: " + methodName); + } + try { + qpsPerCore.put(methodName, Integer.parseInt(qpsText)); + } catch (NumberFormatException e) { + throw new ConfigException("Invalid qps for method: " + methodName, e); + } + } + return qpsPerCore; + } + + public static void validatePositive(String fieldName, int value) throws ConfigException { + if (value <= 0) { + throw new ConfigException(fieldName + " must be positive"); + } + } + + public static void validateNonNegative(String fieldName, long value) throws ConfigException { + if (value < 0) { + throw new ConfigException(fieldName + " must be non-negative"); + } + } + + public static class QpsConfigHandler extends ConfigBase.DefaultConfHandler { + @Override + public void handle(Field field, String confVal) throws Exception { + parseQpsPerCoreConfig(confVal); + super.handle(field, confVal); + } + } + + public static class PositiveIntConfigHandler extends ConfigBase.DefaultConfHandler { + @Override + public void handle(Field field, String confVal) throws Exception { + validatePositive(field.getName(), Integer.parseInt(confVal)); + super.handle(field, confVal); + } + } Review Comment: MetaServiceRpcRateLimitConfigValidator's mutable-config handlers parse numeric values from the raw `confVal` without trimming. `ConfigBase.setMutableConfig` passes the user-supplied value directly to the callback (no `.trim()`), so values like " 2 " will incorrectly fail with `NumberFormatException`, even though the default setter logic supports whitespace. ########## fe/fe-common/src/main/java/org/apache/doris/common/MetaServiceRpcRateLimitConfigValidator.java: ########## @@ -0,0 +1,101 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.common; + +import java.lang.reflect.Field; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public final class MetaServiceRpcRateLimitConfigValidator { + private MetaServiceRpcRateLimitConfigValidator() { + } + + public static Map<String, Integer> parseQpsPerCoreConfig(String config) throws ConfigException { + if (config == null || config.trim().isEmpty()) { + return Collections.emptyMap(); + } + + Map<String, Integer> qpsPerCore = new HashMap<>(); + Set<String> methods = new HashSet<>(); + for (String item : config.split(";")) { + String trimmedItem = item.trim(); + if (trimmedItem.isEmpty()) { + continue; + } + int separatorIndex = trimmedItem.indexOf(':'); + if (separatorIndex <= 0 || separatorIndex != trimmedItem.lastIndexOf(':') + || separatorIndex == trimmedItem.length() - 1) { + throw new ConfigException("Invalid format, expected method1:qps1;method2:qps2"); + } + + String methodName = trimmedItem.substring(0, separatorIndex).trim(); + String qpsText = trimmedItem.substring(separatorIndex + 1).trim(); + if (methodName.isEmpty() || qpsText.isEmpty()) { + throw new ConfigException("Invalid format, expected method1:qps1;method2:qps2"); + } + if (!methods.add(methodName)) { + throw new ConfigException("Duplicate method: " + methodName); + } + try { + qpsPerCore.put(methodName, Integer.parseInt(qpsText)); + } catch (NumberFormatException e) { + throw new ConfigException("Invalid qps for method: " + methodName, e); + } + } + return qpsPerCore; + } + + public static void validatePositive(String fieldName, int value) throws ConfigException { + if (value <= 0) { + throw new ConfigException(fieldName + " must be positive"); + } + } + + public static void validateNonNegative(String fieldName, long value) throws ConfigException { + if (value < 0) { + throw new ConfigException(fieldName + " must be non-negative"); + } + } + + public static class QpsConfigHandler extends ConfigBase.DefaultConfHandler { + @Override + public void handle(Field field, String confVal) throws Exception { + parseQpsPerCoreConfig(confVal); + super.handle(field, confVal); + } + } + + public static class PositiveIntConfigHandler extends ConfigBase.DefaultConfHandler { + @Override + public void handle(Field field, String confVal) throws Exception { + validatePositive(field.getName(), Integer.parseInt(confVal)); + super.handle(field, confVal); + } + } + + public static class NonNegativeLongConfigHandler extends ConfigBase.DefaultConfHandler { + @Override + public void handle(Field field, String confVal) throws Exception { + validateNonNegative(field.getName(), Long.parseLong(confVal)); + super.handle(field, confVal); + } + } Review Comment: MetaServiceRpcRateLimitConfigValidator's `NonNegativeLongConfigHandler` parses `confVal` without trimming. Since `ConfigBase.setMutableConfig` passes the raw value into callbacks, values with leading/trailing spaces can fail to set even though whitespace is otherwise accepted by `setConfigField()`. ########## fe/fe-core/src/main/java/org/apache/doris/cloud/rpc/MetaServiceRpcRateLimiter.java: ########## @@ -0,0 +1,253 @@ +// 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.doris.cloud.rpc; + +import org.apache.doris.common.Config; +import org.apache.doris.common.ConfigException; +import org.apache.doris.common.MetaServiceRpcRateLimitConfigValidator; +import org.apache.doris.metric.CloudMetrics; +import org.apache.doris.metric.MetricRepo; +import org.apache.doris.rpc.RpcException; + +import com.google.common.collect.Maps; +import io.github.resilience4j.ratelimiter.RateLimiter; +import io.github.resilience4j.ratelimiter.RateLimiterConfig; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.time.Duration; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +class MetaServiceRpcRateLimiter { + private static final Logger LOG = LogManager.getLogger(MetaServiceRpcRateLimiter.class); + + private static final int CPU_CORES = Runtime.getRuntime().availableProcessors(); + private static final RateLimitConfigSnapshot EMPTY_SNAPSHOT = + new RateLimitConfigSnapshot(0, "", 1, 0); + + private final ReentrantLock configLock = new ReentrantLock(); + private final ConcurrentMap<String, RateLimiterHolder> rateLimiters = Maps.newConcurrentMap(); + private volatile RateLimitConfigSnapshot currentSnapshot = EMPTY_SNAPSHOT; + private volatile Map<String, Integer> methodQpsPerCore = Collections.emptyMap(); + + long acquire(String methodName) throws RpcException { + return acquire(methodName, 1); + } + + long acquire(String methodName, int permits) throws RpcException { + if (!Config.meta_service_rpc_rate_limit_enabled) { + return 0; + } + + RateLimiterHolder holder = getRateLimiter(methodName); + if (holder == null) { + return 0; + } + + int permitsToAcquire = Math.min(Math.max(permits, 1), holder.limitForPeriod); + // Resilience4j returns negative when the estimated wait exceeds the configured timeout. + // Otherwise the returned wait time is within meta_service_rpc_rate_limit_wait_timeout_ms. + long nanosToWait = holder.rateLimiter.reservePermission(permitsToAcquire); + if (nanosToWait < 0) { + throw new MetaServiceRateLimitException(methodName, + Config.meta_service_rpc_rate_limit_wait_timeout_ms); + } + if (nanosToWait == 0) { + return 0; + } + + long waitMs = TimeUnit.NANOSECONDS.toMillis(nanosToWait); + if (LOG.isDebugEnabled()) { + LOG.debug("meta service rpc rate limiter waits before acquiring permission, method: {}, permits: {}, " + + "limit for period: {}, burst seconds: {}, wait ms: {}", + methodName, permitsToAcquire, holder.limitForPeriod, holder.burstSeconds, + waitMs); + } + long waitStartNs = System.nanoTime(); + try { + TimeUnit.NANOSECONDS.sleep(nanosToWait); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RpcException("", e.getMessage(), e); + } Review Comment: If the thread is interrupted while waiting for a rate-limiter permission, the thrown `RpcException` loses the method context and may end up with a null message (`e.getMessage()`). Including `methodName` in the error message makes debugging/observability much easier. ########## fe/fe-core/src/main/java/org/apache/doris/cloud/rpc/MetaServiceProxy.java: ########## @@ -105,24 +107,72 @@ public Cloud.GetInstanceResponse getInstance(Cloud.GetInstanceRequest request) } try { + acquireRateLimit(methodName); final MetaServiceClient client = getProxy(); Cloud.GetInstanceResponse response = client.getInstance(request); if (MetricRepo.isInit && Config.isCloudMode()) { CloudMetrics.META_SERVICE_RPC_LATENCY.getOrAdd(methodName) .update(System.currentTimeMillis() - startTime); } return response; + } catch (MetaServiceRateLimitException e) { + recordRpcRateLimited(methodName, startTime); + throw e; } catch (Exception e) { - if (MetricRepo.isInit && Config.isCloudMode()) { - CloudMetrics.META_SERVICE_RPC_ALL_FAILED.increase(1L); - CloudMetrics.META_SERVICE_RPC_FAILED.getOrAdd(methodName).increase(1L); - CloudMetrics.META_SERVICE_RPC_LATENCY.getOrAdd(methodName) - .update(System.currentTimeMillis() - startTime); - } + recordRpcFailed(methodName, startTime); throw new RpcException("", e.getMessage(), e); } } + private static long acquireRateLimit(String methodName) throws RpcException { + return META_SERVICE_RPC_RATE_LIMITER.acquire(methodName); + } + + private static long acquireRateLimit(String methodName, int permits) throws RpcException { + return META_SERVICE_RPC_RATE_LIMITER.acquire(methodName, permits); + } + + private static int getGetVersionRateLimitPermits(Cloud.GetVersionRequest request) { + if (!request.getBatchMode()) { + return 1; + } + int permits = request.hasIsTableVersion() && request.getIsTableVersion() + ? request.getTableIdsCount() + : request.getPartitionIdsCount(); + return Math.max(permits, 1); + } + + static void resetMetaServiceRpcRateLimitForTest() { + META_SERVICE_RPC_RATE_LIMITER.reset(); + } + + private static void recordRpcFailed(String methodName, long startTime) { + if (MetricRepo.isInit && Config.isCloudMode()) { + CloudMetrics.META_SERVICE_RPC_ALL_FAILED.increase(1L); + CloudMetrics.META_SERVICE_RPC_FAILED.getOrAdd(methodName).increase(1L); + CloudMetrics.META_SERVICE_RPC_LATENCY.getOrAdd(methodName) + .update(System.currentTimeMillis() - startTime); + } + } + + private static void recordRpcRateLimited(String methodName, long startTime) { + recordRpcFailed(methodName, startTime); + if (MetricRepo.isInit && Config.isCloudMode()) { + CloudMetrics.META_SERVICE_RPC_ALL_RATE_LIMITED.increase(1L); + CloudMetrics.META_SERVICE_RPC_RATE_LIMITED.getOrAdd(methodName).increase(1L); + } + } Review Comment: `recordRpcRateLimited()` currently calls `recordRpcFailed()`, which increments `meta_service_rpc_failed` / `meta_service_rpc_all_failed` even though rate limiting happens before making any RPC (`acquireRateLimit()` is invoked before `getProxy()` / client calls). This makes the "failed RPC calls" metrics include non-RPC rejections and double-count failures now that dedicated rate-limit counters exist. -- 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]
