Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@
import org.opensearch.dataprepper.model.configuration.PluginModel;
import org.opensearch.dataprepper.model.configuration.PluginSetting;
import org.opensearch.dataprepper.model.event.Event;
import org.opensearch.dataprepper.model.plugin.PluginFactory;
import org.opensearch.dataprepper.model.record.Record;
import org.opensearch.dataprepper.model.source.SourceCoordinationStore;
import org.opensearch.dataprepper.model.source.coordinator.SourceCoordinator;
import org.opensearch.dataprepper.core.parser.model.SourceCoordinationConfig;
import org.opensearch.dataprepper.plugins.codec.CompressionOption;
import org.opensearch.dataprepper.plugins.s3.common.ownership.BucketOwnerProvider;
import org.opensearch.dataprepper.plugins.s3.common.source.S3ObjectPluginMetrics;
import org.opensearch.dataprepper.expression.ExpressionEvaluator;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanBucketOption;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanBucketOptions;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanScanOptions;
Expand Down Expand Up @@ -224,8 +226,11 @@ private ScanObjectWorker createObjectUnderTest(final RecordsGenerator recordsGen
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
acknowledgementSetManager = new DefaultAcknowledgementSetManager(executor);

return new ScanObjectWorker(s3Client, scanOptions, createObjectUnderTest(s3ObjectRequest)
,bucketOwnerProvider, sourceCoordinator, s3SourceConfig, acknowledgementSetManager, s3ObjectDeleteWorker, 30000, pluginMetrics);
final S3ScanProcessingConditionEvaluator conditionEvaluator =
new S3ScanProcessingConditionEvaluator(s3Client, mock(ExpressionEvaluator.class), mock(PluginFactory.class), Collections.emptyList());
return new ScanObjectWorker(s3Client, scanOptions, createObjectUnderTest(s3ObjectRequest),
bucketOwnerProvider, sourceCoordinator, s3SourceConfig, acknowledgementSetManager, s3ObjectDeleteWorker, 30000, pluginMetrics,
conditionEvaluator, Collections.emptyMap());
}

