add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / backwards / src / test / org / apache / lucene / index / TestIndexWriterOnDiskFull.java
1 package org.apache.lucene.index;
2
3 /**
4  * Licensed to the Apache Software Foundation (ASF) under one or more
5  * contributor license agreements.  See the NOTICE file distributed with
6  * this work for additional information regarding copyright ownership.
7  * The ASF licenses this file to You under the Apache License, Version 2.0
8  * (the "License"); you may not use this file except in compliance with
9  * the License.  You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 import java.io.IOException;
21
22 import org.apache.lucene.analysis.MockAnalyzer;
23 import org.apache.lucene.document.Document;
24 import org.apache.lucene.document.Field;
25 import org.apache.lucene.index.IndexWriterConfig.OpenMode;
26 import org.apache.lucene.search.IndexSearcher;
27 import org.apache.lucene.search.ScoreDoc;
28 import org.apache.lucene.search.TermQuery;
29 import org.apache.lucene.store.Directory;
30 import org.apache.lucene.store.MockDirectoryWrapper;
31 import org.apache.lucene.store.RAMDirectory;
32 import org.apache.lucene.util.LuceneTestCase;
33 import org.apache.lucene.util._TestUtil;
34
35 import static org.apache.lucene.index.TestIndexWriter.assertNoUnreferencedFiles;
36
37 /**
38  * Tests for IndexWriter when the disk runs out of space
39  */
40 public class TestIndexWriterOnDiskFull extends LuceneTestCase {
41
42   /*
43    * Make sure IndexWriter cleans up on hitting a disk
44    * full exception in addDocument.
45    * TODO: how to do this on windows with FSDirectory?
46    */
47   public void testAddDocumentOnDiskFull() throws IOException {
48
49     for(int pass=0;pass<2;pass++) {
50       if (VERBOSE) {
51         System.out.println("TEST: pass=" + pass);
52       }
53       boolean doAbort = pass == 1;
54       long diskFree = _TestUtil.nextInt(random, 100, 300);
55       while(true) {
56         if (VERBOSE) {
57           System.out.println("TEST: cycle: diskFree=" + diskFree);
58         }
59         MockDirectoryWrapper dir = new MockDirectoryWrapper(random, new RAMDirectory());
60         dir.setMaxSizeInBytes(diskFree);
61         IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random)));
62         writer.setInfoStream(VERBOSE ? System.out : null);
63         MergeScheduler ms = writer.getConfig().getMergeScheduler();
64         if (ms instanceof ConcurrentMergeScheduler) {
65           // This test intentionally produces exceptions
66           // in the threads that CMS launches; we don't
67           // want to pollute test output with these.
68           ((ConcurrentMergeScheduler) ms).setSuppressExceptions();
69         }
70
71         boolean hitError = false;
72         try {
73           for(int i=0;i<200;i++) {
74             addDoc(writer);
75           }
76           if (VERBOSE) {
77             System.out.println("TEST: done adding docs; now commit");
78           }
79           writer.commit();
80         } catch (IOException e) {
81           if (VERBOSE) {
82             System.out.println("TEST: exception on addDoc");
83             e.printStackTrace(System.out);
84           }
85           hitError = true;
86         }
87
88         if (hitError) {
89           if (doAbort) {
90             if (VERBOSE) {
91               System.out.println("TEST: now rollback");
92             }
93             writer.rollback();
94           } else {
95             try {
96               if (VERBOSE) {
97                 System.out.println("TEST: now close");
98               }
99               writer.close();
100             } catch (IOException e) {
101               if (VERBOSE) {
102                 System.out.println("TEST: exception on close; retry w/ no disk space limit");
103                 e.printStackTrace(System.out);
104               }
105               dir.setMaxSizeInBytes(0);
106               writer.close();
107             }
108           }
109
110           //_TestUtil.syncConcurrentMerges(ms);
111
112           if (_TestUtil.anyFilesExceptWriteLock(dir)) {
113             assertNoUnreferencedFiles(dir, "after disk full during addDocument");
114             
115             // Make sure reader can open the index:
116             IndexReader.open(dir, true).close();
117           }
118             
119           dir.close();
120           // Now try again w/ more space:
121
122           diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random, 400, 600) : _TestUtil.nextInt(random, 3000, 5000);
123         } else {
124           //_TestUtil.syncConcurrentMerges(writer);
125           dir.setMaxSizeInBytes(0);
126           writer.close();
127           dir.close();
128           break;
129         }
130       }
131     }
132   }
133   
134   /*
135   Test: make sure when we run out of disk space or hit
136   random IOExceptions in any of the addIndexes(*) calls
137   that 1) index is not corrupt (searcher can open/search
138   it) and 2) transactional semantics are followed:
139   either all or none of the incoming documents were in
140   fact added.
141    */
142   public void testAddIndexOnDiskFull() throws IOException
143   {
144     int START_COUNT = 57;
145     int NUM_DIR = 50;
146     int END_COUNT = START_COUNT + NUM_DIR*25;
147     
148     // Build up a bunch of dirs that have indexes which we
149     // will then merge together by calling addIndexes(*):
150     Directory[] dirs = new Directory[NUM_DIR];
151     long inputDiskUsage = 0;
152     for(int i=0;i<NUM_DIR;i++) {
153       dirs[i] = newDirectory();
154       IndexWriter writer  = new IndexWriter(dirs[i], newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random)));
155       for(int j=0;j<25;j++) {
156         addDocWithIndex(writer, 25*i+j);
157       }
158       writer.close();
159       String[] files = dirs[i].listAll();
160       for(int j=0;j<files.length;j++) {
161         inputDiskUsage += dirs[i].fileLength(files[j]);
162       }
163     }
164     
165     // Now, build a starting index that has START_COUNT docs.  We
166     // will then try to addIndexesNoOptimize into a copy of this:
167     MockDirectoryWrapper startDir = newDirectory();
168     IndexWriter writer = new IndexWriter(startDir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random)));
169     for(int j=0;j<START_COUNT;j++) {
170       addDocWithIndex(writer, j);
171     }
172     writer.close();
173     
174     // Make sure starting index seems to be working properly:
175     Term searchTerm = new Term("content", "aaa");        
176     IndexReader reader = IndexReader.open(startDir, true);
177     assertEquals("first docFreq", 57, reader.docFreq(searchTerm));
178     
179     IndexSearcher searcher = newSearcher(reader);
180     ScoreDoc[] hits = searcher.search(new TermQuery(searchTerm), null, 1000).scoreDocs;
181     assertEquals("first number of hits", 57, hits.length);
182     searcher.close();
183     reader.close();
184     
185     // Iterate with larger and larger amounts of free
186     // disk space.  With little free disk space,
187     // addIndexes will certainly run out of space &
188     // fail.  Verify that when this happens, index is
189     // not corrupt and index in fact has added no
190     // documents.  Then, we increase disk space by 2000
191     // bytes each iteration.  At some point there is
192     // enough free disk space and addIndexes should
193     // succeed and index should show all documents were
194     // added.
195     
196     // String[] files = startDir.listAll();
197     long diskUsage = startDir.sizeInBytes();
198     
199     long startDiskUsage = 0;
200     String[] files = startDir.listAll();
201     for(int i=0;i<files.length;i++) {
202       startDiskUsage += startDir.fileLength(files[i]);
203     }
204     
205     for(int iter=0;iter<3;iter++) {
206       
207       if (VERBOSE)
208         System.out.println("TEST: iter=" + iter);
209       
210       // Start with 100 bytes more than we are currently using:
211       long diskFree = diskUsage+_TestUtil.nextInt(random, 50, 200);
212       
213       int method = iter;
214       
215       boolean success = false;
216       boolean done = false;
217       
218       String methodName;
219       if (0 == method) {
220         methodName = "addIndexes(Directory[]) + optimize()";
221       } else if (1 == method) {
222         methodName = "addIndexes(IndexReader[])";
223       } else {
224         methodName = "addIndexes(Directory[])";
225       }
226       
227       while(!done) {
228         if (VERBOSE) {
229           System.out.println("TEST: cycle...");
230         }
231         
232         // Make a new dir that will enforce disk usage:
233         MockDirectoryWrapper dir = new MockDirectoryWrapper(random, new RAMDirectory(startDir));
234         writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random)).setOpenMode(OpenMode.APPEND).setMergePolicy(newLogMergePolicy()));
235         IOException err = null;
236         writer.setInfoStream(VERBOSE ? System.out : null);
237
238         MergeScheduler ms = writer.getConfig().getMergeScheduler();
239         for(int x=0;x<2;x++) {
240           if (ms instanceof ConcurrentMergeScheduler)
241             // This test intentionally produces exceptions
242             // in the threads that CMS launches; we don't
243             // want to pollute test output with these.
244             if (0 == x)
245               ((ConcurrentMergeScheduler) ms).setSuppressExceptions();
246             else
247               ((ConcurrentMergeScheduler) ms).clearSuppressExceptions();
248           
249           // Two loops: first time, limit disk space &
250           // throw random IOExceptions; second time, no
251           // disk space limit:
252           
253           double rate = 0.05;
254           double diskRatio = ((double) diskFree)/diskUsage;
255           long thisDiskFree;
256           
257           String testName = null;
258           
259           if (0 == x) {
260             thisDiskFree = diskFree;
261             if (diskRatio >= 2.0) {
262               rate /= 2;
263             }
264             if (diskRatio >= 4.0) {
265               rate /= 2;
266             }
267             if (diskRatio >= 6.0) {
268               rate = 0.0;
269             }
270             if (VERBOSE)
271               testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes";
272           } else {
273             thisDiskFree = 0;
274             rate = 0.0;
275             if (VERBOSE)
276               testName = "disk full test " + methodName + " with unlimited disk space";
277           }
278           
279           if (VERBOSE)
280             System.out.println("\ncycle: " + testName);
281           
282           dir.setTrackDiskUsage(true);
283           dir.setMaxSizeInBytes(thisDiskFree);
284           dir.setRandomIOExceptionRate(rate);
285           
286           try {
287             
288             if (0 == method) {
289               writer.addIndexes(dirs);
290               writer.optimize();
291             } else if (1 == method) {
292               IndexReader readers[] = new IndexReader[dirs.length];
293               for(int i=0;i<dirs.length;i++) {
294                 readers[i] = IndexReader.open(dirs[i], true);
295               }
296               try {
297                 writer.addIndexes(readers);
298               } finally {
299                 for(int i=0;i<dirs.length;i++) {
300                   readers[i].close();
301                 }
302               }
303             } else {
304               writer.addIndexes(dirs);
305             }
306             
307             success = true;
308             if (VERBOSE) {
309               System.out.println("  success!");
310             }
311             
312             if (0 == x) {
313               done = true;
314             }
315             
316           } catch (IOException e) {
317             success = false;
318             err = e;
319             if (VERBOSE) {
320               System.out.println("  hit IOException: " + e);
321               e.printStackTrace(System.out);
322             }
323             
324             if (1 == x) {
325               e.printStackTrace(System.out);
326               fail(methodName + " hit IOException after disk space was freed up");
327             }
328           }
329           
330           // Make sure all threads from
331           // ConcurrentMergeScheduler are done
332           _TestUtil.syncConcurrentMerges(writer);
333           
334           if (VERBOSE) {
335             System.out.println("  now test readers");
336           }
337           
338           // Finally, verify index is not corrupt, and, if
339           // we succeeded, we see all docs added, and if we
340           // failed, we see either all docs or no docs added
341           // (transactional semantics):
342           try {
343             reader = IndexReader.open(dir, true);
344           } catch (IOException e) {
345             e.printStackTrace(System.out);
346             fail(testName + ": exception when creating IndexReader: " + e);
347           }
348           int result = reader.docFreq(searchTerm);
349           if (success) {
350             if (result != START_COUNT) {
351               fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT);
352             }
353           } else {
354             // On hitting exception we still may have added
355             // all docs:
356             if (result != START_COUNT && result != END_COUNT) {
357               err.printStackTrace(System.out);
358               fail(testName + ": method did throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT + " or " + END_COUNT);
359             }
360           }
361           
362           searcher = newSearcher(reader);
363           try {
364             hits = searcher.search(new TermQuery(searchTerm), null, END_COUNT).scoreDocs;
365           } catch (IOException e) {
366             e.printStackTrace(System.out);
367             fail(testName + ": exception when searching: " + e);
368           }
369           int result2 = hits.length;
370           if (success) {
371             if (result2 != result) {
372               fail(testName + ": method did not throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result);
373             }
374           } else {
375             // On hitting exception we still may have added
376             // all docs:
377             if (result2 != result) {
378               err.printStackTrace(System.out);
379               fail(testName + ": method did throw exception but hits.length for search on term 'aaa' is " + result2 + " instead of expected " + result);
380             }
381           }
382           
383           searcher.close();
384           reader.close();
385           if (VERBOSE) {
386             System.out.println("  count is " + result);
387           }
388           
389           if (done || result == END_COUNT) {
390             break;
391           }
392         }
393         
394         if (VERBOSE) {
395           System.out.println("  start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.getMaxUsedSizeInBytes());
396         }
397         
398         if (done) {
399           // Javadocs state that temp free Directory space
400           // required is at most 2X total input size of
401           // indices so let's make sure:
402           assertTrue("max free Directory space required exceeded 1X the total input index sizes during " + methodName +
403                      ": max temp usage = " + (dir.getMaxUsedSizeInBytes()-startDiskUsage) + " bytes vs limit=" + (2*(startDiskUsage + inputDiskUsage)) +
404                      "; starting disk usage = " + startDiskUsage + " bytes; " +
405                      "input index disk usage = " + inputDiskUsage + " bytes",
406                      (dir.getMaxUsedSizeInBytes()-startDiskUsage) < 2*(startDiskUsage + inputDiskUsage));
407         }
408         
409         // Make sure we don't hit disk full during close below:
410         dir.setMaxSizeInBytes(0);
411         dir.setRandomIOExceptionRate(0.0);
412         
413         writer.close();
414         
415         // Wait for all BG threads to finish else
416         // dir.close() will throw IOException because
417         // there are still open files
418         _TestUtil.syncConcurrentMerges(ms);
419         
420         dir.close();
421         
422         // Try again with more free space:
423         diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random, 4000, 8000) : _TestUtil.nextInt(random, 40000, 80000);
424       }
425     }
426     
427     startDir.close();
428     for (Directory dir : dirs)
429       dir.close();
430   }
431   
432   private static class FailTwiceDuringMerge extends MockDirectoryWrapper.Failure {
433     public boolean didFail1;
434     public boolean didFail2;
435
436     @Override
437     public void eval(MockDirectoryWrapper dir)  throws IOException {
438       if (!doFail) {
439         return;
440       }
441       StackTraceElement[] trace = new Exception().getStackTrace();
442       for (int i = 0; i < trace.length; i++) {
443         if ("org.apache.lucene.index.SegmentMerger".equals(trace[i].getClassName()) && "mergeTerms".equals(trace[i].getMethodName()) && !didFail1) {
444           didFail1 = true;
445           throw new IOException("fake disk full during mergeTerms");
446         }
447         if ("org.apache.lucene.util.BitVector".equals(trace[i].getClassName()) && "write".equals(trace[i].getMethodName()) && !didFail2) {
448           didFail2 = true;
449           throw new IOException("fake disk full while writing BitVector");
450         }
451       }
452     }
453   }
454   
455   // LUCENE-2593
456   public void testCorruptionAfterDiskFullDuringMerge() throws IOException {
457     MockDirectoryWrapper dir = newDirectory();
458     //IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setReaderPooling(true));
459     IndexWriter w = new IndexWriter(
460         dir,
461         newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
462             setMergeScheduler(new SerialMergeScheduler()).
463             setReaderPooling(true).
464             setMergePolicy(newLogMergePolicy(2))
465     );
466
467     _TestUtil.keepFullyDeletedSegments(w);
468
469     ((LogMergePolicy) w.getMergePolicy()).setMergeFactor(2);
470
471     Document doc = new Document();
472     doc.add(newField("f", "doctor who", Field.Store.YES, Field.Index.ANALYZED));
473     w.addDocument(doc);
474     w.commit();
475
476     w.deleteDocuments(new Term("f", "who"));
477     w.addDocument(doc);
478     
479     // disk fills up!
480     FailTwiceDuringMerge ftdm = new FailTwiceDuringMerge();
481     ftdm.setDoFail();
482     dir.failOn(ftdm);
483
484     try {
485       w.commit();
486       fail("fake disk full IOExceptions not hit");
487     } catch (IOException ioe) {
488       // expected
489       assertTrue(ftdm.didFail1 || ftdm.didFail2);
490     }
491     _TestUtil.checkIndex(dir);
492     ftdm.clearDoFail();
493     w.addDocument(doc);
494     w.close();
495
496     dir.close();
497   }
498   
499   // LUCENE-1130: make sure immeidate disk full on creating
500   // an IndexWriter (hit during DW.ThreadState.init()) is
501   // OK:
502   public void testImmediateDiskFull() throws IOException {
503     MockDirectoryWrapper dir = newDirectory();
504     IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random))
505         .setMaxBufferedDocs(2).setMergeScheduler(new ConcurrentMergeScheduler()));
506     dir.setMaxSizeInBytes(Math.max(1, dir.getRecomputedActualSizeInBytes()));
507     final Document doc = new Document();
508     doc.add(newField("field", "aaa bbb ccc ddd eee fff ggg hhh iii jjj", Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
509     try {
510       writer.addDocument(doc);
511       fail("did not hit disk full");
512     } catch (IOException ioe) {
513     }
514     // Without fix for LUCENE-1130: this call will hang:
515     try {
516       writer.addDocument(doc);
517       fail("did not hit disk full");
518     } catch (IOException ioe) {
519     }
520     try {
521       writer.close(false);
522       fail("did not hit disk full");
523     } catch (IOException ioe) {
524     }
525
526     // Make sure once disk space is avail again, we can
527     // cleanly close:
528     dir.setMaxSizeInBytes(0);
529     writer.close(false);
530     dir.close();
531   }
532   
533   // TODO: these are also in TestIndexWriter... add a simple doc-writing method
534   // like this to LuceneTestCase?
535   private void addDoc(IndexWriter writer) throws IOException
536   {
537       Document doc = new Document();
538       doc.add(newField("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
539       writer.addDocument(doc);
540   }
541   
542   private void addDocWithIndex(IndexWriter writer, int index) throws IOException
543   {
544       Document doc = new Document();
545       doc.add(newField("content", "aaa " + index, Field.Store.YES, Field.Index.ANALYZED));
546       doc.add(newField("id", "" + index, Field.Store.YES, Field.Index.ANALYZED));
547       writer.addDocument(doc);
548   }
549 }