|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the Elastic License; |
| 4 | + * you may not use this file except in compliance with the Elastic License. |
| 5 | + */ |
| 6 | + |
| 7 | +package org.elasticsearch.xpack.core.security.authz.accesscontrol; |
| 8 | + |
| 9 | +import org.apache.logging.log4j.LogManager; |
| 10 | +import org.apache.logging.log4j.Logger; |
| 11 | +import org.apache.lucene.index.IndexReader; |
| 12 | +import org.apache.lucene.index.IndexReaderContext; |
| 13 | +import org.apache.lucene.index.LeafReaderContext; |
| 14 | +import org.apache.lucene.index.ReaderUtil; |
| 15 | +import org.apache.lucene.search.IndexSearcher; |
| 16 | +import org.apache.lucene.search.Query; |
| 17 | +import org.apache.lucene.search.ScoreMode; |
| 18 | +import org.apache.lucene.search.Scorer; |
| 19 | +import org.apache.lucene.search.Weight; |
| 20 | +import org.apache.lucene.util.Accountable; |
| 21 | +import org.apache.lucene.util.BitSet; |
| 22 | +import org.apache.lucene.util.FixedBitSet; |
| 23 | +import org.elasticsearch.common.Nullable; |
| 24 | +import org.elasticsearch.common.cache.Cache; |
| 25 | +import org.elasticsearch.common.cache.CacheBuilder; |
| 26 | +import org.elasticsearch.common.collect.MapBuilder; |
| 27 | +import org.elasticsearch.common.settings.Setting; |
| 28 | +import org.elasticsearch.common.settings.Setting.Property; |
| 29 | +import org.elasticsearch.common.settings.Settings; |
| 30 | +import org.elasticsearch.common.unit.ByteSizeUnit; |
| 31 | +import org.elasticsearch.common.unit.ByteSizeValue; |
| 32 | +import org.elasticsearch.common.unit.TimeValue; |
| 33 | +import org.elasticsearch.common.util.set.Sets; |
| 34 | + |
| 35 | +import java.io.Closeable; |
| 36 | +import java.util.Arrays; |
| 37 | +import java.util.List; |
| 38 | +import java.util.Map; |
| 39 | +import java.util.Objects; |
| 40 | +import java.util.Set; |
| 41 | +import java.util.concurrent.ConcurrentHashMap; |
| 42 | +import java.util.concurrent.ExecutionException; |
| 43 | + |
| 44 | +/** |
| 45 | + * This is a cache for {@link BitSet} instances that are used with the {@link DocumentSubsetReader}. |
| 46 | + * It is bounded by memory size and access time. |
| 47 | + * |
| 48 | + * @see org.elasticsearch.index.cache.bitset.BitsetFilterCache |
| 49 | + */ |
| 50 | +public final class DocumentSubsetBitsetCache implements IndexReader.ClosedListener, Closeable, Accountable { |
| 51 | + |
| 52 | + /** |
| 53 | + * The TTL defaults to 1 week. We depend on the {@code max_bytes} setting to keep the cache to a sensible size, by evicting LRU |
| 54 | + * entries, however there is benefit in reclaiming memory by expiring bitsets that have not be used for some period of time. |
| 55 | + * Because {@link org.elasticsearch.xpack.core.security.authz.permission.IndicesPermission.Group#query} can be templated, it is |
| 56 | + * not uncommon for a query to only be used for a relatively short period of time (e.g. because a user's metadata changed, or because |
| 57 | + * that user is an infrequent user of Elasticsearch). This access time expiry helps free up memory in those circumstances even if the |
| 58 | + * cache is never filled. |
| 59 | + */ |
| 60 | + static final Setting<TimeValue> CACHE_TTL_SETTING = |
| 61 | + Setting.timeSetting("xpack.security.dls.bitset.cache.ttl", TimeValue.timeValueHours(24 * 7), Property.NodeScope); |
| 62 | + |
| 63 | + static final Setting<ByteSizeValue> CACHE_SIZE_SETTING = Setting.byteSizeSetting("xpack.security.dls.bitset.cache.size", |
| 64 | + new ByteSizeValue(50, ByteSizeUnit.MB), Property.NodeScope); |
| 65 | + |
| 66 | + private static final BitSet NULL_MARKER = new FixedBitSet(0); |
| 67 | + |
| 68 | + private final Logger logger; |
| 69 | + private final Cache<BitsetCacheKey, BitSet> bitsetCache; |
| 70 | + private final Map<IndexReader.CacheKey, Set<BitsetCacheKey>> keysByIndex; |
| 71 | + |
| 72 | + public DocumentSubsetBitsetCache(Settings settings) { |
| 73 | + this.logger = LogManager.getLogger(getClass()); |
| 74 | + final TimeValue ttl = CACHE_TTL_SETTING.get(settings); |
| 75 | + final ByteSizeValue size = CACHE_SIZE_SETTING.get(settings); |
| 76 | + this.bitsetCache = CacheBuilder.<BitsetCacheKey, BitSet>builder() |
| 77 | + .setExpireAfterAccess(ttl) |
| 78 | + .setMaximumWeight(size.getBytes()) |
| 79 | + .weigher((key, bitSet) -> bitSet == NULL_MARKER ? 0 : bitSet.ramBytesUsed()).build(); |
| 80 | + this.keysByIndex = new ConcurrentHashMap<>(); |
| 81 | + } |
| 82 | + |
| 83 | + @Override |
| 84 | + public void onClose(IndexReader.CacheKey ownerCoreCacheKey) { |
| 85 | + final Set<BitsetCacheKey> keys = keysByIndex.remove(ownerCoreCacheKey); |
| 86 | + if (keys != null) { |
| 87 | + // Because this Set has been removed from the map, and the only update to the set is performed in a |
| 88 | + // Map#compute call, it should not be possible to get a concurrent modification here. |
| 89 | + keys.forEach(bitsetCache::invalidate); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + @Override |
| 94 | + public void close() { |
| 95 | + clear("close"); |
| 96 | + } |
| 97 | + |
| 98 | + public void clear(String reason) { |
| 99 | + logger.debug("clearing all DLS bitsets because [{}]", reason); |
| 100 | + // Due to the order here, it is possible than a new entry could be added _after_ the keysByIndex map is cleared |
| 101 | + // but _before_ the cache is cleared. This would mean it sits orphaned in keysByIndex, but this is not a issue. |
| 102 | + // When the index is closed, the key will be removed from the map, and there will not be a corresponding item |
| 103 | + // in the cache, which will make the cache-invalidate a no-op. |
| 104 | + // Since the entry is not in the cache, if #getBitSet is called, it will be loaded, and the new key will be added |
| 105 | + // to the index without issue. |
| 106 | + keysByIndex.clear(); |
| 107 | + bitsetCache.invalidateAll(); |
| 108 | + } |
| 109 | + |
| 110 | + int entryCount() { |
| 111 | + return this.bitsetCache.count(); |
| 112 | + } |
| 113 | + |
| 114 | + @Override |
| 115 | + public long ramBytesUsed() { |
| 116 | + return this.bitsetCache.weight(); |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Obtain the {@link BitSet} for the given {@code query} in the given {@code context}. |
| 121 | + * If there is a cached entry for that query and context, it will be returned. |
| 122 | + * Otherwise a new BitSet will be created and stored in the cache. |
| 123 | + * The returned BitSet may be null (e.g. if the query has no results). |
| 124 | + */ |
| 125 | + @Nullable |
| 126 | + public BitSet getBitSet(final Query query, final LeafReaderContext context) throws ExecutionException { |
| 127 | + final IndexReader.CacheHelper coreCacheHelper = context.reader().getCoreCacheHelper(); |
| 128 | + if (coreCacheHelper == null) { |
| 129 | + throw new IllegalArgumentException("Reader " + context.reader() + " does not support caching"); |
| 130 | + } |
| 131 | + coreCacheHelper.addClosedListener(this); |
| 132 | + final IndexReader.CacheKey indexKey = coreCacheHelper.getKey(); |
| 133 | + final BitsetCacheKey cacheKey = new BitsetCacheKey(indexKey, query); |
| 134 | + |
| 135 | + final BitSet bitSet = bitsetCache.computeIfAbsent(cacheKey, ignore1 -> { |
| 136 | + // This ensures all insertions into the set are guarded by ConcurrentHashMap's atomicity guarantees. |
| 137 | + keysByIndex.compute(indexKey, (ignore2, set) -> { |
| 138 | + if (set == null) { |
| 139 | + set = Sets.newConcurrentHashSet(); |
| 140 | + } |
| 141 | + set.add(cacheKey); |
| 142 | + return set; |
| 143 | + }); |
| 144 | + final IndexReaderContext topLevelContext = ReaderUtil.getTopLevelContext(context); |
| 145 | + final IndexSearcher searcher = new IndexSearcher(topLevelContext); |
| 146 | + searcher.setQueryCache(null); |
| 147 | + final Weight weight = searcher.createWeight(searcher.rewrite(query), ScoreMode.COMPLETE_NO_SCORES, 1f); |
| 148 | + Scorer s = weight.scorer(context); |
| 149 | + if (s == null) { |
| 150 | + // A cache loader is not allowed to return null, return a marker object instead. |
| 151 | + return NULL_MARKER; |
| 152 | + } else { |
| 153 | + return BitSet.of(s.iterator(), context.reader().maxDoc()); |
| 154 | + } |
| 155 | + }); |
| 156 | + if (bitSet == NULL_MARKER) { |
| 157 | + return null; |
| 158 | + } else { |
| 159 | + return bitSet; |
| 160 | + } |
| 161 | + } |
| 162 | + |
| 163 | + public static List<Setting<?>> getSettings() { |
| 164 | + return Arrays.asList(CACHE_TTL_SETTING, CACHE_SIZE_SETTING); |
| 165 | + } |
| 166 | + |
| 167 | + public Map<String, Object> usageStats() { |
| 168 | + final ByteSizeValue ram = new ByteSizeValue(ramBytesUsed(), ByteSizeUnit.BYTES); |
| 169 | + return new MapBuilder() |
| 170 | + .put("count", entryCount()) |
| 171 | + .put("memory", ram.toString()) |
| 172 | + .put("memory_in_bytes", ram.getBytes()) |
| 173 | + .immutableMap(); |
| 174 | + } |
| 175 | + |
| 176 | + private class BitsetCacheKey { |
| 177 | + final IndexReader.CacheKey index; |
| 178 | + final Query query; |
| 179 | + |
| 180 | + private BitsetCacheKey(IndexReader.CacheKey index, Query query) { |
| 181 | + this.index = index; |
| 182 | + this.query = query; |
| 183 | + } |
| 184 | + |
| 185 | + @Override |
| 186 | + public boolean equals(Object other) { |
| 187 | + if (this == other) { |
| 188 | + return true; |
| 189 | + } |
| 190 | + if (other == null || getClass() != other.getClass()) { |
| 191 | + return false; |
| 192 | + } |
| 193 | + final BitsetCacheKey that = (BitsetCacheKey) other; |
| 194 | + return Objects.equals(this.index, that.index) && |
| 195 | + Objects.equals(this.query, that.query); |
| 196 | + } |
| 197 | + |
| 198 | + @Override |
| 199 | + public int hashCode() { |
| 200 | + return Objects.hash(index, query); |
| 201 | + } |
| 202 | + |
| 203 | + @Override |
| 204 | + public String toString() { |
| 205 | + return getClass().getSimpleName() + "(" + index + "," + query + ")"; |
| 206 | + } |
| 207 | + } |
| 208 | +} |
0 commit comments