Package org.apache.lucene.store

Examples of org.apache.lucene.store.MockDirectoryWrapper$FakeIOException


      writer.addDocument(doc);
  }

  // LUCENE-1044: test exception during sync
  public void testExceptionDuringSync() throws IOException {
    MockDirectoryWrapper dir = newMockDirectory();
    FailOnlyInSync failure = new FailOnlyInSync();
    dir.failOn(failure);

    IndexWriter writer = new IndexWriter(
        dir,
        newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).
            setMaxBufferedDocs(2).
            setMergeScheduler(new ConcurrentMergeScheduler()).
            setMergePolicy(newLogMergePolicy(5))
    );
    failure.setDoFail();

    for (int i = 0; i < 23; i++) {
      addDoc(writer);
      if ((i-1)%2 == 0) {
        try {
          writer.commit();
        } catch (IOException ioe) {
          // expected
        }
      }
    }
    ((ConcurrentMergeScheduler) writer.getConfig().getMergeScheduler()).sync();
    assertTrue(failure.didFail);
    failure.clearDoFail();
    writer.close();

    IndexReader reader = DirectoryReader.open(dir);
    assertEquals(23, reader.numDocs());
    reader.close();
    dir.close();
  }
View Full Code Here


        new FailOnlyInCommit(true, FailOnlyInCommit.PREPARE_STAGE), // fail after global field map is written
        new FailOnlyInCommit(false, FailOnlyInCommit.FINISH_STAGE// fail while running finishCommit   
    };
   
    for (FailOnlyInCommit failure : failures) {
      MockDirectoryWrapper dir = newMockDirectory();
      dir.setFailOnCreateOutput(false);
      IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
          TEST_VERSION_CURRENT, new MockAnalyzer(random())));
      Document doc = new Document();
      doc.add(newTextField("field", "a field", Field.Store.YES));
      w.addDocument(doc);
      dir.failOn(failure);
      try {
        w.close();
        fail();
      } catch (IOException ioe) {
        fail("expected only RuntimeException");
      } catch (RuntimeException re) {
        // Expected
      }
      assertTrue(failure.failOnCommit && failure.failOnDeleteFile);
      w.rollback();
      assertEquals(0, dir.listAll().length);
      dir.close();
    }
  }
View Full Code Here

    int iter = TEST_NIGHTLY ? 200 : 10;
    for(int i=0;i<iter;i++) {
      if (VERBOSE) {
        System.out.println("TEST: iter " + i);
      }
      MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new RAMDirectory(startDir, newIOContext(random())));
      conf = newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMergeScheduler(new ConcurrentMergeScheduler());
      ((ConcurrentMergeScheduler) conf.getMergeScheduler()).setSuppressExceptions();
      w = new IndexWriter(dir, conf);
      dir.setRandomIOExceptionRate(0.5);
      try {
        w.forceMerge(1);
      } catch (IOException ioe) {
        if (ioe.getCause() == null)
          fail("forceMerge threw IOException without root cause");
      }
      dir.setRandomIOExceptionRate(0);
      w.close();
      dir.close();
    }
    startDir.close();
  }
View Full Code Here

        new FailOnTermVectors(FailOnTermVectors.AFTER_INIT_STAGE),
        new FailOnTermVectors(FailOnTermVectors.INIT_STAGE), };
    int num = atLeast(1);
    for (int j = 0; j < num; j++) {
      for (FailOnTermVectors failure : failures) {
        MockDirectoryWrapper dir = newMockDirectory();
        IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(
            TEST_VERSION_CURRENT, new MockAnalyzer(random())));
        dir.failOn(failure);
        int numDocs = 10 + random().nextInt(30);
        for (int i = 0; i < numDocs; i++) {
          Document doc = new Document();
          Field field = newTextField(random(), "field", "a field", Field.Store.YES);
          doc.add(field);
          // random TV
          try {
            w.addDocument(doc);
            assertFalse(field.fieldType().storeTermVectors());
          } catch (RuntimeException e) {
            assertTrue(e.getMessage().startsWith(FailOnTermVectors.EXC_MSG));
          }
          if (random().nextInt(20) == 0) {
            w.commit();
            _TestUtil.checkIndex(dir);
          }
           
        }
        Document document = new Document();
        document.add(new TextField("field", "a field", Field.Store.YES));
        w.addDocument(document);

        for (int i = 0; i < numDocs; i++) {
          Document doc = new Document();
          Field field = newTextField(random(), "field", "a field", Field.Store.YES);
          doc.add(field);
          // random TV
          try {
            w.addDocument(doc);
            assertFalse(field.fieldType().storeTermVectors());
          } catch (RuntimeException e) {
            assertTrue(e.getMessage().startsWith(FailOnTermVectors.EXC_MSG));
          }
          if (random().nextInt(20) == 0) {
            w.commit();
            _TestUtil.checkIndex(dir);
          }
        }
        document = new Document();
        document.add(new TextField("field", "a field", Field.Store.YES));
        w.addDocument(document);
        w.close();
        IndexReader reader = DirectoryReader.open(dir);
        assertTrue(reader.numDocs() > 0);
        SegmentInfos sis = new SegmentInfos();
        sis.read(dir);
        for(AtomicReaderContext context : reader.leaves()) {
          assertFalse(context.reader().getFieldInfos().hasVectors());
        }
        reader.close();
        dir.close();
      }
    }
  }
