From 255af6038ab81ae138479d4535ed8d8d14ddd1b2 Mon Sep 17 00:00:00 2001 From: Stuart Tettemer Date: Mon, 18 Oct 2021 20:57:46 -0500 Subject: [PATCH 1/3] Script: Restore the scripting general cache Restore the scripting general cache in preparation for deprecation of the context cache, then removal of the context cache in master. Brings back the general cache settings: * `script.max_compilations_rate` * `script.cache.expire` * `script.cache.max_size` `script.cache.max_size` and `script.cache.expire` are now dynamic settings. The context cache is still default, the switch to general cache as default will happen on context cache deprecation. System script contexts can now opt-out of compilation rate limiting using a flag rather than a sentinel rate limit value. Duplicated defaults for system contexts have been coalesced. Other than that, this code is the same as what was in 7.x to make a `master`-first commit and backport strategy easy. Refs: #62899 Backport: #79414 --- .../script/AbstractFieldScript.java | 44 +++++-------- .../script/IngestConditionalScript.java | 5 +- .../elasticsearch/script/IngestScript.java | 5 +- .../org/elasticsearch/script/ScriptCache.java | 13 ++-- .../script/ScriptCacheStats.java | 2 +- .../elasticsearch/script/ScriptContext.java | 24 ++++++-- .../elasticsearch/script/ScriptService.java | 15 +++-- .../org/elasticsearch/script/ScriptStats.java | 7 +++ .../elasticsearch/script/TemplateScript.java | 5 +- .../script/ScriptCacheTests.java | 61 ++++++++++++++++++- .../script/ScriptServiceTests.java | 35 ++++++++--- .../script/ScriptStatsTests.java | 9 +++ .../elasticsearch/xpack/watcher/Watcher.java | 4 +- .../condition/WatcherConditionScript.java | 5 +- .../script/WatcherTransformScript.java | 5 +- 15 files changed, 155 insertions(+), 84 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java b/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java index 14c780c08ba73..f2b1f2a6ac7e0 100644 --- a/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java +++ b/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java @@ -19,8 +19,6 @@ import java.util.Map; import java.util.function.Function; -import static org.elasticsearch.core.TimeValue.timeValueMillis; - /** * Abstract base for scripts to execute to build scripted fields. Inspired by * {@link AggregationScript} but hopefully with less historical baggage. @@ -32,33 +30,21 @@ public abstract class AbstractFieldScript extends DocBasedScript { public static final int MAX_VALUES = 100; static ScriptContext newContext(String name, Class factoryClass) { - return new ScriptContext<>( - name, - factoryClass, - /* - * We rely on the script cache in two ways: - * 1. It caches the "heavy" part of mappings generated at runtime. - * 2. Mapping updates tend to try to compile the script twice. Not - * for any good reason. They just do. - * Thus we use the default 100. - */ - 100, - timeValueMillis(0), - /* - * Disable compilation rate limits for runtime fields so we - * don't prevent mapping updates because we've performed too - * many recently. That'd just be lame. We also compile these - * scripts during search requests so this could totally be a - * source of runaway script compilations. We think folks will - * mostly reuse scripts though. - */ - ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), - /* - * Disable runtime fields scripts from being allowed - * to be stored as part of the script meta data. - */ - false - ); + /* + * We rely on the script cache in two ways: + * 1. It caches the "heavy" part of mappings generated at runtime. + * 2. Mapping updates tend to try to compile the script twice. Not + * for any good reason. They just do. + * Thus we use the default cache size. + * + * We also disable compilation rate limits for runtime fields so we + * don't prevent mapping updates because we've performed too + * many recently. That'd just be lame. We also compile these + * scripts during search requests so this could totally be a + * source of runaway script compilations. We think folks will + * mostly reuse scripts though. + */ + return new ScriptContext<>(name, factoryClass, false); } private static final Map> PARAMS_FUNCTIONS = org.elasticsearch.core.Map.of( diff --git a/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java b/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java index 430f6c22a116f..424f30e35973f 100644 --- a/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java +++ b/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java @@ -8,8 +8,6 @@ package org.elasticsearch.script; -import org.elasticsearch.core.TimeValue; - import java.util.Map; /** @@ -20,8 +18,7 @@ public abstract class IngestConditionalScript { public static final String[] PARAMETERS = { "ctx" }; /** The context used to compile {@link IngestConditionalScript} factories. */ - public static final ScriptContext CONTEXT = new ScriptContext<>("processor_conditional", Factory.class, - 200, TimeValue.timeValueMillis(0), ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), true); + public static final ScriptContext CONTEXT = new ScriptContext<>("processor_conditional", Factory.class, true); /** The generic runtime parameters for the script. */ private final Map params; diff --git a/server/src/main/java/org/elasticsearch/script/IngestScript.java b/server/src/main/java/org/elasticsearch/script/IngestScript.java index a0fa0d9bbdde8..4e9a7aa35a3a7 100644 --- a/server/src/main/java/org/elasticsearch/script/IngestScript.java +++ b/server/src/main/java/org/elasticsearch/script/IngestScript.java @@ -9,8 +9,6 @@ package org.elasticsearch.script; -import org.elasticsearch.core.TimeValue; - import java.util.Map; /** @@ -21,8 +19,7 @@ public abstract class IngestScript { public static final String[] PARAMETERS = { "ctx" }; /** The context used to compile {@link IngestScript} factories. */ - public static final ScriptContext CONTEXT = new ScriptContext<>("ingest", Factory.class, - 200, TimeValue.timeValueMillis(0), ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), true); + public static final ScriptContext CONTEXT = new ScriptContext<>("ingest", Factory.class, true); /** The generic runtime parameters for the script. */ private final Map params; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptCache.java b/server/src/main/java/org/elasticsearch/script/ScriptCache.java index 6e1ab496105da..b2fcdc9f24572 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptCache.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptCache.java @@ -44,12 +44,7 @@ public class ScriptCache { private final double compilesAllowedPerNano; private final String contextRateSetting; - ScriptCache( - int cacheMaxSize, - TimeValue cacheExpire, - CompilationRate maxCompilationRate, - String contextRateSetting - ) { + ScriptCache(int cacheMaxSize, TimeValue cacheExpire, CompilationRate maxCompilationRate, String contextRateSetting) { this.cacheSize = cacheMaxSize; this.cacheExpire = cacheExpire; this.contextRateSetting = contextRateSetting; @@ -94,8 +89,10 @@ FactoryType compile( logger.trace("context [{}]: compiling script, type: [{}], lang: [{}], options: [{}]", context.name, type, lang, options); } - // Check whether too many compilations have happened - checkCompilationLimit(); + if (context.compilationRateLimited) { + // Check whether too many compilations have happened + checkCompilationLimit(); + } Object compiledScript = scriptEngine.compile(id, idOrCode, context, options); // Since the cache key is the script content itself we don't need to // invalidate/check the cache if an indexed script changes. diff --git a/server/src/main/java/org/elasticsearch/script/ScriptCacheStats.java b/server/src/main/java/org/elasticsearch/script/ScriptCacheStats.java index d580f94a65a68..28183c1d46308 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptCacheStats.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptCacheStats.java @@ -21,7 +21,7 @@ import java.util.Objects; import java.util.stream.Collectors; -// This class is deprecated in favor of ScriptStats and ScriptContextStats. It is removed in 8. +// This class is deprecated in favor of ScriptStats and ScriptContextStats public class ScriptCacheStats implements Writeable, ToXContentFragment { private final Map context; private final ScriptStats general; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptContext.java b/server/src/main/java/org/elasticsearch/script/ScriptContext.java index eb158f444096c..aafee11d82b07 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptContext.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptContext.java @@ -47,6 +47,8 @@ * be {@code boolean needs_score()}. */ public final class ScriptContext { + /** The default compilation rate limit for contexts with compilation rate limiting enabled */ + public static final Tuple DEFAULT_COMPILATION_RATE_LIMIT = new Tuple<>(150, TimeValue.timeValueMinutes(5)); /** A unique identifier for this context. */ public final String name; @@ -66,15 +68,15 @@ public final class ScriptContext { /** The default expiration of a script in the cache for the context, if not overridden */ public final TimeValue cacheExpireDefault; - /** The default max compilation rate for scripts in this context. Script compilation is throttled if this is exceeded */ - public final Tuple maxCompilationRateDefault; + /** Is compilation rate limiting enabled for this context? */ + public final boolean compilationRateLimited; /** Determines if the script can be stored as part of the cluster state. */ public final boolean allowStoredScript; /** Construct a context with the related instance and compiled classes with caller provided cache defaults */ - public ScriptContext(String name, Class factoryClazz, int cacheSizeDefault, TimeValue cacheExpireDefault, - Tuple maxCompilationRateDefault, boolean allowStoredScript) { + ScriptContext(String name, Class factoryClazz, int cacheSizeDefault, TimeValue cacheExpireDefault, + boolean compilationRateLimited, boolean allowStoredScript) { this.name = name; this.factoryClazz = factoryClazz; Method newInstanceMethod = findMethod("FactoryType", factoryClazz, "newInstance"); @@ -98,7 +100,7 @@ public ScriptContext(String name, Class factoryClazz, int cacheSize this.cacheSizeDefault = cacheSizeDefault; this.cacheExpireDefault = cacheExpireDefault; - this.maxCompilationRateDefault = maxCompilationRateDefault; + this.compilationRateLimited = compilationRateLimited; this.allowStoredScript = allowStoredScript; } @@ -106,7 +108,17 @@ public ScriptContext(String name, Class factoryClazz, int cacheSize * maxCompilationRateDefault and allow scripts of this context to be stored scripts */ public ScriptContext(String name, Class factoryClazz) { // cache size default, cache expire default, max compilation rate are defaults from ScriptService. - this(name, factoryClazz, 100, TimeValue.timeValueMillis(0), new Tuple<>(75, TimeValue.timeValueMinutes(5)), true); + this(name, factoryClazz, 100, TimeValue.timeValueMillis(0), true, true); + } + + /** + * Construct a context for a system script usage, using the: + * - default cache size (only relevant when context caching enabled): 200 + * - default cache expiration: no expiration + * - unlimited compilation rate + */ + public ScriptContext(String name, Class factoryClazz, boolean allowStoredScript) { + this(name, factoryClazz, 200, TimeValue.timeValueMillis(0), false, allowStoredScript); } /** Returns a method with the given name, or throws an exception if multiple are found. */ diff --git a/server/src/main/java/org/elasticsearch/script/ScriptService.java b/server/src/main/java/org/elasticsearch/script/ScriptService.java index d760978b1d93e..b79c89150656a 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptService.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptService.java @@ -231,7 +231,7 @@ void registerClusterSettingsListeners(ClusterSettings clusterSettings) { // Handle all settings for context and general caches, this flips between general and context caches. clusterSettings.addSettingsUpdateConsumer( - (settings) -> setCacheHolder(settings), + this::setCacheHolder, Arrays.asList(SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING, SCRIPT_GENERAL_CACHE_EXPIRE_SETTING, SCRIPT_GENERAL_CACHE_SIZE_SETTING, @@ -565,8 +565,9 @@ void setCacheHolder(Settings settings) { } else if (current.general == null) { // Flipping to general cacheHolder.set(generalCacheHolder(settings)); - } else if (current.general.rate.equals(SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.get(settings)) == false) { - // General compilation rate changed, that setting is the only dynamically updated general setting + } else if (current.general.rate.equals(SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.get(settings)) == false || + current.general.cacheExpire.equals(SCRIPT_GENERAL_CACHE_EXPIRE_SETTING.get(settings)) == false || + current.general.cacheSize != SCRIPT_GENERAL_CACHE_SIZE_SETTING.get(settings)) { cacheHolder.set(generalCacheHolder(settings)); } } @@ -592,13 +593,15 @@ ScriptCache contextCache(Settings settings, ScriptContext context) { Setting rateSetting = SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getConcreteSettingForNamespace(context.name); - ScriptCache.CompilationRate rate = null; - if (SCRIPT_DISABLE_MAX_COMPILATIONS_RATE_SETTING.get(settings) || compilationLimitsEnabled() == false) { + ScriptCache.CompilationRate rate; + if (SCRIPT_DISABLE_MAX_COMPILATIONS_RATE_SETTING.get(settings) + || compilationLimitsEnabled() == false + || context.compilationRateLimited == false) { rate = SCRIPT_COMPILATION_RATE_ZERO; } else if (rateSetting.existsOrFallbackExists(settings)) { rate = rateSetting.get(settings); } else { - rate = new ScriptCache.CompilationRate(context.maxCompilationRateDefault); + rate = new ScriptCache.CompilationRate(ScriptContext.DEFAULT_COMPILATION_RATE_LIMIT); } return new ScriptCache(cacheSize, cacheExpire, rate, rateSetting.getKey()); diff --git a/server/src/main/java/org/elasticsearch/script/ScriptStats.java b/server/src/main/java/org/elasticsearch/script/ScriptStats.java index 832d44a46771e..b360a669052aa 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptStats.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptStats.java @@ -109,6 +109,13 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(Fields.COMPILATIONS, compilations); builder.field(Fields.CACHE_EVICTIONS, cacheEvictions); builder.field(Fields.COMPILATION_LIMIT_TRIGGERED, compilationLimitTriggered); + /* TODO(stu): master only + builder.startArray(Fields.CONTEXTS); + for (ScriptContextStats contextStats: contextStats) { + contextStats.toXContent(builder, params); + } + builder.endArray(); + */ builder.endObject(); return builder; } diff --git a/server/src/main/java/org/elasticsearch/script/TemplateScript.java b/server/src/main/java/org/elasticsearch/script/TemplateScript.java index d1777316434cf..ea7699ff3c883 100644 --- a/server/src/main/java/org/elasticsearch/script/TemplateScript.java +++ b/server/src/main/java/org/elasticsearch/script/TemplateScript.java @@ -8,8 +8,6 @@ package org.elasticsearch.script; -import org.elasticsearch.core.TimeValue; - import java.util.Map; /** @@ -41,6 +39,5 @@ public interface Factory { // Remove compilation rate limit for ingest. Ingest pipelines may use many mustache templates, triggering compilation // rate limiting. MustacheScriptEngine explicitly checks for TemplateScript. Rather than complicating the implementation there by // creating a new Script class (as would be customary), this context is used to avoid the default rate limit. - public static final ScriptContext INGEST_CONTEXT = new ScriptContext<>("ingest_template", Factory.class, - 200, TimeValue.timeValueMillis(0), ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), true); + public static final ScriptContext INGEST_CONTEXT = new ScriptContext<>("ingest_template", Factory.class, true); } diff --git a/server/src/test/java/org/elasticsearch/script/ScriptCacheTests.java b/server/src/test/java/org/elasticsearch/script/ScriptCacheTests.java index 6dc3cb3db72fc..efcbf07cd3f76 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptCacheTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptCacheTests.java @@ -8,14 +8,54 @@ package org.elasticsearch.script; import org.elasticsearch.common.breaker.CircuitBreakingException; +import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.core.TimeValue; import org.elasticsearch.test.ESTestCase; +import java.util.stream.Collectors; + public class ScriptCacheTests extends ESTestCase { // even though circuit breaking is allowed to be configured per minute, we actually weigh this over five minutes // simply by multiplying by five, so even setting it to one, requires five compilations to break public void testCompilationCircuitBreaking() throws Exception { + String context = randomFrom( + ScriptModule.CORE_CONTEXTS.values().stream().filter( + c -> c.compilationRateLimited + ).collect(Collectors.toList()) + ).name; + final TimeValue expire = ScriptService.SCRIPT_CACHE_EXPIRE_SETTING.getConcreteSettingForNamespace(context).get(Settings.EMPTY); + final Integer size = ScriptService.SCRIPT_CACHE_SIZE_SETTING.getConcreteSettingForNamespace(context).get(Settings.EMPTY); + Setting rateSetting = + ScriptService.SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getConcreteSettingForNamespace(context); + ScriptCache.CompilationRate rate = + ScriptService.SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getConcreteSettingForNamespace(context).get(Settings.EMPTY); + String rateSettingName = rateSetting.getKey(); + ScriptCache cache = new ScriptCache(size, expire, + new ScriptCache.CompilationRate(1, TimeValue.timeValueMinutes(1)), rateSettingName); + cache.checkCompilationLimit(); // should pass + expectThrows(CircuitBreakingException.class, cache::checkCompilationLimit); + cache = new ScriptCache(size, expire, new ScriptCache.CompilationRate(2, TimeValue.timeValueMinutes(1)), rateSettingName); + cache.checkCompilationLimit(); // should pass + cache.checkCompilationLimit(); // should pass + expectThrows(CircuitBreakingException.class, cache::checkCompilationLimit); + int count = randomIntBetween(5, 50); + cache = new ScriptCache(size, expire, new ScriptCache.CompilationRate(count, TimeValue.timeValueMinutes(1)), rateSettingName); + for (int i = 0; i < count; i++) { + cache.checkCompilationLimit(); // should pass + } + expectThrows(CircuitBreakingException.class, cache::checkCompilationLimit); + cache = new ScriptCache(size, expire, new ScriptCache.CompilationRate(0, TimeValue.timeValueMinutes(1)), rateSettingName); + expectThrows(CircuitBreakingException.class, cache::checkCompilationLimit); + cache = new ScriptCache(size, expire, + new ScriptCache.CompilationRate(Integer.MAX_VALUE, TimeValue.timeValueMinutes(1)), rateSettingName); + int largeLimit = randomIntBetween(1000, 10000); + for (int i = 0; i < largeLimit; i++) { + cache.checkCompilationLimit(); + } + } + + public void testGeneralCompilationCircuitBreaking() throws Exception { final TimeValue expire = ScriptService.SCRIPT_GENERAL_CACHE_EXPIRE_SETTING.get(Settings.EMPTY); final Integer size = ScriptService.SCRIPT_GENERAL_CACHE_SIZE_SETTING.get(Settings.EMPTY); String settingName = ScriptService.SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.getKey(); @@ -35,7 +75,7 @@ public void testCompilationCircuitBreaking() throws Exception { cache = new ScriptCache(size, expire, new ScriptCache.CompilationRate(0, TimeValue.timeValueMinutes(1)), settingName); expectThrows(CircuitBreakingException.class, cache::checkCompilationLimit); cache = new ScriptCache(size, expire, - new ScriptCache.CompilationRate(Integer.MAX_VALUE, TimeValue.timeValueMinutes(1)), settingName); + new ScriptCache.CompilationRate(Integer.MAX_VALUE, TimeValue.timeValueMinutes(1)), settingName); int largeLimit = randomIntBetween(1000, 10000); for (int i = 0; i < largeLimit; i++) { cache.checkCompilationLimit(); @@ -43,6 +83,25 @@ public void testCompilationCircuitBreaking() throws Exception { } public void testUnlimitedCompilationRate() { + String context = randomFrom( + ScriptModule.CORE_CONTEXTS.values().stream().filter( + c -> c.compilationRateLimited + ).collect(Collectors.toList()) + ).name; + final Integer size = ScriptService.SCRIPT_CACHE_SIZE_SETTING.getConcreteSettingForNamespace(context).get(Settings.EMPTY); + final TimeValue expire = ScriptService.SCRIPT_CACHE_EXPIRE_SETTING.getConcreteSettingForNamespace(context).get(Settings.EMPTY); + String settingName = ScriptService.SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getConcreteSettingForNamespace(context).getKey(); + ScriptCache cache = new ScriptCache(size, expire, ScriptCache.UNLIMITED_COMPILATION_RATE, settingName); + ScriptCache.TokenBucketState initialState = cache.tokenBucketState.get(); + for(int i=0; i < 3000; i++) { + cache.checkCompilationLimit(); + ScriptCache.TokenBucketState currentState = cache.tokenBucketState.get(); + assertEquals(initialState.lastInlineCompileTime, currentState.lastInlineCompileTime); + assertEquals(initialState.availableTokens, currentState.availableTokens, 0.0); // delta of 0.0 because it should never change + } + } + + public void testGeneralUnlimitedCompilationRate() { final Integer size = ScriptService.SCRIPT_GENERAL_CACHE_SIZE_SETTING.get(Settings.EMPTY); final TimeValue expire = ScriptService.SCRIPT_GENERAL_CACHE_EXPIRE_SETTING.get(Settings.EMPTY); String settingName = ScriptService.SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.getKey(); diff --git a/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java b/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java index 826340d6e2233..a201a65390fc8 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java @@ -38,6 +38,7 @@ import static org.elasticsearch.script.ScriptService.SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING; import static org.elasticsearch.script.ScriptService.SCRIPT_GENERAL_CACHE_SIZE_SETTING; import static org.elasticsearch.script.ScriptService.SCRIPT_MAX_COMPILATIONS_RATE_SETTING; +import static org.elasticsearch.script.ScriptService.USE_CONTEXT_RATE_KEY; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -51,6 +52,7 @@ public class ScriptServiceTests extends ESTestCase { private ScriptService scriptService; private Settings baseSettings; private ClusterSettings clusterSettings; + private Map> rateLimitedContexts; @Before public void setup() throws IOException { @@ -69,6 +71,7 @@ public void setup() throws IOException { engines.put(scriptEngine.getType(), scriptEngine); engines.put("test", new MockScriptEngine("test", scripts, Collections.emptyMap())); logger.info("--> setup script service"); + rateLimitedContexts = compilationRateLimitedContexts(); } private void buildScriptService(Settings additionalSettings) throws IOException { @@ -249,9 +252,9 @@ public void testCacheEvictionCountedInCacheEvictionsStats() throws IOException { } public void testContextCacheStats() throws IOException { - ScriptContext contextA = randomFrom(contexts.values()); + ScriptContext contextA = randomFrom(rateLimitedContexts.values()); String aRate = "2/10m"; - ScriptContext contextB = randomValueOtherThan(contextA, () -> randomFrom(contexts.values())); + ScriptContext contextB = randomValueOtherThan(contextA, () -> randomFrom(rateLimitedContexts.values())); String bRate = "3/10m"; BiFunction msg = (rate, ctx) -> ( "[script] Too many dynamic script compilations within, max: [" + rate + @@ -259,6 +262,7 @@ public void testContextCacheStats() throws IOException { ".max_compilations_rate] setting" ); buildScriptService(Settings.builder() + .put(SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.getKey(), USE_CONTEXT_RATE_KEY) .put(SCRIPT_CACHE_SIZE_SETTING.getConcreteSettingForNamespace(contextA.name).getKey(), 1) .put(SCRIPT_MAX_COMPILATIONS_RATE_SETTING.getConcreteSettingForNamespace(contextA.name).getKey(), aRate) .put(SCRIPT_CACHE_SIZE_SETTING.getConcreteSettingForNamespace(contextB.name).getKey(), 2) @@ -458,8 +462,8 @@ public void testCacheHolderGeneralConstructor() throws IOException { } public void testCacheHolderContextConstructor() throws IOException { - String a = randomFrom(contexts.keySet()); - String b = randomValueOtherThan(a, () -> randomFrom(contexts.keySet())); + String a = randomFrom(rateLimitedContexts.keySet()); + String b = randomValueOtherThan(a, () -> randomFrom(rateLimitedContexts.keySet())); String aCompilationRate = "77/5m"; String bCompilationRate = "78/6m"; @@ -525,7 +529,8 @@ public void testDisableCompilationRateSetting() throws IOException { } public void testCacheHolderChangeSettings() throws IOException { - Set contextNames = contexts.keySet(); + Set contextNames = contexts.entrySet().stream().filter(e -> e.getValue().compilationRateLimited) + .map(Map.Entry::getKey).collect(Collectors.toSet()); String a = randomFrom(contextNames); String aRate = "77/5m"; String b = randomValueOtherThan(a, () -> randomFrom(contextNames)); @@ -605,7 +610,7 @@ public void testFallbackToContextDefaults() throws IOException { Settings.builder().put(SCRIPT_GENERAL_MAX_COMPILATIONS_RATE_SETTING.getKey(), "75/5m").build() ); - String name = "ingest"; + String name = "score"; // Use context specific scriptService.setCacheHolder(Settings.builder() @@ -624,7 +629,7 @@ public void testFallbackToContextDefaults() throws IOException { assertEquals(contextCacheSize, holder.contextCache.get(name).get().cacheSize); assertEquals(contextExpire, holder.contextCache.get(name).get().cacheExpire); - ScriptContext ingest = contexts.get(name); + ScriptContext score = contexts.get(name); // Fallback to context defaults buildScriptService(Settings.EMPTY); @@ -633,9 +638,19 @@ public void testFallbackToContextDefaults() throws IOException { assertNotNull(holder.contextCache.get(name)); assertNotNull(holder.contextCache.get(name).get()); - assertEquals(ingest.maxCompilationRateDefault, holder.contextCache.get(name).get().rate.asTuple()); - assertEquals(ingest.cacheSizeDefault, holder.contextCache.get(name).get().cacheSize); - assertEquals(ingest.cacheExpireDefault, holder.contextCache.get(name).get().cacheExpire); + assertEquals(ScriptContext.DEFAULT_COMPILATION_RATE_LIMIT, holder.contextCache.get(name).get().rate.asTuple()); + assertEquals(score.cacheSizeDefault, holder.contextCache.get(name).get().cacheSize); + assertEquals(score.cacheExpireDefault, holder.contextCache.get(name).get().cacheExpire); + } + + protected HashMap> compilationRateLimitedContexts() { + HashMap> rateLimited = new HashMap<>(); + for (Map.Entry> entry: contexts.entrySet()) { + if (entry.getValue().compilationRateLimited) { + rateLimited.put(entry.getKey(), entry.getValue()); + } + } + return rateLimited; } private void assertCompileRejected(String lang, String script, ScriptType scriptType, ScriptContext scriptContext) { diff --git a/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java b/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java index adbcc2df1ece5..d7d5614f446b9 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java @@ -40,6 +40,15 @@ public void testXContent() throws IOException { stats.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); + /* TODO(stu): master only + String expected = "{\n" + + " \"script\" : {\n" + + " \"compilations\" : 1100,\n" + + " \"cache_evictions\" : 2211,\n" + + " \"compilation_limit_triggered\" : 3322\n" + + " }\n" + + "}"; + */ String expected = "{\n" + " \"script\" : {\n" + " \"compilations\" : 1100,\n" + diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java index 6dabe0fd2ddf4..00d722ab3cc34 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java @@ -53,7 +53,6 @@ import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestHandler; -import org.elasticsearch.script.ScriptCache; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.script.ScriptService; import org.elasticsearch.script.TemplateScript; @@ -236,8 +235,7 @@ public class Watcher extends Plugin implements SystemIndexPlugin, ScriptPlugin, new ByteSizeValue(1, ByteSizeUnit.MB), new ByteSizeValue(10, ByteSizeUnit.MB), NodeScope); public static final ScriptContext SCRIPT_TEMPLATE_CONTEXT - = new ScriptContext<>("xpack_template", TemplateScript.Factory.class, - 200, TimeValue.timeValueMillis(0), ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), true); + = new ScriptContext<>("xpack_template", TemplateScript.Factory.class, true); private static final Logger logger = LogManager.getLogger(Watcher.class); private WatcherIndexingListener listener; diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java index bc38efd0c6572..bd6446b82cb9c 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java @@ -6,8 +6,6 @@ */ package org.elasticsearch.xpack.watcher.condition; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.script.ScriptCache; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.watcher.support.Variables; @@ -44,6 +42,5 @@ public interface Factory { WatcherConditionScript newInstance(Map params, WatchExecutionContext watcherContext); } - public static ScriptContext CONTEXT = new ScriptContext<>("watcher_condition", Factory.class, - 200, TimeValue.timeValueMillis(0), ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), true); + public static ScriptContext CONTEXT = new ScriptContext<>("watcher_condition", Factory.class, true); } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java index 465f87cc26bd8..e661ea56711b4 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java @@ -6,8 +6,6 @@ */ package org.elasticsearch.xpack.watcher.transform.script; -import org.elasticsearch.core.TimeValue; -import org.elasticsearch.script.ScriptCache; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.watch.Payload; @@ -45,6 +43,5 @@ public interface Factory { WatcherTransformScript newInstance(Map params, WatchExecutionContext watcherContext, Payload payload); } - public static ScriptContext CONTEXT = new ScriptContext<>("watcher_transform", Factory.class, - 200, TimeValue.timeValueMillis(0), ScriptCache.UNLIMITED_COMPILATION_RATE.asTuple(), true); + public static ScriptContext CONTEXT = new ScriptContext<>("watcher_transform", Factory.class, true); } From 0a81b513156b365c5fdb805f29ec7e8a170ce58e Mon Sep 17 00:00:00 2001 From: Stuart Tettemer Date: Tue, 19 Oct 2021 07:41:55 -0500 Subject: [PATCH 2/3] Import Collectors --- .../test/java/org/elasticsearch/script/ScriptServiceTests.java | 1 + 1 file changed, 1 insertion(+) diff --git a/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java b/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java index a201a65390fc8..2ce96e03a639c 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptServiceTests.java @@ -31,6 +31,7 @@ import java.util.Set; import java.util.function.BiFunction; import java.util.function.Function; +import java.util.stream.Collectors; import static org.elasticsearch.script.ScriptService.SCRIPT_CACHE_EXPIRE_SETTING; import static org.elasticsearch.script.ScriptService.SCRIPT_CACHE_SIZE_SETTING; From 329162396ef39c9861d83d89197db8f3d8122ef9 Mon Sep 17 00:00:00 2001 From: Stuart Tettemer Date: Tue, 19 Oct 2021 12:01:50 -0500 Subject: [PATCH 3/3] Use full ScriptContext constructor, remove comments --- .../script/AbstractFieldScript.java | 44 ++++++++++++------- .../script/IngestConditionalScript.java | 5 ++- .../elasticsearch/script/IngestScript.java | 5 ++- .../elasticsearch/script/ScriptContext.java | 16 ++----- .../org/elasticsearch/script/ScriptStats.java | 7 --- .../elasticsearch/script/TemplateScript.java | 5 ++- .../script/ScriptStatsTests.java | 9 ---- .../elasticsearch/xpack/watcher/Watcher.java | 3 +- .../condition/WatcherConditionScript.java | 4 +- .../script/WatcherTransformScript.java | 4 +- 10 files changed, 52 insertions(+), 50 deletions(-) diff --git a/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java b/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java index f2b1f2a6ac7e0..73ae88fdebc57 100644 --- a/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java +++ b/server/src/main/java/org/elasticsearch/script/AbstractFieldScript.java @@ -19,6 +19,8 @@ import java.util.Map; import java.util.function.Function; +import static org.elasticsearch.core.TimeValue.timeValueMillis; + /** * Abstract base for scripts to execute to build scripted fields. Inspired by * {@link AggregationScript} but hopefully with less historical baggage. @@ -30,21 +32,33 @@ public abstract class AbstractFieldScript extends DocBasedScript { public static final int MAX_VALUES = 100; static ScriptContext newContext(String name, Class factoryClass) { - /* - * We rely on the script cache in two ways: - * 1. It caches the "heavy" part of mappings generated at runtime. - * 2. Mapping updates tend to try to compile the script twice. Not - * for any good reason. They just do. - * Thus we use the default cache size. - * - * We also disable compilation rate limits for runtime fields so we - * don't prevent mapping updates because we've performed too - * many recently. That'd just be lame. We also compile these - * scripts during search requests so this could totally be a - * source of runaway script compilations. We think folks will - * mostly reuse scripts though. - */ - return new ScriptContext<>(name, factoryClass, false); + return new ScriptContext<>( + name, + factoryClass, + /* + * We rely on the script cache in two ways: + * 1. It caches the "heavy" part of mappings generated at runtime. + * 2. Mapping updates tend to try to compile the script twice. Not + * for any good reason. They just do. + * Thus we use the default 100. + */ + 100, + timeValueMillis(0), + /* + * Disable compilation rate limits for runtime fields so we + * don't prevent mapping updates because we've performed too + * many recently. That'd just be lame. We also compile these + * scripts during search requests so this could totally be a + * source of runaway script compilations. We think folks will + * mostly reuse scripts though. + */ + false, + /* + * Disable runtime fields scripts from being allowed + * to be stored as part of the script meta data. + */ + false + ); } private static final Map> PARAMS_FUNCTIONS = org.elasticsearch.core.Map.of( diff --git a/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java b/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java index 424f30e35973f..caa6cbbe0164b 100644 --- a/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java +++ b/server/src/main/java/org/elasticsearch/script/IngestConditionalScript.java @@ -8,6 +8,8 @@ package org.elasticsearch.script; +import org.elasticsearch.core.TimeValue; + import java.util.Map; /** @@ -18,7 +20,8 @@ public abstract class IngestConditionalScript { public static final String[] PARAMETERS = { "ctx" }; /** The context used to compile {@link IngestConditionalScript} factories. */ - public static final ScriptContext CONTEXT = new ScriptContext<>("processor_conditional", Factory.class, true); + public static final ScriptContext CONTEXT = new ScriptContext<>("processor_conditional", Factory.class, + 200, TimeValue.timeValueMillis(0), false, true); /** The generic runtime parameters for the script. */ private final Map params; diff --git a/server/src/main/java/org/elasticsearch/script/IngestScript.java b/server/src/main/java/org/elasticsearch/script/IngestScript.java index 4e9a7aa35a3a7..bb444b132d1d0 100644 --- a/server/src/main/java/org/elasticsearch/script/IngestScript.java +++ b/server/src/main/java/org/elasticsearch/script/IngestScript.java @@ -9,6 +9,8 @@ package org.elasticsearch.script; +import org.elasticsearch.core.TimeValue; + import java.util.Map; /** @@ -19,7 +21,8 @@ public abstract class IngestScript { public static final String[] PARAMETERS = { "ctx" }; /** The context used to compile {@link IngestScript} factories. */ - public static final ScriptContext CONTEXT = new ScriptContext<>("ingest", Factory.class, true); + public static final ScriptContext CONTEXT = new ScriptContext<>("ingest", Factory.class, + 200, TimeValue.timeValueMillis(0), false, true); /** The generic runtime parameters for the script. */ private final Map params; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptContext.java b/server/src/main/java/org/elasticsearch/script/ScriptContext.java index aafee11d82b07..1e84d36b08b13 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptContext.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptContext.java @@ -75,8 +75,8 @@ public final class ScriptContext { public final boolean allowStoredScript; /** Construct a context with the related instance and compiled classes with caller provided cache defaults */ - ScriptContext(String name, Class factoryClazz, int cacheSizeDefault, TimeValue cacheExpireDefault, - boolean compilationRateLimited, boolean allowStoredScript) { + public ScriptContext(String name, Class factoryClazz, int cacheSizeDefault, TimeValue cacheExpireDefault, + boolean compilationRateLimited, boolean allowStoredScript) { this.name = name; this.factoryClazz = factoryClazz; Method newInstanceMethod = findMethod("FactoryType", factoryClazz, "newInstance"); @@ -105,22 +105,12 @@ public final class ScriptContext { } /** Construct a context with the related instance and compiled classes with defaults for cacheSizeDefault, cacheExpireDefault and - * maxCompilationRateDefault and allow scripts of this context to be stored scripts */ + * compilationRateLimited and allow scripts of this context to be stored scripts */ public ScriptContext(String name, Class factoryClazz) { // cache size default, cache expire default, max compilation rate are defaults from ScriptService. this(name, factoryClazz, 100, TimeValue.timeValueMillis(0), true, true); } - /** - * Construct a context for a system script usage, using the: - * - default cache size (only relevant when context caching enabled): 200 - * - default cache expiration: no expiration - * - unlimited compilation rate - */ - public ScriptContext(String name, Class factoryClazz, boolean allowStoredScript) { - this(name, factoryClazz, 200, TimeValue.timeValueMillis(0), false, allowStoredScript); - } - /** Returns a method with the given name, or throws an exception if multiple are found. */ private Method findMethod(String type, Class clazz, String methodName) { Method foundMethod = null; diff --git a/server/src/main/java/org/elasticsearch/script/ScriptStats.java b/server/src/main/java/org/elasticsearch/script/ScriptStats.java index b360a669052aa..832d44a46771e 100644 --- a/server/src/main/java/org/elasticsearch/script/ScriptStats.java +++ b/server/src/main/java/org/elasticsearch/script/ScriptStats.java @@ -109,13 +109,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field(Fields.COMPILATIONS, compilations); builder.field(Fields.CACHE_EVICTIONS, cacheEvictions); builder.field(Fields.COMPILATION_LIMIT_TRIGGERED, compilationLimitTriggered); - /* TODO(stu): master only - builder.startArray(Fields.CONTEXTS); - for (ScriptContextStats contextStats: contextStats) { - contextStats.toXContent(builder, params); - } - builder.endArray(); - */ builder.endObject(); return builder; } diff --git a/server/src/main/java/org/elasticsearch/script/TemplateScript.java b/server/src/main/java/org/elasticsearch/script/TemplateScript.java index ea7699ff3c883..7356be0bbdc32 100644 --- a/server/src/main/java/org/elasticsearch/script/TemplateScript.java +++ b/server/src/main/java/org/elasticsearch/script/TemplateScript.java @@ -8,6 +8,8 @@ package org.elasticsearch.script; +import org.elasticsearch.core.TimeValue; + import java.util.Map; /** @@ -39,5 +41,6 @@ public interface Factory { // Remove compilation rate limit for ingest. Ingest pipelines may use many mustache templates, triggering compilation // rate limiting. MustacheScriptEngine explicitly checks for TemplateScript. Rather than complicating the implementation there by // creating a new Script class (as would be customary), this context is used to avoid the default rate limit. - public static final ScriptContext INGEST_CONTEXT = new ScriptContext<>("ingest_template", Factory.class, true); + public static final ScriptContext INGEST_CONTEXT = new ScriptContext<>("ingest_template", Factory.class, + 200, TimeValue.timeValueMillis(0), false, true); } diff --git a/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java b/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java index d7d5614f446b9..adbcc2df1ece5 100644 --- a/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java +++ b/server/src/test/java/org/elasticsearch/script/ScriptStatsTests.java @@ -40,15 +40,6 @@ public void testXContent() throws IOException { stats.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); - /* TODO(stu): master only - String expected = "{\n" + - " \"script\" : {\n" + - " \"compilations\" : 1100,\n" + - " \"cache_evictions\" : 2211,\n" + - " \"compilation_limit_triggered\" : 3322\n" + - " }\n" + - "}"; - */ String expected = "{\n" + " \"script\" : {\n" + " \"compilations\" : 1100,\n" + diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java index 00d722ab3cc34..badfb05261c1d 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/Watcher.java @@ -235,7 +235,8 @@ public class Watcher extends Plugin implements SystemIndexPlugin, ScriptPlugin, new ByteSizeValue(1, ByteSizeUnit.MB), new ByteSizeValue(10, ByteSizeUnit.MB), NodeScope); public static final ScriptContext SCRIPT_TEMPLATE_CONTEXT - = new ScriptContext<>("xpack_template", TemplateScript.Factory.class, true); + = new ScriptContext<>("xpack_template", TemplateScript.Factory.class, + 200, TimeValue.timeValueMillis(0), false, true); private static final Logger logger = LogManager.getLogger(Watcher.class); private WatcherIndexingListener listener; diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java index bd6446b82cb9c..04d4b97a8508c 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/WatcherConditionScript.java @@ -6,6 +6,7 @@ */ package org.elasticsearch.xpack.watcher.condition; +import org.elasticsearch.core.TimeValue; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.watcher.support.Variables; @@ -42,5 +43,6 @@ public interface Factory { WatcherConditionScript newInstance(Map params, WatchExecutionContext watcherContext); } - public static ScriptContext CONTEXT = new ScriptContext<>("watcher_condition", Factory.class, true); + public static ScriptContext CONTEXT = new ScriptContext<>("watcher_condition", Factory.class, + 200, TimeValue.timeValueMillis(0), false, true); } diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java index e661ea56711b4..3a48e25635f1d 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/transform/script/WatcherTransformScript.java @@ -6,6 +6,7 @@ */ package org.elasticsearch.xpack.watcher.transform.script; +import org.elasticsearch.core.TimeValue; import org.elasticsearch.script.ScriptContext; import org.elasticsearch.xpack.core.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.core.watcher.watch.Payload; @@ -43,5 +44,6 @@ public interface Factory { WatcherTransformScript newInstance(Map params, WatchExecutionContext watcherContext, Payload payload); } - public static ScriptContext CONTEXT = new ScriptContext<>("watcher_transform", Factory.class, true); + public static ScriptContext CONTEXT = new ScriptContext<>("watcher_transform", Factory.class, + 200, TimeValue.timeValueMillis(0), false, true); }