BryanMLima commented on code in PR #9605:
URL: https://github.com/apache/cloudstack/pull/9605#discussion_r1771422822


##########
plugins/database/quota/src/main/java/org/apache/cloudstack/api/response/QuotaValidateActivationRuleResponse.java:
##########
@@ -0,0 +1,76 @@
+//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.cloudstack.api.response;
+
+import com.cloud.serializer.Param;
+import com.google.gson.annotations.SerializedName;
+import org.apache.cloudstack.api.BaseResponse;
+
+public class QuotaValidateActivationRuleResponse extends BaseResponse {
+
+    @SerializedName("activationrule")
+    @Param(description = "The validated activation rule.")

Review Comment:
   ```suggestion
       @Param(description = "The activation rule to be validated.")
   ```



##########
server/src/main/java/org/apache/cloudstack/jsinterpreter/JsInterpreterHelper.java:
##########
@@ -0,0 +1,235 @@
+// 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.cloudstack.jsinterpreter;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.logging.log4j.Logger;
+import org.apache.logging.log4j.LogManager;
+import org.openjdk.nashorn.api.scripting.ScriptUtils;
+import org.openjdk.nashorn.internal.runtime.Context;
+import org.openjdk.nashorn.internal.runtime.ErrorManager;
+import org.openjdk.nashorn.internal.runtime.options.Options;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class JsInterpreterHelper {
+    private final Logger logger = LogManager.getLogger(getClass());
+
+    private int callExpressions;
+
+    private StringBuilder variable;
+
+    private Set<String> variables;
+
+    /**
+     * Returns all variables from the given script.
+     *
+     * @param script the script to extract the variables.
+     * @return A {@link Set<String>} containing all variables in the script.
+     */
+    public Set<String> getScriptVariables(String script) {
+        String parseTree = getScriptAsJsonTree(script);
+        ObjectMapper mapper = new ObjectMapper();
+        JsonNode jsonNode = null;
+        variables = new HashSet<>();
+        variable = new StringBuilder();
+
+        try {
+            jsonNode = mapper.readTree(parseTree);
+        } catch (JsonProcessingException e) {
+            logger.error("Unable to create the script JSON tree due to: 
[{}].", e.getMessage(), e);
+        }
+
+        logger.trace("Searching script variables from [{}].", script);
+        iterateOverJsonTree(jsonNode.fields());
+
+        if (StringUtils.isNotBlank(variable.toString())) {
+            logger.trace("Adding variable [{}] into the variables set.", 
variable);
+            removeCallFunctionsFromVariable();
+            variables.add(variable.toString());
+        }
+
+        logger.trace("Found the following variables from the given script: 
[{}]", variables);
+        return variables;
+    }
+
+    private String getScriptAsJsonTree(String script) {
+        logger.trace("Creating JSON Tree for script [{}].", script);
+        Options options = new Options("nashorn");
+        options.set("anon.functions", true);
+        options.set("parse.only", true);
+        options.set("scripting", true);
+
+        ErrorManager errors = new ErrorManager();
+        Context context = new Context(options, errors, 
Thread.currentThread().getContextClassLoader());
+        Context.setGlobal(context.createGlobal());
+
+        return ScriptUtils.parse(script, "nashorn", false);
+    }
+
+    protected void iterateOverJsonTree(Iterator<Map.Entry<String, JsonNode>> 
iterator) {
+        while (iterator.hasNext()) {
+            iterateOverJsonTree(iterator.next());
+        }
+    }
+
+    protected void iterateOverJsonTree(Map.Entry<String, JsonNode> fields) {
+        JsonNode node = null;
+
+        if (fields.getValue().isArray()) {
+            iterateOverArrayNodes(fields);
+        } else {
+            node = fields.getValue();
+        }
+
+        String fieldName = searchIntoObjectNodes(node);
+
+        if (fieldName == null) {
+            String key = fields.getKey();
+            if ("type".equals(key) && 
"CallExpression".equals(node.textValue())) {
+                callExpressions++;
+            }
+
+            if ("name".equals(key) || "property".equals(key)) {

Review Comment:
   You could extract the Strings constants to variable, as they are used in 
other methods of this class.



##########
plugins/database/quota/src/main/java/org/apache/cloudstack/api/response/QuotaResponseBuilderImpl.java:
##########
@@ -928,4 +937,82 @@ protected QuotaConfigureEmailResponse 
createQuotaConfigureEmailResponse(QuotaEma
 
         return quotaConfigureEmailResponse;
     }
+
+    @Override
+    public QuotaValidateActivationRuleResponse 
validateActivationRule(QuotaValidateActivationRuleCmd cmd) {
+        String message;
+        String activationRule = cmd.getActivationRule();
+        QuotaTypes quotaType = cmd.getQuotaType();
+        String quotaName = quotaType.getQuotaName();
+        List<Pair<String, String>> usageTypeVariablesAndDescriptions = new 
ArrayList<>();
+
+        addAllPresetVariables(PresetVariables.class, quotaType, 
usageTypeVariablesAndDescriptions, null);
+        List<String> usageTypeVariables = 
usageTypeVariablesAndDescriptions.stream().map(Pair::first).collect(Collectors.toList());
+
+        try (JsInterpreter jsInterpreter = new 
JsInterpreter(QuotaConfig.QuotaActivationRuleTimeout.value())) {
+            Map<String, String> newVariables = 
injectUsageTypeVariables(jsInterpreter, usageTypeVariables);
+            String scriptToExecute = 
jsInterpreterHelper.replaceScriptVariables(activationRule, newVariables);
+            jsInterpreter.executeScript(String.format("new Function(\"%s\")", 
scriptToExecute.replaceAll("\n", "")));
+        } catch (IOException | CloudRuntimeException e) {
+            logger.error("Unable to execute activation rule due to: [{}].", 
e.getMessage(), e);
+            message = "Error while executing activation rule. Check if there 
are no syntax errors and all variables are compatible with the given usage 
type.";
+            return createValidateActivationRuleResponse(activationRule, 
quotaName, false, message);
+        }
+
+        Set<String> scriptVariables = 
jsInterpreterHelper.getScriptVariables(activationRule);
+        if (isScriptVariablesValid(scriptVariables, usageTypeVariables)) {
+            message = "The script has no syntax errors and all variables are 
compatible with the given usage type.";
+            return createValidateActivationRuleResponse(activationRule, 
quotaName, true, message);
+        }
+
+        message = "Found variables that are not compatible with the given 
usage type.";
+        return createValidateActivationRuleResponse(activationRule, quotaName, 
false, message);
+    }
+
+    /**
+     * Checks whether script variables are compatible with the usage type. 
First, we remove all script variables that correspond to the script's usage 
type variables.
+     * Then, returns true if none of the remaining script variables match any 
usage types variables, and false otherwise.
+     *
+     * @param scriptVariables Script variables.
+     * @param scriptUsageTypeVariables Script usage type variables.
+     * @return True if the script variables are valid, false otherwise.
+     */
+    protected boolean isScriptVariablesValid(Set<String> scriptVariables, 
List<String> scriptUsageTypeVariables) {
+        List<Pair<String, String>> allUsageTypeVariablesAndDescriptions = new 
ArrayList<>();
+        addAllPresetVariables(PresetVariables.class, null, 
allUsageTypeVariablesAndDescriptions, null);
+        List<String> allUsageTypesVariables = 
allUsageTypeVariablesAndDescriptions.stream().map(Pair::first).collect(Collectors.toList());
+
+        List<String> matchVariables = 
scriptVariables.stream().filter(scriptUsageTypeVariables::contains).collect(Collectors.toList());
+        matchVariables.forEach(scriptVariables::remove);
+
+        return 
scriptVariables.stream().noneMatch(allUsageTypesVariables::contains);
+    }
+
+    /**
+     *  Injects variables into JavaScript interpreter. It's necessary to 
remove all dots from the given variables for the interpreter

Review Comment:
   Just a minor suggestion
   ```suggestion
        *  Injects variables into JavaScript interpreter. It's necessary to 
remove all dots from the given variables, as the interpreter
   ```



-- 
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...@cloudstack.apache.org

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

Reply via email to