View Full Code Here

    }
  }
 
  public void testExceptionOnCtor() throws Exception {
    UOEDirectory uoe = new UOEDirectory();
    Directory d = new MockDirectoryWrapper(random(), uoe);
    IndexWriter iw = new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT, null));
    iw.addDocument(new Document());
    iw.close();
    uoe.doFail = true;
    try {
      new IndexWriter(d, newIndexWriterConfig(TEST_VERSION_CURRENT, null));
      fail("should have gotten a UOE");
    } catch (UnsupportedOperationException expected) {
    }

    uoe.doFail = false;
    d.close();
  }
View Full Code Here

          }
        }
      }
    };

    MockDirectoryWrapper dir = newMockDirectory();
    // The exception is only thrown on open input
    dir.setFailOnOpenInput(true);
    dir.failOn(failure);

    // Create an index with one document
    IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
    IndexWriter iw = new IndexWriter(dir, iwc);
    Document doc = new Document();
    doc.add(new StringField("foo", "bar", Field.Store.NO));
    iw.addDocument(doc); // add a document
    iw.commit();
    DirectoryReader ir = DirectoryReader.open(dir);
    assertEquals(1, ir.numDocs());
    ir.close();
    iw.close();

    // Open and close the index a few times
    for (int i = 0; i < 10; i++) {
      failure.setDoFail();
      iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
      try {
        iw = new IndexWriter(dir, iwc);
      } catch (CorruptIndexException ex) {
        // Exceptions are fine - we are running out of file handlers here
        continue;
      } catch (FileNotFoundException ex) {
        continue;
      }
      failure.clearDoFail();
      iw.close();
      ir = DirectoryReader.open(dir);
      assertEquals("lost document after iteration: " + i, 1, ir.numDocs());
      ir.close();
    }

    // Check if document is still there
    failure.clearDoFail();
    ir = DirectoryReader.open(dir);
    assertEquals(1, ir.numDocs());
    ir.close();

    dir.close();
  }
