You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tika.apache.org by ta...@apache.org on 2025/12/09 12:38:16 UTC
(tika) branch main updated: TIKA-4556 (#2425)
This is an automated email from the ASF dual-hosted git repository.
tallison pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tika.git
The following commit(s) were added to refs/heads/main by this push:
new 2df306988 TIKA-4556 (#2425)
2df306988 is described below
commit 2df306988b451d1efbfbdb44f012812ede4128f6
Author: Tim Allison <ta...@apache.org>
AuthorDate: Tue Dec 9 07:38:11 2025 -0500
TIKA-4556 (#2425)
* TIKA-4556 -- refactor client/server protocol in tika-pipes
---
.../test/resources/configs/config-template.json | 3 +-
.../apache/tika/pipes/grpc/TikaGrpcServerImpl.java | 2 +-
.../apache/tika/pipes/grpc/TikaGrpcServerTest.java | 2 +-
.../src/test/resources/tika-pipes-test-config.xml | 2 +-
.../src/test/resources/kafka/plugins-template.json | 3 +-
.../src/test/resources/tika-config-kafka.xml | 2 +-
.../resources/opensearch/plugins-template.json | 3 +-
.../opensearch/tika-config-opensearch.json | 4 +-
.../src/test/resources/s3/plugins-template.json | 3 +-
.../resources/tika-config-s3-integration-test.xml | 2 +-
.../src/test/resources/solr/plugins-template.json | 3 +-
.../src/test/resources/tika-config-solr-urls.json | 3 +-
.../src/test/resources/tika-config-solr-urls.xml | 2 +-
.../org/apache/tika/async/cli/PluginsWriter.java | 1 -
.../tika/async/cli/TikaConfigAsyncWriterTest.java | 2 +-
.../test/resources/configs/config-template.json | 3 +-
.../org/apache/tika/pipes/api/PipesResult.java | 198 ++++-
.../org/apache/tika/pipes/core/PipesClient.java | 727 +++++++--------
.../org/apache/tika/pipes/core/PipesConfig.java | 90 +-
.../org/apache/tika/pipes/core/PipesResults.java | 14 +-
.../org/apache/tika/pipes/core/PipesServer.java | 971 ---------------------
...ion.java => ServerInitializationException.java} | 15 +-
.../tika/pipes/core/async/AsyncProcessor.java | 12 +-
.../apache/tika/pipes/core/server/EmitHandler.java | 217 +++++
.../tika/pipes/core/server/FetchHandler.java | 101 +++
.../IntermediateResult.java} | 21 +-
.../core/server/MetadataListAndEmbeddedBytes.java | 76 ++
.../tika/pipes/core/server/ParseHandler.java | 229 +++++
.../apache/tika/pipes/core/server/PipesServer.java | 526 +++++++++++
.../apache/tika/pipes/core/server/PipesWorker.java | 192 ++++
.../test/resources/configs/TIKA-3865-params.xml | 2 +-
.../apache/tika/pipes/core/CrashingDetector.java} | 18 +-
.../apache/tika/pipes/core/PassbackFilterTest.java | 4 +-
.../apache/tika/pipes/core/PipesClientTest.java | 443 +++++++++-
.../apache/tika/pipes/core/PipesServerTest.java | 37 +-
.../apache/tika/pipes/core/PluginsTestHelper.java | 1 -
.../pipes/core/async/AsyncChaosMonkeyTest.java | 52 +-
.../resources/configs/tika-config-bad-class.json | 16 +
.../configs/tika-config-bad-java-path.json | 17 +
.../configs/tika-config-bad-jvm-args.json | 16 +
.../test/resources/configs/tika-config-basic.json | 3 +-
.../configs/tika-config-crashing-detector.json | 29 +
.../resources/configs/tika-config-emit-all.json | 26 +
.../resources/configs/tika-config-passback.json | 3 +-
.../configs/tika-config-timeout-lt-heartbeat.json | 27 +
.../resources/configs/tika-config-truncate.json | 3 +-
.../tika/pipes/emitter/fs/FileSystemEmitter.java | 21 +-
.../apache/tika/pipes/reporter/fs/AsyncStatus.java | 6 +-
.../reporter/fs/FileSystemStatusReporter.java | 4 +-
.../reporter/fs/TestFileSystemStatusReporter.java | 26 +-
.../pipes/reporter/jdbc/JDBCPipesReporter.java | 4 +-
.../pipes/reporter/jdbc/TestJDBCPipesReporter.java | 50 +-
.../tika/pipes/reporters/PipesReporterBase.java | 22 +-
.../apache/tika/config/loader/DetectorLoader.java | 18 +-
.../tika/config/loader/EncodingDetectorLoader.java | 37 +-
.../apache/tika/config/loader/ParserLoader.java | 40 +-
.../tika/server/core/resource/PipesResource.java | 56 +-
.../core/TikaServerPipesIntegrationTest.java | 18 +-
.../resources/configs/cxf-test-base-template.json | 3 +-
.../resources/configs/cxf-test-base-template.json | 3 +-
60 files changed, 2835 insertions(+), 1599 deletions(-)
diff --git a/tika-app/src/test/resources/configs/config-template.json b/tika-app/src/test/resources/configs/config-template.json
index 4039a1628..783012094 100644
--- a/tika-app/src/test/resources/configs/config-template.json
+++ b/tika-app/src/test/resources/configs/config-template.json
@@ -43,7 +43,7 @@
"queueSize": 10000,
"numEmitters": 1,
"emitIntermediateResults": false,
- "maxForEmitBatchBytes": 100000,
+ "directEmitThresholdBytes": 100000,
"timeoutMillis": 60000,
"startupTimeoutMillis": 240000,
"sleepOnStartupTimeoutMillis": 240000,
@@ -53,7 +53,6 @@
"staleFetcherTimeoutSeconds": 600,
"staleFetcherDelaySeconds": 60,
"forkedJvmArgs": ["-Xmx1g", "-XX:+UseG1GC"],
- "tikaConfig": "TIKA_CONFIG",
"javaPath": "java"
},
"plugin-roots": "PLUGIN_ROOTS"
diff --git a/tika-grpc/src/main/java/org/apache/tika/pipes/grpc/TikaGrpcServerImpl.java b/tika-grpc/src/main/java/org/apache/tika/pipes/grpc/TikaGrpcServerImpl.java
index cfea3203c..f5f1eb1f2 100644
--- a/tika-grpc/src/main/java/org/apache/tika/pipes/grpc/TikaGrpcServerImpl.java
+++ b/tika-grpc/src/main/java/org/apache/tika/pipes/grpc/TikaGrpcServerImpl.java
@@ -244,7 +244,7 @@ class TikaGrpcServerImpl extends TikaGrpc.TikaImplBase {
FetchAndParseReply.newBuilder()
.setFetchKey(request.getFetchKey())
.setStatus(pipesResult.status().name());
- if (pipesResult.status().equals(PipesResult.STATUS.FETCH_EXCEPTION)) {
+ if (pipesResult.status().equals(PipesResult.RESULT_STATUS.FETCH_EXCEPTION)) {
fetchReplyBuilder.setErrorMessage(pipesResult.message());
}
if (pipesResult.emitData() != null && pipesResult.emitData().getMetadataList() != null) {
diff --git a/tika-grpc/src/test/java/org/apache/tika/pipes/grpc/TikaGrpcServerTest.java b/tika-grpc/src/test/java/org/apache/tika/pipes/grpc/TikaGrpcServerTest.java
index 809de1d0e..d09864ca6 100644
--- a/tika-grpc/src/test/java/org/apache/tika/pipes/grpc/TikaGrpcServerTest.java
+++ b/tika-grpc/src/test/java/org/apache/tika/pipes/grpc/TikaGrpcServerTest.java
@@ -236,7 +236,7 @@ public class TikaGrpcServerTest {
@Override
public void onNext(FetchAndParseReply fetchAndParseReply) {
LOG.debug("Fetched {} with metadata {}", fetchAndParseReply.getFetchKey(), fetchAndParseReply.getFieldsMap());
- if (PipesResult.STATUS.FETCH_EXCEPTION.name().equals(fetchAndParseReply.getStatus())) {
+ if (PipesResult.RESULT_STATUS.FETCH_EXCEPTION.name().equals(fetchAndParseReply.getStatus())) {
errors.add(fetchAndParseReply);
} else {
successes.add(fetchAndParseReply);
diff --git a/tika-grpc/src/test/resources/tika-pipes-test-config.xml b/tika-grpc/src/test/resources/tika-pipes-test-config.xml
index e4006edb3..d796a05a0 100644
--- a/tika-grpc/src/test/resources/tika-pipes-test-config.xml
+++ b/tika-grpc/src/test/resources/tika-pipes-test-config.xml
@@ -27,7 +27,7 @@
<arg>-XX:ParallelGCThreads=2</arg>
</forkedJvmArgs>
<timeoutMillis>60000</timeoutMillis>
- <maxForEmitBatchBytes>-1</maxForEmitBatchBytes> <!-- disable emit -->
+ <directEmitThresholdBytes>-1</directEmitThresholdBytes> <!-- disable emit -->
</params>
</pipes>
<fetchers>
diff --git a/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/kafka/plugins-template.json b/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/kafka/plugins-template.json
index 79a47981c..5cf6b03d1 100644
--- a/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/kafka/plugins-template.json
+++ b/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/kafka/plugins-template.json
@@ -94,12 +94,11 @@
}
},
"pipes": {
- "maxForEmitBatchBytes": 10000,
+ "directEmitThresholdBytes": 10000,
"emitMaxEstimatedBytes": 100000,
"emitWithinMillis": 10,
"numEmitters": 1,
"numClients": 1,
- "tikaConfig": "TIKA_CONFIG",
"forkedJvmArgs": [
"-Xmx1g",
"-XX:ParallelGCThreads=2",
diff --git a/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/tika-config-kafka.xml b/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/tika-config-kafka.xml
index 5e655a6b8..8471ea5e5 100644
--- a/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/tika-config-kafka.xml
+++ b/tika-integration-tests/tika-pipes-kafka-integration-tests/src/test/resources/tika-config-kafka.xml
@@ -66,7 +66,7 @@
</metadataFilters>
<async>
<params>
- <maxForEmitBatchBytes>10000</maxForEmitBatchBytes>
+ <directEmitThresholdBytes>10000</directEmitThresholdBytes>
<emitMaxEstimatedBytes>100000</emitMaxEstimatedBytes>
<emitWithinMillis>10</emitWithinMillis>
<numEmitters>1</numEmitters>
diff --git a/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/plugins-template.json b/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/plugins-template.json
index c301f3226..781e2cfa8 100644
--- a/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/plugins-template.json
+++ b/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/plugins-template.json
@@ -60,12 +60,11 @@
}
},
"pipes": {
- "maxForEmitBatchBytes": 10000,
+ "directEmitThresholdBytes": 10000,
"emitMaxEstimatedBytes": 100000,
"emitWithinMillis": 60000,
"numEmitters": 1,
"numClients": 3,
- "tikaConfig": "TIKA_CONFIG",
"forkedJvmArgs": [
"-Xmx512m",
"-XX:ParallelGCThreads=2",
diff --git a/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/tika-config-opensearch.json b/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/tika-config-opensearch.json
index d304e3c9b..b15e7c437 100644
--- a/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/tika-config-opensearch.json
+++ b/tika-integration-tests/tika-pipes-opensearch-integration-tests/src/test/resources/opensearch/tika-config-opensearch.json
@@ -101,13 +101,11 @@
}
},
"pipes": {
- "maxForEmitBatchBytes": 10000,
+ "directEmitThresholdBytes": 10000,
"emitMaxEstimatedBytes": 100000,
"emitWithinMillis": 60000,
"numEmitters": 1,
"numClients": 3,
- "tikaConfig": "TIKA_CONFIG",
- "pipesPluginsConfig": "PLUGINS_CONFIG",
"forkedJvmArgs": [
"-Xmx512m",
"-XX:ParallelGCThreads=2",
diff --git a/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/s3/plugins-template.json b/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/s3/plugins-template.json
index 52f9c7ab1..1415f1876 100644
--- a/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/s3/plugins-template.json
+++ b/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/s3/plugins-template.json
@@ -56,12 +56,11 @@
}
},
"pipes": {
- "maxForEmitBatchBytes": 10000,
+ "directEmitThresholdBytes": 10000,
"emitMaxEstimatedBytes": 100000,
"emitWithinMillis": 10,
"numEmitters": 1,
"numClients": 1,
- "tikaConfig": "{TIKA_CONFIG}",
"forkedJvmArgs": [
"-Xmx1g",
"-XX:ParallelGCThreads=2",
diff --git a/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/tika-config-s3-integration-test.xml b/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/tika-config-s3-integration-test.xml
index 9c2ea8e54..1ac0e28c4 100644
--- a/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/tika-config-s3-integration-test.xml
+++ b/tika-integration-tests/tika-pipes-s3-integration-tests/src/test/resources/tika-config-s3-integration-test.xml
@@ -63,7 +63,7 @@
</metadataFilter>
</metadataFilters>
<async>
- <maxForEmitBatchBytes>10000</maxForEmitBatchBytes>
+ <directEmitThresholdBytes>10000</directEmitThresholdBytes>
<emitMaxEstimatedBytes>100000</emitMaxEstimatedBytes>
<emitWithinMillis>10</emitWithinMillis>
<numEmitters>1</numEmitters>
diff --git a/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/solr/plugins-template.json b/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/solr/plugins-template.json
index 1588f4f7a..94f1ec99b 100644
--- a/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/solr/plugins-template.json
+++ b/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/solr/plugins-template.json
@@ -91,12 +91,11 @@
}
},
"pipes": {
- "maxForEmitBatchBytes": 10000,
+ "directEmitThresholdBytes": 10000,
"emitMaxEstimatedBytes": 100000,
"emitWithinMillis": 10,
"numEmitters": 1,
"numClients": 1,
- "tikaConfig": "TIKA_CONFIG",
"forkedJvmArgs": [
"-Xmx1g",
"-XX:ParallelGCThreads=2",
diff --git a/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.json b/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.json
index baee81c2b..134f77962 100644
--- a/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.json
+++ b/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.json
@@ -41,12 +41,11 @@
}
],
"pipes": {
- "maxForEmitBatchBytes": 10000,
+ "directEmitThresholdBytes": 10000,
"emitMaxEstimatedBytes": 100000,
"emitWithinMillis": 10,
"numEmitters": 1,
"numClients": 1,
- "tikaConfig": "{TIKA_CONFIG}",
"forkedJvmArgs": [
"-Xmx1g",
"-XX:ParallelGCThreads=2",
diff --git a/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.xml b/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.xml
index 3423de325..7b4acb036 100644
--- a/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.xml
+++ b/tika-integration-tests/tika-pipes-solr-integration-tests/src/test/resources/tika-config-solr-urls.xml
@@ -63,7 +63,7 @@
</metadataFilter>
</metadataFilters>
<async>
- <maxForEmitBatchBytes>10000</maxForEmitBatchBytes>
+ <directEmitThresholdBytes>10000</directEmitThresholdBytes>
<emitMaxEstimatedBytes>100000</emitMaxEstimatedBytes>
<emitWithinMillis>10</emitWithinMillis>
<numEmitters>1</numEmitters>
diff --git a/tika-pipes/tika-async-cli/src/main/java/org/apache/tika/async/cli/PluginsWriter.java b/tika-pipes/tika-async-cli/src/main/java/org/apache/tika/async/cli/PluginsWriter.java
index 5c863c491..3093b59b6 100644
--- a/tika-pipes/tika-async-cli/src/main/java/org/apache/tika/async/cli/PluginsWriter.java
+++ b/tika-pipes/tika-async-cli/src/main/java/org/apache/tika/async/cli/PluginsWriter.java
@@ -64,7 +64,6 @@ public class PluginsWriter {
PipesConfig pipesConfig = new PipesConfig();
pipesConfig.setNumClients(simpleAsyncConfig.getNumClients() == null ? 2 : simpleAsyncConfig.getNumClients());
- pipesConfig.setTikaConfig(output.toAbsolutePath().toString());
if (simpleAsyncConfig.getXmx() != null) {
pipesConfig.setForkedJvmArgs(new ArrayList<>(List.of(simpleAsyncConfig.getXmx())));
diff --git a/tika-pipes/tika-async-cli/src/test/java/org/apache/tika/async/cli/TikaConfigAsyncWriterTest.java b/tika-pipes/tika-async-cli/src/test/java/org/apache/tika/async/cli/TikaConfigAsyncWriterTest.java
index 225bf031e..de22996ff 100644
--- a/tika-pipes/tika-async-cli/src/test/java/org/apache/tika/async/cli/TikaConfigAsyncWriterTest.java
+++ b/tika-pipes/tika-async-cli/src/test/java/org/apache/tika/async/cli/TikaConfigAsyncWriterTest.java
@@ -45,7 +45,7 @@ public class TikaConfigAsyncWriterTest {
Path tmp = Files.createTempFile(dir, "plugins-",".json");
pluginsWriter.write(tmp);
TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tmp);
- PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tmp);
assertEquals("-Xmx1g", pipesConfig.getForkedJvmArgs().get(0));
}
diff --git a/tika-pipes/tika-async-cli/src/test/resources/configs/config-template.json b/tika-pipes/tika-async-cli/src/test/resources/configs/config-template.json
index 082939278..41db19628 100644
--- a/tika-pipes/tika-async-cli/src/test/resources/configs/config-template.json
+++ b/tika-pipes/tika-async-cli/src/test/resources/configs/config-template.json
@@ -27,7 +27,7 @@
"queueSize": 10000,
"numEmitters": 1,
"emitIntermediateResults": false,
- "maxForEmitBatchBytes": 100000,
+ "directEmitThresholdBytes": 100000,
"timeoutMillis": 60000,
"startupTimeoutMillis": 240000,
"sleepOnStartupTimeoutMillis": 240000,
@@ -37,7 +37,6 @@
"staleFetcherTimeoutSeconds": 600,
"staleFetcherDelaySeconds": 60,
"forkedJvmArgs": ["-Xmx1g", "-XX:+UseG1GC"],
- "tikaConfig": "TIKA_CONFIG",
"javaPath": "java"
},
"plugin-roots": "PLUGIN_ROOTS"
diff --git a/tika-pipes/tika-pipes-api/src/main/java/org/apache/tika/pipes/api/PipesResult.java b/tika-pipes/tika-pipes-api/src/main/java/org/apache/tika/pipes/api/PipesResult.java
index bc7d08115..86d84ad5b 100644
--- a/tika-pipes/tika-pipes-api/src/main/java/org/apache/tika/pipes/api/PipesResult.java
+++ b/tika-pipes/tika-pipes-api/src/main/java/org/apache/tika/pipes/api/PipesResult.java
@@ -16,36 +16,190 @@
*/
package org.apache.tika.pipes.api;
+import java.io.Serializable;
+
import org.apache.tika.pipes.api.emitter.EmitData;
-public record PipesResult(STATUS status, EmitData emitData, String message, boolean intermediate) {
- public enum STATUS {
- CLIENT_UNAVAILABLE_WITHIN_MS,
- FETCHER_INITIALIZATION_EXCEPTION,
- FETCH_EXCEPTION,
- EMPTY_OUTPUT,
- PARSE_EXCEPTION_NO_EMIT, //within the pipes server
- PARSE_EXCEPTION_EMIT, //within the pipes server
- PARSE_SUCCESS, //when passed back to the async processor for emit
- PARSE_SUCCESS_WITH_EXCEPTION,//when passed back to the async processor for emit
- OOM, TIMEOUT, UNSPECIFIED_CRASH,
- NO_EMITTER_FOUND,
- EMIT_SUCCESS, EMIT_SUCCESS_PARSE_EXCEPTION, EMIT_EXCEPTION,
- EMIT_SUCCESS_PASSBACK,//emit happened and some data is returned
- INTERRUPTED_EXCEPTION, NO_FETCHER_FOUND,
- INTERMEDIATE_RESULT;
+public record PipesResult(RESULT_STATUS status, EmitData emitData, String message) implements Serializable {
+
+ /**
+ * High-level categorization of result statuses.
+ * <p>
+ * Categories help distinguish between:
+ * <ul>
+ * <li>Process crashes (OOM, timeout, system-level failures)</li>
+ * <li>Application errors (process ran but encountered errors)</li>
+ * <li>Successful processing (possibly with warnings)</li>
+ * </ul>
+ */
+ public enum CATEGORY {
+ /** Forked process crashed due to OOM, timeout, or other system failure */
+ PROCESS_CRASH,
+
+ /** Process completed but encountered application-level errors */
+ APPLICATION_ERROR,
+
+ /** Processing completed successfully (possibly with warnings) */
+ SUCCESS
+ }
+
+ public enum RESULT_STATUS {
+ // Process crashes
+ OOM(CATEGORY.PROCESS_CRASH),
+ TIMEOUT(CATEGORY.PROCESS_CRASH),
+ UNSPECIFIED_CRASH(CATEGORY.PROCESS_CRASH),
+
+ // Initialization failures
+ FAILED_TO_INITIALIZE(CATEGORY.APPLICATION_ERROR),
+
+ // Process crashes (system-level failures)
+ CLIENT_UNAVAILABLE_WITHIN_MS(CATEGORY.APPLICATION_ERROR),
+
+ // Fetch failures
+ FETCHER_INITIALIZATION_EXCEPTION(CATEGORY.APPLICATION_ERROR),
+ FETCH_EXCEPTION(CATEGORY.APPLICATION_ERROR),
+
+ // Success with edge case
+ EMPTY_OUTPUT(CATEGORY.SUCCESS),
+
+
+ // Parse success states
+ PARSE_SUCCESS(CATEGORY.SUCCESS),
+ PARSE_SUCCESS_WITH_EXCEPTION(CATEGORY.SUCCESS),
+ PARSE_EXCEPTION_NO_EMIT(CATEGORY.SUCCESS),
+
+
+ // Emit success states
+ EMIT_SUCCESS(CATEGORY.SUCCESS),
+ EMIT_SUCCESS_PARSE_EXCEPTION(CATEGORY.SUCCESS),
+ EMIT_SUCCESS_PASSBACK(CATEGORY.SUCCESS),
+
+ // Emit failure
+ EMIT_EXCEPTION(CATEGORY.APPLICATION_ERROR),
+
+ // Other errors
+ INTERRUPTED_EXCEPTION(CATEGORY.APPLICATION_ERROR),
+ FETCHER_NOT_FOUND(CATEGORY.APPLICATION_ERROR),
+ EMITTER_NOT_FOUND(CATEGORY.APPLICATION_ERROR);
+
+
+ private final CATEGORY category;
+
+ RESULT_STATUS(CATEGORY category) {
+ this.category = category;
+ }
+
+ /**
+ * Gets the high-level category for this result status.
+ *
+ * @return the category (PROCESS_CRASH, APPLICATION_ERROR, or SUCCESS)
+ */
+ public CATEGORY getCategory() {
+ return category;
+ }
+
+ /**
+ * Checks if this status represents a process crash (OOM, timeout, etc.).
+ *
+ * @return true if the forked process crashed
+ */
+ public boolean isProcessCrash() {
+ return category == CATEGORY.PROCESS_CRASH;
+ }
+
+ /**
+ * Checks if this status represents an application error.
+ *
+ * @return true if the process ran but encountered an error
+ */
+ public boolean isApplicationError() {
+ return category == CATEGORY.APPLICATION_ERROR;
+ }
+
+ /**
+ * Checks if this status represents successful processing. Successful
+ * processing includes handling standard runtime exceptions during the
+ * parse.
+ *
+ * @return true if processing completed successfully (possibly with warnings)
+ */
+ public boolean isSuccess() {
+ return category == CATEGORY.SUCCESS;
+ }
+
+ public static RESULT_STATUS lookup(int b) {
+ if (b < 1) {
+ throw new IllegalArgumentException("bad result value: " + b);
+ }
+ int ordinal = b - 1;
+ if (ordinal >= RESULT_STATUS.values().length) {
+ throw new IllegalArgumentException("ordinal > than array length? " + ordinal);
+ }
+ return RESULT_STATUS.values()[ordinal];
+ }
+
+ public byte getByte() {
+ return (byte) (ordinal() + 1);
+ }
+ }
+
+ public PipesResult(RESULT_STATUS status) {
+ this(status, null, null);
+ }
+
+ public PipesResult(RESULT_STATUS status, EmitData emitData) {
+ this(status, emitData, null);
+ }
+
+ public PipesResult(RESULT_STATUS status, String message) {
+ this(status, null, message);
+ }
+
+ /**
+ * Gets the high-level category for this result.
+ *
+ * @return the category (PROCESS_CRASH, APPLICATION_ERROR, or SUCCESS)
+ */
+ public CATEGORY getCategory() {
+ return status.getCategory();
}
- public PipesResult(STATUS status) {
- this(status, null, null, false);
+ /**
+ * Checks if this result represents a process crash (OOM, timeout, etc.).
+ * <p>
+ * Process crashes are system-level failures where the forked process
+ * terminated abnormally, as opposed to application errors where the
+ * process completed but encountered errors during execution.
+ *
+ * @return true if the forked process crashed
+ */
+ public boolean isProcessCrash() {
+ return status.isProcessCrash();
}
- public PipesResult(STATUS status, EmitData emitData, boolean intermediate) {
- this(status, emitData, null, intermediate);
+ /**
+ * Checks if this result represents an application error.
+ * <p>
+ * Application errors occur when the process runs but encounters
+ * errors during fetch, parse, or emit operations. These are
+ * caught runtime exceptions, not process crashes.
+ *
+ * @return true if the process ran but encountered an error
+ */
+ public boolean isApplicationError() {
+ return status.isApplicationError();
}
- public PipesResult(STATUS status, String message) {
- this(status, null, message, false);
+ /**
+ * Checks if this result represents successful processing.
+ * <p>
+ * Success includes normal completion as well as cases where
+ * processing completed with warnings (e.g., PARSE_SUCCESS_WITH_EXCEPTION).
+ *
+ * @return true if processing completed successfully (possibly with warnings)
+ */
+ public boolean isSuccess() {
+ return status.isSuccess();
}
}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesClient.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesClient.java
index 6fa907168..cd3ff0152 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesClient.java
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesClient.java
@@ -17,11 +17,13 @@
package org.apache.tika.pipes.core;
-import static org.apache.tika.pipes.core.PipesServer.STATUS.CALL;
-import static org.apache.tika.pipes.core.PipesServer.STATUS.PING;
-import static org.apache.tika.pipes.core.PipesServer.STATUS.READY;
-import static org.apache.tika.pipes.core.PipesServer.STATUS.lookup;
-import static org.apache.tika.pipes.core.PipesServer.TIMEOUT_EXIT_CODE;
+
+import static org.apache.tika.pipes.api.PipesResult.RESULT_STATUS.TIMEOUT;
+import static org.apache.tika.pipes.api.PipesResult.RESULT_STATUS.UNSPECIFIED_CRASH;
+import static org.apache.tika.pipes.core.PipesClient.COMMANDS.ACK;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.FINISHED;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.OOM;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.READY;
import java.io.Closeable;
import java.io.DataInputStream;
@@ -29,19 +31,25 @@ import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.time.Instant;
import java.util.ArrayList;
-import java.util.Collections;
+import java.util.HexFormat;
import java.util.List;
import java.util.Locale;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.FutureTask;
+import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.commons.io.FileUtils;
import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
import org.slf4j.Logger;
@@ -55,6 +63,9 @@ import org.apache.tika.pipes.api.FetchEmitTuple;
import org.apache.tika.pipes.api.PipesResult;
import org.apache.tika.pipes.api.emitter.EmitKey;
import org.apache.tika.pipes.core.emitter.EmitDataImpl;
+import org.apache.tika.pipes.core.server.IntermediateResult;
+import org.apache.tika.pipes.core.server.PipesServer;
+import org.apache.tika.utils.ExceptionUtils;
import org.apache.tika.utils.ProcessUtils;
import org.apache.tika.utils.StringUtils;
@@ -66,21 +77,25 @@ import org.apache.tika.utils.StringUtils;
*/
public class PipesClient implements Closeable {
+ public enum COMMANDS {
+ PING, ACK, NEW_REQUEST, SHUT_DOWN;
+
+ public byte getByte() {
+ return (byte) (ordinal() + 1);
+ }
+ }
+
+
private static final Logger LOG = LoggerFactory.getLogger(PipesClient.class);
- private static final int MAX_BYTES_BEFORE_READY = 20000;
- private static AtomicInteger CLIENT_COUNTER = new AtomicInteger(0);
+ private static final AtomicInteger CLIENT_COUNTER = new AtomicInteger(0);
private static final long WAIT_ON_DESTROY_MS = 10000;
- //this synchronizes the creation and/or closing of the executorService
- //there are a number of assumptions throughout that PipesClient is run
- //single threaded
- private final Object[] executorServiceLock = new Object[0];
+ public static final int SOCKET_CONNECT_TIMEOUT_MS = 60000;
+ public static final int SOCKET_TIMEOUT_MS = 60000;
+
+
private final PipesConfig pipesConfig;
private final int pipesClientId;
- private volatile boolean closed = false;
- private ExecutorService executorService = Executors.newFixedThreadPool(1);
- private Process process;
- private DataOutputStream output;
- private DataInputStream input;
+ private ServerTuple serverTuple;
private int filesProcessed = 0;
public PipesClient(PipesConfig pipesConfig) {
@@ -93,14 +108,17 @@ public class PipesClient implements Closeable {
}
private boolean ping() {
- if (process == null || !process.isAlive()) {
+ if (serverTuple == null) {
+ return false;
+ }
+ if (serverTuple.process == null || !serverTuple.process.isAlive()) {
return false;
}
try {
- output.write(PING.getByte());
- output.flush();
- int ping = input.read();
- if (ping == PING.getByte()) {
+ serverTuple.output.write(COMMANDS.PING.getByte());
+ serverTuple.output.flush();
+ int ping = serverTuple.input.read();
+ if (ping == COMMANDS.PING.getByte()) {
return true;
}
} catch (IOException e) {
@@ -111,397 +129,384 @@ public class PipesClient implements Closeable {
@Override
public void close() throws IOException {
- if (process != null) {
- try {
- destroyForcibly();
- } catch (InterruptedException e) {
- //swallow
- }
+ try {
+ shutItAllDown();
+ } catch (InterruptedException e) {
+ //swallow
}
- synchronized (executorServiceLock) {
- if (executorService != null) {
- executorService.shutdownNow();
- }
- closed = true;
+ }
+
+ private void shutItAllDown() throws InterruptedException {
+ if (serverTuple == null) {
+ return;
+ }
+ try {
+ serverTuple.output.write(COMMANDS.SHUT_DOWN.getByte());
+ serverTuple.output.flush();
+ } catch (IOException e) {
+ //swallow
+ }
+ List<IOException> exceptions = new ArrayList<>();
+ tryToClose(serverTuple.input, exceptions);
+ tryToClose(serverTuple.output, exceptions);
+ tryToClose(serverTuple.socket, exceptions);
+ tryToClose(serverTuple.serverSocket, exceptions);
+ destroyForcibly();
+
+ deleteDir(serverTuple.tmpDir);
+ serverTuple = null;
+
+ }
+
+ private void tryToClose(Closeable closeable, List<IOException> exceptions) {
+ if (closeable == null) {
+ return;
+ }
+ try {
+ closeable.close();
+ } catch (IOException e) {
+ exceptions.add(e);
}
}
public PipesResult process(FetchEmitTuple t) throws IOException, InterruptedException {
+ //container object to hold latest intermediate result if the parser is doing that
+ IntermediateResult intermediateResult = new IntermediateResult();
+ PipesResult result = null;
+ try {
+ maybeInit();
+ } catch (ServerInitializationException e) {
+ LOG.error("server initialization failed: {} ", t.getId(), e);
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), PipesResult.RESULT_STATUS.FAILED_TO_INITIALIZE, intermediateResult.get(), e.getMessage());
+ } catch (SecurityException e) {
+ LOG.error("security exception during initialization: {} ", t.getId());
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), PipesResult.RESULT_STATUS.FAILED_TO_INITIALIZE, intermediateResult.get());
+ }
+
+ try {
+ writeTask(t);
+ result = waitForServer(t, intermediateResult);
+ filesProcessed++;
+ } catch (InterruptedException | SecurityException e) {
+ throw e;
+ } catch (Exception e) {
+ LOG.error("exception waiting for server to complete task: {} ", t.getId());
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), UNSPECIFIED_CRASH, intermediateResult.get());
+ }
+ return result;
+ }
+
+ private void maybeInit() throws InterruptedException, ServerInitializationException {
boolean restart = false;
if (!ping()) {
restart = true;
- } else if (pipesConfig.getMaxFilesProcessedPerProcess() > 0 &&
- filesProcessed >= pipesConfig.getMaxFilesProcessedPerProcess()) {
- LOG.info("pipesClientId={}: restarting server after hitting max files: {}",
- pipesClientId, filesProcessed);
+ } else if (pipesConfig.getMaxFilesProcessedPerProcess() > 0 && filesProcessed >= pipesConfig.getMaxFilesProcessedPerProcess()) {
+ LOG.info("pipesClientId={}: restarting server after hitting max files: {}", pipesClientId, filesProcessed);
restart = true;
}
+ int maxRestartAttempts = 3;
+ int restartAttempts = 0;
if (restart) {
- boolean successfulRestart = false;
- while (!successfulRestart) {
+ while (true) {
try {
restart();
- successfulRestart = true;
+ return;
+ } catch (ServerInitializationException e) {
+ // Server initialization failed - don't retry, rethrow immediately with original message
+ throw e;
} catch (TimeoutException e) {
- LOG.warn("pipesClientId={}: couldn't restart within {} ms (startupTimeoutMillis)",
- pipesClientId, pipesConfig.getStartupTimeoutMillis());
- Thread.sleep(pipesConfig.getSleepOnStartupTimeoutMillis());
+ LOG.warn("pipesClientId={}: couldn't restart within {} ms (startupTimeoutMillis)", pipesClientId, pipesConfig.getStartupTimeoutMillis());
+ if (++restartAttempts >= maxRestartAttempts) {
+ throw new ServerInitializationException("couldn't start server", e);
+ }
+ } catch (IOException e) {
+ LOG.warn("pipesClientId={}: couldn't restart", pipesClientId, e);
+ if (++restartAttempts > 0) {
+ throw new ServerInitializationException("couldn't start server", e);
+ }
}
}
}
- return actuallyProcess(t);
}
- private PipesResult actuallyProcess(FetchEmitTuple t) throws InterruptedException {
+ private void writeTask(FetchEmitTuple t) throws IOException {
long start = System.currentTimeMillis();
- final PipesResult[] intermediateResult = new PipesResult[1];
- FutureTask<PipesResult> futureTask = new FutureTask<>(() -> {
- UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
- try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
- objectOutputStream.writeObject(t);
- }
+ UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream
+ .builder()
+ .get();
+ try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
+ objectOutputStream.writeObject(t);
+ }
- byte[] bytes = bos.toByteArray();
- output.write(CALL.getByte());
- output.writeInt(bytes.length);
- output.write(bytes);
- output.flush();
- if (LOG.isTraceEnabled()) {
- LOG.trace("pipesClientId={}: timer -- write tuple: {} ms",
- pipesClientId,
- System.currentTimeMillis() - start);
- }
- long readStart = System.currentTimeMillis();
- if (Thread.currentThread().isInterrupted()) {
+ byte[] bytes = bos.toByteArray();
+ serverTuple.output.write(COMMANDS.NEW_REQUEST.getByte());
+ serverTuple.output.writeInt(bytes.length);
+ serverTuple.output.write(bytes);
+ serverTuple.output.flush();
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("pipesClientId={}: timer -- write tuple: {} ms", pipesClientId, System.currentTimeMillis() - start);
+ }
+ }
+
+ private PipesResult waitForServer(FetchEmitTuple t, IntermediateResult intermediateResult) throws InterruptedException {
+ long timeoutMillis = getTimeoutMillis(pipesConfig, t.getParseContext());
+ Instant start = Instant.now();
+ //TODO - implement progress updates
+ Instant lastUpdate = start;
+ long lastProgressCounter = 0;
+ while (true) {
+ if (Thread
+ .currentThread()
+ .isInterrupted()) {
throw new InterruptedException("thread interrupt");
}
- PipesResult result = readResults(t, start);
- while (result.status() == PipesResult.STATUS.INTERMEDIATE_RESULT) {
- intermediateResult[0] = result;
- result = readResults(t, start);
+ long totalElapsed = Duration.between(start, Instant.now()).toMillis();
+ if ( totalElapsed > timeoutMillis) {
+ LOG.warn("timeout on client side: id={} elapsed={} timeoutMillis={}", t.getId(), totalElapsed, timeoutMillis);
+ return buildFatalResult(t.getId(), t.getEmitKey(), PipesResult.RESULT_STATUS.TIMEOUT, intermediateResult.get());
}
- if (LOG.isDebugEnabled()) {
- long elapsed = System.currentTimeMillis() - readStart;
- LOG.debug("finished reading result in {} ms", elapsed);
+ try {
+ //read blocks on the socket
+ PipesServer.PROCESSING_STATUS status = readServerStatus();
+ LOG.trace("switch status id={} status={}", t.getId(), status);
+ String msg = null;
+ switch (status) {
+ case OOM:
+ msg = readResult(String.class);
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), PipesResult.RESULT_STATUS.OOM, intermediateResult.get(), msg);
+ case TIMEOUT:
+ msg = readResult(String.class);
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), TIMEOUT, intermediateResult.get(), msg);
+ case UNSPECIFIED_CRASH:
+ msg = readResult(String.class);
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), UNSPECIFIED_CRASH, intermediateResult.get(), msg);
+ case INTERMEDIATE_RESULT:
+ intermediateResult.set(readResult(Metadata.class));
+ lastUpdate = Instant.now();
+ break;
+ case WORKING:
+ lastProgressCounter = readProgressCounter();
+ lastUpdate = Instant.now();
+ break;
+ case FINISHED:
+ return readResult(PipesResult.class);
+ }
+ } catch (SocketTimeoutException e) {
+ LOG.warn("Socket timeout exception while waiting for server", e);
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), TIMEOUT, intermediateResult.get(), ExceptionUtils.getStackTrace(e));
+ } catch (SecurityException e) {
+ throw e;
+ } catch (Exception e) {
+ //TODO -- catch socket timeout separately
+ LOG.warn("Crash while waiting for server", e);
+ serverTuple.process.waitFor(1, TimeUnit.SECONDS);
+ PipesResult.RESULT_STATUS status = UNSPECIFIED_CRASH;
+ if (! serverTuple.process.isAlive()) {
+ int exitValue = serverTuple.process.exitValue();
+ if (exitValue == PipesServer.OOM_EXIT_CODE) {
+ status = PipesResult.RESULT_STATUS.OOM;
+ } else if (exitValue == PipesServer.TIMEOUT_EXIT_CODE) {
+ status = PipesResult.RESULT_STATUS.TIMEOUT;
+ }
+ LOG.warn("exit value: {}", serverTuple.process.exitValue());
+ } else {
+ LOG.warn("process still alive ?!");
+ }
+ shutItAllDown();
+ return buildFatalResult(t.getId(), t.getEmitKey(), status, intermediateResult.get(), ExceptionUtils.getStackTrace(e));
}
+ }
+ }
- if (LOG.isTraceEnabled()) {
- LOG.trace("pipesClientId={}: timer -- read result: {} ms",
- pipesClientId,
- System.currentTimeMillis() - readStart);
- }
- if (result.status() == PipesResult.STATUS.OOM) {
- return buildFatalResult(result, intermediateResult);
- }
- return result;
- });
+ private long readProgressCounter() throws IOException {
+ return serverTuple.input.readLong();
+ }
- try {
- if (closed) {
- throw new IllegalArgumentException("pipesClientId=" + pipesClientId +
- ": PipesClient closed");
- }
- executorService.execute(futureTask);
- long timeout = TikaTaskTimeout.getTimeoutMillis(t.getParseContext(), pipesConfig.getTimeoutMillis());
- return futureTask.get(timeout, TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- destroyForcibly();
- throw e;
- } catch (ExecutionException e) {
- LOG.error("pipesClientId=" + pipesClientId + ": execution exception", e);
- long elapsed = System.currentTimeMillis() - start;
- pauseThenDestroy();
- if (!process.isAlive() && TIMEOUT_EXIT_CODE == process.exitValue()) {
- LOG.warn("pipesClientId={} server timeout: {} in {} ms", pipesClientId, t.getId(),
- elapsed);
- return buildFatalResult(PipesResults.TIMEOUT, intermediateResult);
- }
- process.waitFor(500, TimeUnit.MILLISECONDS);
- if (process.isAlive()) {
- LOG.warn("pipesClientId={} crash: {} in {} ms with no exit code available",
- pipesClientId, t.getId(), elapsed);
- } else {
- LOG.warn("pipesClientId={} crash: {} in {} ms with exit code {}", pipesClientId,
- t.getId(), elapsed, process.exitValue());
- }
- return buildFatalResult(PipesResults.UNSPECIFIED_CRASH, intermediateResult);
- } catch (TimeoutException e) {
- long elapsed = System.currentTimeMillis() - start;
- destroyForcibly();
- LOG.warn("pipesClientId={} client timeout: {} in {} ms", pipesClientId, t.getId(),
- elapsed);
- return buildFatalResult(PipesResults.TIMEOUT, intermediateResult);
- } finally {
- futureTask.cancel(true);
- }
+
+ private PipesResult buildFatalResult(String id, EmitKey emitKey, PipesResult.RESULT_STATUS status, Optional<Metadata> intermediateResultOpt) {
+ return buildFatalResult(id, emitKey, status, intermediateResultOpt, null);
}
- private PipesResult buildFatalResult(PipesResult result,
- PipesResult[] intermediateResult) {
+ private PipesResult buildFatalResult(String id, EmitKey emitKey, PipesResult.RESULT_STATUS status, Optional<Metadata> intermediateResultOpt, String msg) {
+ LOG.warn("crash id={} status={}", id, status);
+ Metadata intermediateResult = intermediateResultOpt.orElse(new Metadata());
- if (intermediateResult[0] == null) {
- return result;
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("intermediate result: id={}", intermediateResult);
+ }
+ intermediateResult.set(TikaCoreProperties.PIPES_RESULT, status.toString());
+ if (StringUtils.isBlank(msg)) {
+ return new PipesResult(status, new EmitDataImpl(emitKey.getEmitKey(), List.of(intermediateResult)));
} else {
- if (LOG.isTraceEnabled()) {
- LOG.trace("intermediate result: {}", intermediateResult[0].emitData());
- }
- intermediateResult[0].emitData().getMetadataList().get(0).set(
- TikaCoreProperties.PIPES_RESULT, result.status().toString());
- return new PipesResult(result.status(),
- intermediateResult[0].emitData(), true);
+ return new PipesResult(status, new EmitDataImpl(emitKey.getEmitKey(), List.of(intermediateResult)), msg);
}
+
}
private void pauseThenDestroy() throws InterruptedException {
//wait just a little bit to let process end to get exit value
//if there's a timeout on the server side
try {
- process.waitFor(200, TimeUnit.MILLISECONDS);
+ serverTuple.process.waitFor(200, TimeUnit.MILLISECONDS);
} finally {
destroyForcibly();
}
}
private void destroyForcibly() throws InterruptedException {
- process.destroyForcibly();
- process.waitFor(WAIT_ON_DESTROY_MS, TimeUnit.MILLISECONDS);
- //important to close streams so that threads running in this
- //process receive notice that they really ought to stop.
- //TIKA-3588 showed that we can't trust that forcibly destroying
- //the process caused the actuallyProcess thread in this process to stop.
- try {
- input.close();
- } catch (IOException closeException) {
- //swallow
- }
- try {
- output.close();
- } catch (IOException closeException) {
- //swallow
- }
- if (process.isAlive()) {
+ serverTuple.process.destroyForcibly();
+ serverTuple.process.waitFor(WAIT_ON_DESTROY_MS, TimeUnit.MILLISECONDS);
+
+ if (serverTuple.process.isAlive()) {
LOG.error("Process still alive after {}ms", WAIT_ON_DESTROY_MS);
}
}
- private PipesResult readResults(FetchEmitTuple t, long start) throws IOException {
- int statusByte = input.read();
- long millis = System.currentTimeMillis() - start;
- PipesServer.STATUS status = null;
+ private PipesServer.PROCESSING_STATUS readServerStatus() throws IOException {
+ int statusByte = serverTuple.input.read();
+ writeAck();
+ PipesServer.PROCESSING_STATUS status = null;
try {
- status = lookup(statusByte);
+ status = PipesServer.PROCESSING_STATUS.lookup(statusByte);
} catch (IllegalArgumentException e) {
String byteString = "-1";
if (statusByte > -1) {
- byteString = String.format(Locale.US, "%02x", (byte)statusByte);
+ byteString = String.format(Locale.US, "%02x", (byte) statusByte);
}
throw new IOException("problem reading response from server: " + byteString, e);
}
-
- switch (status) {
- case OOM:
- LOG.warn("pipesClientId={} oom: {} in {} ms", pipesClientId, t.getId(), millis);
- return PipesResults.OOM;
- case TIMEOUT:
- LOG.warn("pipesClientId={} server response timeout: {} in {} ms", pipesClientId,
- t.getId(), millis);
- return PipesResults.TIMEOUT;
- case EMIT_EXCEPTION:
- LOG.warn("pipesClientId={} emit exception: {} in {} ms", pipesClientId, t.getId(),
- millis);
- return readMessage(PipesResult.STATUS.EMIT_EXCEPTION);
- case EMITTER_NOT_FOUND:
- LOG.warn("pipesClientId={} emitter not found: {} in {} ms", pipesClientId,
- t.getId(), millis);
- return readMessage(PipesResult.STATUS.NO_EMITTER_FOUND);
- case FETCHER_NOT_FOUND:
- LOG.warn("pipesClientId={} fetcher not found: {} in {} ms", pipesClientId,
- t.getId(), millis);
- return readMessage(PipesResult.STATUS.NO_FETCHER_FOUND);
- case FETCHER_INITIALIZATION_EXCEPTION:
- LOG.warn("pipesClientId={} fetcher initialization exception: {} in {} ms",
- pipesClientId, t.getId(), millis);
- return readMessage(PipesResult.STATUS.FETCHER_INITIALIZATION_EXCEPTION);
- case FETCH_EXCEPTION:
- LOG.warn("pipesClientId={} fetch exception: {} in {} ms", pipesClientId, t.getId(),
- millis);
- return readMessage(PipesResult.STATUS.FETCH_EXCEPTION);
- case INTERMEDIATE_RESULT:
- LOG.debug("pipesClientId={} intermediate success: {} in {} ms", pipesClientId,
- t.getId(), millis);
- return deserializeIntermediateResult(t.getEmitKey(), t.getParseContext());
- case PARSE_SUCCESS:
- //there may have been a parse exception, but the parse didn't crash
- LOG.debug("pipesClientId={} parse success: {} in {} ms", pipesClientId, t.getId(),
- millis);
- return deserializeEmitData(PipesResult.STATUS.PARSE_SUCCESS);
- case EMIT_SUCCESS_PASS_BACK:
- LOG.debug("pipesClientId={} emit success with passback: {} in {} ms", pipesClientId, t.getId(),
- millis);
- return deserializeEmitData(PipesResult.STATUS.EMIT_SUCCESS_PASSBACK);
- case PARSE_EXCEPTION_NO_EMIT:
- return readMessage(PipesResult.STATUS.PARSE_EXCEPTION_NO_EMIT);
- case EMIT_SUCCESS:
- LOG.debug("pipesClientId={} emit success: {} in {} ms", pipesClientId, t.getId(),
- millis);
- return PipesResults.EMIT_SUCCESS;
- case EMIT_SUCCESS_PARSE_EXCEPTION:
- return readMessage(PipesResult.STATUS.EMIT_SUCCESS_PARSE_EXCEPTION);
- case EMPTY_OUTPUT:
- return PipesResults.EMPTY_OUTPUT;
- //fall through
- case READY:
- case CALL:
- case PING:
- case FAILED_TO_START:
- throw new IOException("Not expecting this status: " + status);
- default:
- throw new IOException("Need to handle procesing for: " + status);
- }
-
+ return status;
}
- private PipesResult readMessage(PipesResult.STATUS status) throws IOException {
- //readInt checks for EOF
- int length = input.readInt();
- byte[] bytes = new byte[length];
- input.readFully(bytes);
- String msg = new String(bytes, StandardCharsets.UTF_8);
- return new PipesResult(status, msg);
- }
- private PipesResult deserializeEmitData(PipesResult.STATUS status) throws IOException {
- int length = input.readInt();
- byte[] bytes = new byte[length];
- input.readFully(bytes);
- try (ObjectInputStream objectInputStream = new ObjectInputStream(
- UnsynchronizedByteArrayInputStream.builder().setByteArray(bytes).get())) {
- EmitDataImpl emitData = (EmitDataImpl) objectInputStream.readObject();
-
- String stack = emitData.getContainerStackTrace();
- if (StringUtils.isBlank(stack)) {
- //stack is blank for PARSE_SUCCESS and for PASSBACK
- return new PipesResult(status, emitData, false);
- } else {
- //tweak this
- if (status == PipesResult.STATUS.PARSE_SUCCESS) {
- status = PipesResult.STATUS.PARSE_SUCCESS_WITH_EXCEPTION;
- }
- return new PipesResult(status, emitData, stack, false);
+ private PipesResult.RESULT_STATUS readResultStatus() throws IOException {
+ int statusByte = serverTuple.input.read();
+ PipesResult.RESULT_STATUS status = null;
+ try {
+ status = PipesResult.RESULT_STATUS.lookup(statusByte);
+ } catch (IllegalArgumentException e) {
+ String byteString = "-1";
+ if (statusByte > -1) {
+ byteString = String.format(Locale.US, "%02x", (byte) statusByte);
}
- } catch (ClassNotFoundException e) {
- LOG.error("class not found exception deserializing data", e);
- //this should be catastrophic
- throw new RuntimeException(e);
+ throw new IOException("problem reading response from server: " + byteString, e);
}
+ return status;
}
-
- private PipesResult deserializeIntermediateResult(EmitKey emitKey, ParseContext parseContext) throws IOException {
-
- int length = input.readInt();
- byte[] bytes = new byte[length];
- input.readFully(bytes);
- try (ObjectInputStream objectInputStream = new ObjectInputStream(
- UnsynchronizedByteArrayInputStream.builder().setByteArray(bytes).get())) {
- Metadata metadata = (Metadata) objectInputStream.readObject();
- EmitDataImpl emitDataTuple = new EmitDataImpl(emitKey.getEmitKey(), Collections.singletonList(metadata));
- return new PipesResult(PipesResult.STATUS.INTERMEDIATE_RESULT, emitDataTuple, true);
+ private <T> T readResult(Class<? extends T> clazz) throws IOException {
+ int len = serverTuple.input.readInt();
+ byte[] bytes = new byte[len];
+ serverTuple.input.readFully(bytes);
+ writeAck();
+ try (ObjectInputStream objectInputStream = new ObjectInputStream(UnsynchronizedByteArrayInputStream
+ .builder()
+ .setByteArray(bytes)
+ .get())) {
+ return clazz.cast(objectInputStream.readObject());
} catch (ClassNotFoundException e) {
- LOG.error("class not found exception deserializing data", e);
- //this should be catastrophic
- throw new RuntimeException(e);
+ throw new IOException(e);
}
}
- private void restart() throws IOException, InterruptedException, TimeoutException {
- if (process != null) {
- LOG.debug("process still alive; trying to destroy it");
- destroyForcibly();
- boolean processEnded = process.waitFor(30, TimeUnit.SECONDS);
- if (! processEnded) {
- LOG.warn("pipesClientId={}: process has not yet ended", pipesClientId);
- }
- executorService.shutdownNow();
- boolean shutdown = executorService.awaitTermination(30, TimeUnit.SECONDS);
- if (! shutdown) {
- LOG.warn("pipesClientId={}: executorService has not yet shutdown", pipesClientId);
- }
- synchronized (executorServiceLock) {
- if (closed) {
- throw new IllegalArgumentException("pipesClientId=" + pipesClientId +
- ": PipesClient closed");
- }
- executorService = Executors.newFixedThreadPool(1);
- }
+ private void writeAck() throws IOException {
+ serverTuple.output.write(ACK.getByte());
+ serverTuple.output.flush();
+ }
+
+
+ private void restart() throws InterruptedException, IOException, TimeoutException {
+ if (serverTuple != null && serverTuple.process != null) {
+ shutItAllDown();
LOG.info("pipesClientId={}: restarting process", pipesClientId);
} else {
LOG.info("pipesClientId={}: starting process", pipesClientId);
}
- ProcessBuilder pb = new ProcessBuilder(getCommandline());
- pb.redirectError(ProcessBuilder.Redirect.INHERIT);
-
+ ServerSocket serverSocket = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ int port = serverSocket.getLocalPort();
+ Path tmpDir = Files.createTempDirectory("pipes-server-" + pipesClientId + "-");
+ ProcessBuilder pb = new ProcessBuilder(getCommandline(port, tmpDir));
+ pb.inheritIO();
+ Process process = null;
try {
process = pb.start();
} catch (Exception e) {
+ deleteDir(tmpDir);
//Do we ever want this to be not fatal?!
- LOG.error("failed to start client", e);
- throw new FailedToStartClientException(e);
- }
- input = new DataInputStream(process.getInputStream());
- output = new DataOutputStream(process.getOutputStream());
-
- //wait for ready signal
- final UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
- FutureTask<Integer> futureTask = new FutureTask<>(() -> {
- int b = input.read();
- int read = 1;
- while (read < MAX_BYTES_BEFORE_READY && b != READY.getByte()) {
-
- if (b == -1) {
- throw new RuntimeException(getMsg("pipesClientId=" + pipesClientId + ": " +
- "Couldn't start server -- read EOF before 'ready' byte.\n" +
- " process isAlive=" + process.isAlive(), bos));
- }
- bos.write(b);
- b = input.read();
- read++;
+ LOG.error("failed to start server", e);
+ String msg = "Failed to start server process";
+ if (e.getMessage() != null) {
+ msg += ": " + e.getMessage();
}
- if (read >= MAX_BYTES_BEFORE_READY) {
- throw new RuntimeException(getMsg("pipesClientId=" + pipesClientId + ": " +
- "Couldn't start server: read too many bytes before 'ready' byte.\n" +
- " Make absolutely certain that your logger is not writing to " +
- "stdout.\n", bos));
- }
- if (bos.size() > 0) {
- LOG.warn("pipesClientId={}: From forked process before start byte: {}",
- pipesClientId, bos.toString(StandardCharsets.UTF_8));
+ throw new ServerInitializationException(msg, e);
+ }
+ // Poll for connection with periodic checks if process is still alive
+ serverSocket.setSoTimeout(1000); // 1 second timeout for each poll
+ Socket socket = null;
+ long startTime = System.currentTimeMillis();
+ while (socket == null) {
+ try {
+ socket = serverSocket.accept();
+ } catch (SocketTimeoutException e) {
+ // Check if the process died before connecting
+ if (!process.isAlive()) {
+ int exitValue = process.exitValue();
+ LOG.error("pipesClientId={}: Process exited with code {} before connecting to socket", pipesClientId, exitValue);
+ deleteDir(tmpDir);
+ throw new ServerInitializationException("Process failed to start (exit code " + exitValue + "). Check JVM arguments and classpath.");
+ }
+ // Check if we've exceeded the overall timeout
+ long elapsed = System.currentTimeMillis() - startTime;
+ if (elapsed > SOCKET_CONNECT_TIMEOUT_MS) {
+ LOG.error("pipesClientId={}: Timed out waiting for server to connect after {}ms", pipesClientId, elapsed);
+ deleteDir(tmpDir);
+ throw new ServerInitializationException("Server did not connect within " + SOCKET_CONNECT_TIMEOUT_MS + "ms");
+ }
+ // Continue polling
}
- return 1;
- });
- long start = System.currentTimeMillis();
- executorService.submit(futureTask);
+ }
+ socket.setSoTimeout((int) pipesConfig.getSocketTimeoutMs());
+ serverTuple = new ServerTuple(process, serverSocket, socket, new DataInputStream(socket.getInputStream()),
+ new DataOutputStream(socket.getOutputStream()), tmpDir);
+ waitForStartup();
+ }
+
+ private void waitForStartup() throws IOException {
+ //wait for ready byte
+ int b = serverTuple.input.read();
+ writeAck();
+ if (b == READY.getByte()) {
+ LOG.debug("got ready byte");
+ } else if (b == FINISHED.getByte()) {
+ int len = serverTuple.input.readInt();
+ byte[] bytes = new byte[len];
+ serverTuple.input.readFully(bytes);
+ writeAck();
+ String msg = new String(bytes, StandardCharsets.UTF_8);
+ LOG.error("Server failed to start: {}", msg);
+ throw new ServerInitializationException(msg);
+ } else {
+ LOG.error("Unexpected first byte: " + HexFormat.of().formatHex(new byte[]{ (byte) b }));
+ throw new IOException("Unexpected first byte from server: " + HexFormat.of().formatHex(new byte[]{ (byte) b }));
+ }
+
+ }
+
+ private void deleteDir(Path tmpDir) {
try {
- futureTask.get(pipesConfig.getStartupTimeoutMillis(), TimeUnit.MILLISECONDS);
- } catch (InterruptedException e) {
- destroyForcibly();
- throw e;
- } catch (ExecutionException e) {
- LOG.error("pipesClientId=" + pipesClientId + ": couldn't start server", e);
- destroyForcibly();
- throw new RuntimeException(e);
- } catch (TimeoutException e) {
- long elapsed = System.currentTimeMillis() - start;
- LOG.error("pipesClientId={} didn't receive ready byte from server within " +
- "StartupTimeoutMillis {}; ms elapsed {}; did read >{}<",
- pipesClientId, pipesConfig.getStartupTimeoutMillis(),
- elapsed, bos.toString(StandardCharsets.UTF_8));
- destroyForcibly();
- throw e;
- } finally {
- futureTask.cancel(true);
+ FileUtils.deleteDirectory(tmpDir.toFile());
+ } catch (IOException e) {
+ //swallow
+ LOG.warn("couldn't delete tmp dir {}", tmpDir);
}
}
@@ -514,7 +519,7 @@ public class PipesClient implements Closeable {
}
}
- private String[] getCommandline() {
+ private String[] getCommandline(int port, Path tmpDir) {
List<String> configArgs = pipesConfig.getForkedJvmArgs();
boolean hasClassPath = false;
boolean hasHeadless = false;
@@ -529,8 +534,7 @@ public class PipesClient implements Closeable {
if (arg.equals("-cp") || arg.equals("--classpath")) {
hasClassPath = true;
}
- if (arg.equals("-XX:+ExitOnOutOfMemoryError") ||
- arg.equals("-XX:+CrashOnOutOfMemoryError")) {
+ if (arg.equals("-XX:+ExitOnOutOfMemoryError") || arg.equals("-XX:+CrashOnOutOfMemoryError")) {
hasExitOnOOM = true;
}
if (arg.startsWith("-Dlog4j.configuration")) {
@@ -558,24 +562,41 @@ public class PipesClient implements Closeable {
commandLine.add("-Djava.awt.headless=true");
}
if (hasExitOnOOM) {
- LOG.warn(
- "I notice that you have a jdk setting to exit/crash on OOM. If you run heavy external processes " +
- "like tesseract, this setting may result in orphaned processes which could be disastrous" +
- " for performance.");
+ LOG.warn("I notice that you have a jdk setting to exit/crash on OOM. If you run heavy external processes " +
+ "like tesseract, this setting may result in orphaned processes which could be disastrous" + " for performance.");
}
if (!hasLog4j) {
- commandLine.add(
- "-Dlog4j.configurationFile=classpath:pipes-fork-server-default-log4j2.xml");
+ commandLine.add("-Dlog4j.configurationFile=classpath:pipes-fork-server-default-log4j2.xml");
}
commandLine.add("-DpipesClientId=" + pipesClientId);
commandLine.addAll(configArgs);
- commandLine.add("org.apache.tika.pipes.core.PipesServer");
- commandLine.add(ProcessUtils.escapeCommandLine(
- pipesConfig.getTikaConfigPath().toAbsolutePath().toString()));
- commandLine.add(Long.toString(pipesConfig.getMaxForEmitBatchBytes()));
- commandLine.add(Long.toString(pipesConfig.getTimeoutMillis()));
- commandLine.add(Long.toString(pipesConfig.getShutdownClientAfterMillis()));
+ commandLine.add("-Djava.io.tmpdir=" + tmpDir.toAbsolutePath());
+ commandLine.add("org.apache.tika.pipes.core.server.PipesServer");
+
+ commandLine.add(Integer.toString(port));
+ commandLine.add(pipesConfig.getTikaConfigPath());
LOG.debug("pipesClientId={}: commandline: {}", pipesClientId, commandLine);
return commandLine.toArray(new String[0]);
}
+
+ private record ServerTuple(Process process, ServerSocket serverSocket, Socket socket,
+ DataInputStream input, DataOutputStream output, Path tmpDir) {
+
+ }
+
+ public static long getTimeoutMillis(PipesConfig pipesConfig, ParseContext parseContext) {
+ long defaultTimeoutMillis = pipesConfig.getTimeoutMillis();
+
+ if (parseContext == null) {
+ return defaultTimeoutMillis;
+ }
+
+ TikaTaskTimeout tikaTaskTimeout = parseContext.get(TikaTaskTimeout.class);
+ if (tikaTaskTimeout == null) {
+ return defaultTimeoutMillis;
+ }
+ LOG.debug("applying timeout from parseContext: {}ms", tikaTaskTimeout.getTimeoutMillis());
+ return tikaTaskTimeout.getTimeoutMillis();
+ }
+
}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesConfig.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesConfig.java
index 2acfc486a..51f572e0a 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesConfig.java
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesConfig.java
@@ -18,7 +18,6 @@ package org.apache.tika.pipes.core;
import java.io.IOException;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.ArrayList;
import com.fasterxml.jackson.annotation.JsonIgnore;
@@ -29,11 +28,11 @@ import org.apache.tika.exception.TikaConfigException;
public class PipesConfig {
/**
- * default size to send back to the PipesClient for batch
- * emitting. If an extract is larger than this, it will be emitted
- * directly from the forked PipesServer.
+ * Default threshold in bytes for direct emission from PipesServer.
+ * If an extract is larger than this, it will be emitted
+ * directly from the forked PipesServer rather than passed back to PipesClient.
*/
- public static final long DEFAULT_MAX_FOR_EMIT_BATCH = 100000;
+ public static final long DEFAULT_DIRECT_EMIT_THRESHOLD_BYTES = 100000;
public static final long DEFAULT_TIMEOUT_MILLIS = 60000;
@@ -47,10 +46,16 @@ public class PipesConfig {
public static final long DEFAULT_MAX_WAIT_FOR_CLIENT_MS = 60000;
+ public static final long DEFAULT_SOCKET_TIMEOUT_MS = 60000;
+
+ public static final long DEFAULT_HEARTBEAT_INTERVAL_MS = 1000;
+
//if an extract is larger than this, the forked PipesServer should
//emit the extract directly and not send the contents back to the PipesClient
- private long maxForEmitBatchBytes = DEFAULT_MAX_FOR_EMIT_BATCH;
+ private long directEmitThresholdBytes = DEFAULT_DIRECT_EMIT_THRESHOLD_BYTES;
private long timeoutMillis = DEFAULT_TIMEOUT_MILLIS;
+ private long socketTimeoutMs = DEFAULT_SOCKET_TIMEOUT_MS;
+ private long heartbeatIntervalMs = DEFAULT_HEARTBEAT_INTERVAL_MS;
private long startupTimeoutMillis = DEFAULT_STARTUP_TIMEOUT_MILLIS;
private long sleepOnStartupTimeoutMillis = DEFAULT_STARTUP_TIMEOUT_MILLIS;
@@ -70,6 +75,9 @@ public class PipesConfig {
public static final int DEFAULT_QUEUE_SIZE = 10000;
public static final int DEFAULT_NUM_EMITTERS = 1;
+ @JsonIgnore
+ private volatile String tikaConfigPath = null;
+
private long emitWithinMillis = DEFAULT_EMIT_WITHIN_MILLIS;
private long emitMaxEstimatedBytes = DEFAULT_EMIT_MAX_ESTIMATED_BYTES;
private int queueSize = DEFAULT_QUEUE_SIZE;
@@ -79,16 +87,13 @@ public class PipesConfig {
private ArrayList<String> forkedJvmArgs = new ArrayList<>();
private String javaPath = "java";
-
- private String tikaConfig;
-
/**
* Loads PipesConfig from the "pipes" section of the JSON configuration.
* <p>
* This configuration is used by both PipesServer (forking process) and
* AsyncProcessor (async processing). Some fields are specific to each:
* <ul>
- * <li>PipesServer uses: numClients, timeoutMillis, maxForEmitBatchBytes, etc.</li>
+ * <li>PipesServer uses: numClients, timeoutMillis, directEmitThresholdBytes, etc.</li>
* <li>AsyncProcessor uses: emitWithinMillis, queueSize, numEmitters, etc.</li>
* </ul>
* Unused fields in each context are simply ignored.
@@ -98,14 +103,25 @@ public class PipesConfig {
* @throws IOException if deserialization fails
* @throws TikaConfigException if configuration is invalid
*/
- public static PipesConfig load(TikaJsonConfig tikaJsonConfig) throws IOException, TikaConfigException {
+ public static PipesConfig load(TikaJsonConfig tikaJsonConfig, Path tikaConfigPath) throws IOException, TikaConfigException {
PipesConfig config = tikaJsonConfig.deserialize("pipes", PipesConfig.class);
if (config == null) {
- return new PipesConfig();
+ config = new PipesConfig();
}
+ config.setTikaConfigPath(tikaConfigPath.toAbsolutePath().toString());
return config;
}
+ @JsonIgnore
+ public String getTikaConfigPath() {
+ return tikaConfigPath;
+ }
+
+ void setTikaConfigPath(String tikaConfigPath) {
+ this.tikaConfigPath = tikaConfigPath;
+ }
+
+
public long getTimeoutMillis() {
return timeoutMillis;
}
@@ -118,6 +134,35 @@ public class PipesConfig {
this.timeoutMillis = timeoutMillis;
}
+ public long getSocketTimeoutMs() {
+ return socketTimeoutMs;
+ }
+
+ /**
+ * Socket timeout in milliseconds for reading from the forked process.
+ * If no data is received within this time, the connection is considered timed out.
+ * This is different from timeoutMillis which is the parse/processing timeout.
+ * @param socketTimeoutMs
+ */
+ public void setSocketTimeoutMs(long socketTimeoutMs) {
+ this.socketTimeoutMs = socketTimeoutMs;
+ }
+
+ public long getHeartbeatIntervalMs() {
+ return heartbeatIntervalMs;
+ }
+
+ /**
+ * Interval in milliseconds between heartbeat messages sent from server to client.
+ * Should be significantly less than socketTimeoutMs to ensure the client doesn't timeout.
+ * WARNING: Setting this >= socketTimeoutMs will cause socket timeouts during normal processing.
+ * This only exists for testing. We encourage you never to use it.
+ * @param heartbeatIntervalMs
+ */
+ public void setHeartbeatIntervalMs(long heartbeatIntervalMs) {
+ this.heartbeatIntervalMs = heartbeatIntervalMs;
+ }
+
public long getShutdownClientAfterMillis() {
return shutdownClientAfterMillis;
}
@@ -166,19 +211,6 @@ public class PipesConfig {
this.maxFilesProcessedPerProcess = maxFilesProcessedPerProcess;
}
- @JsonIgnore
- public Path getTikaConfigPath() {
- return tikaConfig != null ? Paths.get(tikaConfig) : null;
- }
-
- public String getTikaConfig() {
- return tikaConfig;
- }
-
- public void setTikaConfig(String tikaConfig) {
- this.tikaConfig = tikaConfig;
- }
-
public String getJavaPath() {
return javaPath;
}
@@ -202,12 +234,12 @@ public class PipesConfig {
*
* @return the threshold extract size at which to emit directly from the forked PipeServer
*/
- public long getMaxForEmitBatchBytes() {
- return maxForEmitBatchBytes;
+ public long getDirectEmitThresholdBytes() {
+ return directEmitThresholdBytes;
}
- public void setMaxForEmitBatchBytes(long maxForEmitBatchBytes) {
- this.maxForEmitBatchBytes = maxForEmitBatchBytes;
+ public void setDirectEmitThresholdBytes(long directEmitThresholdBytes) {
+ this.directEmitThresholdBytes = directEmitThresholdBytes;
}
public long getSleepOnStartupTimeoutMillis() {
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesResults.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesResults.java
index 6c412a5e1..5df292f13 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesResults.java
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesResults.java
@@ -21,12 +21,12 @@ import org.apache.tika.pipes.api.PipesResult;
public class PipesResults {
public static final PipesResult CLIENT_UNAVAILABLE_WITHIN_MS =
- new PipesResult(PipesResult.STATUS.CLIENT_UNAVAILABLE_WITHIN_MS);
- public static final PipesResult TIMEOUT = new PipesResult(PipesResult.STATUS.TIMEOUT);
- public static final PipesResult OOM = new PipesResult(PipesResult.STATUS.OOM);
- public static final PipesResult UNSPECIFIED_CRASH = new PipesResult(PipesResult.STATUS.UNSPECIFIED_CRASH);
- public static final PipesResult EMIT_SUCCESS = new PipesResult(PipesResult.STATUS.EMIT_SUCCESS);
- public static final PipesResult INTERRUPTED_EXCEPTION = new PipesResult(PipesResult.STATUS.INTERRUPTED_EXCEPTION);
- public static final PipesResult EMPTY_OUTPUT = new PipesResult(PipesResult.STATUS.EMPTY_OUTPUT);
+ new PipesResult(PipesResult.RESULT_STATUS.CLIENT_UNAVAILABLE_WITHIN_MS);
+ public static final PipesResult TIMEOUT = new PipesResult(PipesResult.RESULT_STATUS.TIMEOUT);
+ public static final PipesResult OOM = new PipesResult(PipesResult.RESULT_STATUS.OOM);
+ public static final PipesResult UNSPECIFIED_CRASH = new PipesResult(PipesResult.RESULT_STATUS.UNSPECIFIED_CRASH);
+ public static final PipesResult EMIT_SUCCESS = new PipesResult(PipesResult.RESULT_STATUS.EMIT_SUCCESS);
+ public static final PipesResult INTERRUPTED_EXCEPTION = new PipesResult(PipesResult.RESULT_STATUS.INTERRUPTED_EXCEPTION);
+ public static final PipesResult EMPTY_OUTPUT = new PipesResult(PipesResult.RESULT_STATUS.EMPTY_OUTPUT);
}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesServer.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesServer.java
deleted file mode 100644
index bdc31cc43..000000000
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/PipesServer.java
+++ /dev/null
@@ -1,971 +0,0 @@
-/*
- * 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.
- */
-package org.apache.tika.pipes.core;
-
-import static org.apache.tika.pipes.api.pipesiterator.PipesIteratorBaseConfig.DEFAULT_HANDLER_CONFIG;
-
-import java.io.Closeable;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.PrintStream;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Collections;
-import java.util.List;
-import java.util.Optional;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
-import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
-import org.apache.tika.config.TikaTaskTimeout;
-import org.apache.tika.config.loader.TikaJsonConfig;
-import org.apache.tika.config.loader.TikaLoader;
-import org.apache.tika.detect.Detector;
-import org.apache.tika.exception.EncryptedDocumentException;
-import org.apache.tika.exception.TikaConfigException;
-import org.apache.tika.exception.TikaException;
-import org.apache.tika.extractor.DocumentSelector;
-import org.apache.tika.extractor.EmbeddedDocumentByteStoreExtractorFactory;
-import org.apache.tika.extractor.EmbeddedDocumentBytesHandler;
-import org.apache.tika.extractor.EmbeddedDocumentExtractor;
-import org.apache.tika.extractor.EmbeddedDocumentExtractorFactory;
-import org.apache.tika.extractor.RUnpackExtractor;
-import org.apache.tika.extractor.RUnpackExtractorFactory;
-import org.apache.tika.io.TemporaryResources;
-import org.apache.tika.io.TikaInputStream;
-import org.apache.tika.metadata.Metadata;
-import org.apache.tika.metadata.TikaCoreProperties;
-import org.apache.tika.metadata.filter.MetadataFilter;
-import org.apache.tika.metadata.filter.NoOpFilter;
-import org.apache.tika.mime.MediaType;
-import org.apache.tika.parser.AutoDetectParser;
-import org.apache.tika.parser.DigestingParser;
-import org.apache.tika.parser.ParseContext;
-import org.apache.tika.parser.Parser;
-import org.apache.tika.parser.RecursiveParserWrapper;
-import org.apache.tika.pipes.api.FetchEmitTuple;
-import org.apache.tika.pipes.api.HandlerConfig;
-import org.apache.tika.pipes.api.emitter.EmitKey;
-import org.apache.tika.pipes.api.emitter.Emitter;
-import org.apache.tika.pipes.api.emitter.StreamEmitter;
-import org.apache.tika.pipes.api.fetcher.Fetcher;
-import org.apache.tika.pipes.core.emitter.EmitDataImpl;
-import org.apache.tika.pipes.core.emitter.EmitterManager;
-import org.apache.tika.pipes.core.extractor.BasicEmbeddedDocumentBytesHandler;
-import org.apache.tika.pipes.core.extractor.EmbeddedDocumentBytesConfig;
-import org.apache.tika.pipes.core.extractor.EmittingEmbeddedDocumentBytesHandler;
-import org.apache.tika.pipes.core.fetcher.FetcherManager;
-import org.apache.tika.plugins.TikaPluginManager;
-import org.apache.tika.sax.BasicContentHandlerFactory;
-import org.apache.tika.sax.ContentHandlerFactory;
-import org.apache.tika.sax.RecursiveParserWrapperHandler;
-import org.apache.tika.utils.ExceptionUtils;
-import org.apache.tika.utils.StringUtils;
-
-/**
- * This server is forked from the PipesClient. This class isolates
- * parsing from the client to protect the primary JVM.
- * <p>
- * When configuring logging for this class, make absolutely certain
- * not to write to STDOUT. This class uses STDOUT to communicate with
- * the PipesClient.
- */
-public class PipesServer implements Runnable {
-
- private static final Logger LOG = LoggerFactory.getLogger(PipesServer.class);
-
- //this has to be some number not close to 0-3
- //it looks like the server crashes with exit value 3 on OOM, for example
- public static final int TIMEOUT_EXIT_CODE = 17;
- private DigestingParser.Digester digester;
-
- private Detector detector;
-
- public enum STATUS {
- READY, CALL, PING, FAILED_TO_START, FETCHER_NOT_FOUND, EMITTER_NOT_FOUND,
- FETCHER_INITIALIZATION_EXCEPTION, FETCH_EXCEPTION, PARSE_SUCCESS, PARSE_EXCEPTION_NO_EMIT,
- EMIT_SUCCESS, EMIT_SUCCESS_PASS_BACK, EMIT_SUCCESS_PARSE_EXCEPTION, EMIT_EXCEPTION, OOM, TIMEOUT, EMPTY_OUTPUT,
- INTERMEDIATE_RESULT;
-
- byte getByte() {
- return (byte) (ordinal() + 1);
- }
-
- public static STATUS lookup(int val) {
- int i = val - 1;
- if (i < 0) {
- throw new IllegalArgumentException("byte must be > 0");
- }
- STATUS[] statuses = STATUS.values();
-
- if (i >= statuses.length) {
- throw new IllegalArgumentException(
- "byte with index " + i + " must be < " + statuses.length);
- }
- return statuses[i];
- }
- }
-
- public enum EMIT_STRATEGY {
- EMIT_ALL,
- PASSBACK_ALL,
- DYNAMIC
- }
-
- private final Object[] lock = new Object[0];
- private long checkForTimeoutMs = 1000;
- private final DataInputStream input;
- private final DataOutputStream output;
- //if an extract is larger than this value, emit it directly;
- //if it is smaller than this value, write it back to the
- //PipesClient so that it can cache the extracts and then batch emit.
- private final long maxForEmitBatchBytes;
- private final long defaultServerParseTimeoutMillis;
- private final long serverWaitTimeoutMillis;
- private final TikaLoader tikaLoader;
- private final MetadataFilter defaultMetadataFilter;
- private final EMIT_STRATEGY emitStrategy;
- private volatile long serverParseTimeoutMillis;
- private Parser autoDetectParser;
- private Parser rMetaParser;
- private FetcherManager fetcherManager;
- private EmitterManager emitterManager;
- private volatile boolean parsing;
- private volatile long since;
-
-
- public PipesServer(Path tikaConfigPath,
- InputStream in, PrintStream out,
- long maxForEmitBatchBytes, long serverParseTimeoutMillis,
- long serverWaitTimeoutMillis) throws TikaConfigException, IOException {
- this.tikaLoader = TikaLoader.load(tikaConfigPath);
- this.defaultMetadataFilter = tikaLoader.loadMetadataFilters();
- this.input = new DataInputStream(in);
- this.output = new DataOutputStream(out);
- this.maxForEmitBatchBytes = maxForEmitBatchBytes;
- this.defaultServerParseTimeoutMillis = serverParseTimeoutMillis;
- this.serverParseTimeoutMillis = serverParseTimeoutMillis;
- this.serverWaitTimeoutMillis = serverWaitTimeoutMillis;
- this.parsing = false;
- this.since = System.currentTimeMillis();
- if (maxForEmitBatchBytes == 0) {
- emitStrategy = EMIT_STRATEGY.EMIT_ALL;
- } else if (maxForEmitBatchBytes < 0) {
- emitStrategy = EMIT_STRATEGY.PASSBACK_ALL;
- } else {
- emitStrategy = EMIT_STRATEGY.DYNAMIC;
- }
- }
-
-
- public static void main(String[] args) throws Exception {
- try {
- Path tikaConfig = Paths.get(args[0]);
- long maxForEmitBatchBytes = Long.parseLong(args[1]);
- long serverParseTimeoutMillis = Long.parseLong(args[2]);
- long serverWaitTimeoutMillis = Long.parseLong(args[3]);
-
- PipesServer server =
- new PipesServer(tikaConfig, System.in, System.out, maxForEmitBatchBytes,
- serverParseTimeoutMillis, serverWaitTimeoutMillis);
- System.setIn(UnsynchronizedByteArrayInputStream.builder().setByteArray(new byte[0]).get());
- System.setOut(System.err);
- Thread watchdog = new Thread(server, "Tika Watchdog");
- watchdog.setDaemon(true);
- watchdog.start();
-
- server.processRequests();
- } finally {
- LOG.info("server shutting down");
- }
- }
-
- @Override
- public void run() {
- try {
- while (true) {
- synchronized (lock) {
- long elapsed = System.currentTimeMillis() - since;
- long timeout = serverParseTimeoutMillis;
- if (parsing && elapsed > timeout) {
- LOG.warn("timeout server; elapsed {}ms with timeout={}", elapsed, timeout);
- exit(TIMEOUT_EXIT_CODE);
- } else if (!parsing && serverWaitTimeoutMillis > 0 &&
- elapsed > serverWaitTimeoutMillis) {
- LOG.info("closing down from inactivity");
- exit(0);
- }
- }
- Thread.sleep(checkForTimeoutMs);
- }
- } catch (InterruptedException e) {
- LOG.debug("interrupted");
- }
- }
-
- public void processRequests() {
- LOG.debug("processing requests");
- //initialize
- try {
- long start = System.currentTimeMillis();
- initializeResources();
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- initialize parser and other resources: {} ms",
- System.currentTimeMillis() - start);
- }
- LOG.debug("pipes server initialized");
- } catch (Throwable t) {
- LOG.error("couldn't initialize parser", t);
- try {
- output.writeByte(STATUS.FAILED_TO_START.getByte());
- output.flush();
- } catch (IOException e) {
- LOG.warn("couldn't notify of failure to start", e);
- }
- return;
- }
- //main loop
- try {
- write(STATUS.READY);
- long start = System.currentTimeMillis();
- while (true) {
- int request = input.read();
- if (request == -1) {
- LOG.warn("received -1 from client; shutting down");
- exit(1);
- } else if (request == STATUS.PING.getByte()) {
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- ping: {} ms", System.currentTimeMillis() - start);
- }
- write(STATUS.PING);
- start = System.currentTimeMillis();
- } else if (request == STATUS.CALL.getByte()) {
- parseOne();
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- parse one: {} ms", System.currentTimeMillis() - start);
- }
- start = System.currentTimeMillis();
- } else {
- throw new IllegalStateException("Unexpected request");
- }
- output.flush();
- }
- } catch (Throwable t) {
- LOG.error("main loop error (did the forking process shut down?)", t);
- exit(1);
- }
- System.err.flush();
- }
-
- private boolean metadataIsEmpty(List<Metadata> metadataList) {
- return metadataList == null || metadataList.size() == 0;
- }
-
- /**
- * returns stack trace if there was a container exception or empty string
- * if there was no stacktrace
- *
- * @param t
- * @param metadataList
- * @return
- */
- private String getContainerStacktrace(FetchEmitTuple t, List<Metadata> metadataList) {
- if (metadataIsEmpty(metadataList)) {
- return StringUtils.EMPTY;
- }
- String stack = metadataList.get(0).get(TikaCoreProperties.CONTAINER_EXCEPTION);
- return (stack != null) ? stack : StringUtils.EMPTY;
- }
-
-
- private void emit(String taskId, EmitKey emitKey,
- boolean isExtractEmbeddedBytes, MetadataListAndEmbeddedBytes parseData,
- String parseExceptionStack, ParseContext parseContext) {
- Emitter emitter = null;
-
- try {
- emitter = emitterManager.getEmitter(emitKey.getEmitterId());
- } catch (IllegalArgumentException e) {
- String noEmitterMsg = getNoEmitterMsg(taskId, emitKey.getEmitterId());
- LOG.warn(noEmitterMsg);
- write(STATUS.EMITTER_NOT_FOUND, noEmitterMsg);
- return;
- }
- try {
- if (isExtractEmbeddedBytes &&
- parseData.toBePackagedForStreamEmitter()) {
- emitContentsAndBytes(emitter, emitKey, parseData);
- } else {
- emitter.emit(emitKey.getEmitKey(), parseData.getMetadataList(), parseContext);
- }
- } catch (IOException e) {
- LOG.warn("emit exception", e);
- String msg = ExceptionUtils.getStackTrace(e);
- byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
- //for now, we're hiding the parse exception if there was also an emit exception
- write(STATUS.EMIT_EXCEPTION, bytes);
- return;
- }
- writeEmitResponse(emitKey, parseData.metadataList, parseExceptionStack, parseContext);
-
- }
-
- private void writeEmitResponse(EmitKey emitKey, List<Metadata> metadataList, String parseExceptionStack, ParseContext parseContext) {
-
- STATUS status = (StringUtils.isBlank(parseExceptionStack)) ? STATUS.EMIT_SUCCESS :
- STATUS.EMIT_SUCCESS_PARSE_EXCEPTION;
- PassbackFilter filter = parseContext.get(PassbackFilter.class);
- LOG.debug("PASSBACK FILTER: {}", filter);
- if (filter == null) {
- if (status == STATUS.EMIT_SUCCESS) {
- write(status);
- } else {
- write(status, parseExceptionStack.getBytes(StandardCharsets.UTF_8));
- }
- return;
- }
- List<Metadata> filtered = null;
- try {
- filtered = filter.filter(metadataList);
- } catch (TikaException e) {
- LOG.error("problem filtering data for passback", e);
- exit(1);
- }
-
- EmitDataImpl filteredEmitDataTuple = new EmitDataImpl(emitKey.getEmitKey(), filtered, parseExceptionStack);
-
- try {
- UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
- try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
- objectOutputStream.writeObject(filteredEmitDataTuple);
- }
- write(STATUS.EMIT_SUCCESS_PASS_BACK, bos.toByteArray());
- } catch (IOException e) {
- LOG.error("problem writing response data (forking process shutdown?)", e);
- exit(1);
- }
-
- }
-
- private void emitContentsAndBytes(Emitter emitter, EmitKey emitKey,
- MetadataListAndEmbeddedBytes parseData) {
- if (!(emitter instanceof StreamEmitter)) {
- throw new IllegalArgumentException("The emitter for embedded document byte store must" +
- " be a StreamEmitter. I see: " + emitter.getClass());
- }
- //TODO: implement this
- throw new UnsupportedOperationException("this is not yet implemented");
- }
-
- private void parseOne() {
- synchronized (lock) {
- parsing = true;
- since = System.currentTimeMillis();
- }
- FetchEmitTuple t = null;
- try {
- long start = System.currentTimeMillis();
- t = readFetchEmitTuple();
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- read fetchEmitTuple: {} ms",
- System.currentTimeMillis() - start);
- }
- start = System.currentTimeMillis();
- updateTimeout(t);
- actuallyParse(t);
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- actually parsed: {} ms", System.currentTimeMillis() - start);
- }
- } catch (OutOfMemoryError e) {
- handleOOM(t.getId(), e);
- } finally {
- synchronized (lock) {
- parsing = false;
- since = System.currentTimeMillis();
- serverParseTimeoutMillis = defaultServerParseTimeoutMillis;
- }
- }
- }
-
- private void updateTimeout(FetchEmitTuple t) {
- if (t == null) {
- return;
- }
-
- ParseContext parseContext = t.getParseContext();
- if (parseContext == null) {
- return;
- }
-
- TikaTaskTimeout tikaTaskTimeout = parseContext.get(TikaTaskTimeout.class);
- if (tikaTaskTimeout == null) {
- return;
- }
-
- synchronized (lock) {
- serverParseTimeoutMillis = tikaTaskTimeout.getTimeoutMillis();
- LOG.debug("setting per file timeout {}ms", serverParseTimeoutMillis);
- }
- }
-
- private void actuallyParse(FetchEmitTuple t) {
-
- long start = System.currentTimeMillis();
- Fetcher fetcher = getFetcher(t);
- if (fetcher == null) {
- //rely on proper logging/exception handling in getFetcher
- return;
- }
-
- if (LOG.isTraceEnabled()) {
- long elapsed = System.currentTimeMillis() - start;
- LOG.trace("timer -- got fetcher: {}ms", elapsed);
- }
-
- start = System.currentTimeMillis();
- MetadataListAndEmbeddedBytes parseData = null;
-
- try {
- //this can be null if there is a fetch exception
- parseData = parseFromTuple(t, fetcher);
-
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- to parse: {} ms", System.currentTimeMillis() - start);
- }
-
- if (parseData == null || metadataIsEmpty(parseData.getMetadataList())) {
- write(STATUS.EMPTY_OUTPUT);
- return;
- }
-
- emitParseData(t, parseData);
- } finally {
- if (parseData != null && parseData.hasEmbeddedDocumentByteStore() &&
- parseData.getEmbeddedDocumentBytesHandler() instanceof Closeable) {
- try {
- ((Closeable) parseData.getEmbeddedDocumentBytesHandler()).close();
- } catch (IOException e) {
- LOG.warn("problem closing embedded document byte store", e);
- }
- }
- }
- }
-
- private void emitParseData(FetchEmitTuple t, MetadataListAndEmbeddedBytes parseData) {
- long start = System.currentTimeMillis();
- String stack = getContainerStacktrace(t, parseData.getMetadataList());
- //we need to apply the metadata filter after we pull out the stacktrace
- filterMetadata(t, parseData);
- ParseContext parseContext = t.getParseContext();
- FetchEmitTuple.ON_PARSE_EXCEPTION onParseException = t.getOnParseException();
- EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig = parseContext.get(EmbeddedDocumentBytesConfig.class);
- if (StringUtils.isBlank(stack) ||
- onParseException == FetchEmitTuple.ON_PARSE_EXCEPTION.EMIT) {
- injectUserMetadata(t.getMetadata(), parseData.getMetadataList());
- EmitKey emitKey = t.getEmitKey();
- if (StringUtils.isBlank(emitKey.getEmitKey())) {
- emitKey = new EmitKey(emitKey.getEmitterId(), t.getFetchKey().getFetchKey());
- t.setEmitKey(emitKey);
- }
- EmitDataImpl emitDataTuple = new EmitDataImpl(t.getEmitKey().getEmitKey(), parseData.getMetadataList(), stack);
- if (shouldEmit(embeddedDocumentBytesConfig, parseData, emitDataTuple)) {
- emit(t.getId(), emitKey, embeddedDocumentBytesConfig.isExtractEmbeddedDocumentBytes(),
- parseData, stack, parseContext);
- } else {
- //send back to the client
- write(emitDataTuple);
- }
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- emitted: {} ms", System.currentTimeMillis() - start);
- }
- } else {
- write(STATUS.PARSE_EXCEPTION_NO_EMIT, stack);
- }
- }
-
- private boolean shouldEmit(EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig, MetadataListAndEmbeddedBytes parseData, EmitDataImpl emitDataTuple) {
- if (emitStrategy == EMIT_STRATEGY.EMIT_ALL) {
- return true;
- } else if (embeddedDocumentBytesConfig.isExtractEmbeddedDocumentBytes() &&
- parseData.toBePackagedForStreamEmitter()) {
- return true;
- } else if (emitStrategy == EMIT_STRATEGY.PASSBACK_ALL) {
- return false;
- } else if (emitStrategy == EMIT_STRATEGY.DYNAMIC) {
- if (emitDataTuple.getEstimatedSizeBytes() >= maxForEmitBatchBytes) {
- return true;
- }
- }
- return false;
- }
-
- private void filterMetadata(FetchEmitTuple t, MetadataListAndEmbeddedBytes parseData) {
- MetadataFilter filter = t.getParseContext().get(MetadataFilter.class);
- if (filter == null) {
- filter = defaultMetadataFilter;
- }
- if (filter instanceof NoOpFilter) {
- return;
- }
- try {
- parseData.filter(filter);
- } catch (TikaException e) {
- LOG.warn("failed to filter metadata list", e);
- }
- }
-
- private Fetcher getFetcher(FetchEmitTuple t) {
- try {
- return fetcherManager.getFetcher(t.getFetchKey().getFetcherId());
- } catch (IllegalArgumentException e) {
- String noFetcherMsg = getNoFetcherMsg(t.getFetchKey().getFetcherId());
- LOG.warn(noFetcherMsg);
- write(STATUS.FETCHER_NOT_FOUND, noFetcherMsg);
- return null;
- } catch (IOException | TikaException e) {
- LOG.warn("Couldn't initialize fetcher for fetch id '" + t.getId() + "'", e);
- write(STATUS.FETCHER_INITIALIZATION_EXCEPTION, ExceptionUtils.getStackTrace(e));
- return null;
- }
- }
-
- protected MetadataListAndEmbeddedBytes parseFromTuple(FetchEmitTuple t, Fetcher fetcher) {
-
- Metadata metadata = new Metadata();
- try (InputStream stream = fetcher.fetch(t.getFetchKey().getFetchKey(), metadata, t.getParseContext())) {
- return parseWithStream(t, stream, metadata);
- } catch (SecurityException e) {
- LOG.error("security exception " + t.getId(), e);
- throw e;
- } catch (TikaException | IOException e) {
- LOG.warn("fetch exception " + t.getId(), e);
- write(STATUS.FETCH_EXCEPTION, ExceptionUtils.getStackTrace(e));
- }
-
- return null;
- }
-
- private String getNoFetcherMsg(String fetcherId) {
- StringBuilder sb = new StringBuilder();
- sb.append("Fetcher '").append(fetcherId).append("'");
- sb.append(" not found.");
- sb.append("\nThe configured FetcherManager supports:");
- int i = 0;
- for (String f : fetcherManager.getSupported()) {
- if (i++ > 0) {
- sb.append(", ");
- }
- sb.append(f);
- }
- return sb.toString();
- }
-
- private String getNoEmitterMsg(String taskName, String emitterName) {
- StringBuilder sb = new StringBuilder();
- sb.append("Emitter for task='").append(taskName).append("' emitter='").append(emitterName).append("'");
- sb.append(" not found.");
- sb.append("\nThe configured emitterManager supports:");
- int i = 0;
- for (String e : emitterManager.getSupported()) {
- if (i++ > 0) {
- sb.append(", ");
- }
- sb.append(e);
- }
- return sb.toString();
- }
-
-
- private void handleOOM(String taskId, OutOfMemoryError oom) {
- write(STATUS.OOM);
- LOG.error("oom: " + taskId, oom);
- exit(1);
- }
-
- private MetadataListAndEmbeddedBytes parseWithStream(FetchEmitTuple fetchEmitTuple,
- InputStream stream, Metadata metadata)
- throws TikaConfigException {
-
- List<Metadata> metadataList;
- //this adds the EmbeddedDocumentByteStore to the parsecontext
- ParseContext parseContext = setupParseContext(fetchEmitTuple);
- HandlerConfig handlerConfig = parseContext.get(HandlerConfig.class);
- if (handlerConfig.getParseMode() == HandlerConfig.PARSE_MODE.RMETA) {
- metadataList =
- parseRecursive(fetchEmitTuple, handlerConfig, stream, metadata, parseContext);
- } else {
- metadataList = parseConcatenated(fetchEmitTuple, handlerConfig, stream, metadata,
- parseContext);
- }
-
- return new MetadataListAndEmbeddedBytes(metadataList,
- parseContext.get(EmbeddedDocumentBytesHandler.class));
- }
-
- private ParseContext setupParseContext(FetchEmitTuple fetchEmitTuple)
- throws TikaConfigException {
- ParseContext parseContext = fetchEmitTuple.getParseContext();
- if (parseContext.get(HandlerConfig.class) == null) {
- parseContext.set(HandlerConfig.class, DEFAULT_HANDLER_CONFIG);
- }
- EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig = parseContext.get(EmbeddedDocumentBytesConfig.class);
- if (embeddedDocumentBytesConfig == null) {
- //make sure there's one here -- or do we make this default in fetchemit tuple?
- parseContext.set(EmbeddedDocumentBytesConfig.class, EmbeddedDocumentBytesConfig.SKIP);
- return parseContext;
- }
- EmbeddedDocumentExtractorFactory factory = ((AutoDetectParser)autoDetectParser)
- .getAutoDetectParserConfig().getEmbeddedDocumentExtractorFactory();
- if (factory == null) {
- parseContext.set(EmbeddedDocumentExtractor.class, new RUnpackExtractor(parseContext,
- RUnpackExtractorFactory.DEFAULT_MAX_EMBEDDED_BYTES_FOR_EXTRACTION));
- } else {
- if (! (factory instanceof EmbeddedDocumentByteStoreExtractorFactory)) {
- throw new TikaConfigException("EmbeddedDocumentExtractorFactory must be an " +
- "instance of EmbeddedDocumentByteStoreExtractorFactory if you want" +
- "to extract embedded bytes! I see this embedded doc factory: " +
- factory.getClass() + "and a request: " +
- embeddedDocumentBytesConfig);
- }
- }
- //TODO: especially clean this up.
- if (!StringUtils.isBlank(embeddedDocumentBytesConfig.getEmitter())) {
- parseContext.set(EmbeddedDocumentBytesHandler.class,
- new EmittingEmbeddedDocumentBytesHandler(fetchEmitTuple, emitterManager));
- } else {
- parseContext.set(EmbeddedDocumentBytesHandler.class,
- new BasicEmbeddedDocumentBytesHandler(embeddedDocumentBytesConfig));
- }
- return parseContext;
- }
-
- private List<Metadata> parseConcatenated(FetchEmitTuple fetchEmitTuple,
- HandlerConfig handlerConfig, InputStream stream,
- Metadata metadata, ParseContext parseContext) {
-
- ContentHandlerFactory contentHandlerFactory =
- new BasicContentHandlerFactory(handlerConfig.getType(),
- handlerConfig.getWriteLimit(), handlerConfig.isThrowOnWriteLimitReached(),
- parseContext);
-
- ContentHandler handler = contentHandlerFactory.getNewContentHandler();
- parseContext.set(DocumentSelector.class, new DocumentSelector() {
- final int maxEmbedded = handlerConfig.getMaxEmbeddedResources();
- int embedded = 0;
-
- @Override
- public boolean select(Metadata metadata) {
- if (maxEmbedded < 0) {
- return true;
- }
- return embedded++ < maxEmbedded;
- }
- });
-
- String containerException = null;
- long start = System.currentTimeMillis();
- preParse(fetchEmitTuple, stream, metadata, parseContext);
- try {
- autoDetectParser.parse(stream, handler, metadata, parseContext);
- } catch (SAXException e) {
- containerException = ExceptionUtils.getStackTrace(e);
- LOG.warn("sax problem:" + fetchEmitTuple.getId(), e);
- } catch (EncryptedDocumentException e) {
- containerException = ExceptionUtils.getStackTrace(e);
- LOG.warn("encrypted document:" + fetchEmitTuple.getId(), e);
- } catch (SecurityException e) {
- LOG.warn("security exception:" + fetchEmitTuple.getId(), e);
- throw e;
- } catch (Exception e) {
- containerException = ExceptionUtils.getStackTrace(e);
- LOG.warn("parse exception: " + fetchEmitTuple.getId(), e);
- } finally {
- metadata.add(TikaCoreProperties.TIKA_CONTENT, handler.toString());
- if (containerException != null) {
- metadata.add(TikaCoreProperties.CONTAINER_EXCEPTION, containerException);
- }
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- parse only time: {} ms", System.currentTimeMillis() - start);
- }
- }
- return Collections.singletonList(metadata);
- }
-
- private List<Metadata> parseRecursive(FetchEmitTuple fetchEmitTuple,
- HandlerConfig handlerConfig, InputStream stream,
- Metadata metadata, ParseContext parseContext) {
- //Intentionally do not add the metadata filter here!
- //We need to let stacktraces percolate
- RecursiveParserWrapperHandler handler = new RecursiveParserWrapperHandler(
- new BasicContentHandlerFactory(handlerConfig.getType(),
- handlerConfig.getWriteLimit(), handlerConfig.isThrowOnWriteLimitReached(),
- parseContext), handlerConfig.getMaxEmbeddedResources());
-
- long start = System.currentTimeMillis();
-
- preParse(fetchEmitTuple, stream, metadata, parseContext);
- try {
- rMetaParser.parse(stream, handler, metadata, parseContext);
- } catch (SAXException e) {
- LOG.warn("sax problem:" + fetchEmitTuple.getId(), e);
- } catch (EncryptedDocumentException e) {
- LOG.warn("encrypted document:" + fetchEmitTuple.getId(), e);
- } catch (SecurityException e) {
- LOG.warn("security exception:" + fetchEmitTuple.getId(), e);
- throw e;
- } catch (Exception e) {
- LOG.warn("parse exception: " + fetchEmitTuple.getId(), e);
- } finally {
- if (LOG.isTraceEnabled()) {
- LOG.trace("timer -- parse only time: {} ms", System.currentTimeMillis() - start);
- }
- }
- return handler.getMetadataList();
- }
-
- private void preParse(FetchEmitTuple t, InputStream stream, Metadata metadata,
- ParseContext parseContext) {
- TemporaryResources tmp = null;
- try {
- TikaInputStream tis = TikaInputStream.cast(stream);
- if (tis == null) {
- tis = TikaInputStream.get(stream, tmp, metadata);
- }
- _preParse(t, tis, metadata, parseContext);
- } finally {
- IOUtils.closeQuietly(tmp);
- }
- //do we want to filter the metadata to digest, length, content-type?
- writeIntermediate(t.getEmitKey(), metadata);
- }
-
- private void _preParse(FetchEmitTuple t, TikaInputStream tis, Metadata metadata,
- ParseContext parseContext) {
- if (digester != null) {
- try {
- digester.digest(tis, metadata, parseContext);
- } catch (IOException e) {
- LOG.warn("problem digesting: " + t.getId(), e);
- }
- }
- try {
- MediaType mt = detector.detect(tis, metadata);
- metadata.set(Metadata.CONTENT_TYPE, mt.toString());
- metadata.set(TikaCoreProperties.CONTENT_TYPE_PARSER_OVERRIDE, mt.toString());
- } catch (IOException e) {
- LOG.warn("problem detecting: " + t.getId(), e);
- }
- EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig = parseContext.get(EmbeddedDocumentBytesConfig.class);
- if (embeddedDocumentBytesConfig != null &&
- embeddedDocumentBytesConfig.isIncludeOriginal()) {
- EmbeddedDocumentBytesHandler embeddedDocumentByteStore = parseContext.get(EmbeddedDocumentBytesHandler.class);
- try (InputStream is = Files.newInputStream(tis.getPath())) {
- embeddedDocumentByteStore.add(0, metadata, is);
- } catch (IOException e) {
- LOG.warn("problem reading source file into embedded document byte store", e);
- }
- }
- }
-
- private void injectUserMetadata(Metadata userMetadata, List<Metadata> metadataList) {
- for (String n : userMetadata.names()) {
- //overwrite whatever was there
- metadataList.get(0).set(n, null);
- for (String val : userMetadata.getValues(n)) {
- metadataList.get(0).add(n, val);
- }
- }
- }
-
- private void exit(int exitCode) {
- if (exitCode != 0) {
- LOG.error("exiting: {}", exitCode);
- } else {
- LOG.info("exiting: {}", exitCode);
- }
- System.exit(exitCode);
- }
-
-
- private FetchEmitTuple readFetchEmitTuple() {
- try {
- int length = input.readInt();
- byte[] bytes = new byte[length];
- input.readFully(bytes);
- try (ObjectInputStream objectInputStream = new ObjectInputStream(
- UnsynchronizedByteArrayInputStream.builder().setByteArray(bytes).get())) {
- return (FetchEmitTuple) objectInputStream.readObject();
- }
- } catch (IOException e) {
- LOG.error("problem reading tuple", e);
- exit(1);
- } catch (ClassNotFoundException e) {
- LOG.error("can't find class?!", e);
- exit(1);
- }
- //unreachable, no?!
- return null;
- }
-
- protected void initializeResources() throws TikaException, IOException, SAXException {
-
- TikaJsonConfig tikaJsonConfig = tikaLoader.getConfig();
- TikaPluginManager tikaPluginManager = TikaPluginManager.load(tikaJsonConfig);
-
- //TODO allowed named configurations in tika config
- this.fetcherManager = FetcherManager.load(tikaPluginManager, tikaJsonConfig);
- //skip initialization of the emitters if emitting
- //from the pipesserver is turned off.
- if (maxForEmitBatchBytes > -1) {
- this.emitterManager = EmitterManager.load(tikaPluginManager, tikaJsonConfig);
- } else {
- LOG.debug("'maxForEmitBatchBytes' < 0. Not initializing emitters in PipesServer");
- this.emitterManager = null;
- }
- this.autoDetectParser = tikaLoader.loadAutoDetectParser();
- if (((AutoDetectParser) autoDetectParser).getAutoDetectParserConfig()
- .getDigesterFactory() != null) {
- this.digester = ((AutoDetectParser) autoDetectParser).getAutoDetectParserConfig()
- .getDigesterFactory().build();
- //override this value because we'll be digesting before parse
- ((AutoDetectParser) autoDetectParser).getAutoDetectParserConfig().getDigesterFactory()
- .setSkipContainerDocument(true);
- //if the user hasn't configured an embedded document extractor, set up the
- // RUnpackExtractorFactory
- if (((AutoDetectParser) autoDetectParser).getAutoDetectParserConfig()
- .getEmbeddedDocumentExtractorFactory() == null) {
- ((AutoDetectParser) autoDetectParser)
- .getAutoDetectParserConfig().setEmbeddedDocumentExtractorFactory(
- new RUnpackExtractorFactory());
- }
- }
- this.detector = ((AutoDetectParser) this.autoDetectParser).getDetector();
- this.rMetaParser = new RecursiveParserWrapper(autoDetectParser);
- }
-
-
- private void writeIntermediate(EmitKey emitKey, Metadata metadata) {
- try {
- UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
- try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
- objectOutputStream.writeObject(metadata);
- }
- write(STATUS.INTERMEDIATE_RESULT, bos.toByteArray());
- } catch (IOException e) {
- LOG.error("problem writing intermediate data (forking process shutdown?)", e);
- exit(1);
- }
- }
-
- private void write(EmitDataImpl emitData) {
- try {
- UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
- try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
- objectOutputStream.writeObject(emitData);
- }
- write(STATUS.PARSE_SUCCESS, bos.toByteArray());
- } catch (IOException e) {
- LOG.error("problem writing emit data (forking process shutdown?)", e);
- exit(1);
- }
- }
-
- private void write(STATUS status, String msg) {
- byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
- write(status, bytes);
- }
-
- private void write(STATUS status, byte[] bytes) {
- try {
- int len = bytes.length;
- output.write(status.getByte());
- output.writeInt(len);
- output.write(bytes);
- output.flush();
- } catch (IOException e) {
- LOG.error("problem writing data (forking process shutdown?)", e);
- exit(1);
- }
- }
-
- private void write(STATUS status) {
- try {
- output.write(status.getByte());
- output.flush();
- } catch (IOException e) {
- LOG.error("problem writing data (forking process shutdown?)", e);
- exit(1);
- }
- }
-
- static class MetadataListAndEmbeddedBytes {
-
- List<Metadata> metadataList;
- final Optional<EmbeddedDocumentBytesHandler> embeddedDocumentBytesHandler;
-
- public MetadataListAndEmbeddedBytes(List<Metadata> metadataList,
- EmbeddedDocumentBytesHandler embeddedDocumentBytesHandler) {
- this.metadataList = metadataList;
- this.embeddedDocumentBytesHandler = Optional.ofNullable(embeddedDocumentBytesHandler);
- }
-
- public List<Metadata> getMetadataList() {
- return metadataList;
- }
-
- public void filter(MetadataFilter filter) throws TikaException {
- metadataList = filter.filter(metadataList);
- }
-
- public EmbeddedDocumentBytesHandler getEmbeddedDocumentBytesHandler() {
- return embeddedDocumentBytesHandler.get();
- }
-
- /**
- * This tests whether there's any type of embedded document store
- * ...that, for example, may require closing at the end of the parse.
- *
- * @return
- */
- public boolean hasEmbeddedDocumentByteStore() {
- return embeddedDocumentBytesHandler.isPresent();
- }
-
- /**
- * If the intent is that the metadata and byte store be packaged in a zip
- * or similar and emitted via a single stream emitter.
- * <p>
- * This is basically a test that this is not an EmbeddedDocumentEmitterStore.
- *
- * @return
- */
- public boolean toBePackagedForStreamEmitter() {
- return !(embeddedDocumentBytesHandler.get() instanceof EmittingEmbeddedDocumentBytesHandler);
- }
- }
-}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/ServerInitializationException.java
similarity index 65%
copy from tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java
copy to tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/ServerInitializationException.java
index 949bb81e8..ea1025210 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/ServerInitializationException.java
@@ -16,12 +16,19 @@
*/
package org.apache.tika.pipes.core;
+import java.io.IOException;
+
/**
- * This should be catastrophic
+ * Exception thrown when the PipesServer fails to initialize.
+ * This indicates a configuration or resource loading problem that
+ * prevents the server from starting.
*/
-public class FailedToStartClientException extends RuntimeException {
+public class ServerInitializationException extends IOException {
+ public ServerInitializationException(String message) {
+ super(message);
+ }
- public FailedToStartClientException(Throwable t) {
- super(t);
+ public ServerInitializationException(String message, Throwable cause) {
+ super(message, cause);
}
}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/async/AsyncProcessor.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/async/AsyncProcessor.java
index a83387a42..abb9915b6 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/async/AsyncProcessor.java
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/async/AsyncProcessor.java
@@ -84,7 +84,7 @@ public class AsyncProcessor implements Closeable {
TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
TikaPluginManager tikaPluginManager = TikaPluginManager.load(tikaJsonConfig);
MetadataFilter metadataFilter = TikaLoader.load(tikaConfigPath).loadMetadataFilters();
- this.asyncConfig = PipesConfig.load(tikaJsonConfig);
+ this.asyncConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
this.pipesReporter = ReporterManager.load(tikaPluginManager, tikaJsonConfig);
LOG.debug("loaded reporter {}", pipesReporter.getClass());
this.fetchEmitTuples = new ArrayBlockingQueue<>(asyncConfig.getQueueSize());
@@ -95,11 +95,11 @@ public class AsyncProcessor implements Closeable {
this.executorCompletionService =
new ExecutorCompletionService<>(executorService);
try {
- if (asyncConfig.getTikaConfig() != null && !tikaConfigPath.toAbsolutePath().equals(asyncConfig.getTikaConfigPath().toAbsolutePath())) {
+ if (asyncConfig.getTikaConfigPath() != null && !tikaConfigPath.toAbsolutePath().equals(asyncConfig.getTikaConfigPath())) {
LOG.warn("TikaConfig for AsyncProcessor ({}) is different " +
"from TikaConfig for workers ({}). If this is intended," +
" please ignore this warning.", tikaConfigPath.toAbsolutePath(),
- asyncConfig.getTikaConfigPath().toAbsolutePath());
+ asyncConfig.getTikaConfigPath());
}
this.executorCompletionService.submit(() -> {
while (true) {
@@ -338,11 +338,11 @@ public class AsyncProcessor implements Closeable {
private boolean shouldEmit(PipesResult result) {
- if (result.status() == PipesResult.STATUS.PARSE_SUCCESS ||
- result.status() == PipesResult.STATUS.PARSE_SUCCESS_WITH_EXCEPTION) {
+ if (result.status() == PipesResult.RESULT_STATUS.PARSE_SUCCESS ||
+ result.status() == PipesResult.RESULT_STATUS.PARSE_SUCCESS_WITH_EXCEPTION) {
return true;
}
- return result.intermediate() && asyncConfig.isEmitIntermediateResults();
+ return asyncConfig.isEmitIntermediateResults() && (result.isApplicationError() || result.isProcessCrash());
}
}
}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/EmitHandler.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/EmitHandler.java
new file mode 100644
index 000000000..37c504ff4
--- /dev/null
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/EmitHandler.java
@@ -0,0 +1,217 @@
+/*
+ * 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.
+ */
+package org.apache.tika.pipes.core.server;
+
+
+import static org.apache.tika.pipes.core.server.PipesWorker.metadataIsEmpty;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
+import org.apache.tika.metadata.filter.MetadataFilter;
+import org.apache.tika.metadata.filter.NoOpFilter;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.pipes.api.FetchEmitTuple;
+import org.apache.tika.pipes.api.PipesResult;
+import org.apache.tika.pipes.api.emitter.EmitKey;
+import org.apache.tika.pipes.api.emitter.Emitter;
+import org.apache.tika.pipes.api.emitter.StreamEmitter;
+import org.apache.tika.pipes.core.PassbackFilter;
+import org.apache.tika.pipes.core.emitter.EmitDataImpl;
+import org.apache.tika.pipes.core.emitter.EmitterManager;
+import org.apache.tika.pipes.core.extractor.EmbeddedDocumentBytesConfig;
+import org.apache.tika.utils.ExceptionUtils;
+import org.apache.tika.utils.StringUtils;
+
+class EmitHandler {
+
+ private static final Logger LOG = LoggerFactory.getLogger(EmitHandler.class);
+
+ private final MetadataFilter defaultMetadataFilter;
+ private final PipesWorker.EMIT_STRATEGY emitStrategy;
+ private final EmitterManager emitterManager;
+ private final long directEmitThresholdBytes;
+
+
+ public EmitHandler(MetadataFilter defaultMetadataFilter, PipesWorker.EMIT_STRATEGY emitStrategy, EmitterManager emitterManager, long directEmitThresholdBytes) {
+ this.defaultMetadataFilter = defaultMetadataFilter;
+ this.emitStrategy = emitStrategy;
+ this.emitterManager = emitterManager;
+ this.directEmitThresholdBytes = directEmitThresholdBytes;
+ }
+
+ public PipesResult emitParseData(FetchEmitTuple t, MetadataListAndEmbeddedBytes parseData) {
+ long start = System.currentTimeMillis();
+ String stack = getContainerStacktrace(t, parseData.getMetadataList());
+ //we need to apply the metadata filter after we pull out the stacktrace
+ filterMetadata(t, parseData);
+ ParseContext parseContext = t.getParseContext();
+ FetchEmitTuple.ON_PARSE_EXCEPTION onParseException = t.getOnParseException();
+ EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig = parseContext.get(EmbeddedDocumentBytesConfig.class);
+ if (StringUtils.isBlank(stack) ||
+ onParseException == FetchEmitTuple.ON_PARSE_EXCEPTION.EMIT) {
+ injectUserMetadata(t.getMetadata(), parseData.getMetadataList());
+ EmitKey emitKey = t.getEmitKey();
+ if (StringUtils.isBlank(emitKey.getEmitKey())) {
+ emitKey = new EmitKey(emitKey.getEmitterId(), t.getFetchKey().getFetchKey());
+ t.setEmitKey(emitKey);
+ }
+ EmitDataImpl emitDataTuple = new EmitDataImpl(t.getEmitKey().getEmitKey(), parseData.getMetadataList(), stack);
+ if (shouldEmit(embeddedDocumentBytesConfig, parseData, emitDataTuple)) {
+ return emit(t.getId(), emitKey, embeddedDocumentBytesConfig.isExtractEmbeddedDocumentBytes(),
+ parseData, stack, parseContext);
+ } else {
+ if (StringUtils.isBlank(stack)) {
+ return new PipesResult(PipesResult.RESULT_STATUS.PARSE_SUCCESS, emitDataTuple);
+ } else {
+ return new PipesResult(PipesResult.RESULT_STATUS.PARSE_SUCCESS_WITH_EXCEPTION, emitDataTuple);
+ }
+ }
+ } else {
+ return new PipesResult(PipesResult.RESULT_STATUS.PARSE_EXCEPTION_NO_EMIT, stack);
+ }
+ }
+
+ private PipesResult emit(String taskId, EmitKey emitKey,
+ boolean isExtractEmbeddedBytes, MetadataListAndEmbeddedBytes parseData,
+ String parseExceptionStack, ParseContext parseContext) {
+ Emitter emitter = null;
+
+ try {
+ emitter = emitterManager.getEmitter(emitKey.getEmitterId());
+ } catch (IllegalArgumentException e) {
+ String noEmitterMsg = getNoEmitterMsg(taskId);
+ LOG.warn(noEmitterMsg);
+ return new PipesResult(PipesResult.RESULT_STATUS.EMITTER_NOT_FOUND, noEmitterMsg);
+ }
+ try {
+ if (isExtractEmbeddedBytes &&
+ parseData.toBePackagedForStreamEmitter()) {
+ emitContentsAndBytes(emitter, emitKey, parseData);
+ } else {
+ emitter.emit(emitKey.getEmitKey(), parseData.getMetadataList(), parseContext);
+ }
+ } catch (IOException e) {
+ LOG.warn("emit exception", e);
+ String msg = ExceptionUtils.getStackTrace(e);
+ //for now, we're hiding the parse exception if there was also an emit exception
+ return new PipesResult(PipesResult.RESULT_STATUS.EMIT_EXCEPTION, msg);
+ }
+ PassbackFilter passbackFilter = parseContext.get(PassbackFilter.class);
+ if (passbackFilter != null) {
+ List<Metadata> filtered = null;
+ try {
+ filtered = passbackFilter.filter(parseData.metadataList);
+ } catch (TikaException e) {
+ LOG.warn("problem filtering for pass back", e);
+ }
+ if (StringUtils.isBlank(parseExceptionStack)) {
+ return new PipesResult(PipesResult.RESULT_STATUS.EMIT_SUCCESS_PASSBACK, new EmitDataImpl(emitKey.getEmitKey(), filtered));
+ } else {
+ return new PipesResult(PipesResult.RESULT_STATUS.EMIT_SUCCESS_PARSE_EXCEPTION, new EmitDataImpl(emitKey.getEmitKey(), filtered), parseExceptionStack);
+ }
+
+ }
+ if (StringUtils.isBlank(parseExceptionStack)) {
+ return new PipesResult(PipesResult.RESULT_STATUS.EMIT_SUCCESS);
+ } else {
+ return new PipesResult(PipesResult.RESULT_STATUS.EMIT_SUCCESS_PARSE_EXCEPTION, parseExceptionStack);
+ }
+ }
+
+ private void emitContentsAndBytes(Emitter emitter, EmitKey emitKey,
+ MetadataListAndEmbeddedBytes parseData) {
+ if (!(emitter instanceof StreamEmitter)) {
+ throw new IllegalArgumentException("The emitter for embedded document byte store must" +
+ " be a StreamEmitter. I see: " + emitter.getClass());
+ }
+ //TODO: implement this
+ throw new UnsupportedOperationException("this is not yet implemented");
+ }
+
+
+ private boolean shouldEmit(EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig, MetadataListAndEmbeddedBytes parseData, EmitDataImpl emitDataTuple) {
+ if (emitStrategy == PipesWorker.EMIT_STRATEGY.EMIT_ALL) {
+ return true;
+ } else if (embeddedDocumentBytesConfig.isExtractEmbeddedDocumentBytes() &&
+ parseData.toBePackagedForStreamEmitter()) {
+ return true;
+ } else if (emitStrategy == PipesWorker.EMIT_STRATEGY.PASSBACK_ALL) {
+ return false;
+ } else if (emitStrategy == PipesWorker.EMIT_STRATEGY.DYNAMIC) {
+ if (emitDataTuple.getEstimatedSizeBytes() >= directEmitThresholdBytes) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static String getContainerStacktrace(FetchEmitTuple t, List<Metadata> metadataList) {
+ if (metadataIsEmpty(metadataList)) {
+ return StringUtils.EMPTY;
+ }
+ String stack = metadataList.get(0).get(TikaCoreProperties.CONTAINER_EXCEPTION);
+ return (stack != null) ? stack : StringUtils.EMPTY;
+ }
+
+ private void injectUserMetadata(Metadata userMetadata, List<Metadata> metadataList) {
+ for (String n : userMetadata.names()) {
+ //overwrite whatever was there
+ metadataList.get(0).set(n, null);
+ for (String val : userMetadata.getValues(n)) {
+ metadataList.get(0).add(n, val);
+ }
+ }
+ }
+
+ private void filterMetadata(FetchEmitTuple t, MetadataListAndEmbeddedBytes parseData) {
+ MetadataFilter filter = t.getParseContext().get(MetadataFilter.class);
+ if (filter == null) {
+ filter = defaultMetadataFilter;
+ }
+ if (filter instanceof NoOpFilter) {
+ return;
+ }
+ try {
+ parseData.filter(filter);
+ } catch (TikaException e) {
+ LOG.warn("failed to filter metadata list", e);
+ }
+ }
+
+ private String getNoEmitterMsg(String emitterName) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Emitter '").append(emitterName).append("'");
+ sb.append(" not found.");
+ sb.append("\nThe configured emitterManager supports:");
+ int i = 0;
+ for (String e : emitterManager.getSupported()) {
+ if (i++ > 0) {
+ sb.append(", ");
+ }
+ sb.append(e);
+ }
+ return sb.toString();
+ }
+
+}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/FetchHandler.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/FetchHandler.java
new file mode 100644
index 000000000..3fa02b636
--- /dev/null
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/FetchHandler.java
@@ -0,0 +1,101 @@
+/*
+ * 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.
+ */
+package org.apache.tika.pipes.core.server;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.pipes.api.FetchEmitTuple;
+import org.apache.tika.pipes.api.PipesResult;
+import org.apache.tika.pipes.api.fetcher.Fetcher;
+import org.apache.tika.pipes.core.fetcher.FetcherManager;
+import org.apache.tika.utils.ExceptionUtils;
+
+class FetchHandler {
+
+ private static final Logger LOG = LoggerFactory.getLogger(FetchHandler.class);
+
+ private final FetcherManager fetcherManager;
+
+ public FetchHandler(FetcherManager fetcherManager) {
+ this.fetcherManager = fetcherManager;
+ }
+
+ public TisOrResult fetch(FetchEmitTuple fetchEmitTuple, Metadata metadata) {
+ FetcherOrResult fetcherResult = getFetcher(fetchEmitTuple);
+ if (fetcherResult.pipesResult != null) {
+ return new TisOrResult(null, fetcherResult.pipesResult);
+ }
+ InputStream is = null;
+ try {
+ is = fetcherResult.fetcher.fetch(
+ fetchEmitTuple.getFetchKey().getFetchKey(), metadata, fetchEmitTuple.getParseContext());
+ } catch (IOException | TikaException e) {
+ return new TisOrResult(null, new PipesResult(PipesResult.RESULT_STATUS.FETCH_EXCEPTION, ExceptionUtils.getStackTrace(e)));
+ }
+
+ TikaInputStream tis = TikaInputStream.cast(is);
+ if (tis == null) {
+ return new TisOrResult(TikaInputStream.get(is), null);
+ }
+ return new TisOrResult(tis, null);
+ }
+
+ private FetcherOrResult getFetcher(FetchEmitTuple t) {
+ try {
+ return new FetcherOrResult(fetcherManager.getFetcher(t.getFetchKey().getFetcherId()), null);
+ } catch (IllegalArgumentException e) {
+ String noFetcherMsg = getNoFetcherMsg(t.getFetchKey().getFetcherId());
+ LOG.warn(noFetcherMsg);
+ return new FetcherOrResult(null, new PipesResult(PipesResult.RESULT_STATUS.FETCHER_NOT_FOUND, noFetcherMsg));
+ } catch (IOException | TikaException e) {
+ LOG.warn("Couldn't initialize fetcher for fetch id={}", t.getId(), e);
+ return new FetcherOrResult(null, new PipesResult(PipesResult.RESULT_STATUS.FETCHER_INITIALIZATION_EXCEPTION,
+ ExceptionUtils.getStackTrace(e)));
+ }
+ }
+
+
+ private String getNoFetcherMsg(String fetcherId) {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Fetcher '").append(fetcherId).append("'");
+ sb.append(" not found.");
+ sb.append("\nThe configured FetcherManager supports:");
+ int i = 0;
+ for (String f : fetcherManager.getSupported()) {
+ if (i++ > 0) {
+ sb.append(", ");
+ }
+ sb.append(f);
+ }
+ return sb.toString();
+ }
+
+ private record FetcherOrResult(Fetcher fetcher, PipesResult pipesResult) {
+
+ }
+
+ record TisOrResult(TikaInputStream tis, PipesResult pipesResult) {
+
+ }
+}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/IntermediateResult.java
similarity index 68%
copy from tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java
copy to tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/IntermediateResult.java
index 949bb81e8..73460f3ee 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/IntermediateResult.java
@@ -14,14 +14,21 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.tika.pipes.core;
+package org.apache.tika.pipes.core.server;
-/**
- * This should be catastrophic
- */
-public class FailedToStartClientException extends RuntimeException {
+import java.util.Optional;
+
+import org.apache.tika.metadata.Metadata;
+
+public class IntermediateResult {
+
+ private Metadata metadata = null;
+
+ public synchronized void set(Metadata result) {
+ this.metadata = result;
+ }
- public FailedToStartClientException(Throwable t) {
- super(t);
+ public synchronized Optional<Metadata> get() {
+ return Optional.ofNullable(metadata);
}
}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/MetadataListAndEmbeddedBytes.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/MetadataListAndEmbeddedBytes.java
new file mode 100644
index 000000000..fd2386ff0
--- /dev/null
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/MetadataListAndEmbeddedBytes.java
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+package org.apache.tika.pipes.core.server;
+
+import java.util.List;
+
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.extractor.EmbeddedDocumentBytesHandler;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.filter.MetadataFilter;
+import org.apache.tika.pipes.core.extractor.EmittingEmbeddedDocumentBytesHandler;
+
+class MetadataListAndEmbeddedBytes {
+
+ List<Metadata> metadataList;
+ final EmbeddedDocumentBytesHandler embeddedDocumentBytesHandler;
+
+ public MetadataListAndEmbeddedBytes(List<Metadata> metadataList,
+ EmbeddedDocumentBytesHandler embeddedDocumentBytesHandler) {
+ this.metadataList = metadataList;
+ this.embeddedDocumentBytesHandler = embeddedDocumentBytesHandler;
+ }
+
+ public List<Metadata> getMetadataList() {
+ return metadataList;
+ }
+
+ public void filter(MetadataFilter filter) throws TikaException {
+ metadataList = filter.filter(metadataList);
+ }
+
+ public EmbeddedDocumentBytesHandler getEmbeddedDocumentBytesHandler() {
+ return embeddedDocumentBytesHandler;
+ }
+
+ /**
+ * This tests whether there's any type of embedded document store
+ * ...that, for example, may require closing at the end of the parse.
+ *
+ * @return
+ */
+ public boolean hasEmbeddedDocumentByteStore() {
+ return embeddedDocumentBytesHandler != null;
+ }
+
+ /**
+ * If the intent is that the metadata and byte store be packaged in a zip
+ * or similar and emitted via a single stream emitter.
+ * <p>
+ * This is basically a test that this is not an EmbeddedDocumentEmitterStore.
+ *
+ * @return
+ */
+ public boolean toBePackagedForStreamEmitter() {
+ return !(embeddedDocumentBytesHandler instanceof EmittingEmbeddedDocumentBytesHandler);
+ }
+
+ @Override
+ public String toString() {
+ return "MetadataListAndEmbeddedBytes{" + "metadataList=" + metadataList + '}';
+ }
+}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/ParseHandler.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/ParseHandler.java
new file mode 100644
index 000000000..e1360e005
--- /dev/null
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/ParseHandler.java
@@ -0,0 +1,229 @@
+/*
+ * 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.
+ */
+package org.apache.tika.pipes.core.server;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.CountDownLatch;
+
+import org.apache.commons.io.IOUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+
+import org.apache.tika.detect.Detector;
+import org.apache.tika.exception.EncryptedDocumentException;
+import org.apache.tika.exception.TikaConfigException;
+import org.apache.tika.extractor.DocumentSelector;
+import org.apache.tika.extractor.EmbeddedDocumentBytesHandler;
+import org.apache.tika.io.TemporaryResources;
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.TikaCoreProperties;
+import org.apache.tika.mime.MediaType;
+import org.apache.tika.parser.AutoDetectParser;
+import org.apache.tika.parser.DigestingParser;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.RecursiveParserWrapper;
+import org.apache.tika.pipes.api.FetchEmitTuple;
+import org.apache.tika.pipes.api.HandlerConfig;
+import org.apache.tika.pipes.core.extractor.EmbeddedDocumentBytesConfig;
+import org.apache.tika.sax.BasicContentHandlerFactory;
+import org.apache.tika.sax.ContentHandlerFactory;
+import org.apache.tika.sax.RecursiveParserWrapperHandler;
+import org.apache.tika.utils.ExceptionUtils;
+
+class ParseHandler {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ParseHandler.class);
+
+ private final Detector detector;
+ private final DigestingParser.Digester digester;
+ private final ArrayBlockingQueue<Metadata> intermediateResult;
+ private final CountDownLatch countDownLatch;
+ private final AutoDetectParser autoDetectParser;
+ private final RecursiveParserWrapper recursiveParserWrapper;
+
+
+ ParseHandler(Detector detector, DigestingParser.Digester digester, ArrayBlockingQueue<Metadata> intermediateResult,
+ CountDownLatch countDownLatch, AutoDetectParser autoDetectParser,
+ RecursiveParserWrapper recursiveParserWrapper) {
+ this.detector = detector;
+ this.digester = digester;
+ this.intermediateResult = intermediateResult;
+ this.countDownLatch = countDownLatch;
+ this.autoDetectParser = autoDetectParser;
+ this.recursiveParserWrapper = recursiveParserWrapper;
+ }
+
+ PipesWorker.ParseDataOrPipesResult parseWithStream(FetchEmitTuple fetchEmitTuple, InputStream stream, Metadata metadata, ParseContext parseContext)
+ throws TikaConfigException, InterruptedException {
+
+ List<Metadata> metadataList;
+ //this adds the EmbeddedDocumentByteStore to the parsecontext
+ HandlerConfig handlerConfig = parseContext.get(HandlerConfig.class);
+ if (handlerConfig.getParseMode() == HandlerConfig.PARSE_MODE.RMETA) {
+ metadataList =
+ parseRecursive(fetchEmitTuple, handlerConfig, stream, metadata, parseContext);
+ } else {
+ metadataList = parseConcatenated(fetchEmitTuple, handlerConfig, stream, metadata,
+ parseContext);
+ }
+
+ return new PipesWorker.ParseDataOrPipesResult(new MetadataListAndEmbeddedBytes(metadataList,
+ parseContext.get(EmbeddedDocumentBytesHandler.class)), null);
+ }
+
+
+
+ private void _preParse(FetchEmitTuple t, TikaInputStream tis, Metadata metadata,
+ ParseContext parseContext) {
+ if (digester != null) {
+ try {
+ digester.digest(tis, metadata, parseContext);
+ } catch (IOException e) {
+ LOG.warn("problem digesting: " + t.getId(), e);
+ }
+ }
+ try {
+ MediaType mt = detector.detect(tis, metadata);
+ metadata.set(Metadata.CONTENT_TYPE, mt.toString());
+ metadata.set(TikaCoreProperties.CONTENT_TYPE_PARSER_OVERRIDE, mt.toString());
+ } catch (IOException e) {
+ LOG.warn("problem detecting: " + t.getId(), e);
+ }
+ EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig = parseContext.get(EmbeddedDocumentBytesConfig.class);
+ if (embeddedDocumentBytesConfig != null &&
+ embeddedDocumentBytesConfig.isIncludeOriginal()) {
+ EmbeddedDocumentBytesHandler embeddedDocumentByteStore = parseContext.get(EmbeddedDocumentBytesHandler.class);
+ try (InputStream is = Files.newInputStream(tis.getPath())) {
+ embeddedDocumentByteStore.add(0, metadata, is);
+ } catch (IOException e) {
+ LOG.warn("problem reading source file into embedded document byte store", e);
+ }
+ }
+ }
+
+ private Metadata preParse(FetchEmitTuple t, InputStream stream, Metadata metadata,
+ ParseContext parseContext) {
+ TemporaryResources tmp = null;
+ try {
+ TikaInputStream tis = TikaInputStream.cast(stream);
+ if (tis == null) {
+ tis = TikaInputStream.get(stream, tmp, metadata);
+ }
+ _preParse(t, tis, metadata, parseContext);
+ } finally {
+ IOUtils.closeQuietly(tmp);
+ }
+ return metadata;
+ }
+
+ public List<Metadata> parseRecursive(FetchEmitTuple fetchEmitTuple,
+ HandlerConfig handlerConfig, InputStream stream,
+ Metadata metadata, ParseContext parseContext) throws InterruptedException {
+ //Intentionally do not add the metadata filter here!
+ //We need to let stacktraces percolate
+ RecursiveParserWrapperHandler handler = new RecursiveParserWrapperHandler(
+ new BasicContentHandlerFactory(handlerConfig.getType(),
+ handlerConfig.getWriteLimit(), handlerConfig.isThrowOnWriteLimitReached(),
+ parseContext), handlerConfig.getMaxEmbeddedResources());
+
+ long start = System.currentTimeMillis();
+
+ preParse(fetchEmitTuple, stream, metadata, parseContext);
+ //queue better be empty. we deserve an exception if not
+ intermediateResult.add(metadata);
+ countDownLatch.await();
+ try {
+ recursiveParserWrapper.parse(stream, handler, metadata, parseContext);
+ } catch (SAXException e) {
+ LOG.warn("sax problem:" + fetchEmitTuple.getId(), e);
+ } catch (EncryptedDocumentException e) {
+ LOG.warn("encrypted document:" + fetchEmitTuple.getId(), e);
+ } catch (SecurityException e) {
+ LOG.warn("security exception:" + fetchEmitTuple.getId(), e);
+ throw e;
+ } catch (Exception e) {
+ LOG.warn("parse exception: " + fetchEmitTuple.getId(), e);
+ } finally {
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("timer -- parse only time: {} ms", System.currentTimeMillis() - start);
+ }
+ }
+ return handler.getMetadataList();
+ }
+
+ public List<Metadata> parseConcatenated(FetchEmitTuple fetchEmitTuple,
+ HandlerConfig handlerConfig, InputStream stream,
+ Metadata metadata, ParseContext parseContext) {
+
+ ContentHandlerFactory contentHandlerFactory =
+ new BasicContentHandlerFactory(handlerConfig.getType(),
+ handlerConfig.getWriteLimit(), handlerConfig.isThrowOnWriteLimitReached(),
+ parseContext);
+
+ ContentHandler handler = contentHandlerFactory.getNewContentHandler();
+ parseContext.set(DocumentSelector.class, new DocumentSelector() {
+ final int maxEmbedded = handlerConfig.getMaxEmbeddedResources();
+ int embedded = 0;
+
+ @Override
+ public boolean select(Metadata metadata) {
+ if (maxEmbedded < 0) {
+ return true;
+ }
+ return embedded++ < maxEmbedded;
+ }
+ });
+
+ String containerException = null;
+ long start = System.currentTimeMillis();
+ preParse(fetchEmitTuple, stream, metadata, parseContext);
+ //TODO -- add intermediate
+ try {
+ autoDetectParser.parse(stream, handler, metadata, parseContext);
+ } catch (SAXException e) {
+ containerException = ExceptionUtils.getStackTrace(e);
+ LOG.warn("sax problem:" + fetchEmitTuple.getId(), e);
+ } catch (EncryptedDocumentException e) {
+ containerException = ExceptionUtils.getStackTrace(e);
+ LOG.warn("encrypted document:" + fetchEmitTuple.getId(), e);
+ } catch (SecurityException e) {
+ LOG.warn("security exception:" + fetchEmitTuple.getId(), e);
+ throw e;
+ } catch (Exception e) {
+ containerException = ExceptionUtils.getStackTrace(e);
+ LOG.warn("parse exception: " + fetchEmitTuple.getId(), e);
+ } finally {
+ metadata.add(TikaCoreProperties.TIKA_CONTENT, handler.toString());
+ if (containerException != null) {
+ metadata.add(TikaCoreProperties.CONTAINER_EXCEPTION, containerException);
+ }
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("timer -- parse only time: {} ms", System.currentTimeMillis() - start);
+ }
+ }
+ return Collections.singletonList(metadata);
+ }
+
+}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/PipesServer.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/PipesServer.java
new file mode 100644
index 000000000..99e403ce3
--- /dev/null
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/PipesServer.java
@@ -0,0 +1,526 @@
+/*
+ * 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.
+ */
+package org.apache.tika.pipes.core.server;
+
+import static org.apache.tika.pipes.core.PipesClient.COMMANDS.ACK;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.FINISHED;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.INTERMEDIATE_RESULT;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.OOM;
+import static org.apache.tika.pipes.core.server.PipesServer.PROCESSING_STATUS.TIMEOUT;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HexFormat;
+import java.util.Locale;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
+import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.SAXException;
+
+import org.apache.tika.config.loader.TikaJsonConfig;
+import org.apache.tika.config.loader.TikaLoader;
+import org.apache.tika.detect.Detector;
+import org.apache.tika.exception.TikaConfigException;
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.extractor.RUnpackExtractorFactory;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.metadata.filter.MetadataFilter;
+import org.apache.tika.parser.AutoDetectParser;
+import org.apache.tika.parser.DigestingParser;
+import org.apache.tika.parser.RecursiveParserWrapper;
+import org.apache.tika.pipes.api.FetchEmitTuple;
+import org.apache.tika.pipes.api.PipesResult;
+import org.apache.tika.pipes.core.PipesClient;
+import org.apache.tika.pipes.core.PipesConfig;
+import org.apache.tika.pipes.core.emitter.EmitterManager;
+import org.apache.tika.pipes.core.fetcher.FetcherManager;
+import org.apache.tika.plugins.TikaPluginManager;
+import org.apache.tika.utils.ExceptionUtils;
+
+/**
+ * This server is forked from the PipesClient. This class isolates
+ * parsing from the client to protect the primary JVM.
+ * <p>
+ * When configuring logging for this class, make absolutely certain
+ * not to write to STDOUT. This class uses STDOUT to communicate with
+ * the PipesClient.
+ */
+public class PipesServer implements AutoCloseable {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PipesServer.class);
+
+ private final long heartbeatIntervalMs;
+
+ //this has to be some number not close to 0-3
+ //it looks like the server crashes with exit value 3 on uncaught OOM, for example
+ public static final int TIMEOUT_EXIT_CODE = 17;
+ public static final int OOM_EXIT_CODE = 18;
+ public static final int UNSPECIFIED_CRASH_EXIT_CODE = 19;
+
+
+ public enum PROCESSING_STATUS {
+ READY, INTERMEDIATE_RESULT, WORKING, FINISHED,
+ OOM(OOM_EXIT_CODE), TIMEOUT(TIMEOUT_EXIT_CODE), UNSPECIFIED_CRASH(UNSPECIFIED_CRASH_EXIT_CODE);
+
+ int exitCode = -1;
+ public static PROCESSING_STATUS lookup(int b) {
+ if (b < 1) {
+ throw new IllegalArgumentException("bad result value: " + b);
+ }
+ int ordinal = b - 1;
+ if (ordinal >= PROCESSING_STATUS.values().length) {
+ throw new IllegalArgumentException("ordinal > than array length? " + ordinal);
+ }
+ return PROCESSING_STATUS.values()[ordinal];
+ }
+ PROCESSING_STATUS() {
+
+ }
+
+ PROCESSING_STATUS(int exitCode) {
+ this.exitCode = exitCode;
+ }
+
+ public int getExitCode() {
+ return exitCode;
+ }
+
+ public byte getByte() {
+ return (byte) (ordinal() + 1);
+ }
+ }
+ private DigestingParser.Digester digester;
+
+ private Detector detector;
+
+
+
+ private final Object[] lock = new Object[0];
+ private final DataInputStream input;
+ private final DataOutputStream output;
+ //if an extract is larger than this value, emit it directly;
+ //if it is smaller than this value, write it back to the
+ //PipesClient so that it can cache the extracts and then batch emit.
+
+ private final TikaLoader tikaLoader;
+ private final PipesConfig pipesConfig;
+ private final Socket socket;
+ private final MetadataFilter defaultMetadataFilter;
+ private AutoDetectParser autoDetectParser;
+ private RecursiveParserWrapper rMetaParser;
+ private FetcherManager fetcherManager;
+ private EmitterManager emitterManager;
+ private final ExecutorService executorService = Executors.newSingleThreadExecutor();
+ private final ExecutorCompletionService<PipesResult> executorCompletionService = new ExecutorCompletionService<>(executorService);
+ private final PipesWorker.EMIT_STRATEGY emitStrategy;
+
+ public static PipesServer load(int port, Path tikaConfigPath) throws Exception {
+ Socket socket = new Socket();
+ socket.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), port), PipesClient.SOCKET_CONNECT_TIMEOUT_MS);
+
+ DataInputStream dis = new DataInputStream(socket.getInputStream());
+ DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
+ try {
+ TikaLoader tikaLoader = TikaLoader.load(tikaConfigPath);
+ TikaJsonConfig tikaJsonConfig = tikaLoader.getConfig();
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ // Set socket timeout from config after loading PipesConfig
+ socket.setSoTimeout((int) pipesConfig.getSocketTimeoutMs());
+
+ MetadataFilter metadataFilter = tikaLoader.loadMetadataFilters();
+ PipesServer pipesServer = new PipesServer(tikaLoader, pipesConfig, socket, dis, dos, metadataFilter);
+ pipesServer.initializeResources();
+ return pipesServer;
+ } catch (Exception e) {
+ LOG.error("Failed to start up", e);
+ try {
+ // Write FINISHED status byte and await ACK
+ dos.writeByte(FINISHED.getByte());
+ dos.flush();
+ int ack = dis.read();
+ if (ack != PipesClient.COMMANDS.ACK.getByte()) {
+ LOG.warn("Expected ACK but got: {}", ack);
+ }
+
+ // Write error message and await ACK
+ String msg = ExceptionUtils.getStackTrace(e);
+ byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
+ dos.writeInt(bytes.length);
+ dos.write(bytes);
+ dos.flush();
+ ack = dis.read();
+ if (ack != PipesClient.COMMANDS.ACK.getByte()) {
+ LOG.warn("Expected ACK but got: {}", ack);
+ }
+ } catch (IOException ioException) {
+ LOG.error("Failed to send startup failure message to client", ioException);
+ }
+ throw e;
+ }
+ }
+
+ public PipesServer(TikaLoader tikaLoader, PipesConfig pipesConfig, Socket socket, DataInputStream in,
+ DataOutputStream out, MetadataFilter metadataFilter) throws TikaConfigException,
+ IOException {
+
+ this.tikaLoader = tikaLoader;
+ this.pipesConfig = pipesConfig;
+ this.socket = socket;
+ this.defaultMetadataFilter = metadataFilter;
+ this.input = new DataInputStream(in);
+ this.output = new DataOutputStream(out);
+ this.heartbeatIntervalMs = pipesConfig.getHeartbeatIntervalMs();
+
+ // Validate heartbeat interval is less than socket timeout
+ if (heartbeatIntervalMs >= pipesConfig.getSocketTimeoutMs()) {
+ String msg = String.format(Locale.ROOT, "Heartbeat interval (%dms) must be less than socket timeout (%dms). " +
+ "This configuration will cause socket timeouts during normal processing.",
+ heartbeatIntervalMs, pipesConfig.getSocketTimeoutMs());
+
+ // Allow override for testing only
+ if (!"true".equals(System.getProperty("tika.pipes.allowInvalidHeartbeat"))) {
+ throw new TikaConfigException(msg);
+ }
+ LOG.error(msg + " Proceeding because tika.pipes.allowInvalidHeartbeat=true");
+ }
+
+ if (pipesConfig.getDirectEmitThresholdBytes() == 0) {
+ emitStrategy = PipesWorker.EMIT_STRATEGY.EMIT_ALL;
+ } else if (pipesConfig.getDirectEmitThresholdBytes() < 0) {
+ emitStrategy = PipesWorker.EMIT_STRATEGY.PASSBACK_ALL;
+ } else {
+ emitStrategy = PipesWorker.EMIT_STRATEGY.DYNAMIC;
+ }
+ }
+
+
+ public static void main(String[] args) throws Exception {
+ int port = Integer.parseInt(args[0]);
+ Path tikaConfig = Paths.get(args[1]);
+ LOG.debug("starting pipes server on port={} with tikaConfig={}", port, tikaConfig);
+ try (PipesServer server = PipesServer.load(port, tikaConfig)) {
+ LOG.debug("successfully started pipes server");
+ server.mainLoop();
+ } catch (Throwable t) {
+ LOG.error("crashed", t);
+ throw t;
+ } finally {
+ LOG.info("server shutting down");
+ }
+ }
+
+ public void mainLoop() {
+ write(PROCESSING_STATUS.READY.getByte());
+ ArrayBlockingQueue<Metadata> intermediateResult = new ArrayBlockingQueue<>(1);
+
+ LOG.trace("processing requests");
+ //main loop
+ try {
+ long start = System.currentTimeMillis();
+ while (true) {
+ int request = input.read();
+ if (request == -1) {
+ LOG.warn("received -1 from client; shutting down");
+ exit(0);
+ } else if (request == PipesClient.COMMANDS.PING.getByte()) {
+ writeNoAck(PipesClient.COMMANDS.PING.getByte());
+ } else if (request == PipesClient.COMMANDS.NEW_REQUEST.getByte()) {
+ intermediateResult.clear();
+ CountDownLatch countDownLatch = new CountDownLatch(1);
+
+ FetchEmitTuple fetchEmitTuple = readFetchEmitTuple();
+
+ PipesWorker pipesWorker = getPipesWorker(intermediateResult, fetchEmitTuple, countDownLatch);
+ executorCompletionService.submit(pipesWorker);
+ //set progress counter
+ try {
+ loopUntilDone(fetchEmitTuple, executorCompletionService, intermediateResult, countDownLatch);
+ } catch (Throwable t) {
+ LOG.error("Serious problem: {}", HexFormat.of().formatHex(new byte[]{(byte)request}), t);
+ }
+ } else if (request == PipesClient.COMMANDS.SHUT_DOWN.getByte()) {
+ LOG.info("shutting down");
+ try {
+ close();
+ } catch (Exception e) {
+ //swallow
+ }
+ System.exit(0);
+ } else {
+ LOG.error("Unexpected request byte={}", HexFormat.of().formatHex(new byte[]{(byte)request}));
+ throw new IllegalStateException("Unexpected request");
+ }
+ output.flush();
+ }
+ } catch (Throwable t) {
+ LOG.error("main loop error (did the forking process shut down?)", t);
+ exit(1);
+ }
+ }
+
+ private PipesWorker getPipesWorker(ArrayBlockingQueue<Metadata> intermediateResult, FetchEmitTuple fetchEmitTuple, CountDownLatch countDownLatch) {
+ FetchHandler fetchHandler = new FetchHandler(fetcherManager);
+ ParseHandler parseHandler = new ParseHandler(detector, digester, intermediateResult, countDownLatch, autoDetectParser, rMetaParser);
+ EmitHandler emitHandler = new EmitHandler(defaultMetadataFilter, emitStrategy, emitterManager, pipesConfig.getDirectEmitThresholdBytes());
+ PipesWorker pipesWorker = new PipesWorker(fetchEmitTuple, autoDetectParser, emitterManager, fetchHandler, parseHandler, emitHandler);
+ return pipesWorker;
+ }
+
+ private void loopUntilDone(FetchEmitTuple fetchEmitTuple, ExecutorCompletionService<PipesResult> executorCompletionService,
+ ArrayBlockingQueue<Metadata> intermediateResult, CountDownLatch countDownLatch) throws InterruptedException, IOException {
+ Instant start = Instant.now();
+ long timeoutMillis = PipesClient.getTimeoutMillis(pipesConfig, fetchEmitTuple.getParseContext());
+ long mockProgressCounter = 0;
+ boolean wroteIntermediateResult = false;
+
+ while (true) {
+ // Check for intermediate result (pre-parse metadata)
+ if (!wroteIntermediateResult) {
+ Metadata intermediate = intermediateResult.poll(100, TimeUnit.MILLISECONDS);
+ if (intermediate != null) {
+ writeIntermediate(intermediate);
+ countDownLatch.countDown();
+ wroteIntermediateResult = true;
+ }
+ }
+
+ // Check for task completion (can happen even without intermediate result if crash occurs early)
+ Future<PipesResult> future = executorCompletionService.poll(100, TimeUnit.MILLISECONDS);
+ if (future != null) {
+ PipesResult pipesResult = null;
+ try {
+ pipesResult = future.get();
+ } catch (OutOfMemoryError e) {
+ handleCrash(OOM, fetchEmitTuple.getId(), e);
+ } catch (ExecutionException e) {
+ Throwable t = e.getCause();
+ LOG.error("crash: {}", fetchEmitTuple.getId(), t);
+ if (t instanceof OutOfMemoryError) {
+ handleCrash(OOM, fetchEmitTuple.getId(), t);
+ }
+ handleCrash(PROCESSING_STATUS.UNSPECIFIED_CRASH, fetchEmitTuple.getId(), t);
+ }
+ LOG.debug("executor completionService finished task: id={} status={}", fetchEmitTuple.getId(), pipesResult.status());
+ write(FINISHED, pipesResult);
+ return;
+ }
+
+ // Send heartbeat if we've waited long enough
+ long elapsed = System.currentTimeMillis() - start.toEpochMilli();
+ if (elapsed > mockProgressCounter * heartbeatIntervalMs) {
+ LOG.debug("still processing: {}", mockProgressCounter);
+ output.write(PROCESSING_STATUS.WORKING.getByte());
+ output.writeLong(mockProgressCounter++);
+ output.flush();
+ }
+
+ checkTimeout(start, timeoutMillis);
+ }
+
+ }
+
+ private void checkTimeout(Instant start, long timeoutMillis) throws IOException {
+
+ if (Duration.between(start, Instant.now()).toMillis() > timeoutMillis) {
+ write(TIMEOUT.getByte());
+ exit(TIMEOUT_EXIT_CODE);
+ }
+ }
+
+ private void handleCrash(PROCESSING_STATUS processingStatus, String id, Throwable t) {
+ LOG.error("{}: {}", processingStatus, id, t);
+ String msg = (t != null) ? ExceptionUtils.getStackTrace(t) : "";
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
+ oos.writeObject(msg);
+ write(processingStatus, bos.toByteArray());
+ awaitAck();
+ } catch (IOException e) {
+ //swallow
+ LOG.warn("problem writing crash info to client", e);
+ }
+ exit(processingStatus.getExitCode());
+ }
+
+
+ @Override
+ public void close() throws Exception {
+ executorService.shutdownNow();
+ socket.close();
+ }
+
+ private void exit(int exitCode) {
+ if (exitCode != 0) {
+ LOG.error("exiting: {}", exitCode);
+ } else {
+ LOG.info("exiting: {}", exitCode);
+ }
+ System.exit(exitCode);
+ }
+
+
+ private FetchEmitTuple readFetchEmitTuple() {
+ try {
+ int length = input.readInt();
+ byte[] bytes = new byte[length];
+ input.readFully(bytes);
+ try (ObjectInputStream objectInputStream = new ObjectInputStream(
+ UnsynchronizedByteArrayInputStream.builder().setByteArray(bytes).get())) {
+ return (FetchEmitTuple) objectInputStream.readObject();
+ }
+ } catch (IOException e) {
+ LOG.error("problem reading tuple", e);
+ exit(1);
+ } catch (ClassNotFoundException e) {
+ LOG.error("can't find class?!", e);
+ exit(1);
+ }
+ //unreachable, no?!
+ return null;
+ }
+
+ protected void initializeResources() throws TikaException, IOException, SAXException {
+
+ TikaJsonConfig tikaJsonConfig = tikaLoader.getConfig();
+ TikaPluginManager tikaPluginManager = TikaPluginManager.load(tikaJsonConfig);
+
+ //TODO allowed named configurations in tika config
+ this.fetcherManager = FetcherManager.load(tikaPluginManager, tikaJsonConfig);
+ //skip initialization of the emitters if emitting
+ //from the pipesserver is turned off.
+ if (pipesConfig.getDirectEmitThresholdBytes() > -1) {
+ this.emitterManager = EmitterManager.load(tikaPluginManager, tikaJsonConfig);
+ } else {
+ LOG.debug("'directEmitThresholdBytes' < 0. Not initializing emitters in PipesServer");
+ this.emitterManager = null;
+ }
+ this.autoDetectParser = (AutoDetectParser) tikaLoader.loadAutoDetectParser();
+ if (autoDetectParser.getAutoDetectParserConfig()
+ .getDigesterFactory() != null) {
+ this.digester = autoDetectParser.getAutoDetectParserConfig()
+ .getDigesterFactory().build();
+ //override this value because we'll be digesting before parse
+ autoDetectParser.getAutoDetectParserConfig().getDigesterFactory()
+ .setSkipContainerDocument(true);
+ //if the user hasn't configured an embedded document extractor, set up the
+ // RUnpackExtractorFactory
+ if (autoDetectParser.getAutoDetectParserConfig()
+ .getEmbeddedDocumentExtractorFactory() == null) {
+ autoDetectParser
+ .getAutoDetectParserConfig().setEmbeddedDocumentExtractorFactory(
+ new RUnpackExtractorFactory());
+ }
+ }
+ this.detector = this.autoDetectParser.getDetector();
+ this.rMetaParser = new RecursiveParserWrapper(autoDetectParser);
+ }
+
+
+ private void write(PROCESSING_STATUS processingStatus, PipesResult pipesResult) {
+ try {
+ UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
+ try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
+ objectOutputStream.writeObject(pipesResult);
+ }
+ write(processingStatus, bos.toByteArray());
+ } catch (IOException e) {
+ LOG.error("problem writing emit data (forking process shutdown?)", e);
+ exit(1);
+ }
+ }
+
+ private void writeIntermediate(Metadata metadata) {
+ try {
+ UnsynchronizedByteArrayOutputStream bos = UnsynchronizedByteArrayOutputStream.builder().get();
+ try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(bos)) {
+ objectOutputStream.writeObject(metadata);
+ }
+ write(INTERMEDIATE_RESULT, bos.toByteArray());
+ } catch (IOException e) {
+ LOG.error("problem writing intermediate data (forking process shutdown?)", e);
+ exit(1);
+ }
+ }
+
+ private void awaitAck() throws IOException {
+ int b = input.read();
+ if (b == ACK.getByte()) {
+ return;
+ }
+ throw new IOException("Wasn't expecting byte=" + HexFormat.of().formatHex(new byte[]{ (byte) b}));
+ }
+
+ private void writeNoAck(byte b) {
+ try {
+ output.write(b);
+ output.flush();
+ } catch (IOException e) {
+ LOG.error("problem writing data (forking process shutdown?)", e);
+ exit(1);
+ }
+ }
+
+ private void write(byte b) {
+ try {
+ output.write(b);
+ output.flush();
+ awaitAck();
+ } catch (IOException e) {
+ LOG.error("problem writing data (forking process shutdown?)", e);
+ exit(1);
+ }
+ }
+
+
+ private void write(PROCESSING_STATUS status, byte[] bytes) {
+ try {
+ write(status.getByte());
+ int len = bytes.length;
+ output.writeInt(len);
+ output.write(bytes);
+ output.flush();
+ awaitAck();
+ } catch (IOException e) {
+ LOG.error("problem writing data (forking process shutdown?)", e);
+ exit(1);
+ }
+ }
+
+}
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/PipesWorker.java b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/PipesWorker.java
new file mode 100644
index 000000000..61fa43c68
--- /dev/null
+++ b/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/server/PipesWorker.java
@@ -0,0 +1,192 @@
+/*
+ * 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.
+ */
+package org.apache.tika.pipes.core.server;
+
+import static org.apache.tika.pipes.api.pipesiterator.PipesIteratorBaseConfig.DEFAULT_HANDLER_CONFIG;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.concurrent.Callable;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.apache.tika.exception.TikaConfigException;
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.extractor.EmbeddedDocumentByteStoreExtractorFactory;
+import org.apache.tika.extractor.EmbeddedDocumentBytesHandler;
+import org.apache.tika.extractor.EmbeddedDocumentExtractor;
+import org.apache.tika.extractor.EmbeddedDocumentExtractorFactory;
+import org.apache.tika.extractor.RUnpackExtractor;
+import org.apache.tika.extractor.RUnpackExtractorFactory;
+import org.apache.tika.io.TikaInputStream;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.parser.AutoDetectParser;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.pipes.api.FetchEmitTuple;
+import org.apache.tika.pipes.api.HandlerConfig;
+import org.apache.tika.pipes.api.PipesResult;
+import org.apache.tika.pipes.core.PipesResults;
+import org.apache.tika.pipes.core.emitter.EmitterManager;
+import org.apache.tika.pipes.core.extractor.BasicEmbeddedDocumentBytesHandler;
+import org.apache.tika.pipes.core.extractor.EmbeddedDocumentBytesConfig;
+import org.apache.tika.pipes.core.extractor.EmittingEmbeddedDocumentBytesHandler;
+import org.apache.tika.utils.ExceptionUtils;
+import org.apache.tika.utils.StringUtils;
+
+class PipesWorker implements Callable<PipesResult> {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PipesWorker.class);
+
+ public enum EMIT_STRATEGY {
+ EMIT_ALL,
+ PASSBACK_ALL,
+ DYNAMIC
+ }
+
+ private final FetchEmitTuple fetchEmitTuple;
+ private final AutoDetectParser autoDetectParser;
+ private final EmitterManager emitterManager;
+ private final FetchHandler fetchHandler;
+ private final ParseHandler parseHandler;
+ private final EmitHandler emitHandler;
+
+ public PipesWorker(FetchEmitTuple fetchEmitTuple, AutoDetectParser autoDetectParser, EmitterManager emitterManager, FetchHandler fetchHandler, ParseHandler parseHandler,
+ EmitHandler emitHandler) {
+ this.fetchEmitTuple = fetchEmitTuple;
+ this.autoDetectParser = autoDetectParser;
+ this.emitterManager = emitterManager;
+ this.fetchHandler = fetchHandler;
+ this.parseHandler = parseHandler;
+ this.emitHandler = emitHandler;
+ }
+
+ @Override
+ public PipesResult call() throws Exception {
+ Instant start = Instant.now();
+
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("timer -- got fetcher: {}ms", Duration.between(start, Instant.now()).toMillis());
+ }
+ start = Instant.now();
+ MetadataListAndEmbeddedBytes parseData = null;
+ try {
+ //this can be null if there is a fetch exception
+ ParseDataOrPipesResult parseDataResult = parseFromTuple();
+ if (parseDataResult.pipesResult != null) {
+ return parseDataResult.pipesResult;
+ }
+
+ if (LOG.isTraceEnabled()) {
+ LOG.trace("timer -- to parse: {} ms", Duration.between(start, Instant.now()).toMillis());
+ }
+ parseData = parseDataResult.parseDataResult;
+
+ if (parseData == null || metadataIsEmpty(parseData.getMetadataList())) {
+ return PipesResults.EMPTY_OUTPUT;
+ }
+ return emitHandler.emitParseData(fetchEmitTuple, parseData);
+ } finally {
+ if (parseData != null && parseData.hasEmbeddedDocumentByteStore() &&
+ parseData.getEmbeddedDocumentBytesHandler() instanceof Closeable) {
+ try {
+ ((Closeable) parseData.getEmbeddedDocumentBytesHandler()).close();
+ } catch (IOException e) {
+ LOG.warn("problem closing embedded document byte store", e);
+ }
+ }
+ }
+ }
+
+
+ static boolean metadataIsEmpty(List<Metadata> metadataList) {
+ return metadataList == null || metadataList.isEmpty();
+ }
+
+
+ protected ParseDataOrPipesResult parseFromTuple() throws TikaException, InterruptedException {
+ //start a new metadata object to gather info from the fetch process
+ //we want to isolate and not touch the metadata sent into the fetchEmitTuple
+ //so that we can inject it after the filter at the very end
+ Metadata metadata = new Metadata();
+ FetchHandler.TisOrResult tisOrResult = fetchHandler.fetch(fetchEmitTuple, metadata);
+ if (tisOrResult.pipesResult() != null) {
+ return new ParseDataOrPipesResult(null, tisOrResult.pipesResult());
+ }
+
+ ParseContext parseContext = setupParseContext(fetchEmitTuple);
+ try (TikaInputStream tis = tisOrResult.tis()) {
+ return parseHandler.parseWithStream(fetchEmitTuple, tis, metadata, parseContext);
+ } catch (SecurityException e) {
+ LOG.error("security exception id={}", fetchEmitTuple.getId(), e);
+ throw e;
+ } catch (TikaException | IOException e) {
+ LOG.warn("fetch exception id={}", fetchEmitTuple.getId(), e);
+ return new ParseDataOrPipesResult(null,
+ new PipesResult(PipesResult.RESULT_STATUS.UNSPECIFIED_CRASH, ExceptionUtils.getStackTrace(e)));
+ }
+ }
+
+
+
+ private ParseContext setupParseContext(FetchEmitTuple fetchEmitTuple)
+ throws TikaConfigException {
+ ParseContext parseContext = fetchEmitTuple.getParseContext();
+ if (parseContext.get(HandlerConfig.class) == null) {
+ parseContext.set(HandlerConfig.class, DEFAULT_HANDLER_CONFIG);
+ }
+ EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig = parseContext.get(EmbeddedDocumentBytesConfig.class);
+ if (embeddedDocumentBytesConfig == null) {
+ //make sure there's one here -- or do we make this default in fetchemit tuple?
+ parseContext.set(EmbeddedDocumentBytesConfig.class, EmbeddedDocumentBytesConfig.SKIP);
+ return parseContext;
+ }
+ EmbeddedDocumentExtractorFactory factory = autoDetectParser
+ .getAutoDetectParserConfig().getEmbeddedDocumentExtractorFactory();
+ if (factory == null) {
+ parseContext.set(EmbeddedDocumentExtractor.class, new RUnpackExtractor(parseContext,
+ RUnpackExtractorFactory.DEFAULT_MAX_EMBEDDED_BYTES_FOR_EXTRACTION));
+ } else {
+ if (! (factory instanceof EmbeddedDocumentByteStoreExtractorFactory)) {
+ throw new TikaConfigException("EmbeddedDocumentExtractorFactory must be an " +
+ "instance of EmbeddedDocumentByteStoreExtractorFactory if you want" +
+ "to extract embedded bytes! I see this embedded doc factory: " +
+ factory.getClass() + "and a request: " +
+ embeddedDocumentBytesConfig);
+ }
+ }
+ //TODO: especially clean this up.
+ if (!StringUtils.isBlank(embeddedDocumentBytesConfig.getEmitter())) {
+ parseContext.set(EmbeddedDocumentBytesHandler.class,
+ new EmittingEmbeddedDocumentBytesHandler(fetchEmitTuple, emitterManager));
+ } else {
+ parseContext.set(EmbeddedDocumentBytesHandler.class,
+ new BasicEmbeddedDocumentBytesHandler(embeddedDocumentBytesConfig));
+ }
+ return parseContext;
+ }
+
+ //parse data result or a terminal pipesresult
+ record ParseDataOrPipesResult(MetadataListAndEmbeddedBytes parseDataResult, PipesResult pipesResult) {
+
+ }
+
+
+}
diff --git a/tika-pipes/tika-pipes-core/src/test/resources/configs/TIKA-3865-params.xml b/tika-pipes/tika-pipes-core/src/test/resources/configs/TIKA-3865-params.xml
index ec6d6121c..6354d78d8 100644
--- a/tika-pipes/tika-pipes-core/src/test/resources/configs/TIKA-3865-params.xml
+++ b/tika-pipes/tika-pipes-core/src/test/resources/configs/TIKA-3865-params.xml
@@ -20,7 +20,7 @@
<properties>
<async>
<params>
- <maxForEmitBatchBytes>10000</maxForEmitBatchBytes>
+ <directEmitThresholdBytes>10000</directEmitThresholdBytes>
<emitMaxEstimatedBytes>100000</emitMaxEstimatedBytes>
<emitWithinMillis>60000</emitWithinMillis>
<numEmitters>1</numEmitters>
diff --git a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/CrashingDetector.java
similarity index 63%
rename from tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java
rename to tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/CrashingDetector.java
index 949bb81e8..0dc4ace41 100644
--- a/tika-pipes/tika-pipes-core/src/main/java/org/apache/tika/pipes/core/FailedToStartClientException.java
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/CrashingDetector.java
@@ -16,12 +16,22 @@
*/
package org.apache.tika.pipes.core;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.tika.detect.Detector;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.mime.MediaType;
+
/**
- * This should be catastrophic
+ * Detector that crashes with SystemExit
+ * Used for testing crash handling during pre-parse detection phase.
*/
-public class FailedToStartClientException extends RuntimeException {
+public class CrashingDetector implements Detector {
- public FailedToStartClientException(Throwable t) {
- super(t);
+ @Override
+ public MediaType detect(InputStream input, Metadata metadata) throws IOException {
+ System.exit(1);
+ return null;
}
}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PassbackFilterTest.java b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PassbackFilterTest.java
index 0bf8fa545..dad47a170 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PassbackFilterTest.java
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PassbackFilterTest.java
@@ -53,7 +53,7 @@ public class PassbackFilterTest {
public void init(Path tmpDir) throws Exception {
Path pipesConfigPath = PluginsTestHelper.getFileSystemFetcherConfig("tika-config-passback.json", tmpDir);
TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(pipesConfigPath);
- PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, pipesConfigPath);
PluginsTestHelper.copyTestFilesToTmpInput(tmpDir, testPdfFile);
pipesClient = new PipesClient(pipesConfig);
@@ -71,7 +71,7 @@ public class PassbackFilterTest {
FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP));
- assertEquals(PipesResult.STATUS.EMIT_SUCCESS_PASSBACK, pipesResult.status());
+ assertEquals(PipesResult.RESULT_STATUS.EMIT_SUCCESS_PASSBACK, pipesResult.status());
Assertions.assertNotNull(pipesResult
.emitData()
.getMetadataList());
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesClientTest.java b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesClientTest.java
index 5fae57e51..74e6e1a78 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesClientTest.java
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesClientTest.java
@@ -17,7 +17,10 @@
package org.apache.tika.pipes.core;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
@@ -41,15 +44,16 @@ import org.apache.tika.pipes.api.fetcher.FetchKey;
public class PipesClientTest {
String fetcherName = "fsf";
+ String emitterName = "fse";
String testDoc = "testOverlappingText.pdf";
private PipesClient init(Path tmp, String testFileName) throws Exception {
- Path pipesConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(tmp, tmp.resolve("input"), tmp.resolve("output"));
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(tmp, tmp.resolve("input"), tmp.resolve("output"));
PluginsTestHelper.copyTestFilesToTmpInput(tmp, testFileName);
- TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(pipesConfigPath);
- PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig);
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
return new PipesClient(pipesConfig);
}
@@ -102,7 +106,6 @@ public class PipesClientTest {
@Test
public void testTimeout(@TempDir Path tmp) throws Exception {
- //TODO -- add unit test for timeout > default
//TODO -- figure out how to test pipes server timeout alone
//I did both manually during development, but unit tests are better. :D
ParseContext parseContext = new ParseContext();
@@ -117,4 +120,436 @@ public class PipesClientTest {
new EmitKey(), new Metadata(), parseContext, FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP));
assertEquals(PipesResults.TIMEOUT.status(), pipesResult.status());
}
+
+ @Test
+ public void testRuntimeTimeoutChange(@TempDir Path tmp) throws Exception {
+ // Test that TikaTaskTimeout can be changed at runtime via ParseContext
+ // Use a mock file with 3 second delay
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+ String mockContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<mock>" +
+ "<metadata action=\"add\" name=\"dc:creator\">Test</metadata>" +
+ "<write element=\"p\">main_content</write>" +
+ "<fakeload millis=\"3000\" cpu=\"1\" mb=\"10\"/>" +
+ "</mock>";
+ String testFile = "mock-3s-delay.xml";
+ Files.write(inputDir.resolve(testFile), mockContent.getBytes(StandardCharsets.UTF_8));
+
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(tmp, inputDir, tmp.resolve("output"));
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ // First test: Short timeout (1 second) - should timeout
+ ParseContext shortTimeoutContext = new ParseContext();
+ shortTimeoutContext.set(TikaTaskTimeout.class, new TikaTaskTimeout(1000));
+
+ PipesResult timeoutResult = pipesClient.process(
+ new FetchEmitTuple(testFile, new FetchKey(fetcherName, testFile),
+ new EmitKey(), new Metadata(), shortTimeoutContext,
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP));
+
+ assertEquals(PipesResult.RESULT_STATUS.TIMEOUT, timeoutResult.status(),
+ "Should timeout with 1 second timeout on 3 second file");
+
+ // Second test: Long timeout (10 seconds) - should succeed
+ ParseContext longTimeoutContext = new ParseContext();
+ longTimeoutContext.set(TikaTaskTimeout.class, new TikaTaskTimeout(10000));
+
+ PipesResult successResult = pipesClient.process(
+ new FetchEmitTuple(testFile, new FetchKey(fetcherName, testFile),
+ new EmitKey(), new Metadata(), longTimeoutContext,
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP));
+
+ assertEquals(PipesResult.RESULT_STATUS.PARSE_SUCCESS, successResult.status(),
+ "Should succeed with 10 second timeout on 3 second file");
+ Assertions.assertNotNull(successResult.emitData().getMetadataList());
+ assertTrue(successResult.emitData().getMetadataList().size() > 0);
+ }
+ }
+
+ @Test
+ public void testStartupFailure(@TempDir Path tmp) throws Exception {
+ // Create a config that references a non-existent fetcher plugin
+ // This should cause PipesServer to fail during initialization
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(
+ "tika-config-bad-class.json", tmp);
+
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testDoc,
+ new FetchKey("bad-fetcher", testDoc),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+ assertEquals(PipesResult.RESULT_STATUS.FAILED_TO_INITIALIZE, pipesResult.status());
+ assertTrue(pipesResult.isApplicationError(), "FAILED_TO_INITIALIZE should be an application error");
+ Assertions.assertNotNull(pipesResult.message(), "Should have error message from server");
+ assertTrue(pipesResult.message().contains("non-existent-fetcher-plugin") ||
+ pipesResult.message().contains("TikaConfigException") ||
+ pipesResult.message().contains("error") ||
+ pipesResult.message().contains("Exception"),
+ "Error message should contain details about the failure");
+ }
+ }
+
+ @Test
+ public void testJvmStartupFailure(@TempDir Path tmp) throws Exception {
+ // Create a config with bad JVM arguments
+ // This should cause the JVM process to fail before it can connect
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(
+ "tika-config-bad-jvm-args.json", tmp);
+ PluginsTestHelper.copyTestFilesToTmpInput(tmp, testDoc);
+
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testDoc,
+ new FetchKey("fsf", testDoc),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+ assertEquals(PipesResult.RESULT_STATUS.FAILED_TO_INITIALIZE, pipesResult.status());
+ assertTrue(pipesResult.isApplicationError(), "FAILED_TO_INITIALIZE should be an application error");
+ Assertions.assertNotNull(pipesResult.message(), "Should have error message");
+ assertTrue(pipesResult.message().contains("exit code") ||
+ pipesResult.message().contains("JVM") ||
+ pipesResult.message().contains("Process failed"),
+ "Error message should indicate process failure: " + pipesResult.message());
+ }
+ }
+
+ @Test
+ public void testFailureBeforeJvm(@TempDir Path tmp) throws Exception {
+ // Create a config with bad application path
+ // This will cause failure before the process begins
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(
+ "tika-config-bad-java-path.json", tmp);
+ PluginsTestHelper.copyTestFilesToTmpInput(tmp, testDoc);
+
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testDoc,
+ new FetchKey("fsf", testDoc),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+ assertEquals(PipesResult.RESULT_STATUS.FAILED_TO_INITIALIZE, pipesResult.status());
+ assertTrue(pipesResult.isApplicationError(), "FAILED_TO_INITIALIZE should be an application error");
+ Assertions.assertNotNull(pipesResult.message(), "Should have error message");
+ assertTrue(pipesResult.message().contains("No such file") || pipesResult.message().contains("thisIsntJava"),
+ "Error message should indicate process failure: " + pipesResult.message());
+ }
+ }
+
+ @Test
+ public void testCrashDuringDetection(@TempDir Path tmp) throws Exception {
+ // Test that crashes during pre-parse detection phase are handled correctly
+ // The detector will throw RuntimeException which should NOT be caught in pre-parse
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(
+ "tika-config-crashing-detector.json", tmp);
+ PluginsTestHelper.copyTestFilesToTmpInput(tmp, testDoc);
+
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testDoc,
+ new FetchKey("fsf", testDoc),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+
+ // Should be UNSPECIFIED_CRASH because RuntimeException during detection
+ // is not caught by pre-parse IOException handler
+ assertEquals(PipesResult.RESULT_STATUS.UNSPECIFIED_CRASH, pipesResult.status());
+ assertTrue(pipesResult.isProcessCrash() || pipesResult.isApplicationError(),
+ "Should be categorized as a crash or application error");
+
+ // Should have error message about the crash
+ Assertions.assertNotNull(pipesResult.message(), "Should have error message");
+ assertTrue(pipesResult.message().contains("problem reading response") |
+ pipesResult.message().contains("SocketException"),
+ "Error message should mention the detection crash: " + pipesResult.message());
+
+ // Note: Because crash happens during pre-parse (before intermediate result is sent),
+ // the emitData will have minimal metadata - just what was captured before the crash
+ }
+ }
+
+ @Test
+ public void testSocketTimeout(@TempDir Path tmp) throws Exception {
+ // Test socket timeout when heartbeats are sent too slowly
+ // Config has heartbeatIntervalMs=10000 (10 seconds) but socketTimeoutMs=3000 (3 seconds)
+ // This simulates a server that appears unresponsive (different from parse timeout)
+ // NOTE: This is an invalid configuration that would never be used in production,
+ // but we allow it for testing via system property
+
+ // Create input directory and mock XML file with 10 second fakeload
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+ String mockContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<mock>" +
+ "<metadata action=\"add\" name=\"dc:creator\">Test</metadata>" +
+ "<write element=\"p\">main_content</write>" +
+ "<fakeload millis=\"10000\" cpu=\"1\" mb=\"10\"/>" +
+ "</mock>";
+ String testFile = "mock-slow.xml";
+ Files.write(inputDir.resolve(testFile), mockContent.getBytes(StandardCharsets.UTF_8));
+
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(
+ "tika-config-timeout-lt-heartbeat.json", tmp);
+
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ // Verify the misconfiguration that triggers socket timeout
+ assertEquals(3000, pipesConfig.getSocketTimeoutMs(), "Socket timeout should be 3 seconds");
+ assertEquals(10000, pipesConfig.getHeartbeatIntervalMs(), "Heartbeat interval should be 10 seconds");
+ assertTrue(pipesConfig.getHeartbeatIntervalMs() > pipesConfig.getSocketTimeoutMs(),
+ "Test requires heartbeat > socket timeout to trigger timeout");
+
+ // The config file includes -Dtika.pipes.allowInvalidHeartbeat=true in forkedJvmArgs
+ // to allow this invalid configuration for testing only
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testFile,
+ new FetchKey("fsf", testFile),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ long startTime = System.currentTimeMillis();
+ PipesResult pipesResult = pipesClient.process(tuple);
+ long elapsed = System.currentTimeMillis() - startTime;
+
+ // Should timeout due to socket timeout (no heartbeats received within socketTimeoutMs)
+ assertEquals(PipesResult.RESULT_STATUS.TIMEOUT, pipesResult.status(),
+ "Should timeout when socket times out");
+
+ // Should timeout relatively quickly (within ~5 seconds including overhead)
+ // Socket timeout is 3 seconds, but allow some buffer for processing
+ assertTrue(elapsed < 10000,
+ "Socket timeout should occur quickly (elapsed: " + elapsed + "ms)");
+
+ // Verify it's a process crash category (socket timeout means process isn't responding)
+ assertTrue(pipesResult.isProcessCrash(),
+ "Socket timeout should be categorized as process crash");
+ }
+ }
+
+ @Test
+ public void testParseSuccessWithException(@TempDir Path tmp) throws Exception {
+ // Test PARSE_SUCCESS_WITH_EXCEPTION status
+ // This occurs when parsing completes with some content but throws a non-fatal exception
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+
+ // Mock file that writes content then throws IOException
+ String mockContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<mock>" +
+ "<metadata action=\"add\" name=\"dc:creator\">Test Author</metadata>" +
+ "<write element=\"p\">Some content before exception</write>" +
+ "<throw class=\"java.io.IOException\">Non-fatal parse exception</throw>" +
+ "</mock>";
+ String testFile = "mock-parse-exception.xml";
+ Files.write(inputDir.resolve(testFile), mockContent.getBytes(StandardCharsets.UTF_8));
+
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(tmp, inputDir, tmp.resolve("output"));
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testFile,
+ new FetchKey(fetcherName, testFile),
+ new EmitKey(emitterName, ""), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.EMIT);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+
+ // Should be PARSE_SUCCESS_WITH_EXCEPTION because content was produced despite exception
+ assertEquals(PipesResult.RESULT_STATUS.PARSE_SUCCESS_WITH_EXCEPTION, pipesResult.status(),
+ "Should return PARSE_SUCCESS_WITH_EXCEPTION when parse throws but produces content");
+
+ // Verify it's still categorized as SUCCESS
+ assertTrue(pipesResult.isSuccess(), "PARSE_SUCCESS_WITH_EXCEPTION should be success category");
+
+ // Verify we got the metadata before the exception
+ Assertions.assertNotNull(pipesResult.emitData().getMetadataList());
+ assertTrue(pipesResult.emitData().getMetadataList().size() > 0);
+ Metadata metadata = pipesResult.emitData().getMetadataList().get(0);
+ assertEquals("Test Author", metadata.get("dc:creator"));
+ }
+ }
+
+ @Test
+ public void testFetchException(@TempDir Path tmp) throws Exception {
+ // Test FETCH_EXCEPTION status
+ // Occurs when fetcher fails to retrieve the file
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(tmp, inputDir, tmp.resolve("output"));
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ // Request a file that doesn't exist
+ String nonExistentFile = "does-not-exist.pdf";
+ FetchEmitTuple tuple = new FetchEmitTuple(nonExistentFile,
+ new FetchKey(fetcherName, nonExistentFile),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+
+ // Should be FETCH_EXCEPTION because file doesn't exist
+ assertEquals(PipesResult.RESULT_STATUS.FETCH_EXCEPTION, pipesResult.status(),
+ "Should return FETCH_EXCEPTION when file cannot be fetched");
+
+ // Verify it's categorized as APPLICATION_ERROR
+ assertTrue(pipesResult.isApplicationError(),
+ "FETCH_EXCEPTION should be application error category");
+
+ // Verify error message contains useful information
+ Assertions.assertNotNull(pipesResult.message());
+ assertTrue(pipesResult.message().contains("does-not-exist") ||
+ pipesResult.message().contains("NoSuchFileException") ||
+ pipesResult.message().contains("not found"),
+ "Error message should indicate file not found");
+ }
+ }
+
+ @Test
+ public void testEmitException(@TempDir Path tmp) throws Exception {
+ // Test EMIT_EXCEPTION status
+ // Occurs when emitter fails to write results
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+
+ // Create valid test file
+ String testFile = "test.xml";
+ String mockContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<mock>" +
+ "<metadata action=\"add\" name=\"dc:creator\">Test</metadata>" +
+ "<write element=\"p\">content</write>" +
+ "</mock>";
+ Files.write(inputDir.resolve(testFile), mockContent.getBytes(StandardCharsets.UTF_8));
+
+ // Create output directory and pre-create the output file to trigger onExists=EXCEPTION
+ Path outputDir = tmp.resolve("output");
+ Files.createDirectories(outputDir);
+ // The emitter will try to create test.xml.json, so pre-create it
+ Files.writeString(outputDir.resolve("test.xml.json"), "existing file");
+
+ // Use config with directEmitThresholdBytes=0 to force server-side emission
+ // Config has onExists=EXCEPTION which will trigger FileAlreadyExistsException
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig("tika-config-emit-all.json", tmp, inputDir, outputDir, false);
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ FetchEmitTuple tuple = new FetchEmitTuple(testFile,
+ new FetchKey(fetcherName, testFile),
+ new EmitKey(emitterName, ""), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+
+ // Should be EMIT_EXCEPTION because output file exists and onExists=EXCEPTION
+ assertEquals(PipesResult.RESULT_STATUS.EMIT_EXCEPTION, pipesResult.status(),
+ "Should return EMIT_EXCEPTION when emitter fails to write");
+
+ // Verify it's categorized as APPLICATION_ERROR
+ assertTrue(pipesResult.isApplicationError(),
+ "EMIT_EXCEPTION should be application error category");
+ }
+ }
+
+ @Test
+ public void testFetcherNotFound(@TempDir Path tmp) throws Exception {
+ // Test FETCHER_NOT_FOUND status
+ // Occurs when FetchKey references a fetcher that doesn't exist
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig(tmp, inputDir, tmp.resolve("output"));
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ // Use invalid fetcher name
+ FetchEmitTuple tuple = new FetchEmitTuple("test.pdf",
+ new FetchKey("non-existent-fetcher", "test.pdf"),
+ new EmitKey(), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+
+ // Should be FETCHER_NOT_FOUND
+ assertEquals(PipesResult.RESULT_STATUS.FETCHER_NOT_FOUND, pipesResult.status(),
+ "Should return FETCHER_NOT_FOUND when fetcher name is invalid");
+
+ // Verify it's categorized as APPLICATION_ERROR
+ assertTrue(pipesResult.isApplicationError(),
+ "FETCHER_NOT_FOUND should be application error category");
+
+ // Verify error message mentions the fetcher name
+ Assertions.assertNotNull(pipesResult.message());
+ assertTrue(pipesResult.message().contains("non-existent-fetcher") ||
+ pipesResult.message().contains("not found") ||
+ pipesResult.message().contains("fetcher"),
+ "Error message should mention the missing fetcher");
+ }
+ }
+
+ @Test
+ public void testEmitterNotFound(@TempDir Path tmp) throws Exception {
+ // Test EMITTER_NOT_FOUND status
+ // Occurs when EmitKey references an emitter that doesn't exist
+ Path inputDir = tmp.resolve("input");
+ Files.createDirectories(inputDir);
+
+ // Create valid test file
+ String testFile = "test.xml";
+ String mockContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<mock>" +
+ "<metadata action=\"add\" name=\"dc:creator\">Test</metadata>" +
+ "<write element=\"p\">content</write>" +
+ "</mock>";
+ Files.write(inputDir.resolve(testFile), mockContent.getBytes(StandardCharsets.UTF_8));
+
+ // Use config with directEmitThresholdBytes=0 to force server-side emission
+ Path tikaConfigPath = PluginsTestHelper.getFileSystemFetcherConfig("tika-config-emit-all.json", tmp, inputDir, tmp.resolve("output"), false);
+ TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfigPath);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfigPath);
+
+ try (PipesClient pipesClient = new PipesClient(pipesConfig)) {
+ // Use invalid emitter name
+ FetchEmitTuple tuple = new FetchEmitTuple(testFile,
+ new FetchKey(fetcherName, testFile),
+ new EmitKey("non-existent-emitter", ""), new Metadata(), new ParseContext(),
+ FetchEmitTuple.ON_PARSE_EXCEPTION.SKIP);
+
+ PipesResult pipesResult = pipesClient.process(tuple);
+
+ // Should be EMITTER_NOT_FOUND
+ assertEquals(PipesResult.RESULT_STATUS.EMITTER_NOT_FOUND, pipesResult.status(),
+ "Should return EMITTER_NOT_FOUND when emitter name is invalid");
+
+ // Verify it's categorized as APPLICATION_ERROR
+ assertTrue(pipesResult.isApplicationError(),
+ "EMITTER_NOT_FOUND should be application error category");
+
+ // Verify error message mentions the emitter name
+ Assertions.assertNotNull(pipesResult.message());
+ assertTrue(pipesResult.message().contains("non-existent-emitter") ||
+ pipesResult.message().contains("not found") ||
+ pipesResult.message().contains("emitter"),
+ "Error message should mention the missing emitter");
+ }
+ }
}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesServerTest.java b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesServerTest.java
index eca8ed017..854246c62 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesServerTest.java
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PipesServerTest.java
@@ -16,32 +16,10 @@
*/
package org.apache.tika.pipes.core;
-import static org.junit.jupiter.api.Assertions.assertEquals;
-import java.io.PrintStream;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Path;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
-import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
import org.apache.tika.TikaTest;
-import org.apache.tika.config.loader.TikaJsonConfig;
-import org.apache.tika.metadata.Metadata;
-import org.apache.tika.parser.ParseContext;
-import org.apache.tika.pipes.api.FetchEmitTuple;
-import org.apache.tika.pipes.api.HandlerConfig;
-import org.apache.tika.pipes.api.emitter.EmitKey;
-import org.apache.tika.pipes.api.fetcher.FetchKey;
-import org.apache.tika.pipes.api.fetcher.Fetcher;
-import org.apache.tika.pipes.api.pipesiterator.PipesIteratorBaseConfig;
-import org.apache.tika.pipes.core.extractor.BasicEmbeddedDocumentBytesHandler;
-import org.apache.tika.pipes.core.extractor.EmbeddedDocumentBytesConfig;
-import org.apache.tika.pipes.core.fetcher.FetcherManager;
-import org.apache.tika.plugins.TikaPluginManager;
public class PipesServerTest extends TikaTest {
@@ -52,19 +30,16 @@ public class PipesServerTest extends TikaTest {
* @param tmp
* @throws Exception
*/
+ /*
@Test
public void testBasic(@TempDir Path tmp) throws Exception {
String testDoc = "mock_times.xml";
Path tikaConfig = PluginsTestHelper.getFileSystemFetcherConfig(tmp);
PluginsTestHelper.copyTestFilesToTmpInput(tmp, testDoc);
- PipesServer pipesServer = new PipesServer(tikaConfig,
- UnsynchronizedByteArrayInputStream.builder().setByteArray(new byte[0]).get(),
- new PrintStream(UnsynchronizedByteArrayOutputStream.builder().get(), true,
- StandardCharsets.UTF_8.name()),
- -1, 30000, 30000);
-
- pipesServer.initializeResources();
+ TikaLoader tikaLoader = TikaLoader.load(tikaConfig);
+ PipesConfig pipesConfig = PipesConfig.load(tikaLoader.getConfig(), tikaConfig);
+ PipesServer pipesServer = PipesServer.load(40, tikaConfig);
FetchEmitTuple fetchEmitTuple = new FetchEmitTuple("id",
new FetchKey("fsf", testDoc),
@@ -72,7 +47,7 @@ public class PipesServerTest extends TikaTest {
TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfig);
TikaPluginManager pluginManager = TikaPluginManager.load(tikaJsonConfig);
Fetcher fetcher = FetcherManager.load(pluginManager, tikaJsonConfig).getFetcher();
- PipesServer.MetadataListAndEmbeddedBytes
+
parseData = pipesServer.parseFromTuple(fetchEmitTuple, fetcher);
assertEquals("5f3b924303e960ce35d7f705e91d3018dd110a9c3cef0546a91fe013d6dad6fd",
parseData.metadataList.get(0).get("X-TIKA:digest:SHA-256"));
@@ -172,5 +147,5 @@ public class PipesServerTest extends TikaTest {
assertEquals(10, bytes1.length);
assertEquals("fdaa937c96d1ed010b8d307ccddf9d11c3b48db732a8771eaafe99d59e076d0a",
parseData.metadataList.get(0).get("X-TIKA:digest:SHA-256"));
- }
+ }*/
}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PluginsTestHelper.java b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PluginsTestHelper.java
index 6f728e409..834a389be 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PluginsTestHelper.java
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/PluginsTestHelper.java
@@ -70,7 +70,6 @@ public class PluginsTestHelper {
LOG.warn("Couldn't find plugins from {}", pwd.toAbsolutePath());
}
json = json.replace("EMIT_INTERMEDIATE_RESULTS", String.valueOf(emitIntermediateResults));
- json = json.replace("TIKA_CONFIG", pipesConfig.toAbsolutePath().toString());
json = json.replace("\\", "/");
Files.write(pipesConfig, json.getBytes(StandardCharsets.UTF_8));
return pipesConfig;
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/async/AsyncChaosMonkeyTest.java b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/async/AsyncChaosMonkeyTest.java
index e352e3c9a..54fb0bba4 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/async/AsyncChaosMonkeyTest.java
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/java/org/apache/tika/pipes/core/async/AsyncChaosMonkeyTest.java
@@ -62,6 +62,9 @@ public class AsyncChaosMonkeyTest {
"<write element=\"p\">main_content</write>" +
"<system_exit/>" + "</mock>";
+ private final String STACK_OVERFLOW = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<mock>" +
+ "<throw class=\"java.lang.StackOverflowError\">stack overflow message</throw>\n</mock>";
+
private final int totalFiles = 100;
private Path inputDir;
@@ -70,7 +73,8 @@ public class AsyncChaosMonkeyTest {
private int ok = 0;
private int oom = 0;
private int timeouts = 0;
- private int crash = 0;
+ private int systemExit = 0;
+ private int stackOverflow = 0;
public Path setUp(Path tmpDir, boolean emitIntermediateResults) throws Exception {
@@ -83,7 +87,8 @@ public class AsyncChaosMonkeyTest {
ok = 0;
oom = 0;
timeouts = 0;
- crash = 0;
+ systemExit = 0;
+ stackOverflow = 0;
Random r = new Random();
@@ -94,14 +99,18 @@ public class AsyncChaosMonkeyTest {
oom++;
} else if (f < 0.10) {
Files.write(inputDir.resolve(i + ".xml"), SYSTEM_EXIT.getBytes(StandardCharsets.UTF_8));
- crash++;
+ systemExit++;
} else if (f < 0.13) {
Files.write(inputDir.resolve(i + ".xml"), TIMEOUT.getBytes(StandardCharsets.UTF_8));
timeouts++;
+ } else if (f < 0.16) {
+ Files.write(inputDir.resolve(i + ".xml"), STACK_OVERFLOW.getBytes(StandardCharsets.UTF_8));
+ stackOverflow++;
} else {
Files.write(inputDir.resolve(i + ".xml"), OK.getBytes(StandardCharsets.UTF_8));
ok++;
}
+
}
MockReporter.RESULTS.clear();
return PluginsTestHelper.getFileSystemFetcherConfig(configDir, inputDir, outputDir, emitIntermediateResults);
@@ -142,8 +151,15 @@ public class AsyncChaosMonkeyTest {
for (File f : outputDir.toFile().listFiles()) {
emitKeys.add(f.getName());
}
+
+ // When emitIntermediateResults = false, only successful files are emitted
assertEquals(ok, emitKeys.size());
- //TODO -- add mock reporter back
+
+ // Verify we got the expected distribution of file types
+ int expectedCrashes = oom + timeouts + systemExit + stackOverflow;
+ assertEquals(totalFiles, ok + expectedCrashes,
+ "Total files should equal sum of ok and crashes");
+
}
@Test
@@ -164,6 +180,10 @@ public class AsyncChaosMonkeyTest {
processor.close();
Set<String> emitKeys = new HashSet<>();
int observedOOM = 0;
+ int observedTimeout = 0;
+ int observedUnspecifiedCrash = 0;
+ int observedSuccess = 0;
+
for (File f : outputDir.toFile().listFiles()) {
emitKeys.add(f.getName());
List<Metadata> metadataList;
@@ -175,11 +195,31 @@ public class AsyncChaosMonkeyTest {
assertEquals("application/mock+xml",
metadataList.get(0).get(Metadata.CONTENT_TYPE));
String val = metadataList.get(0).get(TikaCoreProperties.PIPES_RESULT);
- if ("OOM".equals(val)) {
+ if (val == null) {
+ // Null means success (no crash status was set)
+ observedSuccess++;
+ } else if ("OOM".equals(val)) {
observedOOM++;
+ } else if ("TIMEOUT".equals(val)) {
+ observedTimeout++;
+ } else if ("UNSPECIFIED_CRASH".equals(val)) {
+ observedUnspecifiedCrash++;
}
}
+
+ // When emitIntermediateResults = true, all files are emitted (success and crashes)
assertEquals(totalFiles, emitKeys.size());
- assertEquals(oom, observedOOM);
+
+ // Verify each crash type was counted correctly
+ assertEquals(ok, observedSuccess, "Expected " + ok + " successful files but observed " + observedSuccess);
+ assertEquals(oom, observedOOM, "Expected " + oom + " OOM crashes but observed " + observedOOM);
+ assertEquals(timeouts, observedTimeout, "Expected " + timeouts + " timeout crashes but observed " + observedTimeout);
+
+ // System exit and stack overflow should both be UNSPECIFIED_CRASH
+ int expectedUnspecifiedCrash = systemExit + stackOverflow;
+ assertEquals(expectedUnspecifiedCrash, observedUnspecifiedCrash,
+ "Expected " + expectedUnspecifiedCrash + " unspecified crashes (systemExit=" +
+ systemExit + " + stackOverflow=" + stackOverflow + ") but observed " + observedUnspecifiedCrash);
+
}
}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-class.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-class.json
new file mode 100644
index 000000000..51e22b0ad
--- /dev/null
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-class.json
@@ -0,0 +1,16 @@
+{
+ "fetchers": {
+ "non-existent-fetcher-plugin": {
+ "bad-fetcher": {
+ "basePath": "FETCHER_BASE_PATH"
+ }
+ }
+ },
+ "pipes": {
+ "numClients": 1,
+ "timeoutMillis": 5000,
+ "forkedJvmArgs": ["-Xmx256m"],
+ "directEmitThresholdBytes": 1000000
+ },
+ "plugin-roots": "PLUGINS_PATHS"
+}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-java-path.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-java-path.json
new file mode 100644
index 000000000..cf7f051c2
--- /dev/null
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-java-path.json
@@ -0,0 +1,17 @@
+{
+ "fetchers": {
+ "non-existent-fetcher-plugin": {
+ "bad-fetcher": {
+ "basePath": "FETCHER_BASE_PATH"
+ }
+ }
+ },
+ "pipes": {
+ "numClients": 1,
+ "timeoutMillis": 5000,
+ "javaPath": "thisIsntJava",
+ "forkedJvmArgs": ["-Xmx256m"],
+ "directEmitThresholdBytes": 1000000
+ },
+ "plugin-roots": "PLUGINS_PATHS"
+}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-jvm-args.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-jvm-args.json
new file mode 100644
index 000000000..5c63904cd
--- /dev/null
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-bad-jvm-args.json
@@ -0,0 +1,16 @@
+{
+ "fetchers": {
+ "non-existent-fetcher-plugin": {
+ "bad-fetcher": {
+ "basePath": "FETCHER_BASE_PATH"
+ }
+ }
+ },
+ "pipes": {
+ "numClients": 1,
+ "timeoutMillis": 5000,
+ "forkedJvmArgs": ["-Xmx256m", "-ThisIsntAThing"],
+ "directEmitThresholdBytes": 1000000
+ },
+ "plugin-roots": "PLUGINS_PATHS"
+}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-basic.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-basic.json
index 57e9dc813..a8fbe4f10 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-basic.json
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-basic.json
@@ -39,12 +39,11 @@
}
},
"pipes": {
- "tikaConfig": "TIKA_CONFIG",
"numClients": 4,
"timeoutMillis": 5000,
"emitIntermediateResults": EMIT_INTERMEDIATE_RESULTS,
"forkedJvmArgs": ["-Xmx512m"],
- "maxForEmitBatchBytes": 1000000
+ "directEmitThresholdBytes": 1000000
},
"auto-detect-parser": {
"spoolToDisk": 1000000,
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-crashing-detector.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-crashing-detector.json
new file mode 100644
index 000000000..61fcd5032
--- /dev/null
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-crashing-detector.json
@@ -0,0 +1,29 @@
+{
+ "fetchers": {
+ "file-system-fetcher": {
+ "fsf": {
+ "basePath": "FETCHER_BASE_PATH",
+ "extractFileSystemMetadata": false
+ }
+ }
+ },
+ "emitters": {
+ "file-system-emitter": {
+ "fse": {
+ "basePath": "EMITTER_BASE_PATH",
+ "fileExtension": "json",
+ "onExists": "EXCEPTION"
+ }
+ }
+ },
+ "pipes": {
+ "numClients": 1,
+ "timeoutMillis": 5000,
+ "forkedJvmArgs": ["-Xmx256m"],
+ "directEmitThresholdBytes": 1000000
+ },
+ "detectors": [
+ {"org.apache.tika.pipes.core.CrashingDetector": {}}
+ ],
+ "plugin-roots": "PLUGINS_PATHS"
+}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-emit-all.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-emit-all.json
new file mode 100644
index 000000000..6389562eb
--- /dev/null
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-emit-all.json
@@ -0,0 +1,26 @@
+{
+ "fetchers": {
+ "file-system-fetcher": {
+ "fsf": {
+ "basePath": "FETCHER_BASE_PATH",
+ "extractFileSystemMetadata": false
+ }
+ }
+ },
+ "emitters": {
+ "file-system-emitter": {
+ "fse": {
+ "basePath": "EMITTER_BASE_PATH",
+ "fileExtension": "json",
+ "onExists": "EXCEPTION"
+ }
+ }
+ },
+ "pipes": {
+ "numClients": 1,
+ "timeoutMillis": 60000,
+ "forkedJvmArgs": ["-Xmx256m"],
+ "directEmitThresholdBytes": 0
+ },
+ "plugin-roots": "PLUGINS_PATHS"
+}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-passback.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-passback.json
index c92cf24d7..3f81bdd19 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-passback.json
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-passback.json
@@ -39,12 +39,11 @@
}
},
"pipes": {
- "tikaConfig": "TIKA_CONFIG",
"numClients": 4,
"timeoutMillis": 5000,
"emitIntermediateResults": EMIT_INTERMEDIATE_RESULTS,
"forkedJvmArgs": ["-Xmx512m"],
- "maxForEmitBatchBytes": 0
+ "directEmitThresholdBytes": 0
},
"auto-detect-parser": {
"spoolToDisk": 1000000,
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-timeout-lt-heartbeat.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-timeout-lt-heartbeat.json
new file mode 100644
index 000000000..c40ff1407
--- /dev/null
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-timeout-lt-heartbeat.json
@@ -0,0 +1,27 @@
+{
+ "fetchers": {
+ "file-system-fetcher": {
+ "fsf": {
+ "basePath": "FETCHER_BASE_PATH",
+ "extractFileSystemMetadata": false
+ }
+ }
+ },
+ "emitters": {
+ "file-system-emitter": {
+ "fse": {
+ "basePath": "EMITTER_BASE_PATH",
+ "fileExtension": "json",
+ "onExists": "EXCEPTION"
+ }
+ }
+ },
+ "pipes": {
+ "numClients": 1,
+ "timeoutMillis": 60000,
+ "socketTimeoutMs": 3000,
+ "heartbeatIntervalMs": 10000,
+ "forkedJvmArgs": ["-Xmx256m", "-Dtika.pipes.allowInvalidHeartbeat=true"]
+ },
+ "plugin-roots": "PLUGINS_PATHS"
+}
diff --git a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-truncate.json b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-truncate.json
index 811e8da1b..e13838e1a 100644
--- a/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-truncate.json
+++ b/tika-pipes/tika-pipes-integration-tests/src/test/resources/configs/tika-config-truncate.json
@@ -39,12 +39,11 @@
}
},
"pipes": {
- "tikaConfig": "TIKA_CONFIG",
"numClients": 4,
"timeoutMillis": 5000,
"emitIntermediateResults": EMIT_INTERMEDIATE_RESULTS,
"forkedJvmArgs": ["-Xmx512m"],
- "maxForEmitBatchBytes": 1000000
+ "directEmitThresholdBytes": 1000000
},
"auto-detect-parser": {
"spoolToDisk": 1000000,
diff --git a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/emitter/fs/FileSystemEmitter.java b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/emitter/fs/FileSystemEmitter.java
index 809c60591..65f229891 100644
--- a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/emitter/fs/FileSystemEmitter.java
+++ b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/emitter/fs/FileSystemEmitter.java
@@ -25,6 +25,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
@@ -110,8 +111,24 @@ public class FileSystemEmitter extends AbstractStreamEmitter {
if (output.getParent() != null && !Files.isDirectory(output.getParent())) {
Files.createDirectories(output.getParent());
}
- try (Writer writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) {
- JsonMetadataList.toJson(metadataList, writer, config.prettyPrint());
+
+ // Check onExists configuration
+ if (config.onExists() == FileSystemEmitterConfig.ON_EXISTS.SKIP) {
+ if (Files.exists(output)) {
+ LOG.debug("Skipping existing file: {}", output);
+ return;
+ }
+ }
+ if (config.onExists() == FileSystemEmitterConfig.ON_EXISTS.EXCEPTION) {
+ try (Writer writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8,
+ StandardOpenOption.CREATE_NEW)) { //CREATE_NEW forces an IOException if the file already exists
+ JsonMetadataList.toJson(metadataList, writer, config.prettyPrint());
+ }
+ } else {
+ try (Writer writer = Files.newBufferedWriter(output, StandardCharsets.UTF_8)) {
+ JsonMetadataList.toJson(metadataList, writer, config.prettyPrint());
+ }
+
}
}
diff --git a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/AsyncStatus.java b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/AsyncStatus.java
index 7b8ab5db2..4927f73df 100644
--- a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/AsyncStatus.java
+++ b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/AsyncStatus.java
@@ -35,7 +35,7 @@ class AsyncStatus {
private Instant lastUpdate;
private TotalCountResult totalCountResult = new TotalCountResult(0, TotalCountResult.STATUS.NOT_COMPLETED);
- private Map<PipesResult.STATUS, Long> statusCounts = new HashMap<>();
+ private Map<PipesResult.RESULT_STATUS, Long> statusCounts = new HashMap<>();
private ASYNC_STATUS asyncStatus = ASYNC_STATUS.STARTED;
private String crashMessage = StringUtils.EMPTY;
@@ -45,7 +45,7 @@ class AsyncStatus {
lastUpdate = started;
}
- public synchronized void update(Map<PipesResult.STATUS, Long> statusCounts,
+ public synchronized void update(Map<PipesResult.RESULT_STATUS, Long> statusCounts,
TotalCountResult totalCountResult, ASYNC_STATUS status) {
this.lastUpdate = Instant.now();
this.statusCounts = statusCounts;
@@ -69,7 +69,7 @@ class AsyncStatus {
return totalCountResult;
}
- public Map<PipesResult.STATUS, Long> getStatusCounts() {
+ public Map<PipesResult.RESULT_STATUS, Long> getStatusCounts() {
return statusCounts;
}
diff --git a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/FileSystemStatusReporter.java b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/FileSystemStatusReporter.java
index c85bcaaf3..83a527d0c 100644
--- a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/FileSystemStatusReporter.java
+++ b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/main/java/org/apache/tika/pipes/reporter/fs/FileSystemStatusReporter.java
@@ -71,7 +71,7 @@ public class FileSystemStatusReporter extends AbstractTikaExtension implements P
private volatile boolean crashed = false;
Thread reporterThread;
- private ConcurrentHashMap<PipesResult.STATUS, LongAdder> counts = new ConcurrentHashMap<>();
+ private ConcurrentHashMap<PipesResult.RESULT_STATUS, LongAdder> counts = new ConcurrentHashMap<>();
private AsyncStatus asyncStatus = new AsyncStatus();
private TotalCountResult totalCountResult = new TotalCountResult(0,
@@ -118,7 +118,7 @@ public class FileSystemStatusReporter extends AbstractTikaExtension implements P
}
private synchronized void report(AsyncStatus.ASYNC_STATUS status) {
- Map<PipesResult.STATUS, Long> localCounts = new HashMap<>();
+ Map<PipesResult.RESULT_STATUS, Long> localCounts = new HashMap<>();
counts.entrySet().forEach( e -> localCounts.put(e.getKey(), e.getValue().longValue()));
asyncStatus.update(localCounts, totalCountResult, status);
try (Writer writer = Files.newBufferedWriter(config.statusFile(), StandardCharsets.UTF_8)) {
diff --git a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/test/java/org/apache/tika/pipes/reporter/fs/TestFileSystemStatusReporter.java b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/test/java/org/apache/tika/pipes/reporter/fs/TestFileSystemStatusReporter.java
index 9095d0f49..3d3bf61f2 100644
--- a/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/test/java/org/apache/tika/pipes/reporter/fs/TestFileSystemStatusReporter.java
+++ b/tika-pipes/tika-pipes-plugins/tika-pipes-file-system/src/test/java/org/apache/tika/pipes/reporter/fs/TestFileSystemStatusReporter.java
@@ -94,7 +94,7 @@ public class TestFileSystemStatusReporter {
});
readerThread.start();
- Map<PipesResult.STATUS, Long> total = runBatch(reporter, 10, 200);
+ Map<PipesResult.RESULT_STATUS, Long> total = runBatch(reporter, 10, 200);
readerThread.interrupt();
@@ -102,9 +102,9 @@ public class TestFileSystemStatusReporter {
reporter.report(new TotalCountResult(30000, TotalCountResult.STATUS.COMPLETED));
reporter.close();
AsyncStatus asyncStatus = objectMapper.readValue(path.toFile(), AsyncStatus.class);
- Map<PipesResult.STATUS, Long> map = asyncStatus.getStatusCounts();
+ Map<PipesResult.RESULT_STATUS, Long> map = asyncStatus.getStatusCounts();
assertEquals(total.size(), map.size());
- for (Map.Entry<PipesResult.STATUS, Long> e : total.entrySet()) {
+ for (Map.Entry<PipesResult.RESULT_STATUS, Long> e : total.entrySet()) {
assertTrue(map.containsKey(e.getKey()), e.getKey().toString());
assertEquals(e.getValue(), map.get(e.getKey()), e.getKey().toString());
}
@@ -113,9 +113,9 @@ public class TestFileSystemStatusReporter {
assertEquals(TotalCountResult.STATUS.COMPLETED, asyncStatus.getTotalCountResult().getStatus());
}
- private Map<PipesResult.STATUS, Long> runBatch(FileSystemStatusReporter reporter,
- int numThreads,
- int numIterations)
+ private Map<PipesResult.RESULT_STATUS, Long> runBatch(FileSystemStatusReporter reporter,
+ int numThreads,
+ int numIterations)
throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
ExecutorCompletionService executorCompletionService =
@@ -127,7 +127,7 @@ public class TestFileSystemStatusReporter {
executorCompletionService.submit(reportWorker);
}
- Map<PipesResult.STATUS, Long> total = new HashMap<>();
+ Map<PipesResult.RESULT_STATUS, Long> total = new HashMap<>();
int finished = 0;
while (finished < numThreads) {
Future<Integer> future = executorCompletionService.poll();
@@ -137,8 +137,8 @@ public class TestFileSystemStatusReporter {
}
}
for (ReportWorker r : workerList) {
- Map<PipesResult.STATUS, Long> local = r.getWritten();
- for (Map.Entry<PipesResult.STATUS, Long> e : local.entrySet()) {
+ Map<PipesResult.RESULT_STATUS, Long> local = r.getWritten();
+ for (Map.Entry<PipesResult.RESULT_STATUS, Long> e : local.entrySet()) {
Long t = total.get(e.getKey());
if (t == null) {
t = e.getValue();
@@ -152,7 +152,7 @@ public class TestFileSystemStatusReporter {
}
private class ReportWorker implements Callable<Integer> {
- Map<PipesResult.STATUS, Long> written = new HashMap<>();
+ Map<PipesResult.RESULT_STATUS, Long> written = new HashMap<>();
private final PipesReporter reporter;
private final int numIterations;
@@ -162,10 +162,10 @@ public class TestFileSystemStatusReporter {
}
@Override
public Integer call() throws Exception {
- PipesResult.STATUS[] statuses = PipesResult.STATUS.values();
+ PipesResult.RESULT_STATUS[] statuses = PipesResult.RESULT_STATUS.values();
Random random = new Random();
for (int i = 0; i < numIterations; i++) {
- PipesResult.STATUS status = statuses[random.nextInt(statuses.length)];
+ PipesResult.RESULT_STATUS status = statuses[random.nextInt(statuses.length)];
PipesResult pipesResult = new PipesResult(status);
reporter.report(PipesIterator.COMPLETED_SEMAPHORE, pipesResult, 100l);
@@ -185,7 +185,7 @@ public class TestFileSystemStatusReporter {
return 1;
}
- Map<PipesResult.STATUS, Long> getWritten() {
+ Map<PipesResult.RESULT_STATUS, Long> getWritten() {
return written;
}
}
diff --git a/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/main/java/org/apache/tika/pipes/reporter/jdbc/JDBCPipesReporter.java b/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/main/java/org/apache/tika/pipes/reporter/jdbc/JDBCPipesReporter.java
index bc51bf329..f3239b446 100644
--- a/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/main/java/org/apache/tika/pipes/reporter/jdbc/JDBCPipesReporter.java
+++ b/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/main/java/org/apache/tika/pipes/reporter/jdbc/JDBCPipesReporter.java
@@ -163,9 +163,9 @@ public class JDBCPipesReporter extends PipesReporterBase {
static IdStatusPair END_SEMAPHORE = new IdStatusPair(null, null);
private final String id;
- private final PipesResult.STATUS status;
+ private final PipesResult.RESULT_STATUS status;
- public IdStatusPair(String id, PipesResult.STATUS status) {
+ public IdStatusPair(String id, PipesResult.RESULT_STATUS status) {
this.id = id;
this.status = status;
}
diff --git a/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/test/java/org/apache/tika/pipes/reporter/jdbc/TestJDBCPipesReporter.java b/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/test/java/org/apache/tika/pipes/reporter/jdbc/TestJDBCPipesReporter.java
index 99eb5f60c..986f4119e 100644
--- a/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/test/java/org/apache/tika/pipes/reporter/jdbc/TestJDBCPipesReporter.java
+++ b/tika-pipes/tika-pipes-plugins/tika-pipes-jdbc/src/test/java/org/apache/tika/pipes/reporter/jdbc/TestJDBCPipesReporter.java
@@ -16,8 +16,8 @@
*/
package org.apache.tika.pipes.reporter.jdbc;
-import static org.apache.tika.pipes.api.PipesResult.STATUS.PARSE_SUCCESS;
-import static org.apache.tika.pipes.api.PipesResult.STATUS.PARSE_SUCCESS_WITH_EXCEPTION;
+import static org.apache.tika.pipes.api.PipesResult.RESULT_STATUS.PARSE_SUCCESS;
+import static org.apache.tika.pipes.api.PipesResult.RESULT_STATUS.PARSE_SUCCESS_WITH_EXCEPTION;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -92,13 +92,13 @@ public class TestJDBCPipesReporter {
.replace("\\", "/");
JDBCPipesReporter reporter = JDBCPipesReporter.build(new ExtensionConfig("test-jdbc", "jdbc-reporter", json));
- Map<PipesResult.STATUS, Long> expected = runBatch(reporter, numThreads, numIterations);
+ Map<PipesResult.RESULT_STATUS, Long> expected = runBatch(reporter, numThreads, numIterations);
reporter.close();
- Map<PipesResult.STATUS, Long> total = countReported(connectionString);
+ Map<PipesResult.RESULT_STATUS, Long> total = countReported(connectionString);
assertEquals(expected.size(), total.size());
long sum = 0;
- for (Map.Entry<PipesResult.STATUS, Long> e : expected.entrySet()) {
+ for (Map.Entry<PipesResult.RESULT_STATUS, Long> e : expected.entrySet()) {
assertTrue(total.containsKey(e.getKey()), e.getKey().toString());
assertEquals(e.getValue(), total.get(e.getKey()), e.getKey().toString());
sum += e.getValue();
@@ -119,12 +119,12 @@ public class TestJDBCPipesReporter {
int numThreads = 10;
int numIterations = 200;
- Map<PipesResult.STATUS, Long> expected = runBatch(reporter, numThreads, numIterations);
+ Map<PipesResult.RESULT_STATUS, Long> expected = runBatch(reporter, numThreads, numIterations);
reporter.close();
- Map<PipesResult.STATUS, Long> total = countReported(connectionString);
+ Map<PipesResult.RESULT_STATUS, Long> total = countReported(connectionString);
assertEquals(2, total.size());
long sum = 0;
- for (Map.Entry<PipesResult.STATUS, Long> e : expected.entrySet()) {
+ for (Map.Entry<PipesResult.RESULT_STATUS, Long> e : expected.entrySet()) {
if (e.getKey() == PARSE_SUCCESS || e.getKey() == PARSE_SUCCESS_WITH_EXCEPTION) {
assertTrue(total.containsKey(e.getKey()), e.getKey().toString());
assertEquals(e.getValue(), total.get(e.getKey()), e.getKey().toString());
@@ -148,12 +148,12 @@ public class TestJDBCPipesReporter {
int numThreads = 10;
int numIterations = 200;
- Map<PipesResult.STATUS, Long> expected = runBatch(reporter, numThreads, numIterations);
+ Map<PipesResult.RESULT_STATUS, Long> expected = runBatch(reporter, numThreads, numIterations);
reporter.close();
- Map<PipesResult.STATUS, Long> total = countReported(connectionString);
- assertEquals(17, total.size());
+ Map<PipesResult.RESULT_STATUS, Long> total = countReported(connectionString);
+ assertEquals(16, total.size());
long sum = 0;
- for (Map.Entry<PipesResult.STATUS, Long> e : expected.entrySet()) {
+ for (Map.Entry<PipesResult.RESULT_STATUS, Long> e : expected.entrySet()) {
if (e.getKey() != PARSE_SUCCESS && e.getKey() != PARSE_SUCCESS_WITH_EXCEPTION) {
assertTrue(total.containsKey(e.getKey()), e.getKey().toString());
assertEquals(e.getValue(), total.get(e.getKey()), e.getKey().toString());
@@ -165,9 +165,9 @@ public class TestJDBCPipesReporter {
assertEquals(numThreads * numIterations, sum);
}
- private Map<PipesResult.STATUS, Long> countReported(String connectionString) throws
+ private Map<PipesResult.RESULT_STATUS, Long> countReported(String connectionString) throws
SQLException {
- Map<PipesResult.STATUS, Long> counts = new HashMap<>();
+ Map<PipesResult.RESULT_STATUS, Long> counts = new HashMap<>();
try (Connection connection = DriverManager.getConnection(connectionString)) {
try (Statement st = connection.createStatement()) {
String sql = "select * from tika_status";
@@ -175,7 +175,7 @@ public class TestJDBCPipesReporter {
while (rs.next()) {
String fetchKey = rs.getString(1);
String name = rs.getString(2);
- PipesResult.STATUS status = PipesResult.STATUS.valueOf(name);
+ PipesResult.RESULT_STATUS status = PipesResult.RESULT_STATUS.valueOf(name);
Long cnt = counts.get(status);
if (cnt == null) {
cnt = 1L;
@@ -190,9 +190,9 @@ public class TestJDBCPipesReporter {
return counts;
}
- private Map<PipesResult.STATUS, Long> runBatch(PipesReporter reporter,
- int numThreads,
- int numIterations)
+ private Map<PipesResult.RESULT_STATUS, Long> runBatch(PipesReporter reporter,
+ int numThreads,
+ int numIterations)
throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
ExecutorCompletionService<Integer> executorCompletionService =
@@ -204,7 +204,7 @@ public class TestJDBCPipesReporter {
executorCompletionService.submit(reportWorker);
}
- Map<PipesResult.STATUS, Long> total = new HashMap<>();
+ Map<PipesResult.RESULT_STATUS, Long> total = new HashMap<>();
int finished = 0;
while (finished < numThreads) {
Future<Integer> future = executorCompletionService.poll();
@@ -214,8 +214,8 @@ public class TestJDBCPipesReporter {
}
}
for (ReportWorker r : workerList) {
- Map<PipesResult.STATUS, Long> local = r.getWritten();
- for (Map.Entry<PipesResult.STATUS, Long> e : local.entrySet()) {
+ Map<PipesResult.RESULT_STATUS, Long> local = r.getWritten();
+ for (Map.Entry<PipesResult.RESULT_STATUS, Long> e : local.entrySet()) {
Long t = total.get(e.getKey());
if (t == null) {
t = e.getValue();
@@ -229,7 +229,7 @@ public class TestJDBCPipesReporter {
}
private static class ReportWorker implements Callable<Integer> {
- Map<PipesResult.STATUS, Long> written = new HashMap<>();
+ Map<PipesResult.RESULT_STATUS, Long> written = new HashMap<>();
private static final AtomicInteger TOTAL_ADDED = new AtomicInteger(0);
private final PipesReporter reporter;
private final int numIterations;
@@ -239,10 +239,10 @@ public class TestJDBCPipesReporter {
}
@Override
public Integer call() throws Exception {
- PipesResult.STATUS[] statuses = PipesResult.STATUS.values();
+ PipesResult.RESULT_STATUS[] statuses = PipesResult.RESULT_STATUS.values();
Random random = new Random();
for (int i = 0; i < numIterations; i++) {
- PipesResult.STATUS status = statuses[random.nextInt(statuses.length)];
+ PipesResult.RESULT_STATUS status = statuses[random.nextInt(statuses.length)];
PipesResult pipesResult = new PipesResult(status);
String id = "id " + TOTAL_ADDED.getAndIncrement();
FetchEmitTuple t = new FetchEmitTuple(id,
@@ -267,7 +267,7 @@ public class TestJDBCPipesReporter {
return 1;
}
- Map<PipesResult.STATUS, Long> getWritten() {
+ Map<PipesResult.RESULT_STATUS, Long> getWritten() {
return written;
}
}
diff --git a/tika-pipes/tika-pipes-reporter-commons/src/main/java/org/apache/tika/pipes/reporters/PipesReporterBase.java b/tika-pipes/tika-pipes-reporter-commons/src/main/java/org/apache/tika/pipes/reporters/PipesReporterBase.java
index eee33fd78..2c31d69b5 100644
--- a/tika-pipes/tika-pipes-reporter-commons/src/main/java/org/apache/tika/pipes/reporters/PipesReporterBase.java
+++ b/tika-pipes/tika-pipes-reporter-commons/src/main/java/org/apache/tika/pipes/reporters/PipesReporterBase.java
@@ -26,7 +26,7 @@ import org.apache.tika.plugins.AbstractTikaExtension;
import org.apache.tika.plugins.ExtensionConfig;
/**
- * Base class that includes filtering by {@link PipesResult.STATUS}
+ * Base class that includes filtering by {@link PipesResult.RESULT_STATUS}
*/
public abstract class PipesReporterBase extends AbstractTikaExtension implements PipesReporter {
@@ -68,36 +68,36 @@ public abstract class PipesReporterBase extends AbstractTikaExtension implements
* @param status
* @return
*/
- public boolean accept(PipesResult.STATUS status) {
+ public boolean accept(PipesResult.RESULT_STATUS status) {
return statusFilter.accept(status);
}
private abstract static class StatusFilter {
- abstract boolean accept(PipesResult.STATUS status);
+ abstract boolean accept(PipesResult.RESULT_STATUS status);
}
private static class IncludesFilter extends StatusFilter {
- private final Set<PipesResult.STATUS> includes;
+ private final Set<PipesResult.RESULT_STATUS> includes;
private IncludesFilter(Set<String> includesStrings) {
this.includes = convert(includesStrings);
}
@Override
- boolean accept(PipesResult.STATUS status) {
+ boolean accept(PipesResult.RESULT_STATUS status) {
return includes.contains(status);
}
}
private static class ExcludesFilter extends StatusFilter {
- private final Set<PipesResult.STATUS> excludes;
+ private final Set<PipesResult.RESULT_STATUS> excludes;
ExcludesFilter(Set<String> excludes) {
this.excludes = convert(excludes);
}
@Override
- boolean accept(PipesResult.STATUS status) {
+ boolean accept(PipesResult.RESULT_STATUS status) {
return !excludes.contains(status);
}
}
@@ -105,15 +105,15 @@ public abstract class PipesReporterBase extends AbstractTikaExtension implements
private static class AcceptAllFilter extends StatusFilter {
@Override
- boolean accept(PipesResult.STATUS status) {
+ boolean accept(PipesResult.RESULT_STATUS status) {
return true;
}
}
- private static Set<PipesResult.STATUS> convert(Set<String> statusStrings) {
- Set<PipesResult.STATUS> ret = new HashSet<>();
+ private static Set<PipesResult.RESULT_STATUS> convert(Set<String> statusStrings) {
+ Set<PipesResult.RESULT_STATUS> ret = new HashSet<>();
for (String s : statusStrings) {
- ret.add(PipesResult.STATUS.valueOf(s));
+ ret.add(PipesResult.RESULT_STATUS.valueOf(s));
}
return ret;
}
diff --git a/tika-serialization/src/main/java/org/apache/tika/config/loader/DetectorLoader.java b/tika-serialization/src/main/java/org/apache/tika/config/loader/DetectorLoader.java
index f2146cfc1..3f19de4f1 100644
--- a/tika-serialization/src/main/java/org/apache/tika/config/loader/DetectorLoader.java
+++ b/tika-serialization/src/main/java/org/apache/tika/config/loader/DetectorLoader.java
@@ -171,8 +171,20 @@ public class DetectorLoader {
ComponentRegistry registry)
throws TikaConfigException {
try {
- // Get detector class
- Class<?> detectorClass = registry.getComponentClass(name);
+ // Get detector class - try component name first, then FQCN fallback
+ Class<?> detectorClass;
+ try {
+ detectorClass = registry.getComponentClass(name);
+ } catch (TikaConfigException e) {
+ // If not found as component name, try as fully qualified class name
+ try {
+ detectorClass = Class.forName(name, false, classLoader);
+ LOG.debug("Loaded detector by FQCN: {}", name);
+ } catch (ClassNotFoundException ex) {
+ throw new TikaConfigException("Unknown detector: '" + name +
+ "'. Not found as component name or FQCN.", e);
+ }
+ }
// Extract framework config
FrameworkConfig frameworkConfig = FrameworkConfig.extract(configNode, objectMapper);
@@ -182,6 +194,8 @@ public class DetectorLoader {
return detector;
+ } catch (TikaConfigException e) {
+ throw e;
} catch (Exception e) {
throw new TikaConfigException("Failed to load detector '" + name + "'", e);
}
diff --git a/tika-serialization/src/main/java/org/apache/tika/config/loader/EncodingDetectorLoader.java b/tika-serialization/src/main/java/org/apache/tika/config/loader/EncodingDetectorLoader.java
index 35079dfeb..426140ff8 100644
--- a/tika-serialization/src/main/java/org/apache/tika/config/loader/EncodingDetectorLoader.java
+++ b/tika-serialization/src/main/java/org/apache/tika/config/loader/EncodingDetectorLoader.java
@@ -92,15 +92,26 @@ public class EncodingDetectorLoader {
if (excludeName.isTextual()) {
String detectorName = excludeName.asText();
try {
- Class<?> detectorClass = registry.getComponentClass(detectorName);
+ Class<?> detectorClass;
+ // Try as component name first
+ try {
+ detectorClass = registry.getComponentClass(detectorName);
+ } catch (TikaConfigException e) {
+ // If not found as component name, try as FQCN
+ try {
+ detectorClass = Class.forName(detectorName, false, classLoader);
+ } catch (ClassNotFoundException ex) {
+ LOG.warn("Unknown encoding detector in default-encoding-detector exclude list: {}", detectorName);
+ continue;
+ }
+ }
@SuppressWarnings("unchecked")
Class<? extends EncodingDetector> detectorTyped =
(Class<? extends EncodingDetector>) detectorClass;
excludedDetectorClasses.add(detectorTyped);
LOG.debug("Excluding encoding detector from SPI: {}", detectorName);
- } catch (TikaConfigException e) {
- LOG.warn("Unknown encoding detector in default-encoding-detector exclude list: {}",
- detectorName);
+ } catch (Exception e) {
+ LOG.warn("Failed to exclude encoding detector '{}': {}", detectorName, e.getMessage());
}
}
}
@@ -159,8 +170,20 @@ public class EncodingDetectorLoader {
ComponentRegistry registry)
throws TikaConfigException {
try {
- // Get encoding detector class
- Class<?> detectorClass = registry.getComponentClass(name);
+ // Get encoding detector class - try component name first, then FQCN fallback
+ Class<?> detectorClass;
+ try {
+ detectorClass = registry.getComponentClass(name);
+ } catch (TikaConfigException e) {
+ // If not found as component name, try as fully qualified class name
+ try {
+ detectorClass = Class.forName(name, false, classLoader);
+ LOG.debug("Loaded encoding detector by FQCN: {}", name);
+ } catch (ClassNotFoundException ex) {
+ throw new TikaConfigException("Unknown encoding detector: '" + name +
+ "'. Not found as component name or FQCN.", e);
+ }
+ }
// Extract framework config
FrameworkConfig frameworkConfig = FrameworkConfig.extract(configNode, objectMapper);
@@ -171,6 +194,8 @@ public class EncodingDetectorLoader {
return detector;
+ } catch (TikaConfigException e) {
+ throw e;
} catch (Exception e) {
throw new TikaConfigException("Failed to load encoding detector '" + name + "'", e);
}
diff --git a/tika-serialization/src/main/java/org/apache/tika/config/loader/ParserLoader.java b/tika-serialization/src/main/java/org/apache/tika/config/loader/ParserLoader.java
index b6bb8ebff..96a8698e7 100644
--- a/tika-serialization/src/main/java/org/apache/tika/config/loader/ParserLoader.java
+++ b/tika-serialization/src/main/java/org/apache/tika/config/loader/ParserLoader.java
@@ -125,9 +125,25 @@ public class ParserLoader {
for (JsonNode excludeName : excludeNode) {
if (excludeName.isTextual()) {
String parserName = excludeName.asText();
- Class<?> parserClass = registry.getComponentClass(parserName);
- excludedParserClasses.add(parserClass);
- LOG.debug("Excluding parser from SPI: {}", parserName);
+ try {
+ Class<?> parserClass;
+ // Try as component name first
+ try {
+ parserClass = registry.getComponentClass(parserName);
+ } catch (TikaConfigException e) {
+ // If not found as component name, try as FQCN
+ try {
+ parserClass = Class.forName(parserName, false, classLoader);
+ } catch (ClassNotFoundException ex) {
+ LOG.warn("Unknown parser in default-parser exclude list: {}", parserName);
+ continue;
+ }
+ }
+ excludedParserClasses.add(parserClass);
+ LOG.debug("Excluding parser from SPI: {}", parserName);
+ } catch (Exception e) {
+ LOG.warn("Failed to exclude parser '{}': {}", parserName, e.getMessage());
+ }
}
}
}
@@ -204,8 +220,20 @@ public class ParserLoader {
ComponentRegistry registry)
throws TikaConfigException {
try {
- // Get parser class
- Class<?> parserClass = registry.getComponentClass(name);
+ // Get parser class - try component name first, then FQCN fallback
+ Class<?> parserClass;
+ try {
+ parserClass = registry.getComponentClass(name);
+ } catch (TikaConfigException e) {
+ // If not found as component name, try as fully qualified class name
+ try {
+ parserClass = Class.forName(name, false, classLoader);
+ LOG.debug("Loaded parser by FQCN: {}", name);
+ } catch (ClassNotFoundException ex) {
+ throw new TikaConfigException("Unknown parser: '" + name +
+ "'. Not found as component name or FQCN.", e);
+ }
+ }
// Extract framework config
FrameworkConfig frameworkConfig = FrameworkConfig.extract(configNode, objectMapper);
@@ -215,6 +243,8 @@ public class ParserLoader {
return new ParsedParserConfig(name, parser, frameworkConfig.getDecoration());
+ } catch (TikaConfigException e) {
+ throw e;
} catch (Exception e) {
throw new TikaConfigException("Failed to load parser '" + name + "'", e);
}
diff --git a/tika-server/tika-server-core/src/main/java/org/apache/tika/server/core/resource/PipesResource.java b/tika-server/tika-server-core/src/main/java/org/apache/tika/server/core/resource/PipesResource.java
index 69426d17f..8c1530511 100644
--- a/tika-server/tika-server-core/src/main/java/org/apache/tika/server/core/resource/PipesResource.java
+++ b/tika-server/tika-server-core/src/main/java/org/apache/tika/server/core/resource/PipesResource.java
@@ -54,12 +54,12 @@ public class PipesResource {
public PipesResource(java.nio.file.Path tikaConfig) throws TikaConfigException, IOException {
TikaJsonConfig tikaJsonConfig = TikaJsonConfig.load(tikaConfig);
- PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig);
+ PipesConfig pipesConfig = PipesConfig.load(tikaJsonConfig, tikaConfig);
//this has to be zero. everything must be emitted through the PipesServer
- long maxEmit = pipesConfig.getMaxForEmitBatchBytes();
+ long maxEmit = pipesConfig.getDirectEmitThresholdBytes();
if (maxEmit != 0) {
- pipesConfig.setMaxForEmitBatchBytes(0);
- if (maxEmit != PipesConfig.DEFAULT_MAX_FOR_EMIT_BATCH) {
+ pipesConfig.setDirectEmitThresholdBytes(0);
+ if (maxEmit != PipesConfig.DEFAULT_DIRECT_EMIT_THRESHOLD_BYTES) {
LOG.warn("resetting max for emit batch to 0");
}
}
@@ -96,36 +96,20 @@ public class PipesResource {
private Map<String, String> processTuple(FetchEmitTuple fetchEmitTuple) throws InterruptedException, PipesException, IOException {
PipesResult pipesResult = pipesParser.parse(fetchEmitTuple);
+ if (pipesResult.isProcessCrash()) {
+ return returnProcessCrash(pipesResult.status().toString());
+ } else if (pipesResult.isApplicationError()) {
+ return returnApplicationError(pipesResult
+ .status()
+ .toString());
+ }
switch (pipesResult.status()) {
- case CLIENT_UNAVAILABLE_WITHIN_MS:
- throw new IllegalStateException("client not available within " + "allotted amount of time");
- case EMIT_EXCEPTION:
- return returnEmitException(pipesResult.message());
- case PARSE_SUCCESS:
- case PARSE_SUCCESS_WITH_EXCEPTION:
- throw new IllegalArgumentException("Should have emitted in forked process?!");
- case EMIT_SUCCESS:
- return returnSuccess();
case EMIT_SUCCESS_PARSE_EXCEPTION:
return parseException(pipesResult.message(), true);
- case PARSE_EXCEPTION_EMIT:
- throw new IllegalArgumentException("Should have tried to emit in forked " + "process?!");
case PARSE_EXCEPTION_NO_EMIT:
return parseException(pipesResult.message(), false);
- case TIMEOUT:
- return returnError("timeout");
- case OOM:
- return returnError("oom");
- case UNSPECIFIED_CRASH:
- return returnError("unknown_crash");
- case NO_EMITTER_FOUND: {
- throw new IllegalArgumentException("Couldn't find emitter that matched: " + fetchEmitTuple
- .getEmitKey()
- .getEmitterId());
- }
- default:
- throw new IllegalArgumentException("I'm sorry, I don't yet handle a status of " + "this type: " + pipesResult.status());
}
+ return returnSuccess();
}
private Map<String, String> parseException(String msg, boolean emitted) {
@@ -136,23 +120,23 @@ public class PipesResource {
return statusMap;
}
- private Map<String, String> returnEmitException(String msg) {
+ private Map<String, String> returnSuccess() {
Map<String, String> statusMap = new HashMap<>();
- statusMap.put("status", "emit_exception");
- statusMap.put("message", msg);
+ statusMap.put("status", "ok");
return statusMap;
}
- private Map<String, String> returnSuccess() {
+ private Map<String, String> returnProcessCrash(String type) {
Map<String, String> statusMap = new HashMap<>();
- statusMap.put("status", "ok");
+ statusMap.put("status", "process_crash");
+ statusMap.put("type", type);
return statusMap;
}
- private Map<String, String> returnError(String type) {
+ private Map<String, String> returnApplicationError(String type) {
Map<String, String> statusMap = new HashMap<>();
- statusMap.put("status", "parse_error");
- statusMap.put("parse_error", type);
+ statusMap.put("status", "application_error");
+ statusMap.put("type", type);
return statusMap;
}
diff --git a/tika-server/tika-server-core/src/test/java/org/apache/tika/server/core/TikaServerPipesIntegrationTest.java b/tika-server/tika-server-core/src/test/java/org/apache/tika/server/core/TikaServerPipesIntegrationTest.java
index eb77aeee4..b9b5ae88e 100644
--- a/tika-server/tika-server-core/src/test/java/org/apache/tika/server/core/TikaServerPipesIntegrationTest.java
+++ b/tika-server/tika-server-core/src/test/java/org/apache/tika/server/core/TikaServerPipesIntegrationTest.java
@@ -143,11 +143,11 @@ public class TikaServerPipesIntegrationTest extends IntegrationTestBase {
.toAbsolutePath()
.toString())});
JsonNode node = testOne("system_exit.xml", false);
- assertEquals("parse_error", node
+ assertEquals("process_crash", node
.get("status")
.asText());
- assertContains("unknown_crash", node
- .get("parse_error")
+ assertContains("UNSPECIFIED_CRASH", node
+ .get("type")
.asText());
}
@@ -160,11 +160,11 @@ public class TikaServerPipesIntegrationTest extends IntegrationTestBase {
.toAbsolutePath()
.toString())});
JsonNode node = testOne("fake_oom.xml", false);
- assertEquals("parse_error", node
+ assertEquals("process_crash", node
.get("status")
.asText());
- assertContains("oom", node
- .get("parse_error")
+ assertContains("OOM", node
+ .get("type")
.asText());
} catch (ProcessingException e) {
//depending on timing, there may be a connection exception --
@@ -180,11 +180,11 @@ public class TikaServerPipesIntegrationTest extends IntegrationTestBase {
.toAbsolutePath()
.toString())});
JsonNode node = testOne("heavy_hang_30000.xml", false);
- assertEquals("parse_error", node
+ assertEquals("process_crash", node
.get("status")
.asText());
- assertContains("timeout", node
- .get("parse_error")
+ assertContains("TIMEOUT", node
+ .get("type")
.asText());
}
diff --git a/tika-server/tika-server-core/src/test/resources/configs/cxf-test-base-template.json b/tika-server/tika-server-core/src/test/resources/configs/cxf-test-base-template.json
index 0182e2bd0..475441885 100644
--- a/tika-server/tika-server-core/src/test/resources/configs/cxf-test-base-template.json
+++ b/tika-server/tika-server-core/src/test/resources/configs/cxf-test-base-template.json
@@ -34,14 +34,13 @@
]
},
"pipes": {
- "tikaConfig": "TIKA_CONFIG",
"numClients": 2,
"timeoutMillis": TIMEOUT_MILLIS,
"emitIntermediateResults": false,
"forkedJvmArgs": [
"-Xmx512m"
],
- "maxForEmitBatchBytes": 1000000
+ "directEmitThresholdBytes": 0
},
"auto-detect-parser": {
"spoolToDisk": 1000000,
diff --git a/tika-server/tika-server-standard/src/test/resources/configs/cxf-test-base-template.json b/tika-server/tika-server-standard/src/test/resources/configs/cxf-test-base-template.json
index 0182e2bd0..475441885 100644
--- a/tika-server/tika-server-standard/src/test/resources/configs/cxf-test-base-template.json
+++ b/tika-server/tika-server-standard/src/test/resources/configs/cxf-test-base-template.json
@@ -34,14 +34,13 @@
]
},
"pipes": {
- "tikaConfig": "TIKA_CONFIG",
"numClients": 2,
"timeoutMillis": TIMEOUT_MILLIS,
"emitIntermediateResults": false,
"forkedJvmArgs": [
"-Xmx512m"
],
- "maxForEmitBatchBytes": 1000000
+ "directEmitThresholdBytes": 0
},
"auto-detect-parser": {
"spoolToDisk": 1000000,