xiangfu0 commented on code in PR #18784:
URL: https://github.com/apache/pinot/pull/18784#discussion_r3435663051


##########
pinot-core/src/main/java/org/apache/pinot/core/data/manager/realtime/ServerIngestionOomProtectionManager.java:
##########
@@ -0,0 +1,464 @@
+/**
+ * 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.pinot.core.data.manager.realtime;
+
+import com.google.common.annotations.VisibleForTesting;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.BooleanSupplier;
+import java.util.function.LongSupplier;
+import java.util.function.Supplier;
+import javax.annotation.Nullable;
+import org.apache.pinot.common.metrics.ServerGauge;
+import org.apache.pinot.common.metrics.ServerMetrics;
+import org.apache.pinot.spi.config.provider.PinotClusterConfigChangeListener;
+import org.apache.pinot.spi.config.table.TableConfig;
+import org.apache.pinot.spi.config.table.ingestion.IngestionConfig;
+import 
org.apache.pinot.spi.config.table.ingestion.ServerIngestionOomProtectionConfig;
+import org.apache.pinot.spi.config.table.ingestion.StreamIngestionConfig;
+import org.apache.pinot.spi.env.PinotConfiguration;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.apache.pinot.spi.utils.ResourceUsageUtils;
+import org.apache.pinot.spi.utils.builder.TableNameBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/// Applies server-local backpressure to realtime ingestion while JVM heap 
usage is above a configured threshold.
+public class ServerIngestionOomProtectionManager {
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(ServerIngestionOomProtectionManager.class);
+  private static final AtomicLong LAST_GC_REQUEST_TIME_MS = new 
AtomicLong(-1L);
+  private static final Object DEFAULT_SERVER_THROTTLE_STATE_LOCK = new 
Object();
+  private static final String SERVER_INSTANCE_CONFIG_PREFIX =
+      CommonConstants.Server.INSTANCE_DATA_MANAGER_CONFIG_PREFIX + ".";
+  private static final Set<String> SERVER_INGESTION_OOM_PROTECTION_CONFIG_KEYS 
= Set.of(
+      CommonConstants.Server.CONFIG_OF_SERVER_INGESTION_OOM_PROTECTION_MODE,
+      
CommonConstants.Server.CONFIG_OF_SERVER_INGESTION_OOM_PROTECTION_HEAP_USAGE_THROTTLE_THRESHOLD,
+      
CommonConstants.Server.CONFIG_OF_SERVER_INGESTION_OOM_PROTECTION_HEAP_USAGE_RECOVERY_THRESHOLD,
+      
CommonConstants.Server.CONFIG_OF_SERVER_INGESTION_OOM_PROTECTION_CHECK_INTERVAL_MS,
+      
CommonConstants.Server.CONFIG_OF_SERVER_INGESTION_OOM_PROTECTION_GC_INTERVAL_MS);
+  private static final PinotClusterConfigChangeListener 
CLUSTER_CONFIG_CHANGE_LISTENER =
+      ServerIngestionOomProtectionManager::onClusterConfigChange;
+
+  @Nullable
+  private static volatile ServerThrottleState _defaultServerThrottleState;
+  private static volatile Map<String, String> 
_clusterConfigsForDefaultThrottleState = Map.of();
+
+  enum ServerMode {
+    ENABLE, UPSERT_DEDUP_ONLY, DISABLE
+  }
+
+  private final Supplier<TableConfig> _tableConfigSupplier;
+  private final BooleanSupplier _isUpsertOrDedupEnabledSupplier;
+  private final ServerThrottleState _serverThrottleState;
+
+  public ServerIngestionOomProtectionManager(@Nullable PinotConfiguration 
instanceDataManagerConfig,
+      Supplier<TableConfig> tableConfigSupplier,
+      BooleanSupplier isUpsertOrDedupEnabledSupplier, ServerMetrics 
serverMetrics) {
+    this(instanceDataManagerConfig, tableConfigSupplier, 
isUpsertOrDedupEnabledSupplier,
+        getOrCreateDefaultServerThrottleState(instanceDataManagerConfig, 
serverMetrics));
+  }
+
+  @VisibleForTesting
+  ServerIngestionOomProtectionManager(@Nullable PinotConfiguration 
instanceDataManagerConfig,
+      Supplier<TableConfig> tableConfigSupplier,
+      BooleanSupplier isUpsertOrDedupEnabledSupplier, ServerMetrics 
serverMetrics, LongSupplier usedHeapSupplier,
+      LongSupplier maxHeapSupplier, LongSupplier currentTimeMsSupplier) {
+    this(instanceDataManagerConfig, tableConfigSupplier, 
isUpsertOrDedupEnabledSupplier, serverMetrics,
+        usedHeapSupplier, maxHeapSupplier, currentTimeMsSupplier, System::gc);
+  }
+
+  @VisibleForTesting
+  ServerIngestionOomProtectionManager(@Nullable PinotConfiguration 
instanceDataManagerConfig,
+      Supplier<TableConfig> tableConfigSupplier,
+      BooleanSupplier isUpsertOrDedupEnabledSupplier, ServerMetrics 
serverMetrics, LongSupplier usedHeapSupplier,
+      LongSupplier maxHeapSupplier, LongSupplier currentTimeMsSupplier, 
Runnable gcRunner) {
+    this(instanceDataManagerConfig, tableConfigSupplier, 
isUpsertOrDedupEnabledSupplier,
+        new ServerThrottleState(instanceDataManagerConfig, serverMetrics, 
usedHeapSupplier, maxHeapSupplier,
+            currentTimeMsSupplier, gcRunner));
+  }
+
+  @VisibleForTesting
+  ServerIngestionOomProtectionManager(@Nullable PinotConfiguration 
instanceDataManagerConfig,
+      Supplier<TableConfig> tableConfigSupplier, BooleanSupplier 
isUpsertOrDedupEnabledSupplier,
+      ServerThrottleState serverThrottleState) {
+    _tableConfigSupplier = tableConfigSupplier;
+    _isUpsertOrDedupEnabledSupplier = isUpsertOrDedupEnabledSupplier;
+    _serverThrottleState = serverThrottleState;
+  }
+
+  public boolean waitIfProtectionNeeded(BooleanSupplier stopCondition)
+      throws InterruptedException {
+    boolean waited = false;
+    while (!stopCondition.getAsBoolean() && shouldThrottle()) {
+      waited = true;
+      Thread.sleep(_serverThrottleState.getCheckIntervalMs());
+    }
+    return waited;
+  }
+
+  @VisibleForTesting
+  boolean shouldThrottle() {
+    return isEnabledForTable(_tableConfigSupplier.get()) && 
_serverThrottleState.shouldThrottle();
+  }
+
+  @VisibleForTesting
+  boolean isThrottling() {
+    return _serverThrottleState.isThrottling();
+  }
+
+  @VisibleForTesting
+  void resetMetrics() {
+    _serverThrottleState.resetMetrics();
+  }
+
+  private boolean isEnabledForTable(@Nullable TableConfig tableConfig) {
+    if (tableConfig == null || 
!TableNameBuilder.isRealtimeTableResource(tableConfig.getTableName())) {
+      return false;
+    }
+    ServerIngestionOomProtectionConfig config = getConfig(tableConfig);
+    ServerIngestionOomProtectionConfig.Mode tableOverride = config != null ? 
config.getMode() : null;
+    if (tableOverride == ServerIngestionOomProtectionConfig.Mode.ENABLE) {
+      return true;
+    }
+    if (tableOverride == ServerIngestionOomProtectionConfig.Mode.DISABLE) {
+      return false;
+    }
+    ServerMode serverMode = _serverThrottleState.getMode();
+    return serverMode == ServerMode.ENABLE
+        || (serverMode == ServerMode.UPSERT_DEDUP_ONLY && 
_isUpsertOrDedupEnabledSupplier.getAsBoolean());
+  }
+
+  @Nullable
+  private static ServerIngestionOomProtectionConfig getConfig(@Nullable 
TableConfig tableConfig) {
+    if (tableConfig == null) {
+      return null;
+    }
+    IngestionConfig ingestionConfig = tableConfig.getIngestionConfig();
+    if (ingestionConfig == null) {
+      return null;
+    }
+    StreamIngestionConfig streamIngestionConfig = 
ingestionConfig.getStreamIngestionConfig();
+    return streamIngestionConfig != null ? 
streamIngestionConfig.getOomProtectionConfig() : null;
+  }
+
+  @VisibleForTesting
+  static void resetGcRequestTime() {
+    LAST_GC_REQUEST_TIME_MS.set(-1L);
+  }
+
+  @VisibleForTesting
+  static void resetDefaultServerThrottleState() {
+    _defaultServerThrottleState = null;
+    _clusterConfigsForDefaultThrottleState = Map.of();
+    resetGcRequestTime();
+  }
+
+  public static PinotClusterConfigChangeListener 
getClusterConfigChangeListener() {
+    return CLUSTER_CONFIG_CHANGE_LISTENER;
+  }
+
+  private static ServerThrottleState getOrCreateDefaultServerThrottleState(
+      @Nullable PinotConfiguration instanceDataManagerConfig, ServerMetrics 
serverMetrics) {
+    ServerThrottleState state = _defaultServerThrottleState;
+    if (state != null) {
+      return state;
+    }
+    synchronized (DEFAULT_SERVER_THROTTLE_STATE_LOCK) {
+      state = _defaultServerThrottleState;
+      if (state == null) {
+        state = new ServerThrottleState(instanceDataManagerConfig, 
serverMetrics, ResourceUsageUtils::getUsedHeapSize,
+            ResourceUsageUtils::getMaxHeapSize, System::currentTimeMillis, 
System::gc,
+            _clusterConfigsForDefaultThrottleState);
+        _defaultServerThrottleState = state;
+      }
+      return state;
+    }
+  }
+
+  private static void onClusterConfigChange(Set<String> changedConfigs, 
Map<String, String> clusterConfigs) {
+    if (!containsIngestionOomProtectionConfig(changedConfigs)) {
+      return;
+    }
+    Map<String, String> clusterConfigSnapshot = Map.copyOf(clusterConfigs);
+    _clusterConfigsForDefaultThrottleState = clusterConfigSnapshot;

Review Comment:
   This stores the raw cluster-config snapshot before validating it. If someone 
pushes a malformed OOM-protection value here, and the shared throttle state has 
not been created yet, `getOrCreateDefaultServerThrottleState()` will later 
rebuild `ConfigSnapshot` from `_clusterConfigsForDefaultThrottleState` outside 
the `updateConfigFromClusterConfigs()` try/catch and fail the first 
realtime-table initialization instead of ignoring the bad dynamic update. 
Please only publish the last known-good snapshot/config after validation 
succeeds.



-- 
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]

Reply via email to