shounakmk219 commented on code in PR #14226:
URL: https://github.com/apache/pinot/pull/14226#discussion_r1806355671


##########
pinot-broker/src/main/java/org/apache/pinot/broker/queryquota/HelixExternalViewBasedQueryQuotaManager.java:
##########
@@ -81,15 +81,32 @@ public class HelixExternalViewBasedQueryQuotaManager 
implements ClusterChangeHan
   private final AtomicInteger _lastKnownBrokerResourceVersion = new 
AtomicInteger(-1);
   private final Map<String, QueryQuotaEntity> _rateLimiterMap = new 
ConcurrentHashMap<>();
   private final Map<String, QueryQuotaEntity> _databaseRateLimiterMap = new 
ConcurrentHashMap<>();
+  private final Map<String, QueryQuotaEntity> _applicationRateLimiterMap = new 
ConcurrentHashMap<>();
   private double _defaultQpsQuotaForDatabase;
+  private double _defaultQpsQuotaForApplication;
 
   private HelixManager _helixManager;
   private ZkHelixPropertyStore<ZNRecord> _propertyStore;
   private volatile boolean _queryRateLimitDisabled;
 
+  public interface RateLimiterFactory {

Review Comment:
   nit: can we move this after the constructor?



##########
pinot-broker/src/main/java/org/apache/pinot/broker/queryquota/HelixExternalViewBasedQueryQuotaManager.java:
##########
@@ -81,15 +81,32 @@ public class HelixExternalViewBasedQueryQuotaManager 
implements ClusterChangeHan
   private final AtomicInteger _lastKnownBrokerResourceVersion = new 
AtomicInteger(-1);
   private final Map<String, QueryQuotaEntity> _rateLimiterMap = new 
ConcurrentHashMap<>();
   private final Map<String, QueryQuotaEntity> _databaseRateLimiterMap = new 
ConcurrentHashMap<>();
+  private final Map<String, QueryQuotaEntity> _applicationRateLimiterMap = new 
ConcurrentHashMap<>();
   private double _defaultQpsQuotaForDatabase;
+  private double _defaultQpsQuotaForApplication;

Review Comment:
   What does a default application quota signify?



##########
pinot-broker/src/main/java/org/apache/pinot/broker/requesthandler/BaseSingleStageBrokerRequestHandler.java:
##########
@@ -308,6 +308,16 @@ protected BrokerResponse handleRequest(long requestId, 
String query, SqlNodeAndO
         }
       }
 
+      // check app qps before doing anything

Review Comment:
   Can we move the check even earlier before the query compilation? Actually 
can we do this at the `BaseBrokerRequestHandler` itself right after the 
`sqlNodeAndOptions` is parsed?



##########
pinot-broker/src/main/java/org/apache/pinot/broker/queryquota/HelixExternalViewBasedQueryQuotaManager.java:
##########
@@ -264,12 +318,22 @@ public void updateDatabaseRateLimiter(String 
databaseName) {
     createOrUpdateDatabaseRateLimiter(Collections.singletonList(databaseName));
   }
 
