1 package org.apache.lucene.index;
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 import java.io.IOException;
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;
35 import static org.apache.lucene.index.TestIndexWriter.assertNoUnreferencedFiles;
38 * Tests for IndexWriter when the disk runs out of space
40 public class TestIndexWriterOnDiskFull extends LuceneTestCase {
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?
47 public void testAddDocumentOnDiskFull() throws IOException {
49 for(int pass=0;pass<2;pass++) {
51 System.out.println("TEST: pass=" + pass);
53 boolean doAbort = pass == 1;
54 long diskFree = _TestUtil.nextInt(random, 100, 300);
57 System.out.println("TEST: cycle: diskFree=" + diskFree);
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();
71 boolean hitError = false;
73 for(int i=0;i<200;i++) {
77 System.out.println("TEST: done adding docs; now commit");
80 } catch (IOException e) {
82 System.out.println("TEST: exception on addDoc");
83 e.printStackTrace(System.out);
91 System.out.println("TEST: now rollback");
97 System.out.println("TEST: now close");
100 } catch (IOException e) {
102 System.out.println("TEST: exception on close; retry w/ no disk space limit");
103 e.printStackTrace(System.out);
105 dir.setMaxSizeInBytes(0);
110 //_TestUtil.syncConcurrentMerges(ms);
112 if (_TestUtil.anyFilesExceptWriteLock(dir)) {
113 assertNoUnreferencedFiles(dir, "after disk full during addDocument");
115 // Make sure reader can open the index:
116 IndexReader.open(dir, true).close();
120 // Now try again w/ more space:
122 diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random, 400, 600) : _TestUtil.nextInt(random, 3000, 5000);
124 //_TestUtil.syncConcurrentMerges(writer);
125 dir.setMaxSizeInBytes(0);
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
142 public void testAddIndexOnDiskFull() throws IOException
144 int START_COUNT = 57;
146 int END_COUNT = START_COUNT + NUM_DIR*25;
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);
159 String[] files = dirs[i].listAll();
160 for(int j=0;j<files.length;j++) {
161 inputDiskUsage += dirs[i].fileLength(files[j]);
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);
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));
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);
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
196 // String[] files = startDir.listAll();
197 long diskUsage = startDir.sizeInBytes();
199 long startDiskUsage = 0;
200 String[] files = startDir.listAll();
201 for(int i=0;i<files.length;i++) {
202 startDiskUsage += startDir.fileLength(files[i]);
205 for(int iter=0;iter<3;iter++) {
208 System.out.println("TEST: iter=" + iter);
210 // Start with 100 bytes more than we are currently using:
211 long diskFree = diskUsage+_TestUtil.nextInt(random, 50, 200);
215 boolean success = false;
216 boolean done = false;
220 methodName = "addIndexes(Directory[]) + optimize()";
221 } else if (1 == method) {
222 methodName = "addIndexes(IndexReader[])";
224 methodName = "addIndexes(Directory[])";
229 System.out.println("TEST: cycle...");
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);
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.
245 ((ConcurrentMergeScheduler) ms).setSuppressExceptions();
247 ((ConcurrentMergeScheduler) ms).clearSuppressExceptions();
249 // Two loops: first time, limit disk space &
250 // throw random IOExceptions; second time, no
254 double diskRatio = ((double) diskFree)/diskUsage;
257 String testName = null;
260 thisDiskFree = diskFree;
261 if (diskRatio >= 2.0) {
264 if (diskRatio >= 4.0) {
267 if (diskRatio >= 6.0) {
271 testName = "disk full test " + methodName + " with disk full at " + diskFree + " bytes";
276 testName = "disk full test " + methodName + " with unlimited disk space";
280 System.out.println("\ncycle: " + testName);
282 dir.setTrackDiskUsage(true);
283 dir.setMaxSizeInBytes(thisDiskFree);
284 dir.setRandomIOExceptionRate(rate);
289 writer.addIndexes(dirs);
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);
297 writer.addIndexes(readers);
299 for(int i=0;i<dirs.length;i++) {
304 writer.addIndexes(dirs);
309 System.out.println(" success!");
316 } catch (IOException e) {
320 System.out.println(" hit IOException: " + e);
321 e.printStackTrace(System.out);
325 e.printStackTrace(System.out);
326 fail(methodName + " hit IOException after disk space was freed up");
330 // Make sure all threads from
331 // ConcurrentMergeScheduler are done
332 _TestUtil.syncConcurrentMerges(writer);
335 System.out.println(" now test readers");
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):
343 reader = IndexReader.open(dir, true);
344 } catch (IOException e) {
345 e.printStackTrace(System.out);
346 fail(testName + ": exception when creating IndexReader: " + e);
348 int result = reader.docFreq(searchTerm);
350 if (result != START_COUNT) {
351 fail(testName + ": method did not throw exception but docFreq('aaa') is " + result + " instead of expected " + START_COUNT);
354 // On hitting exception we still may have added
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);
362 searcher = newSearcher(reader);
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);
369 int result2 = hits.length;
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);
375 // On hitting exception we still may have added
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);
386 System.out.println(" count is " + result);
389 if (done || result == END_COUNT) {
395 System.out.println(" start disk = " + startDiskUsage + "; input disk = " + inputDiskUsage + "; max used = " + dir.getMaxUsedSizeInBytes());
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));
409 // Make sure we don't hit disk full during close below:
410 dir.setMaxSizeInBytes(0);
411 dir.setRandomIOExceptionRate(0.0);
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);
422 // Try again with more free space:
423 diskFree += TEST_NIGHTLY ? _TestUtil.nextInt(random, 4000, 8000) : _TestUtil.nextInt(random, 40000, 80000);
428 for (Directory dir : dirs)
432 private static class FailTwiceDuringMerge extends MockDirectoryWrapper.Failure {
433 public boolean didFail1;
434 public boolean didFail2;
437 public void eval(MockDirectoryWrapper dir) throws IOException {
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) {
445 throw new IOException("fake disk full during mergeTerms");
447 if ("org.apache.lucene.util.BitVector".equals(trace[i].getClassName()) && "write".equals(trace[i].getMethodName()) && !didFail2) {
449 throw new IOException("fake disk full while writing BitVector");
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(
461 newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
462 setMergeScheduler(new SerialMergeScheduler()).
463 setReaderPooling(true).
464 setMergePolicy(newLogMergePolicy(2))
467 _TestUtil.keepFullyDeletedSegments(w);
469 ((LogMergePolicy) w.getMergePolicy()).setMergeFactor(2);
471 Document doc = new Document();
472 doc.add(newField("f", "doctor who", Field.Store.YES, Field.Index.ANALYZED));
476 w.deleteDocuments(new Term("f", "who"));
480 FailTwiceDuringMerge ftdm = new FailTwiceDuringMerge();
486 fail("fake disk full IOExceptions not hit");
487 } catch (IOException ioe) {
489 assertTrue(ftdm.didFail1 || ftdm.didFail2);
491 _TestUtil.checkIndex(dir);
499 // LUCENE-1130: make sure immeidate disk full on creating
500 // an IndexWriter (hit during DW.ThreadState.init()) is
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));
510 writer.addDocument(doc);
511 fail("did not hit disk full");
512 } catch (IOException ioe) {
514 // Without fix for LUCENE-1130: this call will hang:
516 writer.addDocument(doc);
517 fail("did not hit disk full");
518 } catch (IOException ioe) {
522 fail("did not hit disk full");
523 } catch (IOException ioe) {
526 // Make sure once disk space is avail again, we can
528 dir.setMaxSizeInBytes(0);
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
537 Document doc = new Document();
538 doc.add(newField("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
539 writer.addDocument(doc);
542 private void addDocWithIndex(IndexWriter writer, int index) throws IOException
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);