View Full Code Here

  public void testNoLostDeletesOrUpdates() throws Exception {
    int deleteCount = 0;
    int docBase = 0;
    int docCount = 0;

    MockDirectoryWrapper dir = newMockDirectory();
    final AtomicBoolean shouldFail = new AtomicBoolean();
    dir.failOn(new MockDirectoryWrapper.Failure() {
     
      @Override
      public void eval(MockDirectoryWrapper dir) throws IOException {
        StackTraceElement[] trace = new Exception().getStackTrace();
        if (shouldFail.get() == false) {
          return;
        }
       
        boolean sawSeal = false;
        boolean sawWrite = false;
        for (int i = 0; i < trace.length; i++) {
          if ("sealFlushedSegment".equals(trace[i].getMethodName())) {
            sawSeal = true;
            break;
          }
          if ("writeLiveDocs".equals(trace[i].getMethodName()) || "writeFieldUpdates".equals(trace[i].getMethodName())) {
            sawWrite = true;
          }
        }
       
        // Don't throw exc if we are "flushing", else
        // the segment is aborted and docs are lost:
        if (sawWrite && sawSeal == false && random().nextInt(3) == 2) {
          // Only sometimes throw the exc, so we get
          // it sometimes on creating the file, on
          // flushing buffer, on closing the file:
          if (VERBOSE) {
            System.out.println("TEST: now fail; thread=" + Thread.currentThread().getName() + " exc:");
            new Throwable().printStackTrace(System.out);
          }
          shouldFail.set(false);
          throw new FakeIOException();
        }
      }
    });
   
    RandomIndexWriter w = null;

    for(int iter=0;iter<10*RANDOM_MULTIPLIER;iter++) {
      int numDocs = atLeast(100);
      if (VERBOSE) {
        System.out.println("\nTEST: iter=" + iter + " numDocs=" + numDocs + " docBase=" + docBase + " delCount=" + deleteCount);
      }
      if (w == null) {
        IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));
        final MergeScheduler ms = iwc.getMergeScheduler();
        if (ms instanceof ConcurrentMergeScheduler) {
          final ConcurrentMergeScheduler suppressFakeIOE = new ConcurrentMergeScheduler() {
              @Override
              protected void handleMergeException(Throwable exc) {
                // suppress only FakeIOException:
                if (!(exc instanceof FakeIOException)) {
                  super.handleMergeException(exc);
                }
              }
            };
          final ConcurrentMergeScheduler cms = (ConcurrentMergeScheduler) ms;
          suppressFakeIOE.setMaxMergesAndThreads(cms.getMaxMergeCount(), cms.getMaxThreadCount());
          suppressFakeIOE.setMergeThreadPriority(cms.getMergeThreadPriority());
          iwc.setMergeScheduler(suppressFakeIOE);
        }
       
        w = new RandomIndexWriter(random(), dir, iwc);
        // Since we hit exc during merging, a partial
        // forceMerge can easily return when there are still
        // too many segments in the index:
        w.setDoRandomForceMergeAssert(false);
      }
      for(int i=0;i<numDocs;i++) {
        Document doc = new Document();
        doc.add(new StringField("id", ""+(docBase+i), Field.Store.NO));
        if (defaultCodecSupportsDocValues()) {
          doc.add(new NumericDocValuesField("f", 1L));
          doc.add(new NumericDocValuesField("cf", 2L));
        }
        w.addDocument(doc);
      }
      docCount += numDocs;

      // TODO: we could make the test more evil, by letting
      // it throw more than one exc, randomly, before "recovering"

      // TODO: we could also install an infoStream and try
      // to fail in "more evil" places inside BDS

      shouldFail.set(true);
      boolean doClose = false;

      try {

        boolean defaultCodecSupportsFieldUpdates = defaultCodecSupportsFieldUpdates();
        for(int i=0;i<numDocs;i++) {
          if (random().nextInt(10) == 7) {
            boolean fieldUpdate = defaultCodecSupportsFieldUpdates && random().nextBoolean();
            if (fieldUpdate) {
              long value = iter;
              if (VERBOSE) {
                System.out.println("  update id=" + (docBase+i) + " to value " + value);
              }
              w.updateNumericDocValue(new Term("id", Integer.toString(docBase + i)), "f", value);
              w.updateNumericDocValue(new Term("id", Integer.toString(docBase + i)), "cf", value * 2);
            }
           
            // sometimes do both deletes and updates
            if (!fieldUpdate || random().nextBoolean()) {
              if (VERBOSE) {
                System.out.println("  delete id=" + (docBase+i));
              }
              deleteCount++;
              w.deleteDocuments(new Term("id", ""+(docBase+i)));
            }
          }
        }

        // Trigger writeLiveDocs so we hit fake exc:
        IndexReader r = w.getReader(true);

        // Sometimes we will make it here (we only randomly
        // throw the exc):
        assertEquals(docCount-deleteCount, r.numDocs());
        r.close();
       
        // Sometimes close, so the disk full happens on close:
        if (random().nextBoolean()) {
          if (VERBOSE) {
            System.out.println("  now close writer");
          }
          doClose = true;
          w.close();
          w = null;
        }

      } catch (IOException ioe) {
        // FakeIOException can be thrown from mergeMiddle, in which case IW
        // registers it before our CMS gets to suppress it. IW.forceMerge later
        // throws it as a wrapped IOE, so don't fail in this case.
        if (ioe instanceof FakeIOException || (ioe.getCause() != null && ioe.getCause() instanceof FakeIOException)) {
          // expected
          if (VERBOSE) {
            System.out.println("TEST: w.close() hit expected IOE");
          }
        } else {
          throw ioe;
        }
      }
      shouldFail.set(false);

      IndexReader r;

      if (doClose && w != null) {
        if (VERBOSE) {
          System.out.println("  now 2nd close writer");
        }
        w.close();
        w = null;
      }

      if (w == null || random().nextBoolean()) {
        // Open non-NRT reader, to make sure the "on
        // disk" bits are good:
        if (VERBOSE) {
          System.out.println("TEST: verify against non-NRT reader");
        }
        if (w != null) {
          w.commit();
        }
        r = DirectoryReader.open(dir);
      } else {
        if (VERBOSE) {
          System.out.println("TEST: verify against NRT reader");
        }
        r = w.getReader();
      }
      assertEquals(docCount-deleteCount, r.numDocs());
      if (defaultCodecSupportsDocValues()) {
        for (AtomicReaderContext context : r.leaves()) {
          Bits liveDocs = context.reader().getLiveDocs();
          NumericDocValues f = context.reader().getNumericDocValues("f");
          NumericDocValues cf = context.reader().getNumericDocValues("cf");
          for (int i = 0; i < context.reader().maxDoc(); i++) {
            if (liveDocs == null || liveDocs.get(i)) {
              assertEquals("doc=" + (docBase + i), cf.get(i), f.get(i) * 2);
            }
          }
        }
      }

      r.close();

      // Sometimes re-use RIW, other times open new one:
      if (w != null && random().nextBoolean()) {
        if (VERBOSE) {
          System.out.println("TEST: close writer");
        }
        w.close();
        w = null;
      }

      docBase += numDocs;
    }

    if (w != null) {
      w.close();
    }

    // Final verify:
    IndexReader r = DirectoryReader.open(dir);
    assertEquals(docCount-deleteCount, r.numDocs());
    r.close();

    dir.close();
  }
