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 @@ -64,7 +64,7 @@ public final class AzureBlobSinkTask extends SinkTask {
private BufferTracker bufferTracker;
private final Map<String, AzureBlobWriter> activeBlobWriters = new HashMap<>();
private static final long AZURE_WRITE_BUFFER_SIZE_BYTES_PER_TASK = 60 * 1024 * 1024L; // 60 MiB
private static final long AZURE_WRITE_INTERVAL_MS = 10_000L; // 10 seconds
private long azureWriteIntervalMs; // 10 seconds by default

private long currentBufferedBytes;
final Clock clock;
Expand Down Expand Up @@ -103,6 +103,7 @@ public void start(final Map<String, String> props) {
this.config = new AzureBlobSinkConfig(props);
BlobServiceClient blobServiceClient;
final UserAgentPolicy userAgentPolicy = new UserAgentPolicy(config.getUserAgent());
azureWriteIntervalMs = config.getMaxLingerMs();

final RetryOptions retryOptions = new RetryOptions(
new ExponentialBackoffOptions().setMaxRetries(config.getAzureRetryBackoffMaxAttempts())
Expand Down Expand Up @@ -173,13 +174,13 @@ public void put(final Collection<SinkRecord> records) {
checkRecordSize();
// Trigger write to Azure if the buffer size threshold is reached or the time interval has passed.
if (currentBufferedBytes >= AZURE_WRITE_BUFFER_SIZE_BYTES_PER_TASK
|| clock.millis() - lastWriteMs >= AZURE_WRITE_INTERVAL_MS) {
|| clock.millis() - lastWriteMs >= azureWriteIntervalMs) {
if (currentBufferedBytes >= AZURE_WRITE_BUFFER_SIZE_BYTES_PER_TASK) {
LOG.debug("Azure write buffer size of {} bytes reached. Writing buffered records to Azure.",
currentBufferedBytes);
} else {
LOG.debug("Azure write interval of {} ms reached. Writing buffered records to Azure.",
AZURE_WRITE_INTERVAL_MS);
azureWriteIntervalMs);
}
writeBufferedRecordsToAzure();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import com.azure.storage.blob.models.BlobItem;
import com.azure.storage.blob.specialized.BlobOutputStream;
import com.azure.storage.blob.specialized.BlockBlobClient;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand Down Expand Up @@ -127,7 +128,8 @@ void testPutAndFlush() throws Exception {
}

@Test
void noWriteWhenUnderThresholds() {
void noWriteWhenUnderThresholds() throws IllegalAccessException {
FieldUtils.writeField(task, "azureWriteIntervalMs", 10_000L, true);
// Buffered size < AZURE_WRITE_BUFFER_SIZE_BYTES_PER_TASK AND time < AZURE_WRITE_INTERVAL_MS -> no write.
task.put(Collections.singletonList(createRecord("topic0", 0, "key0", "value0", 0, 1000)));
verify(blockBlobClient, never()).getBlobOutputStream(anyBoolean());
Expand All @@ -138,10 +140,11 @@ void noWriteWhenUnderThresholds() {
}

@Test
void writeWhenTimeThresholdExceeded() throws IOException {
void writeWhenTimeThresholdExceeded() throws IOException, IllegalAccessException {
// Time interval > AZURE_WRITE_INTERVAL_MS -> trigger write during put().
final MutableClock testClock = new MutableClock(Instant.now());
task = new AzureBlobSinkTask(properties, blobServiceClient, testClock);
FieldUtils.writeField(task, "azureWriteIntervalMs", 10_000L, true);
task.initialize(taskContext);

task.put(Collections.singletonList(createRecord("topic0", 0, "key0", "value0", 0, 1000)));
Expand All @@ -157,9 +160,11 @@ void writeWhenTimeThresholdExceeded() throws IOException {
}

@Test
void shouldRequestCommitWhenMaxRecordsPerFileExceeded() {
void shouldRequestCommitWhenMaxRecordsPerFileExceeded() throws IllegalAccessException {
properties.put(AzureBlobSinkConfig.FILE_MAX_RECORDS, "2");
task = new AzureBlobSinkTask(properties, blobServiceClient);
FieldUtils.writeField(task, "azureWriteIntervalMs", 10_000L, true);

task.initialize(taskContext);

task.put(Collections.singletonList(createRecord("topic0", 0, "key0", "val0", 10, 1000)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ void correctFullConfig(final String compression) {
assertThat(config.getCompressionType()).isEqualTo(CompressionType.forName(compression));
assertThat(config.getMaxRecordsPerFile()).isEqualTo(42);
assertThat(config.getPrefix()).isEqualTo("test-prefix");
assertThat(config.getMaxLingerMs()).isEqualTo(10_000L);
assertThat(config.getFilenameTemplate()
.instance()
.bindVariable("topic", () -> "a")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class SinkCommonConfig extends CommonConfig {
public static final String FILE_MAX_RECORDS = "file.max.records";

public static final String FILE_MAX_BYTES = "file.max.bytes";
public static final String MAX_LINGER_MS = "max.linger.ms";
/**
* FileNameFragment to handle FileName based configuration queries.
*/
Expand Down Expand Up @@ -109,6 +110,10 @@ public long getMaxBytesPerFile() {
return sinkConfigFragment.getMaxBytesPerFile();
}

public long getMaxLingerMs() {
return sinkConfigFragment.getMaxLingerMs();
}

public boolean isMaxBytesPerFileLimited() {
return getMaxBytesPerFile() > 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,15 @@
package io.aiven.kafka.connect.common.config;

import static io.aiven.kafka.connect.common.config.SinkCommonConfig.FILE_MAX_BYTES;
import static io.aiven.kafka.connect.common.config.SinkCommonConfig.MAX_LINGER_MS;

import java.util.Map;

import org.apache.kafka.common.config.AbstractConfig;
import org.apache.kafka.common.config.ConfigDef;

import io.aiven.commons.kafka.config.validator.TimeScaleValidator;

/**
* Defines properties that are shared across all Sink implementations.
*/
Expand Down Expand Up @@ -54,6 +57,11 @@ public static ConfigDef update(final ConfigDef configDef) {
ConfigDef.Importance.MEDIUM,
"The maximum number of bytes to put in a single file. " + "Must be a non-negative integer number. "
+ "0 is interpreted as \"unlimited\", which is the default.");
configDef.define(MAX_LINGER_MS, ConfigDef.Type.LONG, 10_000L, TimeScaleValidator.between(1000, 60_000),
ConfigDef.Importance.MEDIUM,
"The maximum amount of time in milliseconds for the sink connector to wait before starting to upload data if no other threshold is met."
+ " The default is 10 seconds, while the minimum allowed is 1 second.");

return configDef;
}

Expand All @@ -67,6 +75,16 @@ public long getMaxBytesPerFile() {
return cfg.getLong(FILE_MAX_BYTES);
}

/**
* A long value that represents the minimum amount of time in milliseconds to wait before a Sink Task will being
* uploading data to its target system
*
* @return Get the minimum amount of time a sink task should wait before uploading data to its target system
*/
public long getMaxLingerMs() {
return cfg.getLong(MAX_LINGER_MS);
}

/**
* The SourceConfigFragment setter.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public final class GcsSinkTask extends SinkTask {
private BufferTracker bufferTracker;
private final Map<String, GcsBlobWriter> activeBlobWriters = new HashMap<>();
private static final long GCS_WRITE_BUFFER_SIZE_BYTES_PER_TASK = 60 * 1024 * 1024L; // 60 MiB
private static final long GCS_WRITE_INTERVAL_MS = 10_000L; // 10 seconds
private long gcsWriteIntervalMs = 10_000L; // 10 seconds

private long currentBufferedBytes;
final Clock clock;
Expand Down Expand Up @@ -95,6 +95,7 @@ public void start(final Map<String, String> props) {
Objects.requireNonNull(props, "props cannot be null");

this.config = new GcsSinkConfig(props);
gcsWriteIntervalMs = config.getMaxLingerMs();
this.storage = StorageOptions.newBuilder()
.setHost(config.getGcsEndpoint())
.setCredentials(config.getCredentials())
Expand Down Expand Up @@ -154,13 +155,12 @@ public void put(final Collection<SinkRecord> records) {
checkRecordSize();
// Trigger write to GCS if the buffer size threshold is reached or the time interval has passed.
if (currentBufferedBytes >= GCS_WRITE_BUFFER_SIZE_BYTES_PER_TASK
|| clock.millis() - lastWriteMs >= GCS_WRITE_INTERVAL_MS) {
|| clock.millis() - lastWriteMs >= gcsWriteIntervalMs) {
if (currentBufferedBytes >= GCS_WRITE_BUFFER_SIZE_BYTES_PER_TASK) {
LOG.debug("GCS write buffer size of {} bytes reached. Writing buffered records to GCS.",
currentBufferedBytes);
} else {
LOG.debug("GCS write interval of {} ms reached. Writing buffered records to GCS.",
GCS_WRITE_INTERVAL_MS);
LOG.debug("GCS write interval of {} ms reached. Writing buffered records to GCS.", gcsWriteIntervalMs);
}
writeBufferedRecordsToGcs();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ void correctMinimalConfig() {
.bindVariable("partition", () -> "b")
.bindVariable("start_offset", () -> "c")
.render()).isEqualTo("a-b-c");
assertThat(config.getMaxLingerMs()).isEqualTo(10_000L);
assertThat(config.getOutputFields())
.containsExactly(new OutputField(OutputFieldType.VALUE, OutputFieldEncodingType.BASE64));
assertThat(config.getFormatType()).isEqualTo(FormatType.forName("csv"));
Expand Down
4 changes: 2 additions & 2 deletions s3-sink-connector/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -596,8 +596,8 @@ timestamp.source=wallclock
To configure S3 multi-part uploads buffer size change:
- `aws.s3.part.size.bytes` - The Part Size in
S3 Multi-part Uploads in bytes.
Maximum is `2GB` and default is `5MB`.
- Multipart uploads begins as soon as the first batch of records are received from Kafka, the upload is completed when it meets the number of allowed records in a single file.
Maximum is `2GiB` the minimum is `5MiB` and default is `60MiB`.
- Multipart uploads begins as soon as a part size of data is available for upload from the records that are received from Kafka, the upload is completed when it meets the number of allowed records in a single file, or a flush is called by the connector.
- AWS has best practices around multipart uploads using [lifecycle configuration](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html) to ensure that you minimise your storage costs.

### Retry strategy configuration
Expand Down
3 changes: 2 additions & 1 deletion s3-sink-connector/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ dependencies {
implementation(logginglibs.slf4j)
implementation(amazonawssdk.s3)
implementation(amazonawssdk.sts)
implementation(aiven.kafka.config)

testImplementation(apache.commons.io)
testImplementation(testFixtures(project(":commons")))
Expand All @@ -90,10 +91,10 @@ dependencies {
testImplementation(apache.kafka.connect.api)
testImplementation(apache.kafka.connect.runtime)
testImplementation(apache.kafka.connect.json)
testImplementation(apache.commons.io)
testImplementation(testinglibs.junit.jupiter)
testImplementation(testinglibs.assertj.core)
testImplementation("io.findify:s3mock_2.13:$s3mockVersion")
testImplementation(aiven.kafka.config)

testImplementation(testinglibs.mockito.core)
testImplementation(testinglibs.mockito.junit.jupiter)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ final void schemaChanged(@TempDir final Path tmpDir, final TestInfo testInfo)
final Map<String, String> connectorConfig = awsSpecificConfig(basicConnectorConfig(compression), topicName);
connectorConfig.put("format.output.fields", "value");
connectorConfig.put("format.output.fields.value.encoding", "none");
connectorConfig.put("aws.s3.part.size.bytes", "5242880");
Comment thread
Claudenw marked this conversation as resolved.
Resolved
createConnector(connectorConfig);

final Schema valueSchema = SchemaBuilder.record("value")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,8 @@ public final class S3SinkTask extends SinkTask {
private long lastWriteMs;
private boolean isOneRecordPerFile;

private static final long S3_WRITE_BUFFER_SIZE_BYTES_PER_TASK = 60 * 1024 * 1024L; // 60 MiB
private static final long S3_WRITE_INTERVAL_MS = 10_000L; // 10 seconds
private long s3WriteBufferSizeBytesPerTask; // 60 MiB by default
private long s3WriteIntervalMs; // 10 seconds

S3ClientFactory s3ClientFactory = new S3ClientFactory();

Expand All @@ -100,6 +100,8 @@ public S3SinkTask(final Map<String, String> props, final S3Client s3Client, fina
public void start(final Map<String, String> props) {
Objects.requireNonNull(props, "props hasn't been set");
config = new S3SinkConfig(props);
s3WriteBufferSizeBytesPerTask = config.getAwsS3PartSize();
s3WriteIntervalMs = config.getMaxLingerMs();
this.topicPartitionManager = new TopicPartitionManager();
this.recordGrouper = RecordGrouperFactory.newRecordGrouper(config);
s3Client = s3ClientFactory.createAmazonS3Client(config);
Expand Down Expand Up @@ -140,14 +142,13 @@ public void put(final Collection<SinkRecord> records) {
// check if we should pause topics
checkRecordSize();
// Trigger write to S3 if the buffer size threshold is reached or the time interval has passed.
if (currentBufferedBytes >= S3_WRITE_BUFFER_SIZE_BYTES_PER_TASK
|| clock.millis() - lastWriteMs >= S3_WRITE_INTERVAL_MS) {
if (currentBufferedBytes >= S3_WRITE_BUFFER_SIZE_BYTES_PER_TASK) {
if (currentBufferedBytes >= s3WriteBufferSizeBytesPerTask
|| clock.millis() - lastWriteMs >= s3WriteIntervalMs) {
Comment thread
Claudenw marked this conversation as resolved.
Resolved
if (currentBufferedBytes >= s3WriteBufferSizeBytesPerTask) {
LOGGER.debug("S3 write buffer size of {} bytes reached. Writing buffered records to S3.",
currentBufferedBytes);
} else {
LOGGER.debug("S3 write interval of {} ms reached. Writing buffered records to S3.",
S3_WRITE_INTERVAL_MS);
LOGGER.debug("S3 write interval of {} ms reached. Writing buffered records to S3.", s3WriteIntervalMs);
}
writeBufferedRecordsToS3();
}
Expand Down Expand Up @@ -317,11 +318,11 @@ public String version() {
// really have no choice but to wait for the framework to call a method on this task that implies
// that it's safe to pause or resume partitions on the consumer.
private void checkRecordSize() {
LOGGER.debug("Record soft limit: {} bytes, current record size: {} bytes", S3_WRITE_BUFFER_SIZE_BYTES_PER_TASK,
LOGGER.debug("Record soft limit: {} bytes, current record size: {} bytes", s3WriteBufferSizeBytesPerTask,
Comment thread
Claudenw marked this conversation as resolved.
Resolved
currentBufferedBytes);
if (currentBufferedBytes > S3_WRITE_BUFFER_SIZE_BYTES_PER_TASK) {
if (currentBufferedBytes > s3WriteBufferSizeBytesPerTask) {
topicPartitionManager.pauseAll();
} else if (currentBufferedBytes <= S3_WRITE_BUFFER_SIZE_BYTES_PER_TASK / 2) {
} else if (currentBufferedBytes <= s3WriteBufferSizeBytesPerTask / 2) {
// resume only if there is a reasonable chance we won't immediately have to pause again.
topicPartitionManager.resumeAll();
}
Expand Down Expand Up @@ -371,6 +372,7 @@ boolean isThresholdReached(final String recordKey) {
return true;
}
}

return config.getMaxRecordsPerFile() > 0
&& fileRecordCounts.getOrDefault(recordKey, 0) >= config.getMaxRecordsPerFile();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.config.ConfigDef.Importance;
import org.apache.kafka.common.config.ConfigDef.Type;
import org.apache.kafka.common.config.ConfigException;

import io.aiven.commons.kafka.config.validator.ScaleValidator;
import io.aiven.commons.util.collections.Scale;
import io.aiven.kafka.connect.common.config.CompressionType;
import io.aiven.kafka.connect.common.config.FileNameFragment;
import io.aiven.kafka.connect.common.config.OutputField;
Expand Down Expand Up @@ -58,6 +59,7 @@ final public class S3SinkConfig extends S3SinkBaseConfig {
// Default values from AWS SDK, since they are hidden
public static final int AWS_S3_RETRY_BACKOFF_DELAY_MS_DEFAULT = 100;
public static final int AWS_S3_RETRY_BACKOFF_MAX_DELAY_MS_DEFAULT = 20_000;
static final int DEFAULT_PART_SIZE = 60 * 1024 * 1024; // 60 MiB
// Comment in AWS SDK for max retries:
// Maximum retry limit. Avoids integer overflow issues.
//
Expand Down Expand Up @@ -93,26 +95,8 @@ private static void addS3partSizeConfig(final ConfigDef configDef) {

// add awsS3SinkCounter if more S3 Sink Specific config is added
// This is used to set orderInGroup
configDef.define(S3ConfigFragment.AWS_S3_PART_SIZE, Type.INT, S3OutputStream.DEFAULT_PART_SIZE,
new ConfigDef.Validator() {

static final int MAX_BUFFER_SIZE = 2_000_000_000;

@Override
public void ensureValid(final String name, final Object value) {
if (value == null) {
throw new ConfigException(name, null, "Part size must be non-null");
}
final var number = (Number) value;
if (number.longValue() <= 0) {
throw new ConfigException(name, value, "Part size must be greater than 0");
}
if (number.longValue() > MAX_BUFFER_SIZE) {
throw new ConfigException(name, value,
"Part size must be no more: " + MAX_BUFFER_SIZE + " bytes (2GB)");
}
}
}, Importance.MEDIUM,
configDef.define(S3ConfigFragment.AWS_S3_PART_SIZE, Type.INT, DEFAULT_PART_SIZE,
ScaleValidator.between(Scale.MiB.asBytes(5), Scale.GiB.asBytes(2), Scale.IEC), Importance.MEDIUM,
"The Part Size in S3 Multi-part Uploads in bytes. Maximum is " + Integer.MAX_VALUE
+ " (2GB) and default is " + S3OutputStream.DEFAULT_PART_SIZE + " (5MB)",
GROUP_AWS, 0, ConfigDef.Width.NONE, S3ConfigFragment.AWS_S3_PART_SIZE);
Expand Down
Loading
Loading