@ParameterizedTest
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
*/
package org.opensearch.dataprepper.plugins.source.s3;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.opensearch.dataprepper.expression.ExpressionEvaluator;
import org.opensearch.dataprepper.model.codec.InputCodec;
import org.opensearch.dataprepper.model.configuration.PluginModel;
import org.opensearch.dataprepper.model.configuration.PluginSetting;
import org.opensearch.dataprepper.model.event.Event;
import org.opensearch.dataprepper.model.event.JacksonEvent;
import org.opensearch.dataprepper.model.plugin.PluginFactory;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanProcessingCondition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.ResponseInputStream;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
* Evaluates {@link S3ScanProcessingCondition} entries for a given S3 object before
* the object is processed. For each applicable condition the evaluator downloads the
* condition object co-located with the S3 object and evaluates the {@code when} expression
* against its content. When a {@code codec} is configured on the condition the object is
* parsed with that codec; otherwise the object is parsed as a JSON document.
*/
public class S3ScanProcessingConditionEvaluator {

private static final Logger LOG = LoggerFactory.getLogger(S3ScanProcessingConditionEvaluator.class);
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

private final S3Client s3Client;
private final ExpressionEvaluator expressionEvaluator;
private final Map<S3ScanProcessingCondition, InputCodec> codecCache;

public S3ScanProcessingConditionEvaluator(final S3Client s3Client,
final ExpressionEvaluator expressionEvaluator,
final PluginFactory pluginFactory,
final Collection<S3ScanProcessingCondition> allConditions) {
this.s3Client = s3Client;
this.expressionEvaluator = expressionEvaluator;
final IdentityHashMap<S3ScanProcessingCondition, InputCodec> cache = new IdentityHashMap<>();
for (final S3ScanProcessingCondition condition : allConditions) {
if (condition.getCodec() != null) {
final PluginModel codecModel = condition.getCodec();
final PluginSetting pluginSetting = new PluginSetting(
codecModel.getPluginName(), codecModel.getPluginSettings());
cache.put(condition, pluginFactory.loadPlugin(InputCodec.class, pluginSetting));
}
}
this.codecCache = Collections.unmodifiableMap(cache);
}

/**
* Returns the first condition in {@code conditions} that is not yet satisfied for the given
* object, or {@link Optional#empty()} if all applicable conditions are met. A condition is
* applicable when {@code applicable_prefix} is absent or the object key starts with at least
* one of the listed applicable prefixes.
*/
public Optional<S3ScanProcessingCondition> firstUnmetCondition(final String bucket,
final String objectKey,
final List<S3ScanProcessingCondition> conditions) {
if (conditions == null || conditions.isEmpty()) {
return Optional.empty();
}
for (final S3ScanProcessingCondition condition : conditions) {
if (!isApplicable(objectKey, condition)) {
continue;
}
final String conditionObjectKey = resolveConditionObjectKey(objectKey, condition.getObjectName());
try {
final Event event;
final InputCodec codec = codecCache.get(condition);
if (codec != null) {
event = parseFirstEventWithCodec(bucket, conditionObjectKey, codec);
} else {
final String content = readS3ObjectAsString(bucket, conditionObjectKey);
final Map<String, Object> data = OBJECT_MAPPER.readValue(
content, new TypeReference<Map<String, Object>>() {});
event = JacksonEvent.builder()
.withEventType("event")
.withData(data)
.build();
}
if (event == null || !expressionEvaluator.evaluateConditional(condition.getWhen(), event)) {
LOG.debug("Processing condition '{}' not satisfied for {}/{} using condition object {}",
condition.getWhen(), bucket, objectKey, conditionObjectKey);
return Optional.of(condition);
}
} catch (final NoSuchKeyException e) {
LOG.debug("Object for condition {}/{} not found yet, condition not met", bucket, conditionObjectKey);
return Optional.of(condition);
} catch (final Exception e) {
LOG.warn("Error reading or evaluating processing condition for {}/{}, processing object as-is",
bucket, objectKey, e);
return Optional.empty();
}
}
return Optional.empty();
}

private boolean isApplicable(final String objectKey, final S3ScanProcessingCondition condition) {
final List<String> includePrefix = condition.getApplicablePrefix();
return includePrefix == null || includePrefix.isEmpty() ||
includePrefix.stream().anyMatch(objectKey::startsWith);
}

private String resolveConditionObjectKey(final String objectKey, final String fileName) {
final String directory = objectKey.contains("/")
? objectKey.substring(0, objectKey.lastIndexOf('/') + 1)
: "";
return directory + fileName;
}

private Event parseFirstEventWithCodec(final String bucket,
final String key,
final InputCodec codec) throws IOException {
final AtomicReference<Event> firstEvent = new AtomicReference<>();
final GetObjectRequest request = GetObjectRequest.builder().bucket(bucket).key(key).build();
try (final ResponseInputStream<GetObjectResponse> response = s3Client.getObject(request)) {
codec.parse(response, record -> firstEvent.compareAndSet(null, record.getData()));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One thing we should make sure of. Does this actually work with a single json object in a file? Last I checked the json codec only supported json arrays. Did you test again with a static json object (not ndjson)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I tested and verified it works with single json object. I uses the actual one of the real manifest file in the below format.

{"totalRecordCount":50000,"processedRecordCount":50000,"successRecordCount":30000,"errorRecordCount":0,"inputTokenCount":5300000,"outputTokenCount":0,"inputAudioSecond":0,"inputVideoSecond":0,"inputStandardImageCount":0,"inputDocumentImageCount":0,"inputTextTokenCount":0,"inputImageTokenCount":0,"inputAudioTokenCount":0,"inputVideoTokenCount":0,"outputTextTokenCount":0,"outputImageTokenCount":0}

}
return firstEvent.get();
}

private String readS3ObjectAsString(final String bucket, final String key) throws IOException {
final GetObjectRequest request = GetObjectRequest.builder().bucket(bucket).key(key).build();
try (final ResponseInputStream<GetObjectResponse> response = s3Client.getObject(request)) {
return new String(response.readAllBytes(), StandardCharsets.UTF_8);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,27 @@
*/
package org.opensearch.dataprepper.plugins.source.s3;

import org.opensearch.dataprepper.expression.ExpressionEvaluator;
import org.opensearch.dataprepper.metrics.PluginMetrics;
import org.opensearch.dataprepper.common.concurrent.BackgroundThreadFactory;
import org.opensearch.dataprepper.model.acknowledgements.AcknowledgementSetManager;
import org.opensearch.dataprepper.model.plugin.PluginFactory;
import org.opensearch.dataprepper.model.source.coordinator.SourceCoordinator;
import org.opensearch.dataprepper.plugins.s3.common.ownership.BucketOwnerProvider;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanBucketOption;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanBucketOptions;
import org.opensearch.dataprepper.plugins.source.s3.configuration.S3ScanProcessingCondition;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
* Class responsible for taking an {@link S3SourceConfig} and creating all the necessary {@link ScanOptions}
Expand All @@ -42,6 +49,8 @@ public class S3ScanService {
private final AcknowledgementSetManager acknowledgementSetManager;
private final S3ObjectDeleteWorker s3ObjectDeleteWorker;
private final PluginMetrics pluginMetrics;
private final ExpressionEvaluator expressionEvaluator;
private final PluginFactory pluginFactory;
private final ExecutorService executorService;
private final List<ScanObjectWorker> workers;

Expand All @@ -52,7 +61,9 @@ public S3ScanService(final S3SourceConfig s3SourceConfig,
final SourceCoordinator<S3SourceProgressState> sourceCoordinator,
final AcknowledgementSetManager acknowledgementSetManager,
final S3ObjectDeleteWorker s3ObjectDeleteWorker,
final PluginMetrics pluginMetrics) {
final PluginMetrics pluginMetrics,
final ExpressionEvaluator expressionEvaluator,
final PluginFactory pluginFactory) {
this.s3SourceConfig = s3SourceConfig;
this.s3ScanBucketOptions = s3SourceConfig.getS3ScanScanOptions().getBuckets();
this.s3ClientBuilderFactory = s3ClientBuilderFactory;
Expand All @@ -65,15 +76,35 @@ public S3ScanService(final S3SourceConfig s3SourceConfig,
this.acknowledgementSetManager = acknowledgementSetManager;
this.s3ObjectDeleteWorker = s3ObjectDeleteWorker;
this.pluginMetrics = pluginMetrics;
this.expressionEvaluator = expressionEvaluator;
this.pluginFactory = pluginFactory;
this.workers = new ArrayList<>();
this.executorService = Executors.newFixedThreadPool(s3SourceConfig.getNumWorkers(), BackgroundThreadFactory.defaultExecutorThreadFactory("s3-source-scan"));
}

public void start() {
long backOffMs = s3SourceConfig.getBackOff().toMillis();
final Map<String, List<S3ScanProcessingCondition>> bucketProcessingConditionsMap = new HashMap<>();
if (s3ScanBucketOptions != null) {
for (final S3ScanBucketOptions bucketOption : s3ScanBucketOptions) {
final S3ScanBucketOption option = bucketOption.getS3ScanBucketOption();
if (option != null && option.getProcessingConditions() != null) {
bucketProcessingConditionsMap
.computeIfAbsent(option.getName(), k -> new ArrayList<>())
.addAll(option.getProcessingConditions());
}
}
}
final List<S3ScanProcessingCondition> allConditions = bucketProcessingConditionsMap.values().stream()
.flatMap(List::stream)
.collect(Collectors.toList());
final S3ScanProcessingConditionEvaluator conditionEvaluator =
new S3ScanProcessingConditionEvaluator(s3ClientBuilderFactory.getS3Client(), expressionEvaluator, pluginFactory, allConditions);
for (int i = 0; i < s3SourceConfig.getNumWorkers(); i++) {
ScanObjectWorker scanObjectWorker = new ScanObjectWorker(s3ClientBuilderFactory.getS3Client(),
getScanOptions(),s3ObjectHandler,bucketOwnerProvider, sourceCoordinator, s3SourceConfig, acknowledgementSetManager, s3ObjectDeleteWorker, backOffMs, pluginMetrics);
getScanOptions(), s3ObjectHandler, bucketOwnerProvider, sourceCoordinator, s3SourceConfig,
acknowledgementSetManager, s3ObjectDeleteWorker, backOffMs, pluginMetrics, conditionEvaluator,
bucketProcessingConditionsMap);
workers.add(scanObjectWorker);
executorService.submit(new Thread(scanObjectWorker));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package org.opensearch.dataprepper.plugins.source.s3;

import org.opensearch.dataprepper.aws.api.AwsCredentialsSupplier;
import org.opensearch.dataprepper.expression.ExpressionEvaluator;
import org.opensearch.dataprepper.metrics.PluginMetrics;
import org.opensearch.dataprepper.model.acknowledgements.AcknowledgementSetManager;
import org.opensearch.dataprepper.model.annotations.DataPrepperPlugin;
Expand Down Expand Up @@ -47,6 +48,7 @@ public class S3Source implements Source<Record<Event>>, UsesSourceCoordination {
private final AcknowledgementSetManager acknowledgementSetManager;
private final AwsCredentialsSupplier awsCredentialsSupplier;
private final boolean acknowledgementsEnabled;
private final ExpressionEvaluator expressionEvaluator;
private SourceCoordinator<S3SourceProgressState> sourceCoordinator;


Expand All @@ -56,14 +58,16 @@ public S3Source(
final S3SourceConfig s3SourceConfig,
final PluginFactory pluginFactory,
final AcknowledgementSetManager acknowledgementSetManager,
final AwsCredentialsSupplier awsCredentialsSupplier) {
final AwsCredentialsSupplier awsCredentialsSupplier,
final ExpressionEvaluator expressionEvaluator) {
this.pluginMetrics = pluginMetrics;
this.s3SourceConfig = s3SourceConfig;
this.pluginFactory = pluginFactory;
this.s3ScanScanOptional = Optional.ofNullable(s3SourceConfig.getS3ScanScanOptions());
this.acknowledgementsEnabled = s3SourceConfig.getAcknowledgements();
this.acknowledgementSetManager = acknowledgementSetManager;
this.awsCredentialsSupplier = awsCredentialsSupplier;
this.expressionEvaluator = expressionEvaluator;
}

@Override
Expand Down Expand Up @@ -126,7 +130,7 @@ public void start(Buffer<Record<Event>> buffer) {
sqsService.start();
}
if(s3ScanScanOptional.isPresent()) {
s3ScanService = new S3ScanService(s3SourceConfig, s3ClientBuilderFactory, s3Handler, bucketOwnerProvider, sourceCoordinator, acknowledgementSetManager, s3ObjectDeleteWorker, pluginMetrics);
s3ScanService = new S3ScanService(s3SourceConfig, s3ClientBuilderFactory, s3Handler, bucketOwnerProvider, sourceCoordinator, acknowledgementSetManager, s3ObjectDeleteWorker, pluginMetrics, expressionEvaluator, pluginFactory);
s3ScanService.start();
}
}
Expand Down
Loading
Loading