View Full Code Here

import org.apache.lucene.util.PrintStreamInfoStream;
import org.apache.lucene.util._TestUtil;

public class TestIndexWriterOutOfFileDescriptors extends LuceneTestCase {
  public void test() throws Exception {
    MockDirectoryWrapper dir = newMockFSDirectory(_TestUtil.getTempDir("TestIndexWriterOutOfFileDescriptors"));
    dir.setPreventDoubleWrite(false);
    double rate = random().nextDouble()*0.01;
    //System.out.println("rate=" + rate);
    dir.setRandomIOExceptionRateOnOpen(rate);
    int iters = atLeast(20);
    LineFileDocs docs = new LineFileDocs(random(), defaultCodecSupportsDocValues());
    IndexReader r = null;
    DirectoryReader r2 = null;
    boolean any = false;
    MockDirectoryWrapper dirCopy = null;
    int lastNumDocs = 0;
    for(int iter=0;iter<iters;iter++) {

      IndexWriter w = null;
      if (VERBOSE) {
        System.out.println("TEST: iter=" + iter);
      }
      try {
        IndexWriterConfig iwc = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()));

        if (VERBOSE) {
          // Do this ourselves instead of relying on LTC so
          // we see incrementing messageID:
          iwc.setInfoStream(new PrintStreamInfoStream(System.out));
        }
        MergeScheduler ms = iwc.getMergeScheduler();
        if (ms instanceof ConcurrentMergeScheduler) {
          ((ConcurrentMergeScheduler) ms).setSuppressExceptions();
        }
        w = new IndexWriter(dir, iwc);
        if (r != null && random().nextInt(5) == 3) {
          if (random().nextBoolean()) {
            if (VERBOSE) {
              System.out.println("TEST: addIndexes IR[]");
            }
            w.addIndexes(new IndexReader[] {r});
          } else {
            if (VERBOSE) {
              System.out.println("TEST: addIndexes Directory[]");
            }
            w.addIndexes(new Directory[] {dirCopy});
          }
        } else {
          if (VERBOSE) {
            System.out.println("TEST: addDocument");
          }
          w.addDocument(docs.nextDoc());
        }
        w.close();
        w = null;

        // NOTE: This is O(N^2)!  Only enable for temporary debugging:
        //dir.setRandomIOExceptionRateOnOpen(0.0);
        //_TestUtil.checkIndex(dir);
        //dir.setRandomIOExceptionRateOnOpen(rate);

        // Verify numDocs only increases, to catch IndexWriter
        // accidentally deleting the index:
        dir.setRandomIOExceptionRateOnOpen(0.0);
        assertTrue(DirectoryReader.indexExists(dir));
        if (r2 == null) {
          r2 = DirectoryReader.open(dir);
        } else {
          DirectoryReader r3 = DirectoryReader.openIfChanged(r2);
          if (r3 != null) {
            r2.close();
            r2 = r3;
          }
        }
        assertTrue("before=" + lastNumDocs + " after=" + r2.numDocs(), r2.numDocs() >= lastNumDocs);
        lastNumDocs = r2.numDocs();
        //System.out.println("numDocs=" + lastNumDocs);
        dir.setRandomIOExceptionRateOnOpen(rate);

        any = true;
        if (VERBOSE) {
          System.out.println("TEST: iter=" + iter + ": success");
        }
      } catch (IOException ioe) {
        if (VERBOSE) {
          System.out.println("TEST: iter=" + iter + ": exception");
          ioe.printStackTrace();
        }
        if (w != null) {
          // NOTE: leave random IO exceptions enabled here,
          // to verify that rollback does not try to write
          // anything:
          w.rollback();
        }
      }

