Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature][ClickhouseFile] Support avro file writer #8361

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from
Draft
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
6 changes: 5 additions & 1 deletion seatunnel-connectors-v2/connector-clickhouse/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@
<artifactId>connector-common</artifactId>
<version>${project.version}</version>
</dependency>

<dependency>
<groupId>org.apache.seatunnel</groupId>
<artifactId>seatunnel-format-avro</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import org.apache.seatunnel.api.sink.SinkWriter;
import org.apache.seatunnel.api.table.type.SeaTunnelRow;
import org.apache.seatunnel.api.table.type.SeaTunnelRowType;
import org.apache.seatunnel.common.config.Common;
import org.apache.seatunnel.common.exception.CommonError;
import org.apache.seatunnel.common.exception.CommonErrorCodeDeprecated;
Expand All @@ -30,7 +31,13 @@
import org.apache.seatunnel.connectors.seatunnel.clickhouse.state.CKFileCommitInfo;
import org.apache.seatunnel.connectors.seatunnel.clickhouse.state.ClickhouseSinkState;
import org.apache.seatunnel.connectors.seatunnel.clickhouse.util.ClickhouseProxy;
import org.apache.seatunnel.format.avro.RowToAvroConverter;
import org.apache.seatunnel.format.avro.SeaTunnelRowTypeToAvroSchemaConverter;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.io.FileUtils;

import lombok.extern.slf4j.Slf4j;
Expand All @@ -43,9 +50,6 @@
import java.io.InputStreamReader;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
Expand Down Expand Up @@ -81,6 +85,9 @@ public class ClickhouseFileSinkWriter

private final SinkWriter.Context context;
private final ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
private Map<Shard, DataFileWriter<GenericRecord>> dataFileWriterMap;
private final Schema schema;
private final SeaTunnelRowType rowType;

public ClickhouseFileSinkWriter(FileReaderOption readerOption, SinkWriter.Context context) {
this.readerOption = readerOption;
Expand Down Expand Up @@ -111,38 +118,42 @@ public ClickhouseFileSinkWriter(FileReaderOption readerOption, SinkWriter.Contex
clickhouseTable.getLocalTableName());
return shardTable.getDataPaths();
}));
schema =
SeaTunnelRowTypeToAvroSchemaConverter.buildAvroSchemaWithRowType(
readerOption.getSeaTunnelRowType());
rowType = readerOption.getSeaTunnelRowType();
dataFileWriterMap = new HashMap<>();
}

@Override
public void write(SeaTunnelRow element) throws IOException {
Shard shard = shardRouter.getShard(element);
FileChannel channel =
rowCache.computeIfAbsent(
shard,
k -> {
String uuid =
UUID.randomUUID()
.toString()
.substring(0, UUID_LENGTH)
.replaceAll("-", "_");
String clickhouseLocalFile =
String.format("%s/%s", readerOption.getFileTempPath(), uuid);
try {
FileUtils.forceMkdir(new File(clickhouseLocalFile));
String clickhouseLocalFileTmpFile =
clickhouseLocalFile + CLICKHOUSE_LOCAL_FILE_SUFFIX;
shardTempFile.put(shard, clickhouseLocalFileTmpFile);
return FileChannel.open(
Paths.get(clickhouseLocalFileTmpFile),
StandardOpenOption.WRITE,
StandardOpenOption.READ,
StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
throw CommonError.fileOperationFailed(
"ClickhouseFile", "write", clickhouseLocalFile, e);
}
});
saveDataToFile(channel, element, shard);
if (!shardTempFile.containsKey(shard)) {
String uuid =
UUID.randomUUID().toString().substring(0, UUID_LENGTH).replaceAll("-", "_");
String clickhouseLocalFile =
String.format("%s/%s", readerOption.getFileTempPath(), uuid);
try {
FileUtils.forceMkdir(new File(clickhouseLocalFile));
String clickhouseLocalFileTmpFile =
clickhouseLocalFile + CLICKHOUSE_LOCAL_FILE_SUFFIX;
shardTempFile.put(shard, clickhouseLocalFileTmpFile);
File file = new File(clickhouseLocalFileTmpFile);
if (!file.exists()) {
file.createNewFile();
DataFileWriter dataFileWriter =
new DataFileWriter<>(new GenericDatumWriter<>(schema));
dataFileWriter.create(schema, new File(shardTempFile.get(shard)));
dataFileWriterMap.put(shard, dataFileWriter);
}
} catch (IOException e) {
throw CommonError.fileOperationFailed(
"ClickhouseFile", "write", clickhouseLocalFile, e);
}
}
RowToAvroConverter rowToAvroConverter = new RowToAvroConverter(rowType);
GenericRecord data = rowToAvroConverter.convertRowToGenericRecord(element);
dataFileWriterMap.get(shard).append(data);
}

private void nodePasswordCheck() {
Expand Down Expand Up @@ -179,6 +190,7 @@ public Optional<CKFileCommitInfo> prepareCommit() throws IOException {
(shard, path) -> {
List<String> clickhouseLocalFiles = null;
try {
dataFileWriterMap.get(shard).flush();
clickhouseLocalFiles = generateClickhouseLocalFiles(path);
// move file to server
moveClickhouseLocalFileToServer(shard, clickhouseLocalFiles);
Expand Down Expand Up @@ -210,47 +222,6 @@ public void close() throws IOException {
}
}

private void saveDataToFile(FileChannel fileChannel, SeaTunnelRow row, Shard shard)
throws IOException {
String data =
this.readerOption.getFields().stream()
.map(
field -> {
Object fieldValueObj =
row.getField(
this.readerOption
.getSeaTunnelRowType()
.indexOf(field));
if (fieldValueObj == null) {
return "";
} else {
return fieldValueObj.toString();
}
})
.collect(Collectors.joining(readerOption.getFileFieldsDelimiter()))
+ "\n";

MappedByteBuffer buffer =
bufferCache.computeIfAbsent(
shard,
k -> {
try {
return fileChannel.map(
FileChannel.MapMode.READ_WRITE, 0, bufferSize);
} catch (IOException e) {
throw CommonError.fileOperationFailed(
"ClickhouseFile", "write", "UNKNOWN", e);
}
});
byte[] byteData = data.getBytes(StandardCharsets.UTF_8);
if (buffer.position() + byteData.length > buffer.capacity()) {
buffer =
fileChannel.map(FileChannel.MapMode.READ_WRITE, fileChannel.size(), bufferSize);
bufferCache.put(shard, buffer);
}
buffer.put(byteData);
}

private List<String> generateClickhouseLocalFiles(String clickhouseLocalFileTmpFile)
throws IOException, InterruptedException {
// temp file path format prefix/<uuid>/suffix
Expand All @@ -270,8 +241,7 @@ private List<String> generateClickhouseLocalFiles(String clickhouseLocalFileTmpF
}
command.add("--file");
command.add(clickhouseLocalFileTmpFile);
command.add("--format_csv_delimiter");
command.add("\"" + readerOption.getFileFieldsDelimiter() + "\"");
command.add(" --input-format Avro");
Comment on lines -274 to +244
Copy link
Member

Choose a reason for hiding this comment

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

@caicancai Can it be made optional here? For example, supporting CSV and AVRO, etc

Copy link
Member Author

Choose a reason for hiding this comment

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

There are many bugs in csv format writing. From my experience, if you want to use csv, you must write a special parse for csv, such as rowconvertTocsv. I am not sure whether you still need to keep csv.

cc @Hisoka-X

command.add("-S");
command.add(
"\""
Expand Down
Loading