|
| 1 | +/* |
| 2 | + * Licensed to Elasticsearch under one or more contributor |
| 3 | + * license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright |
| 5 | + * ownership. Elasticsearch licenses this file to you under |
| 6 | + * the Apache License, Version 2.0 (the "License"); you may |
| 7 | + * not use this file except in compliance with the License. |
| 8 | + * You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.elasticsearch.script; |
| 21 | + |
| 22 | +import org.apache.logging.log4j.LogManager; |
| 23 | +import org.apache.logging.log4j.Logger; |
| 24 | +import org.elasticsearch.common.breaker.CircuitBreaker; |
| 25 | +import org.elasticsearch.common.breaker.CircuitBreakingException; |
| 26 | +import org.elasticsearch.common.cache.Cache; |
| 27 | +import org.elasticsearch.common.cache.CacheBuilder; |
| 28 | +import org.elasticsearch.common.cache.RemovalListener; |
| 29 | +import org.elasticsearch.common.cache.RemovalNotification; |
| 30 | +import org.elasticsearch.common.collect.Tuple; |
| 31 | +import org.elasticsearch.common.unit.TimeValue; |
| 32 | + |
| 33 | +import java.util.Map; |
| 34 | +import java.util.Objects; |
| 35 | + |
| 36 | +/** |
| 37 | + * Script cache and compilation rate limiter. |
| 38 | + */ |
| 39 | +public class ScriptCache { |
| 40 | + |
| 41 | + private static final Logger logger = LogManager.getLogger(ScriptService.class); |
| 42 | + |
| 43 | + private Cache<CacheKey, Object> cache; |
| 44 | + private final ScriptMetrics scriptMetrics = new ScriptMetrics(); |
| 45 | + |
| 46 | + private final Object lock = new Object(); |
| 47 | + |
| 48 | + private Tuple<Integer, TimeValue> rate; |
| 49 | + private long lastInlineCompileTime; |
| 50 | + private double scriptsPerTimeWindow; |
| 51 | + private double compilesAllowedPerNano; |
| 52 | + |
| 53 | + // Cache settings |
| 54 | + private int cacheSize; |
| 55 | + private TimeValue cacheExpire; |
| 56 | + |
| 57 | + public ScriptCache( |
| 58 | + int cacheMaxSize, |
| 59 | + TimeValue cacheExpire, |
| 60 | + Tuple<Integer, TimeValue> maxCompilationRate |
| 61 | + ) { |
| 62 | + CacheBuilder<CacheKey, Object> cacheBuilder = CacheBuilder.builder(); |
| 63 | + if (cacheMaxSize >= 0) { |
| 64 | + cacheBuilder.setMaximumWeight(cacheMaxSize); |
| 65 | + } |
| 66 | + |
| 67 | + if (cacheExpire.getNanos() != 0) { |
| 68 | + cacheBuilder.setExpireAfterAccess(cacheExpire); |
| 69 | + } |
| 70 | + |
| 71 | + logger.debug("using script cache with max_size [{}], expire [{}]", cacheMaxSize, cacheExpire); |
| 72 | + this.cache = cacheBuilder.removalListener(new ScriptCacheRemovalListener()).build(); |
| 73 | + |
| 74 | + this.lastInlineCompileTime = System.nanoTime(); |
| 75 | + |
| 76 | + this.cacheSize = cacheMaxSize; |
| 77 | + this.cacheExpire = cacheExpire; |
| 78 | + this.setMaxCompilationRate(maxCompilationRate); |
| 79 | + } |
| 80 | + |
| 81 | + private Cache<CacheKey,Object> buildCache() { |
| 82 | + CacheBuilder<CacheKey, Object> cacheBuilder = CacheBuilder.builder(); |
| 83 | + if (cacheSize >= 0) { |
| 84 | + cacheBuilder.setMaximumWeight(cacheSize); |
| 85 | + } |
| 86 | + if (cacheExpire.getNanos() != 0) { |
| 87 | + cacheBuilder.setExpireAfterAccess(cacheExpire); |
| 88 | + } |
| 89 | + return cacheBuilder.removalListener(new ScriptCacheRemovalListener()).build(); |
| 90 | + } |
| 91 | + |
| 92 | + <FactoryType> FactoryType compile( |
| 93 | + ScriptContext<FactoryType> context, |
| 94 | + ScriptEngine scriptEngine, |
| 95 | + String id, |
| 96 | + String idOrCode, |
| 97 | + ScriptType type, |
| 98 | + Map<String, String> options |
| 99 | + ) { |
| 100 | + String lang = scriptEngine.getType(); |
| 101 | + CacheKey cacheKey = new CacheKey(lang, idOrCode, context.name, options); |
| 102 | + Object compiledScript = cache.get(cacheKey); |
| 103 | + |
| 104 | + if (compiledScript != null) { |
| 105 | + return context.factoryClazz.cast(compiledScript); |
| 106 | + } |
| 107 | + |
| 108 | + // Synchronize so we don't compile scripts many times during multiple shards all compiling a script |
| 109 | + synchronized (lock) { |
| 110 | + // Retrieve it again in case it has been put by a different thread |
| 111 | + compiledScript = cache.get(cacheKey); |
| 112 | + |
| 113 | + if (compiledScript == null) { |
| 114 | + try { |
| 115 | + // Either an un-cached inline script or indexed script |
| 116 | + // If the script type is inline the name will be the same as the code for identification in exceptions |
| 117 | + // but give the script engine the chance to be better, give it separate name + source code |
| 118 | + // for the inline case, then its anonymous: null. |
| 119 | + if (logger.isTraceEnabled()) { |
| 120 | + logger.trace("context [{}]: compiling script, type: [{}], lang: [{}], options: [{}]", context.name, type, |
| 121 | + lang, options); |
| 122 | + } |
| 123 | + // Check whether too many compilations have happened |
| 124 | + checkCompilationLimit(); |
| 125 | + compiledScript = scriptEngine.compile(id, idOrCode, context, options); |
| 126 | + } catch (ScriptException good) { |
| 127 | + // TODO: remove this try-catch completely, when all script engines have good exceptions! |
| 128 | + throw good; // its already good |
| 129 | + } catch (Exception exception) { |
| 130 | + throw new GeneralScriptException("Failed to compile " + type + " script [" + id + "] using lang [" + lang + "]", |
| 131 | + exception); |
| 132 | + } |
| 133 | + |
| 134 | + // Since the cache key is the script content itself we don't need to |
| 135 | + // invalidate/check the cache if an indexed script changes. |
| 136 | + scriptMetrics.onCompilation(); |
| 137 | + cache.put(cacheKey, compiledScript); |
| 138 | + } |
| 139 | + |
| 140 | + } |
| 141 | + |
| 142 | + return context.factoryClazz.cast(compiledScript); |
| 143 | + } |
| 144 | + |
| 145 | + public ScriptStats stats() { |
| 146 | + return scriptMetrics.stats(); |
| 147 | + } |
| 148 | + |
| 149 | + /** |
| 150 | + * Check whether there have been too many compilations within the last minute, throwing a circuit breaking exception if so. |
| 151 | + * This is a variant of the token bucket algorithm: https://en.wikipedia.org/wiki/Token_bucket |
| 152 | + * |
| 153 | + * It can be thought of as a bucket with water, every time the bucket is checked, water is added proportional to the amount of time that |
| 154 | + * elapsed since the last time it was checked. If there is enough water, some is removed and the request is allowed. If there is not |
| 155 | + * enough water the request is denied. Just like a normal bucket, if water is added that overflows the bucket, the extra water/capacity |
| 156 | + * is discarded - there can never be more water in the bucket than the size of the bucket. |
| 157 | + */ |
| 158 | + void checkCompilationLimit() { |
| 159 | + if (rate.v1() == 0 && rate.v2().getNanos() == 0) { |
| 160 | + // unlimited |
| 161 | + return; |
| 162 | + } |
| 163 | + |
| 164 | + long now = System.nanoTime(); |
| 165 | + long timePassed = now - lastInlineCompileTime; |
| 166 | + lastInlineCompileTime = now; |
| 167 | + |
| 168 | + scriptsPerTimeWindow += (timePassed) * compilesAllowedPerNano; |
| 169 | + |
| 170 | + // It's been over the time limit anyway, readjust the bucket to be level |
| 171 | + if (scriptsPerTimeWindow > rate.v1()) { |
| 172 | + scriptsPerTimeWindow = rate.v1(); |
| 173 | + } |
| 174 | + |
| 175 | + // If there is enough tokens in the bucket, allow the request and decrease the tokens by 1 |
| 176 | + if (scriptsPerTimeWindow >= 1) { |
| 177 | + scriptsPerTimeWindow -= 1.0; |
| 178 | + } else { |
| 179 | + scriptMetrics.onCompilationLimit(); |
| 180 | + // Otherwise reject the request |
| 181 | + throw new CircuitBreakingException("[script] Too many dynamic script compilations within, max: [" + |
| 182 | + rate.v1() + "/" + rate.v2() +"]; please use indexed, or scripts with parameters instead; " + |
| 183 | + "this limit can be changed by the [script.max_compilations_rate] setting", |
| 184 | + CircuitBreaker.Durability.TRANSIENT); |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + /** |
| 189 | + * This configures the maximum script compilations per five minute window. |
| 190 | + * |
| 191 | + * @param newRate the new expected maximum number of compilations per five minute window |
| 192 | + */ |
| 193 | + void setMaxCompilationRate(Tuple<Integer, TimeValue> newRate) { |
| 194 | + synchronized (lock) { |
| 195 | + this.rate = newRate; |
| 196 | + // Reset the counter to allow new compilations |
| 197 | + this.scriptsPerTimeWindow = rate.v1(); |
| 198 | + this.compilesAllowedPerNano = ((double) rate.v1()) / newRate.v2().nanos(); |
| 199 | + |
| 200 | + this.cache = buildCache(); |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + /** |
| 205 | + * A small listener for the script cache that calls each |
| 206 | + * {@code ScriptEngine}'s {@code scriptRemoved} method when the |
| 207 | + * script has been removed from the cache |
| 208 | + */ |
| 209 | + private class ScriptCacheRemovalListener implements RemovalListener<CacheKey, Object> { |
| 210 | + @Override |
| 211 | + public void onRemoval(RemovalNotification<CacheKey, Object> notification) { |
| 212 | + if (logger.isDebugEnabled()) { |
| 213 | + logger.debug( |
| 214 | + "removed [{}] from cache, reason: [{}]", |
| 215 | + notification.getValue(), |
| 216 | + notification.getRemovalReason() |
| 217 | + ); |
| 218 | + } |
| 219 | + scriptMetrics.onCacheEviction(); |
| 220 | + } |
| 221 | + } |
| 222 | + |
| 223 | + private static final class CacheKey { |
| 224 | + final String lang; |
| 225 | + final String idOrCode; |
| 226 | + final String context; |
| 227 | + final Map<String, String> options; |
| 228 | + |
| 229 | + private CacheKey(String lang, String idOrCode, String context, Map<String, String> options) { |
| 230 | + this.lang = lang; |
| 231 | + this.idOrCode = idOrCode; |
| 232 | + this.context = context; |
| 233 | + this.options = options; |
| 234 | + } |
| 235 | + |
| 236 | + @Override |
| 237 | + public boolean equals(Object o) { |
| 238 | + if (this == o) return true; |
| 239 | + if (o == null || getClass() != o.getClass()) return false; |
| 240 | + CacheKey cacheKey = (CacheKey) o; |
| 241 | + return Objects.equals(lang, cacheKey.lang) && |
| 242 | + Objects.equals(idOrCode, cacheKey.idOrCode) && |
| 243 | + Objects.equals(context, cacheKey.context) && |
| 244 | + Objects.equals(options, cacheKey.options); |
| 245 | + } |
| 246 | + |
| 247 | + @Override |
| 248 | + public int hashCode() { |
| 249 | + return Objects.hash(lang, idOrCode, context, options); |
| 250 | + } |
| 251 | + } |
| 252 | +} |
0 commit comments