      if (any && r == null && random().nextBoolean()) {
        // Make a copy of a non-empty index so we can use
        // it to addIndexes later:
        dir.setRandomIOExceptionRateOnOpen(0.0);
        r = DirectoryReader.open(dir);
        dirCopy = newMockFSDirectory(_TestUtil.getTempDir("TestIndexWriterOutOfFileDescriptors.copy"));
        Set<String> files = new HashSet<String>();
        for (String file : dir.listAll()) {
          dir.copy(dirCopy, file, file, IOContext.DEFAULT);
          files.add(file);
        }
        dirCopy.sync(files);
        // Have IW kiss the dir so we remove any leftover
        // files ... we can easily have leftover files at
        // the time we take a copy because we are holding
        // open a reader:
        new IndexWriter(dirCopy, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))).close();
        dirCopy.setRandomIOExceptionRate(rate);
        dir.setRandomIOExceptionRateOnOpen(rate);
      }
    }

    if (r2 != null) {
      r2.close();
    }
    if (r != null) {
      r.close();
      dirCopy.close();
    }
    dir.close();
  }
View Full Code Here

@TimeoutSuite(millis = 4 * TimeUnits.HOUR)
public class Test4GBStoredFields extends LuceneTestCase {

  @Nightly
  public void test() throws Exception {
    MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new MMapDirectory(_TestUtil.getTempDir("4GBStoredFields")));
    dir.setThrottling(MockDirectoryWrapper.Throttling.NEVER);

    IndexWriter w = new IndexWriter(dir,
        new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random()))
        .setMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH)
        .setRAMBufferSizeMB(256.0)
        .setMergeScheduler(new ConcurrentMergeScheduler())
        .setMergePolicy(newLogMergePolicy(false, 10))
        .setOpenMode(IndexWriterConfig.OpenMode.CREATE));

    MergePolicy mp = w.getConfig().getMergePolicy();
    if (mp instanceof LogByteSizeMergePolicy) {
     // 1 petabyte:
     ((LogByteSizeMergePolicy) mp).setMaxMergeMB(1024*1024*1024);
    }

    final Document doc = new Document();
    final FieldType ft = new FieldType();
    ft.setIndexed(false);
    ft.setStored(true);
    ft.freeze();
    final int valueLength = RandomInts.randomIntBetween(random(), 1 << 13, 1 << 20);
    final byte[] value = new byte[valueLength];
    for (int i = 0; i < valueLength; ++i) {
      // random so that even compressing codecs can't compress it
      value[i] = (byte) random().nextInt(256);
    }
    final Field f = new Field("fld", value, ft);
    doc.add(f);

    final int numDocs = (int) ((1L << 32) / valueLength + 100);
    for (int i = 0; i < numDocs; ++i) {
      w.addDocument(doc);
      if (VERBOSE && i % (numDocs / 10) == 0) {
        System.out.println(i + " of " + numDocs + "...");
      }
    }
    w.forceMerge(1);
    w.close();
    if (VERBOSE) {
      boolean found = false;
      for (String file : dir.listAll()) {
        if (file.endsWith(".fdt")) {
          final long fileLength = dir.fileLength(file);
          if (fileLength >= 1L << 32) {
            found = true;
          }
          System.out.println("File length of " + file + " : " + fileLength);
        }
      }
      if (!found) {
        System.out.println("No .fdt file larger than 4GB, test bug?");
      }
    }

    DirectoryReader rd = DirectoryReader.open(dir);
    Document sd = rd.document(numDocs - 1);
    assertNotNull(sd);
    assertEquals(1, sd.getFields().size());
    BytesRef valueRef = sd.getBinaryValue("fld");
    assertNotNull(valueRef);
    assertEquals(new BytesRef(value), valueRef);
    rd.close();

    dir.close();
  }
View Full Code Here

    createIndexNoClose(false, "test", writer);
    writer.commit();

    final Directory[] dirs = new Directory[10];
    for (int i=0;i<10;i++) {
      dirs[i] = new MockDirectoryWrapper(random(), new RAMDirectory(dir1, newIOContext(random())));
    }

    DirectoryReader r = writer.getReader();

    final float SECONDS = 0.5f;
View Full Code Here

TOP

Related Classes of org.apache.lucene.store.MockDirectoryWrapper$FakeIOException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.