Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

LUCENE-5987: IndexWriter forcefully closes itself on hitting aborting exception

Michael McCandlessde4c6513bcb7
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index adf6ae7a73a..3c116065a7f 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -351,6 +351,10 @@ Bug Fixes
* LUCENE-6075: Don't overflow int in SimpleRateLimiter (Boaz Leskes
via Mike McCandless)
+
+* LUCENE-5987: IndexWriter will now forcefully close itself on
+ aborting exception (an exception that would otherwise cause silent
+ data loss). (Robert Muir, Mike McCandless)
Documentation
diff --git a/lucene/core/src/java/org/apache/lucene/index/AbortingException.java b/lucene/core/src/java/org/apache/lucene/index/AbortingException.java
new file mode 100644
index 00000000000..2895f6870f7
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/index/AbortingException.java
@@ -0,0 +1,27 @@
+package org.apache.lucene.index;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/** Thrown and caught internally in {@link IndexWriter} methods when an {@code IOException} would cause it to
+ * lose previously indexed documents. When this happens, the {@link IndexWriter} is forcefully
+ * closed, using {@link IndexWriter#rollback}). */
+class AbortingException extends Exception {
+ AbortingException(Throwable cause) {
+ super(cause);
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java b/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java
index b55e4cc2848..b7a839c1b7e 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DefaultIndexingChain.java
@@ -83,7 +83,7 @@ final class DefaultIndexingChain extends DocConsumer {
}
@Override
- public void flush(SegmentWriteState state) throws IOException {
+ public void flush(SegmentWriteState state) throws IOException, AbortingException {
// NOTE: caller (DocumentsWriterPerThread) handles
// aborting on any exception from this method
@@ -176,7 +176,7 @@ final class DefaultIndexingChain extends DocConsumer {
/** Catch up for all docs before us that had no stored
* fields, or hit non-aborting exceptions before writing
* stored fields. */
- private void fillStoredFields(int docID) throws IOException {
+ private void fillStoredFields(int docID) throws IOException, AbortingException {
while (lastStoredDocID < docID) {
startStoredFields();
finishStoredFields();
@@ -253,36 +253,28 @@ final class DefaultIndexingChain extends DocConsumer {
/** Calls StoredFieldsWriter.startDocument, aborting the
* segment if it hits any exception. */
- private void startStoredFields() throws IOException {
- boolean success = false;
+ private void startStoredFields() throws IOException, AbortingException {
try {
initStoredFieldsWriter();
storedFieldsWriter.startDocument();
- success = true;
- } finally {
- if (success == false) {
- docWriter.setAborting();
- }
+ } catch (Throwable th) {
+ throw new AbortingException(th);
}
lastStoredDocID++;
}
/** Calls StoredFieldsWriter.finishDocument, aborting the
* segment if it hits any exception. */
- private void finishStoredFields() throws IOException {
- boolean success = false;
+ private void finishStoredFields() throws IOException, AbortingException {
try {
storedFieldsWriter.finishDocument();
- success = true;
- } finally {
- if (success == false) {
- docWriter.setAborting();
- }
+ } catch (Throwable th) {
+ throw new AbortingException(th);
}
}
@Override
- public void processDocument() throws IOException {
+ public void processDocument() throws IOException, AbortingException {
// How many indexed field names we've seen (collapses
// multiple field instances by the same name):
@@ -325,16 +317,12 @@ final class DefaultIndexingChain extends DocConsumer {
}
}
- boolean success = false;
try {
termsHash.finishDocument();
- success = true;
- } finally {
- if (success == false) {
- // Must abort, on the possibility that on-disk term
- // vectors are now corrupt:
- docWriter.setAborting();
- }
+ } catch (Throwable th) {
+ // Must abort, on the possibility that on-disk term
+ // vectors are now corrupt:
+ throw new AbortingException(th);
}
// Add stored fields:
@@ -352,9 +340,12 @@ final class DefaultIndexingChain extends DocConsumer {
PerField fp = getOrAddField(fieldName, fieldType, false);
if (fieldType.stored()) {
- abort = true;
- storedFieldsWriter.writeField(fp.fieldInfo, field);
- abort = false;
+ try {
+ storedFieldsWriter.writeField(fp.fieldInfo, field);
+ } catch (Throwable th) {
+ abort = true;
+ throw new AbortingException(th);
+ }
}
DocValuesType dvType = fieldType.docValuesType();
@@ -366,9 +357,7 @@ final class DefaultIndexingChain extends DocConsumer {
}
}
} finally {
- if (abort) {
- docWriter.setAborting();
- } else {
+ if (abort == false) {
finishStoredFields();
}
}
@@ -575,7 +564,7 @@ final class DefaultIndexingChain extends DocConsumer {
/** Inverts one field for one document; first is true
* if this is the first time we are seeing this field
* name in this document. */
- public void invert(IndexableField field, boolean first) throws IOException {
+ public void invert(IndexableField field, boolean first) throws IOException, AbortingException {
if (first) {
// First time we're seeing this field (indexed) in
// this document:
@@ -602,7 +591,6 @@ final class DefaultIndexingChain extends DocConsumer {
* when we fail. We expect some caller to eventually deal with the real exception, so we don't want any 'catch' clauses,
* but rather a finally that takes note of the problem.
*/
- boolean aborting = false;
boolean succeededInProcessingField = false;
try (TokenStream stream = tokenStream = field.tokenStream(docState.analyzer, tokenStream)) {
// reset the TokenStream to the first token
@@ -654,9 +642,21 @@ final class DefaultIndexingChain extends DocConsumer {
// internal state of the terms hash is now
// corrupt and should not be flushed to a
// new segment:
- aborting = true;
- termsHashPerField.add();
- aborting = false;
+ try {
+ termsHashPerField.add();
+ } catch (MaxBytesLengthExceededException e) {
+ byte[] prefix = new byte[30];
+ BytesRef bigTerm = invertState.termAttribute.getBytesRef();
+ System.arraycopy(bigTerm.bytes, bigTerm.offset, prefix, 0, 30);
+ String msg = "Document contains at least one immense term in field=\"" + fieldInfo.name + "\" (whose UTF8 encoding is longer than the max length " + DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8 + "), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '" + Arrays.toString(prefix) + "...', original message: " + e.getMessage();
+ if (docState.infoStream.isEnabled("IW")) {
+ docState.infoStream.message("IW", "ERROR: " + msg);
+ }
+ // Document will be deleted above:
+ throw new IllegalArgumentException(msg, e);
+ } catch (Throwable th) {
+ throw new AbortingException(th);
+ }
}
// trigger streams to perform end-of-stream operations
@@ -669,22 +669,7 @@ final class DefaultIndexingChain extends DocConsumer {
/* if there is an exception coming through, we won't set this to true here:*/
succeededInProcessingField = true;
- } catch (MaxBytesLengthExceededException e) {
- aborting = false;
- byte[] prefix = new byte[30];
- BytesRef bigTerm = invertState.termAttribute.getBytesRef();
- System.arraycopy(bigTerm.bytes, bigTerm.offset, prefix, 0, 30);
- String msg = "Document contains at least one immense term in field=\"" + fieldInfo.name + "\" (whose UTF8 encoding is longer than the max length " + DocumentsWriterPerThread.MAX_TERM_LENGTH_UTF8 + "), all of which were skipped. Please correct the analyzer to not produce such terms. The prefix of the first immense term is: '" + Arrays.toString(prefix) + "...', original message: " + e.getMessage();
- if (docState.infoStream.isEnabled("IW")) {
- docState.infoStream.message("IW", "ERROR: " + msg);
- }
- // Document will be deleted above:
- throw new IllegalArgumentException(msg, e);
} finally {
- if (succeededInProcessingField == false && aborting) {
- docState.docWriter.setAborting();
- }
-
if (!succeededInProcessingField && docState.infoStream.isEnabled("DW")) {
docState.infoStream.message("DW", "An exception was thrown while processing field " + fieldInfo.name);
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocConsumer.java b/lucene/core/src/java/org/apache/lucene/index/DocConsumer.java
index ca9e9360f45..5f23ce7e0dd 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocConsumer.java
@@ -20,7 +20,7 @@ package org.apache.lucene.index;
import java.io.IOException;
abstract class DocConsumer {
- abstract void processDocument() throws IOException;
- abstract void flush(final SegmentWriteState state) throws IOException;
+ abstract void processDocument() throws IOException, AbortingException;
+ abstract void flush(final SegmentWriteState state) throws IOException, AbortingException;
abstract void abort();
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java
index 552c7bf25c1..e3c357f142d 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriter.java
@@ -35,6 +35,7 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Accountable;
+import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.InfoStream;
/**
@@ -203,7 +204,6 @@ final class DocumentsWriter implements Closeable, Accountable {
synchronized void abort(IndexWriter writer) {
assert !Thread.holdsLock(writer) : "IndexWriter lock should never be hold when aborting";
boolean success = false;
- final Set<String> newFilesSet = new HashSet<>();
try {
deleteQueue.clear();
if (infoStream.isEnabled("DW")) {
@@ -214,18 +214,17 @@ final class DocumentsWriter implements Closeable, Accountable {
final ThreadState perThread = perThreadPool.getThreadState(i);
perThread.lock();
try {
- abortThreadState(perThread, newFilesSet);
+ abortThreadState(perThread);
} finally {
perThread.unlock();
}
}
- flushControl.abortPendingFlushes(newFilesSet);
- putEvent(new DeleteNewFilesEvent(newFilesSet));
+ flushControl.abortPendingFlushes();
flushControl.waitForFlush();
success = true;
} finally {
if (infoStream.isEnabled("DW")) {
- infoStream.message("DW", "done abort; abortedFiles=" + newFilesSet + " success=" + success);
+ infoStream.message("DW", "done abort success=" + success);
}
}
}
@@ -239,15 +238,13 @@ final class DocumentsWriter implements Closeable, Accountable {
try {
deleteQueue.clear();
final int limit = perThreadPool.getMaxThreadStates();
- final Set<String> newFilesSet = new HashSet<>();
for (int i = 0; i < limit; i++) {
final ThreadState perThread = perThreadPool.getThreadState(i);
perThread.lock();
- abortThreadState(perThread, newFilesSet);
+ abortThreadState(perThread);
}
deleteQueue.clear();
- flushControl.abortPendingFlushes(newFilesSet);
- putEvent(new DeleteNewFilesEvent(newFilesSet));
+ flushControl.abortPendingFlushes();
flushControl.waitForFlush();
success = true;
} finally {
@@ -261,15 +258,14 @@ final class DocumentsWriter implements Closeable, Accountable {
}
}
- private final void abortThreadState(final ThreadState perThread, Set<String> newFiles) {
+ private final void abortThreadState(final ThreadState perThread) {
assert perThread.isHeldByCurrentThread();
if (perThread.isActive()) { // we might be closed
if (perThread.isInitialized()) {
try {
subtractFlushedNumDocs(perThread.dwpt.getNumDocsInRAM());
- perThread.dwpt.abort(newFiles);
+ perThread.dwpt.abort();
} finally {
- perThread.dwpt.checkAndResetHasAborted();
flushControl.doOnAbort(perThread);
}
} else {
@@ -340,7 +336,7 @@ final class DocumentsWriter implements Closeable, Accountable {
flushControl.setClosed();
}
- private boolean preUpdate() throws IOException {
+ private boolean preUpdate() throws IOException, AbortingException {
ensureOpen();
boolean hasEvents = false;
if (flushControl.anyStalledThreads() || flushControl.numQueuedFlushes() > 0) {
@@ -372,7 +368,7 @@ final class DocumentsWriter implements Closeable, Accountable {
return hasEvents;
}
- private boolean postUpdate(DocumentsWriterPerThread flushingDWPT, boolean hasEvents) throws IOException {
+ private boolean postUpdate(DocumentsWriterPerThread flushingDWPT, boolean hasEvents) throws IOException, AbortingException {
hasEvents |= applyAllDeletes(deleteQueue);
if (flushingDWPT != null) {
hasEvents |= doFlush(flushingDWPT);
@@ -397,7 +393,7 @@ final class DocumentsWriter implements Closeable, Accountable {
}
boolean updateDocuments(final Iterable<? extends IndexDocument> docs, final Analyzer analyzer,
- final Term delTerm) throws IOException {
+ final Term delTerm) throws IOException, AbortingException {
boolean hasEvents = preUpdate();
final ThreadState perThread = flushControl.obtainAndLock();
@@ -414,18 +410,15 @@ final class DocumentsWriter implements Closeable, Accountable {
final int dwptNumDocs = dwpt.getNumDocsInRAM();
try {
dwpt.updateDocuments(docs, analyzer, delTerm);
+ } catch (AbortingException ae) {
+ flushControl.doOnAbort(perThread);
+ dwpt.abort();
+ throw ae;
} finally {
// We don't know how many documents were actually
// counted as indexed, so we must subtract here to
// accumulate our separate counter:
numDocsInRAM.addAndGet(dwpt.getNumDocsInRAM() - dwptNumDocs);
- if (dwpt.checkAndResetHasAborted()) {
- if (!dwpt.pendingFilesToDelete().isEmpty()) {
- putEvent(new DeleteNewFilesEvent(dwpt.pendingFilesToDelete()));
- }
- subtractFlushedNumDocs(dwptNumDocs);
- flushControl.doOnAbort(perThread);
- }
}
final boolean isUpdate = delTerm != null;
flushingDWPT = flushControl.doAfterDocument(perThread, isUpdate);
@@ -437,7 +430,7 @@ final class DocumentsWriter implements Closeable, Accountable {
}
boolean updateDocument(final IndexDocument doc, final Analyzer analyzer,
- final Term delTerm) throws IOException {
+ final Term delTerm) throws IOException, AbortingException {
boolean hasEvents = preUpdate();
@@ -455,18 +448,15 @@ final class DocumentsWriter implements Closeable, Accountable {
final int dwptNumDocs = dwpt.getNumDocsInRAM();
try {
dwpt.updateDocument(doc, analyzer, delTerm);
+ } catch (AbortingException ae) {
+ flushControl.doOnAbort(perThread);
+ dwpt.abort();
+ throw ae;
} finally {
// We don't know whether the document actually
// counted as being indexed, so we must subtract here to
// accumulate our separate counter:
numDocsInRAM.addAndGet(dwpt.getNumDocsInRAM() - dwptNumDocs);
- if (dwpt.checkAndResetHasAborted()) {
- if (!dwpt.pendingFilesToDelete().isEmpty()) {
- putEvent(new DeleteNewFilesEvent(dwpt.pendingFilesToDelete()));
- }
- subtractFlushedNumDocs(dwptNumDocs);
- flushControl.doOnAbort(perThread);
- }
}
final boolean isUpdate = delTerm != null;
flushingDWPT = flushControl.doAfterDocument(perThread, isUpdate);
@@ -477,12 +467,13 @@ final class DocumentsWriter implements Closeable, Accountable {
return postUpdate(flushingDWPT, hasEvents);
}
- private boolean doFlush(DocumentsWriterPerThread flushingDWPT) throws IOException {
+ private boolean doFlush(DocumentsWriterPerThread flushingDWPT) throws IOException, AbortingException {
boolean hasEvents = false;
while (flushingDWPT != null) {
hasEvents = true;
boolean success = false;
SegmentFlushTicket ticket = null;
+ Throwable exc = null;
try {
assert currentFullFlushDelQueue == null
|| flushingDWPT.deleteQueue == currentFullFlushDelQueue : "expected: "
@@ -548,7 +539,6 @@ final class DocumentsWriter implements Closeable, Accountable {
}
} finally {
flushControl.doAfterFlush(flushingDWPT);
- flushingDWPT.checkAndResetHasAborted();
}
flushingDWPT = flushControl.nextPendingFlush();
@@ -597,8 +587,8 @@ final class DocumentsWriter implements Closeable, Accountable {
* two stage operation; the caller must ensure (in try/finally) that finishFlush
* is called after this method, to release the flush lock in DWFlushControl
*/
- final boolean flushAllThreads(final IndexWriter indexWriter)
- throws IOException {
+ final boolean flushAllThreads()
+ throws IOException, AbortingException {
final DocumentsWriterDeleteQueue flushingDeleteQueue;
if (infoStream.isEnabled("DW")) {
infoStream.message("DW", "startFullFlush");
@@ -631,7 +621,7 @@ final class DocumentsWriter implements Closeable, Accountable {
}
ticketQueue.addDeletes(flushingDeleteQueue);
}
- ticketQueue.forcePurge(indexWriter);
+ ticketQueue.forcePurge(writer);
assert !flushingDeleteQueue.anyChanges() && !ticketQueue.hasTickets();
} finally {
assert flushingDeleteQueue == currentFullFlushDelQueue;
@@ -649,9 +639,7 @@ final class DocumentsWriter implements Closeable, Accountable {
// Release the flush lock
flushControl.finishFullFlush();
} else {
- Set<String> newFilesSet = new HashSet<>();
- flushControl.abortFullFlushes(newFilesSet);
- putEvent(new DeleteNewFilesEvent(newFilesSet));
+ flushControl.abortFullFlushes();
}
} finally {
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterFlushControl.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterFlushControl.java
index c5b000f7309..d3c19c8bf40 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterFlushControl.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterFlushControl.java
@@ -310,7 +310,7 @@ final class DocumentsWriterFlushControl implements Accountable {
dwpt = perThreadPool.reset(perThread, closed);
numPending--;
blockedFlushes.add(new BlockedFlush(dwpt, bytes));
- }finally {
+ } finally {
perThread.unlock();
}
}
@@ -611,20 +611,20 @@ final class DocumentsWriterFlushControl implements Accountable {
return true;
}
- synchronized void abortFullFlushes(Set<String> newFiles) {
+ synchronized void abortFullFlushes() {
try {
- abortPendingFlushes(newFiles);
+ abortPendingFlushes();
} finally {
fullFlush = false;
}
}
- synchronized void abortPendingFlushes(Set<String> newFiles) {
+ synchronized void abortPendingFlushes() {
try {
for (DocumentsWriterPerThread dwpt : flushQueue) {
try {
documentsWriter.subtractFlushedNumDocs(dwpt.getNumDocsInRAM());
- dwpt.abort(newFiles);
+ dwpt.abort();
} catch (Throwable ex) {
// ignore - keep on aborting the flush queue
} finally {
@@ -636,7 +636,7 @@ final class DocumentsWriterFlushControl implements Accountable {
flushingWriters
.put(blockedFlush.dwpt, Long.valueOf(blockedFlush.bytes));
documentsWriter.subtractFlushedNumDocs(blockedFlush.dwpt.getNumDocsInRAM());
- blockedFlush.dwpt.abort(newFiles);
+ blockedFlush.dwpt.abort();
} catch (Throwable ex) {
// ignore - keep on aborting the blocked queue
} finally {
diff --git a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
index 79fda8a9d30..6f4d5d871c0 100644
--- a/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
+++ b/lucene/core/src/java/org/apache/lucene/index/DocumentsWriterPerThread.java
@@ -112,9 +112,9 @@ class DocumentsWriterPerThread {
* updating the index files) and must discard all
* currently buffered docs. This resets our state,
* discarding any docs added since last flush. */
- void abort(Set<String> createdFiles) {
+ void abort() {
//System.out.println(Thread.currentThread().getName() + ": now abort seg=" + segmentInfo.name);
- hasAborted = aborting = true;
+ aborted = true;
try {
if (infoStream.isEnabled("DWPT")) {
infoStream.message("DWPT", "now abort");
@@ -125,9 +125,7 @@ class DocumentsWriterPerThread {
}
pendingUpdates.clear();
- createdFiles.addAll(directory.getCreatedFiles());
} finally {
- aborting = false;
if (infoStream.isEnabled("DWPT")) {
infoStream.message("DWPT", "done abort");
}
@@ -145,8 +143,7 @@ class DocumentsWriterPerThread {
// Updates for our still-in-RAM (to be flushed next) segment
final BufferedUpdates pendingUpdates;
private final SegmentInfo segmentInfo; // Current segment we are working on
- boolean aborting = false; // True if an abort is pending
- boolean hasAborted = false; // True if the last exception throws by #updateDocument was aborting
+ boolean aborted = false; // True if we aborted
private final FieldInfos.Builder fieldInfos;
private final InfoStream infoStream;
@@ -189,20 +186,10 @@ class DocumentsWriterPerThread {
consumer = indexWriterConfig.getIndexingChain().getChain(this);
}
- void setAborting() {
- aborting = true;
- }
-
public FieldInfos.Builder getFieldInfosBuilder() {
return fieldInfos;
}
- boolean checkAndResetHasAborted() {
- final boolean retval = hasAborted;
- hasAborted = false;
- return retval;
- }
-
final void testPoint(String message) {
if (infoStream.isEnabled("TP")) {
infoStream.message("TP", message);
@@ -219,7 +206,7 @@ class DocumentsWriterPerThread {
}
}
- public void updateDocument(IndexDocument doc, Analyzer analyzer, Term delTerm) throws IOException {
+ public void updateDocument(IndexDocument doc, Analyzer analyzer, Term delTerm) throws IOException, AbortingException {
testPoint("DocumentsWriterPerThread addDocument start");
assert deleteQueue != null;
docState.doc = doc;
@@ -245,19 +232,15 @@ class DocumentsWriterPerThread {
success = true;
} finally {
if (!success) {
- if (!aborting) {
- // mark document as deleted
- deleteDocID(docState.docID);
- numDocsInRAM++;
- } else {
- abort(filesToDelete);
- }
+ // mark document as deleted
+ deleteDocID(docState.docID);
+ numDocsInRAM++;
}
}
finishDocument(delTerm);
}
- public int updateDocuments(Iterable<? extends IndexDocument> docs, Analyzer analyzer, Term delTerm) throws IOException {
+ public int updateDocuments(Iterable<? extends IndexDocument> docs, Analyzer analyzer, Term delTerm) throws IOException, AbortingException {
testPoint("DocumentsWriterPerThread addDocuments start");
assert deleteQueue != null;
docState.analyzer = analyzer;
@@ -286,14 +269,9 @@ class DocumentsWriterPerThread {
success = true;
} finally {
if (!success) {
- // An exc is being thrown...
- if (!aborting) {
- // Incr here because finishDocument will not
- // be called (because an exc is being thrown):
- numDocsInRAM++;
- } else {
- abort(filesToDelete);
- }
+ // Incr here because finishDocument will not
+ // be called (because an exc is being thrown):
+ numDocsInRAM++;
}
}
finishDocument(null);
@@ -310,7 +288,7 @@ class DocumentsWriterPerThread {
}
} finally {
- if (!allDocsIndexed && !aborting) {
+ if (!allDocsIndexed && !aborted) {
// the iterator threw an exception that is not aborting
// go and mark all docs from this block as deleted
int docID = numDocsInRAM-1;
@@ -403,7 +381,7 @@ class DocumentsWriterPerThread {
}
/** Flush all pending docs to a new segment */
- FlushedSegment flush() throws IOException {
+ FlushedSegment flush() throws IOException, AbortingException {
assert numDocsInRAM > 0;
assert deleteSlice.isEmpty() : "all deletes must be applied in prepareFlush";
segmentInfo.setDocCount(numDocsInRAM);
@@ -424,7 +402,7 @@ class DocumentsWriterPerThread {
pendingUpdates.docIDs.clear();
}
- if (aborting) {
+ if (aborted) {
if (infoStream.isEnabled("DWPT")) {
infoStream.message("DWPT", "flush: skip because aborting is set");
}
@@ -435,8 +413,6 @@ class DocumentsWriterPerThread {
infoStream.message("DWPT", "flush postings as segment " + flushState.segmentInfo.name + " numDocs=" + numDocsInRAM);
}
- boolean success = false;
-
try {
consumer.flush(flushState);
pendingUpdates.terms.clear();
@@ -476,13 +452,11 @@ class DocumentsWriterPerThread {
FlushedSegment fs = new FlushedSegment(segmentInfoPerCommit, flushState.fieldInfos,
segmentDeletes, flushState.liveDocs, flushState.delCountOnFlush);
sealFlushedSegment(fs);
- success = true;
return fs;
- } finally {
- if (!success) {
- abort(filesToDelete);
- }
+ } catch (Throwable th) {
+ abort();
+ throw new AbortingException(th);
}
}
@@ -603,7 +577,7 @@ class DocumentsWriterPerThread {
@Override
public String toString() {
return "DocumentsWriterPerThread [pendingDeletes=" + pendingUpdates
- + ", segment=" + (segmentInfo != null ? segmentInfo.name : "null") + ", aborting=" + aborting + ", numDocsInRAM="
+ + ", segment=" + (segmentInfo != null ? segmentInfo.name : "null") + ", aborted=" + aborted + ", numDocsInRAM="
+ numDocsInRAM + ", deleteQueue=" + deleteQueue + "]";
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexFileDeleter.java b/lucene/core/src/java/org/apache/lucene/index/IndexFileDeleter.java
index cf1a6f43787..762cbade111 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexFileDeleter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexFileDeleter.java
@@ -343,7 +343,7 @@ final class IndexFileDeleter implements Closeable {
}
}
- private void ensureOpen() throws AlreadyClosedException {
+ void ensureOpen() throws AlreadyClosedException {
writer.ensureOpen(false);
// since we allow 'closing' state, we must still check this, we could be closing because we hit e.g. OOM
if (writer.tragedy != null) {
@@ -351,6 +351,16 @@ final class IndexFileDeleter implements Closeable {
}
}
+ // for testing
+ boolean isClosed() {
+ try {
+ ensureOpen();
+ return false;
+ } catch (AlreadyClosedException ace) {
+ return true;
+ }
+ }
+
public SegmentInfos getLastSegmentInfos() {
return lastSegmentInfos;
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
index f0c910ac819..2e0b9374018 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriter.java
@@ -405,7 +405,7 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
synchronized (fullFlushLock) {
boolean success = false;
try {
- anySegmentFlushed = docWriter.flushAllThreads(this);
+ anySegmentFlushed = docWriter.flushAllThreads();
if (!anySegmentFlushed) {
// prevent double increment since docWriter#doFlush increments the flushcount
// if we flushed anything.
@@ -422,8 +422,8 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
infoStream.message("IW", "return reader version=" + r.getVersion() + " reader=" + r);
}
}
- } catch (OutOfMemoryError oom) {
- tragicEvent(oom, "getReader");
+ } catch (AbortingException | OutOfMemoryError tragedy) {
+ tragicEvent(tragedy, "getReader");
// never reached but javac disagrees:
return null;
} finally {
@@ -1231,8 +1231,8 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
}
}
}
- } catch (OutOfMemoryError oom) {
- tragicEvent(oom, "updateDocuments");
+ } catch (AbortingException | OutOfMemoryError tragedy) {
+ tragicEvent(tragedy, "updateDocuments");
}
}
@@ -1401,8 +1401,8 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
}
}
}
- } catch (OutOfMemoryError oom) {
- tragicEvent(oom, "updateDocument");
+ } catch (AbortingException | OutOfMemoryError tragedy) {
+ tragicEvent(tragedy, "updateDocument");
}
}
@@ -2723,7 +2723,7 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
boolean flushSuccess = false;
boolean success = false;
try {
- anySegmentsFlushed = docWriter.flushAllThreads(this);
+ anySegmentsFlushed = docWriter.flushAllThreads();
if (!anySegmentsFlushed) {
// prevent double increment since docWriter#doFlush increments the flushcount
// if we flushed anything.
@@ -2766,8 +2766,8 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
doAfterFlush();
}
}
- } catch (OutOfMemoryError oom) {
- tragicEvent(oom, "prepareCommit");
+ } catch (AbortingException | OutOfMemoryError tragedy) {
+ tragicEvent(tragedy, "prepareCommit");
}
boolean success = false;
@@ -3008,7 +3008,7 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
synchronized (fullFlushLock) {
boolean flushSuccess = false;
try {
- anySegmentFlushed = docWriter.flushAllThreads(this);
+ anySegmentFlushed = docWriter.flushAllThreads();
flushSuccess = true;
} finally {
docWriter.finishFullFlush(flushSuccess);
@@ -3025,8 +3025,8 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
success = true;
return anySegmentFlushed;
}
- } catch (OutOfMemoryError oom) {
- tragicEvent(oom, "doFlush");
+ } catch (AbortingException | OutOfMemoryError tragedy) {
+ tragicEvent(tragedy, "doFlush");
// never hit
return false;
} finally {
@@ -4381,19 +4381,28 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
public abstract void warm(LeafReader reader) throws IOException;
}
- private void tragicEvent(Throwable tragedy, String location) {
+ void tragicEvent(Throwable tragedy, String location) throws IOException {
+ // unbox our internal AbortingException
+ if (tragedy instanceof AbortingException) {
+ tragedy = tragedy.getCause();
+ }
// We cannot hold IW's lock here else it can lead to deadlock:
assert Thread.holdsLock(this) == false;
+ // How can it be a tragedy when nothing happened?
+ assert tragedy != null;
+
if (infoStream.isEnabled("IW")) {
- infoStream.message("IW", "hit " + tragedy.getClass().getSimpleName() + " inside " + location);
+ infoStream.message("IW", "hit tragic " + tragedy.getClass().getSimpleName() + " inside " + location);
}
+
synchronized (this) {
- // its possible you could have a really bad day
+ // it's possible you could have a really bad day
if (this.tragedy == null) {
this.tragedy = tragedy;
}
}
+
// if we are already closed (e.g. called by rollback), this will be a no-op.
synchronized(commitLock) {
if (closing == false) {
@@ -4405,7 +4414,8 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
}
}
}
- IOUtils.reThrowUnchecked(tragedy);
+
+ IOUtils.reThrow(tragedy);
}
// Used for testing. Current points:
@@ -4571,11 +4581,13 @@ public class IndexWriter implements Closeable, TwoPhaseCommit, Accountable {
}
private boolean processEvents(Queue<Event> queue, boolean triggerMerge, boolean forcePurge) throws IOException {
- Event event;
boolean processed = false;
- while((event = queue.poll()) != null) {
- processed = true;
- event.process(this, triggerMerge, forcePurge);
+ if (tragedy == null) {
+ Event event;
+ while((event = queue.poll()) != null) {
+ processed = true;
+ event.process(this, triggerMerge, forcePurge);
+ }
}
return processed;
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java b/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
index da4622632f3..c5be1de7d34 100644
--- a/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
+++ b/lucene/core/src/java/org/apache/lucene/index/IndexWriterConfig.java
@@ -142,6 +142,9 @@ public final class IndexWriterConfig extends LiveIndexWriterConfig {
* if this config is already attached to a writer.
*/
IndexWriterConfig setIndexWriter(IndexWriter writer) {
+ if (this.writer.get() != null) {
+ throw new IllegalStateException("do not share IndexWriterConfig instances across IndexWriters");
+ }
this.writer.set(writer);
return this;
}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingStoredFieldsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingStoredFieldsFormat.java
index e3e3c26b1dc..313dda9a45c 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingStoredFieldsFormat.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/compressing/TestCompressingStoredFieldsFormat.java
@@ -22,17 +22,17 @@ import java.io.IOException;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.IntField;
import org.apache.lucene.index.BaseStoredFieldsFormatTestCase;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.junit.Test;
-
import com.carrotsearch.randomizedtesting.generators.RandomInts;
public class TestCompressingStoredFieldsFormat extends BaseStoredFieldsFormatTestCase {
@@ -84,17 +84,7 @@ public class TestCompressingStoredFieldsFormat extends BaseStoredFieldsFormatTes
iw.commit();
}
finally {
- // next event will cause IW to delete the old files: we use prepareCommit just as example
- iw.prepareCommit();
- int counter = 0;
- for (String fileName : dir.listAll()) {
- if (fileName.endsWith(".fdt") || fileName.endsWith(".fdx")) {
- counter++;
- }
- }
- // Only one .fdt and one .fdx files must have been found
- assertEquals(2, counter);
- iw.rollback();
+ // Abort should have closed the deleter:
dir.close();
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java b/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java
index 700c50ff921..167c7cecfdc 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java
@@ -29,6 +29,7 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.LuceneTestCase;
@@ -81,14 +82,23 @@ public class TestConcurrentMergeScheduler extends LuceneTestCase {
MockDirectoryWrapper directory = newMockDirectory();
FailOnlyOnFlush failure = new FailOnlyOnFlush();
directory.failOn(failure);
-
- IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig(new MockAnalyzer(random()))
- .setMaxBufferedDocs(2));
+ IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()))
+ .setMaxBufferedDocs(2);
+ if (iwc.getMergeScheduler() instanceof ConcurrentMergeScheduler) {
+ iwc.setMergeScheduler(new SuppressingConcurrentMergeScheduler() {
+ @Override
+ protected boolean isOK(Throwable th) {
+ return th instanceof AlreadyClosedException ||
+ (th instanceof IllegalStateException && th.getMessage().contains("this writer hit an unrecoverable error"));
+ }
+ });
+ }
+ IndexWriter writer = new IndexWriter(directory, iwc);
Document doc = new Document();
Field idField = newStringField("id", "", Field.Store.YES);
doc.add(idField);
- int extraCount = 0;
+ outer:
for(int i=0;i<10;i++) {
if (VERBOSE) {
System.out.println("TEST: iter=" + i);
@@ -110,22 +120,20 @@ public class TestConcurrentMergeScheduler extends LuceneTestCase {
if (failure.hitExc) {
fail("failed to hit IOException");
}
- extraCount++;
} catch (IOException ioe) {
if (VERBOSE) {
ioe.printStackTrace(System.out);
}
failure.clearDoFail();
- break;
+ assertTrue(writer.isClosed());
+ // Abort should have closed the deleter:
+ assertTrue(writer.deleter.isClosed());
+ break outer;
}
}
- assertEquals(20*(i+1)+extraCount, writer.numDocs());
}
- writer.close();
- IndexReader reader = DirectoryReader.open(directory);
- assertEquals(200+extraCount, reader.numDocs());
- reader.close();
+ assertFalse(DirectoryReader.indexExists(directory));
directory.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
index f096ca65598..54da47c32a8 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriter.java
@@ -906,6 +906,15 @@ public class TestIndexWriter extends LuceneTestCase {
// LUCENE-2239: won't work with NIOFS/MMAP
adder = new MockDirectoryWrapper(random, new RAMDirectory());
IndexWriterConfig conf = newIndexWriterConfig(random, new MockAnalyzer(random));
+ if (conf.getMergeScheduler() instanceof ConcurrentMergeScheduler) {
+ conf.setMergeScheduler(new SuppressingConcurrentMergeScheduler() {
+ @Override
+ protected boolean isOK(Throwable th) {
+ return th instanceof AlreadyClosedException ||
+ (th instanceof IllegalStateException && th.getMessage().contains("this writer hit an unrecoverable error"));
+ }
+ });
+ }
IndexWriter w = new IndexWriter(adder, conf);
Document doc = new Document();
doc.add(newStringField(random, "id", "500", Field.Store.NO));
@@ -969,6 +978,15 @@ public class TestIndexWriter extends LuceneTestCase {
}
IndexWriterConfig conf = newIndexWriterConfig(random,
new MockAnalyzer(random)).setMaxBufferedDocs(2);
+ if (conf.getMergeScheduler() instanceof ConcurrentMergeScheduler) {
+ conf.setMergeScheduler(new SuppressingConcurrentMergeScheduler() {
+ @Override
+ protected boolean isOK(Throwable th) {
+ return th instanceof AlreadyClosedException ||
+ (th instanceof IllegalStateException && th.getMessage().contains("this writer hit an unrecoverable error"));
+ }
+ });
+ }
//conf.setInfoStream(log);
w = new IndexWriter(dir, conf);
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterAbort.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterAbort.java
deleted file mode 100644
index 572b7ebbf5e..00000000000
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterAbort.java
+++ /dev/null
@@ -1,203 +0,0 @@
-package org.apache.lucene.index;
-
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.Arrays;
-import java.util.Random;
-
-import org.apache.lucene.analysis.Analyzer;
-import org.apache.lucene.analysis.MockAnalyzer;
-import org.apache.lucene.codecs.Codec;
-import org.apache.lucene.codecs.cranky.CrankyCodec;
-import org.apache.lucene.document.BinaryDocValuesField;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field;
-import org.apache.lucene.document.FieldType;
-import org.apache.lucene.document.NumericDocValuesField;
-import org.apache.lucene.document.SortedDocValuesField;
-import org.apache.lucene.document.SortedNumericDocValuesField;
-import org.apache.lucene.document.SortedSetDocValuesField;
-import org.apache.lucene.document.StoredField;
-import org.apache.lucene.document.TextField;
-import org.apache.lucene.store.MockDirectoryWrapper;
-import org.apache.lucene.store.RAMDirectory;
-import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IOUtils;
-import org.apache.lucene.util.LuceneTestCase;
-import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
-import org.apache.lucene.util.TestUtil;
-import org.apache.lucene.util.Rethrow;
-
-/**
- * Creates aborting exceptions and checks that files are cleaned up
- */
-@SuppressCodecs("SimpleText")
-public class TestIndexWriterAbort extends LuceneTestCase {
-
- // just one thread, serial merge policy, hopefully debuggable
- public void testBasics() throws Exception {
- // use an explicit RAMDirectory, we will act-like windows,
- // but no virus scanner (real or fake).
- // TODO: use MDW's check instead of TestIW.assertNoUnreferencedFiles,
- // then turn it all back on
-
- MockDirectoryWrapper dir = new MockDirectoryWrapper(random(), new RAMDirectory());
- dir.setEnableVirusScanner(false); // assert that we actually delete files.
-
- // log all exceptions we hit, in case we fail (for debugging)
- ByteArrayOutputStream exceptionLog = new ByteArrayOutputStream();
- PrintStream exceptionStream = new PrintStream(exceptionLog, true, "UTF-8");
- //PrintStream exceptionStream = System.out;
-
- Analyzer analyzer = new MockAnalyzer(random());
-
- // wrap the actual codec with one that throws random exceptions
- Codec codec = new CrankyCodec(Codec.getDefault(), new Random(random().nextLong()));
-
- IndexWriterConfig conf = newIndexWriterConfig(analyzer);
- // just for now, try to keep this test reproducible
- conf.setMergeScheduler(new SerialMergeScheduler());
- conf.setCodec(codec);
-
- int numDocs = atLeast(500);
-
- IndexWriter iw = new IndexWriter(dir, conf);
- try {
- for (int i = 0; i < numDocs; i++) {
- Document doc = new Document();
- doc.add(newStringField("id", Integer.toString(i), Field.Store.NO));
- doc.add(new NumericDocValuesField("dv", i));
- doc.add(new BinaryDocValuesField("dv2", new BytesRef(Integer.toString(i))));
- doc.add(new SortedDocValuesField("dv3", new BytesRef(Integer.toString(i))));
- doc.add(new SortedSetDocValuesField("dv4", new BytesRef(Integer.toString(i))));
- doc.add(new SortedSetDocValuesField("dv4", new BytesRef(Integer.toString(i-1))));
- doc.add(new SortedNumericDocValuesField("dv5", i));
- doc.add(new SortedNumericDocValuesField("dv5", i-1));
- doc.add(newTextField("text1", TestUtil.randomAnalysisString(random(), 20, true), Field.Store.NO));
- // ensure we store something
- doc.add(new StoredField("stored1", "foo"));
- doc.add(new StoredField("stored1", "bar"));
- // ensure we get some payloads
- doc.add(newTextField("text_payloads", TestUtil.randomAnalysisString(random(), 6, true), Field.Store.NO));
- // ensure we get some vectors
- FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
- ft.setStoreTermVectors(true);
- doc.add(newField("text_vectors", TestUtil.randomAnalysisString(random(), 6, true), ft));
-
- if (random().nextInt(10) > 0) {
- // single doc
- try {
- iw.addDocument(doc);
- // we made it, sometimes delete our doc, or update a dv
- int thingToDo = random().nextInt(4);
- if (thingToDo == 0) {
- iw.deleteDocuments(new Term("id", Integer.toString(i)));
- } else if (thingToDo == 1) {
- iw.updateNumericDocValue(new Term("id", Integer.toString(i)), "dv", i+1L);
- } else if (thingToDo == 2) {
- iw.updateBinaryDocValue(new Term("id", Integer.toString(i)), "dv2", new BytesRef(Integer.toString(i+1)));
- }
- } catch (Exception e) {
- if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
- exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
- e.printStackTrace(exceptionStream);
- } else {
- Rethrow.rethrow(e);
- }
- }
- } else {
- // block docs
- Document doc2 = new Document();
- doc2.add(newStringField("id", Integer.toString(-i), Field.Store.NO));
- doc2.add(newTextField("text1", TestUtil.randomAnalysisString(random(), 20, true), Field.Store.NO));
- doc2.add(new StoredField("stored1", "foo"));
- doc2.add(new StoredField("stored1", "bar"));
- doc2.add(newField("text_vectors", TestUtil.randomAnalysisString(random(), 6, true), ft));
-
- try {
- iw.addDocuments(Arrays.asList(doc, doc2));
- // we made it, sometimes delete our docs
- if (random().nextBoolean()) {
- iw.deleteDocuments(new Term("id", Integer.toString(i)), new Term("id", Integer.toString(-i)));
- }
- } catch (Exception e) {
- if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
- exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
- e.printStackTrace(exceptionStream);
- } else {
- Rethrow.rethrow(e);
- }
- }
- }
-
- if (random().nextInt(10) == 0) {
- // trigger flush:
- try {
- if (random().nextBoolean()) {
- DirectoryReader ir = null;
- try {
- ir = DirectoryReader.open(iw, random().nextBoolean());
- } finally {
- IOUtils.closeWhileHandlingException(ir);
- }
- } else {
- iw.commit();
- }
- } catch (Exception e) {
- if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
- exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
- e.printStackTrace(exceptionStream);
- } else {
- Rethrow.rethrow(e);
- }
- }
- }
- }
-
- try {
- iw.close();
- } catch (Exception e) {
- if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
- exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
- e.printStackTrace(exceptionStream);
- } else {
- Rethrow.rethrow(e);
- }
- }
-
- // test that there are no unreferenced files: any deletes we make should have succeeded
- // TODO: don't use this method, use the MDW one!!!!
- TestIndexWriter.assertNoUnreferencedFiles(dir, "unreferenced files remain after close()");
- // checkindex
- dir.close();
- } catch (Throwable t) {
- System.out.println("Unexpected exception: dumping fake-exception-log:...");
- exceptionStream.flush();
- System.out.println(exceptionLog.toString("UTF-8"));
- System.out.flush();
- Rethrow.rethrow(t);
- }
-
- if (VERBOSE) {
- System.out.println("TEST PASSED: dumping fake-exception-log:...");
- System.out.println(exceptionLog.toString("UTF-8"));
- }
- }
-}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java
index a2125ab5f07..f961b4c82dd 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterConfig.java
@@ -147,7 +147,7 @@ public class TestIndexWriterConfig extends LuceneTestCase {
try {
assertNotNull(new RandomIndexWriter(random(), dir, conf));
fail("should have hit AlreadySetException");
- } catch (AlreadySetException e) {
+ } catch (IllegalStateException ise) {
// expected
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
index 5dd9578c344..f05037103fb 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterDelete.java
@@ -632,11 +632,9 @@ public class TestIndexWriterDelete extends LuceneTestCase {
modifier.rollback();
}
- // If the close() succeeded, make sure there are
- // no unreferenced files.
+ // If the close() succeeded, make sure index is OK:
if (success) {
TestUtil.checkIndex(dir);
- TestIndexWriter.assertNoUnreferencedFiles(dir, "after writer.close");
}
dir.setRandomIOExceptionRate(randomIOExceptionRate);
dir.setMaxSizeInBytes(maxSizeInBytes);
@@ -922,8 +920,8 @@ public class TestIndexWriterDelete extends LuceneTestCase {
break;
}
}
+ assertTrue(modifier.deleter.isClosed());
- modifier.close();
TestIndexWriter.assertNoUnreferencedFiles(dir, "docsWriter.abort() failed to delete unreferenced files");
dir.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
index 950fabb10ac..4d73c823edf 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions.java
@@ -575,8 +575,7 @@ public class TestIndexWriterExceptions extends LuceneTestCase {
}
}
- // LUCENE-1072: make sure an errant exception on flushing
- // one segment only takes out those docs in that one flush
+ // make sure an aborting exception closes the writer:
public void testDocumentsWriterAbort() throws IOException {
MockDirectoryWrapper dir = newMockDirectory();
FailOnlyOnFlush failure = new FailOnlyOnFlush();
@@ -589,20 +588,18 @@ public class TestIndexWriterExceptions extends LuceneTestCase {
String contents = "aa bb cc dd ee ff gg hh ii jj kk";
doc.add(newTextField("content", contents, Field.Store.NO));
boolean hitError = false;
- for(int i=0;i<200;i++) {
- try {
- writer.addDocument(doc);
- } catch (IOException ioe) {
- // only one flush should fail:
- assertFalse(hitError);
- hitError = true;
- }
+ writer.addDocument(doc);
+ try {
+ writer.addDocument(doc);
+ fail("did not hit exception");
+ } catch (IOException ioe) {
+ // only one flush should fail:
+ assertFalse(hitError);
+ hitError = true;
+ assertTrue(writer.deleter.isClosed());
+ assertTrue(writer.isClosed());
}
- assertTrue(hitError);
- writer.close();
- IndexReader reader = DirectoryReader.open(dir);
- assertEquals(198, reader.docFreq(new Term("content", "aa")));
- reader.close();
+ assertFalse(DirectoryReader.indexExists(dir));
dir.close();
}
@@ -1265,6 +1262,7 @@ public class TestIndexWriterExceptions extends LuceneTestCase {
new FailOnTermVectors(FailOnTermVectors.AFTER_INIT_STAGE),
new FailOnTermVectors(FailOnTermVectors.INIT_STAGE), };
int num = atLeast(1);
+ iters:
for (int j = 0; j < num; j++) {
for (FailOnTermVectors failure : failures) {
MockDirectoryWrapper dir = newMockDirectory();
@@ -1273,14 +1271,19 @@ public class TestIndexWriterExceptions extends LuceneTestCase {
int numDocs = 10 + random().nextInt(30);
for (int i = 0; i < numDocs; i++) {
Document doc = new Document();
+ // random TV
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));
+ // This is an aborting exception, so writer is closed:
+ assertTrue(w.deleter.isClosed());
+ assertTrue(w.isClosed());
+ dir.close();
+ continue iters;
}
if (random().nextInt(20) == 0) {
w.commit();
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
index d71e6541554..58e3ac78c94 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterExceptions2.java
@@ -40,14 +40,15 @@ import org.apache.lucene.document.SortedNumericDocValuesField;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.TextField;
+import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
import org.apache.lucene.util.LuceneTestCase;
-import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.Rethrow;
-import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
+import org.apache.lucene.util.TestUtil;
/**
* Causes a bunch of non-aborting and aborting exceptions and checks that
@@ -63,6 +64,7 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
if (dir instanceof MockDirectoryWrapper) {
((MockDirectoryWrapper)dir).setThrottling(MockDirectoryWrapper.Throttling.NEVER);
((MockDirectoryWrapper)dir).setUseSlowOpenClosers(false);
+ ((MockDirectoryWrapper)dir).setPreventDoubleWrite(false);
}
// log all exceptions we hit, in case we fail (for debugging)
@@ -96,11 +98,12 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
// just for now, try to keep this test reproducible
conf.setMergeScheduler(new SerialMergeScheduler());
conf.setCodec(codec);
-
+
int numDocs = atLeast(500);
IndexWriter iw = new IndexWriter(dir, conf);
try {
+ boolean allowAlreadyClosed = false;
for (int i = 0; i < numDocs; i++) {
// TODO: add crankyDocValuesFields, etc
Document doc = new Document();
@@ -136,10 +139,21 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
} else if (thingToDo == 2) {
iw.updateBinaryDocValue(new Term("id", Integer.toString(i)), "dv2", new BytesRef(Integer.toString(i+1)));
}
+ } catch (AlreadyClosedException ace) {
+ // OK: writer was closed by abort; we just reopen now:
+ assertTrue(iw.deleter.isClosed());
+ assertTrue(allowAlreadyClosed);
+ allowAlreadyClosed = false;
+ conf = newIndexWriterConfig(analyzer);
+ // just for now, try to keep this test reproducible
+ conf.setMergeScheduler(new SerialMergeScheduler());
+ conf.setCodec(codec);
+ iw = new IndexWriter(dir, conf);
} catch (Exception e) {
if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
e.printStackTrace(exceptionStream);
+ allowAlreadyClosed = true;
} else {
Rethrow.rethrow(e);
}
@@ -159,10 +173,21 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
if (random().nextBoolean()) {
iw.deleteDocuments(new Term("id", Integer.toString(i)), new Term("id", Integer.toString(-i)));
}
+ } catch (AlreadyClosedException ace) {
+ // OK: writer was closed by abort; we just reopen now:
+ assertTrue(iw.deleter.isClosed());
+ assertTrue(allowAlreadyClosed);
+ allowAlreadyClosed = false;
+ conf = newIndexWriterConfig(analyzer);
+ // just for now, try to keep this test reproducible
+ conf.setMergeScheduler(new SerialMergeScheduler());
+ conf.setCodec(codec);
+ iw = new IndexWriter(dir, conf);
} catch (Exception e) {
if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
e.printStackTrace(exceptionStream);
+ allowAlreadyClosed = true;
} else {
Rethrow.rethrow(e);
}
@@ -186,10 +211,21 @@ public class TestIndexWriterExceptions2 extends LuceneTestCase {
if (DirectoryReader.indexExists(dir)) {
TestUtil.checkIndex(dir);
}
+ } catch (AlreadyClosedException ace) {
+ // OK: writer was closed by abort; we just reopen now:
+ assertTrue(iw.deleter.isClosed());
+ assertTrue(allowAlreadyClosed);
+ allowAlreadyClosed = false;
+ conf = newIndexWriterConfig(analyzer);
+ // just for now, try to keep this test reproducible
+ conf.setMergeScheduler(new SerialMergeScheduler());
+ conf.setCodec(codec);
+ iw = new IndexWriter(dir, conf);
} catch (Exception e) {
if (e.getMessage() != null && e.getMessage().startsWith("Fake IOException")) {
exceptionStream.println("\nTEST: got expected fake exc:" + e.getMessage());
e.printStackTrace(exceptionStream);
+ allowAlreadyClosed = true;
} else {
Rethrow.rethrow(e);
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java
index 5cd69bdebf9..0da99e0259b 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterOnDiskFull.java
@@ -57,6 +57,7 @@ public class TestIndexWriterOnDiskFull extends LuceneTestCase {
}
boolean doAbort = pass == 1;
long diskFree = TestUtil.nextInt(random(), 100, 300);
+ boolean indexExists = false;
while(true) {
if (VERBOSE) {
System.out.println("TEST: cycle: diskFree=" + diskFree);
@@ -82,6 +83,7 @@ public class TestIndexWriterOnDiskFull extends LuceneTestCase {
System.out.println("TEST: done adding docs; now commit");
}
writer.commit();
+ indexExists = true;
} catch (IOException e) {
if (VERBOSE) {
System.out.println("TEST: exception on addDoc");
@@ -118,9 +120,7 @@ public class TestIndexWriterOnDiskFull extends LuceneTestCase {
//_TestUtil.syncConcurrentMerges(ms);
- if (TestUtil.anyFilesExceptWriteLock(dir)) {
- assertNoUnreferencedFiles(dir, "after disk full during addDocument");
-
+ if (indexExists) {
// Make sure reader can open the index:
DirectoryReader.open(dir).close();
}
@@ -548,25 +548,9 @@ public class TestIndexWriterOnDiskFull extends LuceneTestCase {
writer.addDocument(doc);
fail("did not hit disk full");
} catch (IOException ioe) {
+ assertTrue(writer.deleter.isClosed());
+ assertTrue(writer.isClosed());
}
- // Without fix for LUCENE-1130: this call will hang:
- try {
- writer.addDocument(doc);
- fail("did not hit disk full");
- } catch (IOException ioe) {
- }
- try {
- writer.commit();
- fail("did not hit disk full");
- } catch (IOException ioe) {
- } finally {
- writer.close();
- }
-
- // Make sure once disk space is avail again, we can
- // cleanly close:
- dir.setMaxSizeInBytes(0);
- writer.close();
dir.close();
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java
index f26784bd111..4a760e7bbd8 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterWithThreads.java
@@ -110,6 +110,9 @@ public class TestIndexWriterWithThreads extends LuceneTestCase {
}
break;
}
+ } catch (AlreadyClosedException ace) {
+ // OK: abort closes the writer
+ break;
} catch (Throwable t) {
//t.printStackTrace(System.out);
if (noErrors) {
@@ -166,6 +169,9 @@ public class TestIndexWriterWithThreads extends LuceneTestCase {
dir.setMaxSizeInBytes(0);
try {
writer.commit();
+ } catch (AlreadyClosedException ace) {
+ // OK: abort closes the writer
+ assertTrue(writer.deleter.isClosed());
} finally {
writer.close();
}
@@ -300,6 +306,9 @@ public class TestIndexWriterWithThreads extends LuceneTestCase {
writer.commit();
writer.close();
success = true;
+ } catch (AlreadyClosedException ace) {
+ // OK: abort closes the writer
+ assertTrue(writer.deleter.isClosed());
} catch (IOException ioe) {
writer.rollback();
failure.clearDoFail();
@@ -329,10 +338,22 @@ public class TestIndexWriterWithThreads extends LuceneTestCase {
public void _testSingleThreadFailure(MockDirectoryWrapper.Failure failure) throws IOException {
MockDirectoryWrapper dir = newMockDirectory();
- IndexWriter writer = new IndexWriter(dir, newIndexWriterConfig(new MockAnalyzer(random()))
- .setMaxBufferedDocs(2)
- .setMergeScheduler(new ConcurrentMergeScheduler())
- .setCommitOnClose(false));
+ IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()))
+ .setMaxBufferedDocs(2)
+ .setMergeScheduler(new ConcurrentMergeScheduler())
+ .setCommitOnClose(false);
+
+ if (iwc.getMergeScheduler() instanceof ConcurrentMergeScheduler) {
+ iwc.setMergeScheduler(new SuppressingConcurrentMergeScheduler() {
+ @Override
+ protected boolean isOK(Throwable th) {
+ return th instanceof AlreadyClosedException ||
+ (th instanceof IllegalStateException && th.getMessage().contains("this writer hit an unrecoverable error"));
+ }
+ });
+ }
+
+ IndexWriter writer = new IndexWriter(dir, iwc);
final Document doc = new Document();
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.setStoreTermVectors(true);
@@ -353,11 +374,13 @@ public class TestIndexWriterWithThreads extends LuceneTestCase {
} catch (IOException ioe) {
}
failure.clearDoFail();
- writer.addDocument(doc);
try {
+ writer.addDocument(doc);
writer.commit();
- } finally {
writer.close();
+ } catch (AlreadyClosedException ace) {
+ // OK: abort closes the writer
+ assertTrue(writer.deleter.isClosed());
}
dir.close();
}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java b/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java
index 087b9014e7a..f688ba6b0fc 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/codecs/idversion/TestIDVersionPostingsFormat.java
@@ -52,6 +52,7 @@ import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.LiveFieldValues;
import org.apache.lucene.search.SearcherFactory;
import org.apache.lucene.search.SearcherManager;
+import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
@@ -597,8 +598,21 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {
} catch (IllegalArgumentException iae) {
// expected
}
+ try {
+ w.addDocument(doc);
+ fail("should have hit exc");
+ } catch (AlreadyClosedException ace) {
+ // expected
+ }
+ dir.close();
+ }
- doc = new Document();
+ public void testInvalidVersions2() throws IOException {
+ Directory dir = newDirectory();
+ IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));
+ iwc.setCodec(TestUtil.alwaysPostingsFormat(new IDVersionPostingsFormat()));
+ RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
+ Document doc = new Document();
// Long.MAX_VALUE:
doc.add(new StringAndPayloadField("id", "id", new BytesRef(new byte[] {(byte)0x7f, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff, (byte)0xff})));
try {
@@ -608,7 +622,12 @@ public class TestIDVersionPostingsFormat extends LuceneTestCase {
} catch (IllegalArgumentException iae) {
// expected
}
- w.close();
+ try {
+ w.addDocument(doc);
+ fail("should have hit exc");
+ } catch (AlreadyClosedException ace) {
+ // expected
+ }
dir.close();
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/index/SuppressingConcurrentMergeScheduler.java b/lucene/test-framework/src/java/org/apache/lucene/index/SuppressingConcurrentMergeScheduler.java
new file mode 100644
index 00000000000..004db286a8c
--- /dev/null
+++ b/lucene/test-framework/src/java/org/apache/lucene/index/SuppressingConcurrentMergeScheduler.java
@@ -0,0 +1,41 @@
+package org.apache.lucene.index;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.io.IOException;
+
+import org.apache.lucene.store.AlreadyClosedException;
+import org.apache.lucene.util.IOUtils;
+
+/** A {@link ConcurrentMergeScheduler} that ignores AlreadyClosedException. */
+public abstract class SuppressingConcurrentMergeScheduler extends ConcurrentMergeScheduler {
+ @Override
+ protected void handleMergeException(Throwable exc) {
+ while (true) {
+ if (isOK(exc)) {
+ return;
+ }
+ exc = exc.getCause();
+ if (exc == null) {
+ super.handleMergeException(exc);
+ }
+ }
+ }
+
+ protected abstract boolean isOK(Throwable t);
+}