Skip to content
Open
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 @@ -16,7 +16,12 @@

package io.aiven.kafka.connect.azure.source.utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.function.Predicate;
import java.util.stream.Stream;

Expand Down Expand Up @@ -61,9 +66,10 @@ public AzureBlobClient(final AzureBlobSourceConfig config) {
public Stream<BlobItem> getAzureBlobStream(final String offset) {
final ListBlobsOptions options = new ListBlobsOptions().setPrefix(config.getAzurePrefix())
.setMaxResultsPerPage(config.getAzureFetchPageSize());
return offset == null
? containerAsyncClient.listBlobs(options).toStream().filter(filterPredicate)
: containerAsyncClient.listBlobs(options, offset).toStream().filter(filterPredicate);
final Stream<BlobItem> blobs = containerAsyncClient.listBlobs(options).toStream().filter(filterPredicate);
// The second argument of listBlobs is an opaque continuation token returned by the service, not a blob name, so
// "start after this blob" has to be applied here.
return offset == null ? blobs : blobs.filter(blobItem -> blobItem.getName().compareTo(offset) > 0);
}

/**
Expand All @@ -76,6 +82,32 @@ public Flux<ByteBuffer> getBlob(final String blobName) {
return getBlobAsyncClient(blobName).downloadStream();
}

/**
* Downloads the complete blob into a temporary file and opens it for reading. The file is deleted when the stream
* is closed. The whole object is never held in memory.
*
* @param blobName
* Name of the blob which is to be downloaded from Azure.
* @return A stream over the complete content of the blob.
* @throws IOException
* if the temporary file cannot be created or opened.
*/
public InputStream openBlob(final String blobName) throws IOException {
final Path tempFile = Files.createTempFile("azure-source-", ".blob");
boolean opened = false;
try {
// overwrite = true because the temporary file already exists
getBlobAsyncClient(blobName).downloadToFile(tempFile.toString(), true).block();
final InputStream stream = Files.newInputStream(tempFile, StandardOpenOption.DELETE_ON_CLOSE);
opened = true;
return stream;
} finally {
if (!opened) {
Files.deleteIfExists(tempFile);
}
}
}

/**
* Creates an Async BlobClient for a specific Blob in a container.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import io.aiven.kafka.connect.common.source.input.Transformer;

import com.azure.storage.blob.models.BlobItem;
import com.fasterxml.jackson.databind.util.ByteBufferBackedInputStream;
import org.apache.commons.io.function.IOSupplier;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
Expand Down Expand Up @@ -67,7 +66,7 @@ protected Logger getLogger() {

@Override
protected IOSupplier<InputStream> getInputStream(final AzureBlobSourceRecord sourceRecord) {
return () -> new ByteBufferBackedInputStream(azureBlobClient.getBlob(sourceRecord.getNativeKey()).blockFirst());
return () -> azureBlobClient.openBlob(sourceRecord.getNativeKey());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,21 @@

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

Expand Down Expand Up @@ -112,6 +118,48 @@ void testGetBlobReturnsDataAsExpected() {
assertThat(blobContent).isEqualTo(downloadedContent);
}

@Test
void testListAllBlobsWithOffsetReturnsOnlyLexicallyLaterBlobs() {
client = new AzureBlobClient(config);
final PagedFlux<BlobItem> flux = mock(PagedFlux.class);
when(flux.toStream()).thenReturn(createListOfBlobs(100));
when(containerClient.listBlobs(any())).thenReturn(flux);

// names are "0".."99"; lexically after "97" are only "98" and "99"
assertThat(client.getAzureBlobStream("97").map(BlobItem::getName).collect(Collectors.toList()))
.containsExactly("98", "99");
}

@Test
void testOpenBlobRemovesTemporaryFileWhenDownloadFails() {
client = new AzureBlobClient(config);
final AtomicReference<String> target = new AtomicReference<>();
when(blobClient.downloadToFile(anyString(), eq(true))).thenAnswer(invocation -> {
target.set(invocation.getArgument(0));
return Mono.error(new IllegalStateException("download failed"));
});

assertThatThrownBy(() -> client.openBlob("teste-1")).hasMessageContaining("download failed");
assertThat(Path.of(target.get())).doesNotExist();
}

@Test
void testOpenBlobReturnsWholeFile() throws IOException {
client = new AzureBlobClient(config);
final byte[] content = "x".repeat(100_000).getBytes(UTF_8);
final AtomicReference<String> target = new AtomicReference<>();
when(blobClient.downloadToFile(anyString(), eq(true))).thenAnswer(invocation -> {
target.set(invocation.getArgument(0));
Files.write(Path.of(target.get()), content);
return Mono.empty();
});

try (InputStream stream = client.openBlob("teste-1")) {
assertThat(stream.readAllBytes()).isEqualTo(content);
}
assertThat(Path.of(target.get())).doesNotExist();
}

private static Stream<BlobItem> createListOfBlobs(final int numberOfItems) {
final List<BlobItem> items = new ArrayList<>();
final BlobItemProperties props = new BlobItemProperties().setContentLength(10_000L);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.ByteBuffer;
import java.util.stream.Stream;

Expand All @@ -32,7 +36,6 @@

import com.azure.storage.blob.models.BlobItem;
import com.azure.storage.blob.models.BlobItemProperties;
import reactor.core.publisher.Flux;

final public class AzureBlobSourceRecordIteratorTest
extends
Expand Down Expand Up @@ -95,12 +98,15 @@ private Stream<BlobItem> dequeueData() {
return objects.stream();
}

private Flux<ByteBuffer> getStream(final String key) {
private InputStream getStream(final String key) {
final ByteBuffer buffer = getData(key);
if (buffer != null) {
return Flux.just(buffer);
if (buffer == null) {
return InputStream.nullInputStream();
}
return Flux.empty();
final ByteBuffer copy = buffer.duplicate();
final byte[] bytes = new byte[copy.remaining()];
copy.get(bytes);
return new ByteArrayInputStream(bytes);
}

@Override
Expand All @@ -112,7 +118,11 @@ public void build() {

azureBlobClient = mock(AzureBlobClient.class);
when(azureBlobClient.getAzureBlobStream(null)).thenAnswer(env -> dequeueData());
when(azureBlobClient.getBlob(anyString())).thenAnswer(env -> getStream(env.getArgument(0)));
try {
when(azureBlobClient.openBlob(anyString())).thenAnswer(env -> getStream(env.getArgument(0)));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
}
5 changes: 5 additions & 0 deletions commons/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ dependencies {
exclude(group = "io.netty", module = "netty")
}

// Needed at runtime to read Parquet: ParquetReadOptions loads
// org.apache.hadoop.mapreduce.lib.input.FileInputFormat. Without this jar in the
// distribution the source task dies with NoClassDefFoundError.
runtimeOnly(apache.hadoop.mapreduce.client.core) { isTransitive = false }

testFixturesImplementation(apache.kafka.connect.api)
testFixturesImplementation("javax.validation:validation-api:2.0.1.Final")
testFixturesImplementation("org.apache.kafka:connect-runtime:${kafkaTestingVersion}:test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,10 @@ public void run() {
logger.warn("{} interrupted -- EXITING", this.toString());
} catch (RuntimeException e) { // NOPMD AvoidCatchingGenericException
logger.error("{} failed -- EXITING", this.toString(), e);
} catch (Error e) { // NOPMD AvoidCatchingThrowable
// without this an Error such as NoClassDefFoundError never reaches the connector log
logger.error("{} failed -- EXITING", this.toString(), e);
throw e;
}
logger.info("{} finished", this.toString());

Expand Down