+  /**
+   * Updates the application rate limiter if it already exists. It won't  
create a new rate limiter.
+   *
+   * @param applicationName application name for which rate limiter needs to 
be updated
+   */
+  public void updateApplicationRateLimiter(String applicationName) {
+    if (!_applicationRateLimiterMap.containsKey(applicationName)) {
+      return;
+    }
+    
createOrUpdateApplicationRateLimiter(Collections.singletonList(applicationName));

Review Comment:
   nit: can call `createOrUpdateApplicationRateLimiter(String applicationName)` 
directly right?



##########
pinot-broker/src/main/java/org/apache/pinot/broker/queryquota/HelixExternalViewBasedQueryQuotaManager.java:
##########
@@ -308,10 +372,72 @@ private synchronized void 
createOrUpdateDatabaseRateLimiter(List<String> databas
       }
       LOGGER.info("Updating existing query rate limiter for database {} from 
rate {} to {}", databaseName, oldQuota,
           perBrokerQpsQuota);
-      
oldQueryQuotaEntity.setRateLimiter(RateLimiter.create(perBrokerQpsQuota));
+      oldQueryQuotaEntity.setRateLimiter(createRateLimiter(perBrokerQpsQuota));
+    }
+  }
+
+  public synchronized void createOrUpdateApplicationRateLimiter(String 
applicationName) {
+    
createOrUpdateApplicationRateLimiter(Collections.singletonList(applicationName));
+  }
+
+  // Caller method need not worry about getting lock on 
_applicationRateLimiterMap
+  // as this method will do idempotent updates to the application rate limiters
+  private synchronized void createOrUpdateApplicationRateLimiter(List<String> 
applicationNames) {
+    ExternalView brokerResource = getBrokerResource();
+    for (String appName : applicationNames) {
+      double appQpsQuota = getEffectiveQueryQuotaOnApplication(appName);
+      if (appQpsQuota < 0) {
+        buildEmptyOrResetApplicationRateLimiter(appName);
+        continue;
+      }
+      int numOnlineBrokers = getNumOnlineBrokers(brokerResource);
+      double perBrokerQpsQuota = appQpsQuota / numOnlineBrokers;
+      QueryQuotaEntity oldEntity = _applicationRateLimiterMap.get(appName);
+      if (oldEntity == null) {
+        LOGGER.info("Adding new query rate limiter for application {} with 
rate {}.", appName, perBrokerQpsQuota);
+        QueryQuotaEntity queryQuotaEntity =
+            new QueryQuotaEntity(createRateLimiter(perBrokerQpsQuota), new 
HitCounter(ONE_SECOND_TIME_RANGE_IN_SECOND),
+                new MaxHitRateTracker(ONE_MINUTE_TIME_RANGE_IN_SECOND), 
numOnlineBrokers, appQpsQuota, -1);
+        _applicationRateLimiterMap.put(appName, queryQuotaEntity);
+        continue;
+      }
+      boolean isChange = false;
+      double oldQuota = oldEntity.getRateLimiter() != null ? 
oldEntity.getRateLimiter().getRate() : -1;
+      if (oldEntity.getOverallRate() != appQpsQuota) {
+        isChange = true;
+        LOGGER.info("Overall quota changed for the application {} from {} to 
{}", appName, oldEntity.getOverallRate(),
+            appQpsQuota);
+        oldEntity.setOverallRate(appQpsQuota);
+      }
+      if (oldEntity.getNumOnlineBrokers() != numOnlineBrokers) {
+        isChange = true;
+        LOGGER.info("Number of online brokers changed for the application from 
{} to {}",
+            oldEntity.getNumOnlineBrokers(), numOnlineBrokers);
+        oldEntity.setNumOnlineBrokers(numOnlineBrokers);
+      }
+      if (!isChange) {
+        LOGGER.info("No change detected with the query rate limiter for 
application {}", appName);
+        continue;
+      }
+      LOGGER.info("Updating existing query rate limiter for application {} 
from rate {} to {}", appName, oldQuota,
+          perBrokerQpsQuota);
+      oldEntity.setRateLimiter(createRateLimiter(perBrokerQpsQuota));

Review Comment:
   can we extract this section from here and 
`createOrUpdateDatabaseRateLimiter` into a common method?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/helix/core/PinotHelixResourceManager.java:
##########
@@ -1664,6 +1679,18 @@ public void updateDatabaseConfig(DatabaseConfig 
databaseConfig) {
     sendDatabaseConfigRefreshMessage(databaseConfig.getDatabaseName());
   }
 
+  /**
+   * Updates application config and sends out a  refresh message.
+   *
+   * @param applicationName
+   */
+  public void updateApplicationConfig(String applicationName, Double value) {

Review Comment:
   We don't need this right?



##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotApplicationQuotaRestletResource.java:
##########
@@ -0,0 +1,163 @@
+/**
+ * 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.controller.api.resources;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiKeyAuthDefinition;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.Authorization;
+import io.swagger.annotations.SecurityDefinition;
+import io.swagger.annotations.SwaggerDefinition;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.helix.HelixAdmin;
+import org.apache.helix.model.HelixConfigScope;
+import org.apache.helix.model.builder.HelixConfigScopeBuilder;
+import 
org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.core.auth.Actions;
+import org.apache.pinot.core.auth.Authorize;
+import org.apache.pinot.core.auth.TargetType;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static 
org.apache.pinot.spi.utils.CommonConstants.SWAGGER_AUTHORIZATION_KEY;
+
+
+@Api(tags = Constants.DATABASE_TAG, authorizations = {@Authorization(value = 
SWAGGER_AUTHORIZATION_KEY)})
+@SwaggerDefinition(securityDefinition = 
@SecurityDefinition(apiKeyAuthDefinitions = {
+    @ApiKeyAuthDefinition(name = HttpHeaders.AUTHORIZATION, in = 
ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key =
+        SWAGGER_AUTHORIZATION_KEY, description =
+        "The format of the key is  ```\"Basic <token>\" or \"Bearer "
+            + "<token>\"```"), @ApiKeyAuthDefinition(name = 
CommonConstants.APPLICATION, in =
+    ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key = 
CommonConstants.APPLICATION, description =
+    "Application context passed through http header. If no context is provided 
'default' application "
+        + "context will be considered.")
+}))
+@Path("/")
+public class PinotApplicationQuotaRestletResource {
+  public static final Logger LOGGER = 
LoggerFactory.getLogger(PinotApplicationQuotaRestletResource.class);
+
+  @Inject
+  PinotHelixResourceManager _pinotHelixResourceManager;
+
+  /**
+   * API to get application quota configs. Will return null if application 
quotas are not defined
+   */
+  @GET
+  @Produces(MediaType.APPLICATION_JSON)
+  @Path("/applicationQuotas")
+  @Authorize(targetType = TargetType.CLUSTER, action = 
Actions.Cluster.GET_APPLICATION_QUERY_QUOTA)
+  @ApiOperation(value = "Get all application qps quotas", notes = "Get all 
application qps quotas")
+  public Map<String, Double> getApplicationQuotas(@Context HttpHeaders 
httpHeaders) {
+    Map<String, Double> quotas = 
_pinotHelixResourceManager.getApplicationQuotas();
+    if (quotas != null) {
+      return quotas;
+    }
+
+    HelixConfigScope scope = new 
HelixConfigScopeBuilder(HelixConfigScope.ConfigScopeProperty.CLUSTER).forCluster(
+        _pinotHelixResourceManager.getHelixClusterName()).build();
+    HelixAdmin helixAdmin = _pinotHelixResourceManager.getHelixAdmin();
+    String defaultQuota =
+        helixAdmin.getConfig(scope, 
Collections.singletonList(CommonConstants.Helix.APPLICATION_MAX_QUERIES_PER_SECOND))
+            
.getOrDefault(CommonConstants.Helix.APPLICATION_MAX_QUERIES_PER_SECOND, null);
+
+    quotas = new HashMap<>();
+    quotas.put(CommonConstants.DEFAULT_APPLICATION, defaultQuota != null ? 
Double.parseDouble(defaultQuota) : null);
+    return quotas;
+  }
+
+  /**
+   * API to get application quota configs. Will return null if application 
quotas are not defined
+   */
+  @GET
+  @Produces(MediaType.APPLICATION_JSON)
+  @Path("/applicationQuotas/{appName}")
+  @Authorize(targetType = TargetType.CLUSTER, action = 
Actions.Cluster.GET_APPLICATION_QUERY_QUOTA)
+  @ApiOperation(value = "Get application qps quota", notes = "Get application 
qps quota")
+  public Double getApplicationQuota(@Context HttpHeaders httpHeaders, 
@PathParam("appName") String appName) {
+    if (!appName.equals(extractApplicationFromHttpHeaders(httpHeaders))) {

Review Comment:
   Is there a specific usecase to allow application context through headers? If 
so we also need to look for the application header in the query path as well



##########
pinot-controller/src/main/java/org/apache/pinot/controller/api/resources/PinotApplicationQuotaRestletResource.java:
##########
@@ -0,0 +1,163 @@
+/**
+ * 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.controller.api.resources;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiKeyAuthDefinition;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.Authorization;
+import io.swagger.annotations.SecurityDefinition;
+import io.swagger.annotations.SwaggerDefinition;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import javax.inject.Inject;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.helix.HelixAdmin;
+import org.apache.helix.model.HelixConfigScope;
+import org.apache.helix.model.builder.HelixConfigScopeBuilder;
+import 
org.apache.pinot.controller.api.exception.ControllerApplicationException;
+import org.apache.pinot.controller.helix.core.PinotHelixResourceManager;
+import org.apache.pinot.core.auth.Actions;
+import org.apache.pinot.core.auth.Authorize;
+import org.apache.pinot.core.auth.TargetType;
+import org.apache.pinot.spi.utils.CommonConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static 
org.apache.pinot.spi.utils.CommonConstants.SWAGGER_AUTHORIZATION_KEY;
+
+
+@Api(tags = Constants.DATABASE_TAG, authorizations = {@Authorization(value = 
SWAGGER_AUTHORIZATION_KEY)})

Review Comment:
   May need a separate tag for application



-- 
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: commits-unsubscr...@pinot.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscr...@pinot.apache.org
For additional commands, e-mail: commits-h...@pinot.apache.org

Reply via email to