add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / src / java / org / apache / lucene / util / FieldCacheSanityChecker.java
1 package org.apache.lucene.util;
2 /**
3  * Copyright 2009 The Apache Software Foundation
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.apache.lucene.index.IndexReader;
27 import org.apache.lucene.search.FieldCache;
28 import org.apache.lucene.search.FieldCache.CacheEntry;
29
30 /** 
31  * Provides methods for sanity checking that entries in the FieldCache 
32  * are not wasteful or inconsistent.
33  * </p>
34  * <p>
35  * Lucene 2.9 Introduced numerous enhancements into how the FieldCache 
36  * is used by the low levels of Lucene searching (for Sorting and 
37  * ValueSourceQueries) to improve both the speed for Sorting, as well 
38  * as reopening of IndexReaders.  But these changes have shifted the 
39  * usage of FieldCache from "top level" IndexReaders (frequently a 
40  * MultiReader or DirectoryReader) down to the leaf level SegmentReaders.  
41  * As a result, existing applications that directly access the FieldCache 
42  * may find RAM usage increase significantly when upgrading to 2.9 or 
43  * Later.  This class provides an API for these applications (or their 
44  * Unit tests) to check at run time if the FieldCache contains "insane" 
45  * usages of the FieldCache.
46  * </p>
47  * @lucene.experimental
48  * @see FieldCache
49  * @see FieldCacheSanityChecker.Insanity
50  * @see FieldCacheSanityChecker.InsanityType
51  */
52 public final class FieldCacheSanityChecker {
53
54   private RamUsageEstimator ramCalc = null;
55   public FieldCacheSanityChecker() {
56     /* NOOP */
57   }
58   /**
59    * If set, will be used to estimate size for all CacheEntry objects 
60    * dealt with.
61    */
62   public void setRamUsageEstimator(RamUsageEstimator r) {
63     ramCalc = r;
64   }
65
66
67   /** 
68    * Quick and dirty convenience method
69    * @see #check
70    */
71   public static Insanity[] checkSanity(FieldCache cache) {
72     return checkSanity(cache.getCacheEntries());
73   }
74
75   /** 
76    * Quick and dirty convenience method that instantiates an instance with 
77    * "good defaults" and uses it to test the CacheEntrys
78    * @see #check
79    */
80   public static Insanity[] checkSanity(CacheEntry... cacheEntries) {
81     FieldCacheSanityChecker sanityChecker = new FieldCacheSanityChecker();
82     // doesn't check for interned
83     sanityChecker.setRamUsageEstimator(new RamUsageEstimator(false));
84     return sanityChecker.check(cacheEntries);
85   }
86
87
88   /**
89    * Tests a CacheEntry[] for indication of "insane" cache usage.
90    * <p>
91    * <B>NOTE:</b>FieldCache CreationPlaceholder objects are ignored.
92    * (:TODO: is this a bad idea? are we masking a real problem?)
93    * </p>
94    */
95   public Insanity[] check(CacheEntry... cacheEntries) {
96     if (null == cacheEntries || 0 == cacheEntries.length) 
97       return new Insanity[0];
98
99     if (null != ramCalc) {
100       for (int i = 0; i < cacheEntries.length; i++) {
101         cacheEntries[i].estimateSize(ramCalc);
102       }
103     }
104
105     // the indirect mapping lets MapOfSet dedup identical valIds for us
106     //
107     // maps the (valId) identityhashCode of cache values to 
108     // sets of CacheEntry instances
109     final MapOfSets<Integer, CacheEntry> valIdToItems = new MapOfSets<Integer, CacheEntry>(new HashMap<Integer, Set<CacheEntry>>(17));
110     // maps ReaderField keys to Sets of ValueIds
111     final MapOfSets<ReaderField, Integer> readerFieldToValIds = new MapOfSets<ReaderField, Integer>(new HashMap<ReaderField, Set<Integer>>(17));
112     //
113
114     // any keys that we know result in more then one valId
115     final Set<ReaderField> valMismatchKeys = new HashSet<ReaderField>();
116
117     // iterate over all the cacheEntries to get the mappings we'll need
118     for (int i = 0; i < cacheEntries.length; i++) {
119       final CacheEntry item = cacheEntries[i];
120       final Object val = item.getValue();
121
122       if (val instanceof FieldCache.CreationPlaceholder)
123         continue;
124
125       final ReaderField rf = new ReaderField(item.getReaderKey(), 
126                                             item.getFieldName());
127
128       final Integer valId = Integer.valueOf(System.identityHashCode(val));
129
130       // indirect mapping, so the MapOfSet will dedup identical valIds for us
131       valIdToItems.put(valId, item);
132       if (1 < readerFieldToValIds.put(rf, valId)) {
133         valMismatchKeys.add(rf);
134       }
135     }
136
137     final List<Insanity> insanity = new ArrayList<Insanity>(valMismatchKeys.size() * 3);
138
139     insanity.addAll(checkValueMismatch(valIdToItems, 
140                                        readerFieldToValIds, 
141                                        valMismatchKeys));
142     insanity.addAll(checkSubreaders(valIdToItems, 
143                                     readerFieldToValIds));
144                     
145     return insanity.toArray(new Insanity[insanity.size()]);
146   }
147
148   /** 
149    * Internal helper method used by check that iterates over 
150    * valMismatchKeys and generates a Collection of Insanity 
151    * instances accordingly.  The MapOfSets are used to populate 
152    * the Insanity objects. 
153    * @see InsanityType#VALUEMISMATCH
154    */
155   private Collection<Insanity> checkValueMismatch(MapOfSets<Integer, CacheEntry> valIdToItems,
156                                         MapOfSets<ReaderField, Integer> readerFieldToValIds,
157                                         Set<ReaderField> valMismatchKeys) {
158
159     final List<Insanity> insanity = new ArrayList<Insanity>(valMismatchKeys.size() * 3);
160
161     if (! valMismatchKeys.isEmpty() ) { 
162       // we have multiple values for some ReaderFields
163
164       final Map<ReaderField, Set<Integer>> rfMap = readerFieldToValIds.getMap();
165       final Map<Integer, Set<CacheEntry>> valMap = valIdToItems.getMap();
166       for (final ReaderField rf : valMismatchKeys) {
167         final List<CacheEntry> badEntries = new ArrayList<CacheEntry>(valMismatchKeys.size() * 2);
168         for(final Integer value: rfMap.get(rf)) {
169           for (final CacheEntry cacheEntry : valMap.get(value)) {
170             badEntries.add(cacheEntry);
171           }
172         }
173
174         CacheEntry[] badness = new CacheEntry[badEntries.size()];
175         badness = badEntries.toArray(badness);
176
177         insanity.add(new Insanity(InsanityType.VALUEMISMATCH,
178                                   "Multiple distinct value objects for " + 
179                                   rf.toString(), badness));
180       }
181     }
182     return insanity;
183   }
184
185   /** 
186    * Internal helper method used by check that iterates over 
187    * the keys of readerFieldToValIds and generates a Collection 
188    * of Insanity instances whenever two (or more) ReaderField instances are 
189    * found that have an ancestry relationships.  
190    *
191    * @see InsanityType#SUBREADER
192    */
193   private Collection<Insanity> checkSubreaders( MapOfSets<Integer, CacheEntry>  valIdToItems,
194                                       MapOfSets<ReaderField, Integer> readerFieldToValIds) {
195
196     final List<Insanity> insanity = new ArrayList<Insanity>(23);
197
198     Map<ReaderField, Set<ReaderField>> badChildren = new HashMap<ReaderField, Set<ReaderField>>(17);
199     MapOfSets<ReaderField, ReaderField> badKids = new MapOfSets<ReaderField, ReaderField>(badChildren); // wrapper
200
201     Map<Integer, Set<CacheEntry>> viToItemSets = valIdToItems.getMap();
202     Map<ReaderField, Set<Integer>> rfToValIdSets = readerFieldToValIds.getMap();
203
204     Set<ReaderField> seen = new HashSet<ReaderField>(17);
205
206     Set<ReaderField> readerFields = rfToValIdSets.keySet();
207     for (final ReaderField rf : readerFields) {
208       
209       if (seen.contains(rf)) continue;
210
211       List<Object> kids = getAllDecendentReaderKeys(rf.readerKey);
212       for (Object kidKey : kids) {
213         ReaderField kid = new ReaderField(kidKey, rf.fieldName);
214         
215         if (badChildren.containsKey(kid)) {
216           // we've already process this kid as RF and found other problems
217           // track those problems as our own
218           badKids.put(rf, kid);
219           badKids.putAll(rf, badChildren.get(kid));
220           badChildren.remove(kid);
221           
222         } else if (rfToValIdSets.containsKey(kid)) {
223           // we have cache entries for the kid
224           badKids.put(rf, kid);
225         }
226         seen.add(kid);
227       }
228       seen.add(rf);
229     }
230
231     // every mapping in badKids represents an Insanity
232     for (final ReaderField parent : badChildren.keySet()) {
233       Set<ReaderField> kids = badChildren.get(parent);
234
235       List<CacheEntry> badEntries = new ArrayList<CacheEntry>(kids.size() * 2);
236
237       // put parent entr(ies) in first
238       {
239         for (final Integer value  : rfToValIdSets.get(parent)) {
240           badEntries.addAll(viToItemSets.get(value));
241         }
242       }
243
244       // now the entries for the descendants
245       for (final ReaderField kid : kids) {
246         for (final Integer value : rfToValIdSets.get(kid)) {
247           badEntries.addAll(viToItemSets.get(value));
248         }
249       }
250
251       CacheEntry[] badness = new CacheEntry[badEntries.size()];
252       badness = badEntries.toArray(badness);
253
254       insanity.add(new Insanity(InsanityType.SUBREADER,
255                                 "Found caches for decendents of " + 
256                                 parent.toString(),
257                                 badness));
258     }
259
260     return insanity;
261
262   }
263
264   /**
265    * Checks if the seed is an IndexReader, and if so will walk
266    * the hierarchy of subReaders building up a list of the objects 
267    * returned by obj.getFieldCacheKey()
268    */
269   private List<Object> getAllDecendentReaderKeys(Object seed) {
270     List<Object> all = new ArrayList<Object>(17); // will grow as we iter
271     all.add(seed);
272     for (int i = 0; i < all.size(); i++) {
273       Object obj = all.get(i);
274       if (obj instanceof IndexReader) {
275         IndexReader[] subs = ((IndexReader)obj).getSequentialSubReaders();
276         for (int j = 0; (null != subs) && (j < subs.length); j++) {
277           all.add(subs[j].getCoreCacheKey());
278         }
279       }
280       
281     }
282     // need to skip the first, because it was the seed
283     return all.subList(1, all.size());
284   }
285
286   /**
287    * Simple pair object for using "readerKey + fieldName" a Map key
288    */
289   private final static class ReaderField {
290     public final Object readerKey;
291     public final String fieldName;
292     public ReaderField(Object readerKey, String fieldName) {
293       this.readerKey = readerKey;
294       this.fieldName = fieldName;
295     }
296     @Override
297     public int hashCode() {
298       return System.identityHashCode(readerKey) * fieldName.hashCode();
299     }
300     @Override
301     public boolean equals(Object that) {
302       if (! (that instanceof ReaderField)) return false;
303
304       ReaderField other = (ReaderField) that;
305       return (this.readerKey == other.readerKey &&
306               this.fieldName.equals(other.fieldName));
307     }
308     @Override
309     public String toString() {
310       return readerKey.toString() + "+" + fieldName;
311     }
312   }
313
314   /**
315    * Simple container for a collection of related CacheEntry objects that 
316    * in conjunction with each other represent some "insane" usage of the 
317    * FieldCache.
318    */
319   public final static class Insanity {
320     private final InsanityType type;
321     private final String msg;
322     private final CacheEntry[] entries;
323     public Insanity(InsanityType type, String msg, CacheEntry... entries) {
324       if (null == type) {
325         throw new IllegalArgumentException
326           ("Insanity requires non-null InsanityType");
327       }
328       if (null == entries || 0 == entries.length) {
329         throw new IllegalArgumentException
330           ("Insanity requires non-null/non-empty CacheEntry[]");
331       }
332       this.type = type;
333       this.msg = msg;
334       this.entries = entries;
335       
336     }
337     /**
338      * Type of insane behavior this object represents
339      */
340     public InsanityType getType() { return type; }
341     /**
342      * Description of hte insane behavior
343      */
344     public String getMsg() { return msg; }
345     /**
346      * CacheEntry objects which suggest a problem
347      */
348     public CacheEntry[] getCacheEntries() { return entries; }
349     /**
350      * Multi-Line representation of this Insanity object, starting with 
351      * the Type and Msg, followed by each CacheEntry.toString() on it's 
352      * own line prefaced by a tab character
353      */
354     @Override
355     public String toString() {
356       StringBuilder buf = new StringBuilder();
357       buf.append(getType()).append(": ");
358
359       String m = getMsg();
360       if (null != m) buf.append(m);
361
362       buf.append('\n');
363
364       CacheEntry[] ce = getCacheEntries();
365       for (int i = 0; i < ce.length; i++) {
366         buf.append('\t').append(ce[i].toString()).append('\n');
367       }
368
369       return buf.toString();
370     }
371   }
372
373   /**
374    * An Enumeration of the different types of "insane" behavior that 
375    * may be detected in a FieldCache.
376    *
377    * @see InsanityType#SUBREADER
378    * @see InsanityType#VALUEMISMATCH
379    * @see InsanityType#EXPECTED
380    */
381   public final static class InsanityType {
382     private final String label;
383     private InsanityType(final String label) {
384       this.label = label;
385     }
386     @Override
387     public String toString() { return label; }
388
389     /** 
390      * Indicates an overlap in cache usage on a given field 
391      * in sub/super readers.
392      */
393     public final static InsanityType SUBREADER 
394       = new InsanityType("SUBREADER");
395
396     /** 
397      * <p>
398      * Indicates entries have the same reader+fieldname but 
399      * different cached values.  This can happen if different datatypes, 
400      * or parsers are used -- and while it's not necessarily a bug 
401      * it's typically an indication of a possible problem.
402      * </p>
403      * <p>
404      * <bPNOTE:</b> Only the reader, fieldname, and cached value are actually 
405      * tested -- if two cache entries have different parsers or datatypes but 
406      * the cached values are the same Object (== not just equal()) this method 
407      * does not consider that a red flag.  This allows for subtle variations 
408      * in the way a Parser is specified (null vs DEFAULT_LONG_PARSER, etc...)
409      * </p>
410      */
411     public final static InsanityType VALUEMISMATCH 
412       = new InsanityType("VALUEMISMATCH");
413
414     /** 
415      * Indicates an expected bit of "insanity".  This may be useful for 
416      * clients that wish to preserve/log information about insane usage 
417      * but indicate that it was expected. 
418      */
419     public final static InsanityType EXPECTED
420       = new InsanityType("EXPECTED");
421   }
422   
423   
424 }