Writing a custom Kafka Connect connector
When no existing connector fits your system, you can write one with the Connect API: a connector class that plans the work and task classes that move the data. This page builds a source connector with offsets and parallel tasks, a sink with a dead letter queue, config validation and a custom transform, and runs each on a real Connect worker.
Contents
What a connector plugin is made of
Hundreds of connectors exist, but sometimes none fits: an internal API, an unusual file format, a system no vendor supports. The Connect API in the connect-api
A connector plugin has two halves that run in different places:
- The connector class runs once per connector, on one worker. It reads and validates the configuration and decides how to split the work. Its
returns one configuration map per task, for example one list of tables per task. It does not move data.taskConfigs(maxTasks) - The task class runs once per task configuration, each on its own thread, possibly on different workers. A source task returns records from
; a sink task receives records inpoll() .put()
Tasks never talk to each other or to the connector directly. Everything they share goes through their configuration maps, which the worker stores and hands out, and through offsets. If the external system changes, for example a new table appears, the connector calls context.requestTaskReconfiguration()
| Interface or class | You implement | Best for |
|---|---|---|
SourceConnectorSourceTask | taskConfigspoll | Reading an external system into Kafka |
SinkConnectorSinkTask | taskConfigsputflush | Writing topics to an external system |
Transformation<R> | apply | Changing single records in any connector |
Predicate<R> | test | Deciding when a transformation applies |
ConverterHeaderConverter | fromConnectDatatoConnectData | A wire format Connect does not have |
ConfigProvider | get | Reading secrets from a vault into configs |
Declare org.apache.kafka:connect-apiprovidedEmbeddedKafkaKraftBrokerspring-kafka-testHerder
A source connector with offsets and several tasks
The source below emits numbered events for a list of regions. Regions make a good example because each one is an independent stream with its own position, which is exactly what a source partition is. The program runs it with three regions and two tasks, then restarts the worker with a higher limit:
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.config.AbstractConfig;
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.serialization.StringDeserializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo;
import org.apache.kafka.connect.runtime.rest.entities.TaskInfo;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.source.SourceConnector;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.source.SourceTask;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.ConnectorUtils;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class RegionSource {
// The connector: reads its config and splits the regions across tasks
public static class RegionSourceConnector extends SourceConnector {
static final ConfigDef CONFIG = new ConfigDef()
.define("topic", Type.STRING, Importance.HIGH, "Topic to write to")
.define("regions", Type.LIST, Importance.HIGH, "Regions to read")
.define("events.per.region", Type.INT, 2, ConfigDef.Range.atLeast(1),
Importance.MEDIUM, "Stop after this sequence number");
private Map<String, String> props;
private List<String> regions;
@Override
public void start(Map<String, String> props) {
this.props = props;
regions = new AbstractConfig(CONFIG, props).getList("regions"); // validates too
}
@Override public Class<? extends Task> taskClass() { return RegionSourceTask.class; }
@Override public ConfigDef config() { return CONFIG; }
@Override public void stop() { }
@Override public String version() { return "1.0"; }
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
List<Map<String, String>> configs = new ArrayList<>();
for (List<String> group : ConnectorUtils.groupPartitions(regions,
Math.min(maxTasks, regions.size()))) {
Map<String, String> task = new HashMap<>(props);
task.put("regions", String.join(",", group));
configs.add(task);
}
return configs;
}
}
// The task: emits numbered events per region and resumes from stored offsets
public static class RegionSourceTask extends SourceTask {
private String topic;
private int last;
private final Map<String, Long> next = new TreeMap<>();
@Override public String version() { return "1.0"; }
@Override
public void start(Map<String, String> props) {
topic = props.get("topic");
last = Integer.parseInt(props.getOrDefault("events.per.region", "2"));
for (String region : props.get("regions").split(",")) {
Map<String, Object> offset = context.offsetStorageReader()
.offset(Map.of("region", region));
long seq = offset == null ? 1 : (Long) offset.get("seq") + 1;
next.put(region, seq);
}
}
@Override
public List<SourceRecord> poll() throws InterruptedException {
List<SourceRecord> batch = new ArrayList<>();
for (Map.Entry<String, Long> e : next.entrySet()) {
long seq = e.getValue();
if (seq > last) {
continue;
}
batch.add(new SourceRecord(
Map.of("region", e.getKey()), Map.of("seq", seq), topic, null,
Schema.STRING_SCHEMA, e.getKey(),
Schema.STRING_SCHEMA, e.getKey() + " event " + seq));
e.setValue(seq + 1);
}
if (batch.isEmpty()) {
Thread.sleep(200); // nothing new: do not spin
return null;
}
return batch;
}
@Override public void stop() { }
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String bootstrap = broker.getBrokersAsString();
Path dir = Files.createTempDirectory("connect");
Map<String, String> config = new HashMap<>(Map.of(
"name", "regions",
"connector.class", RegionSourceConnector.class.getName(),
"topic", "events", "regions", "eu,us,apac", "tasks.max", "2",
"value.converter", "org.apache.kafka.connect.storage.StringConverter"));
try (KafkaConsumer<String, String> consumer = consumer(bootstrap)) {
consumer.subscribe(List.of("events"));
StandaloneHerder herder = startWorker(bootstrap, dir);
create(herder, config);
FutureCallback<List<TaskInfo>> tasks = new FutureCallback<>();
herder.taskConfigs("regions", tasks);
for (TaskInfo t : tasks.get()) {
System.out.println("task " + t.id().task() + " got regions="
+ t.config().get("regions"));
}
read(consumer, 6);
Thread.sleep(1500); // let the worker flush source offsets
herder.stop();
System.out.println("restart with events.per.region=3");
config.put("events.per.region", "3");
StandaloneHerder again = startWorker(bootstrap, dir);
create(again, config);
read(consumer, 3);
again.stop();
} finally {
broker.destroy();
}
}
static void create(StandaloneHerder herder, Map<String, String> config) throws Exception {
FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
herder.putConnectorConfig(config.get("name"), config, false, created);
created.get();
}
// reads records and prints them sorted, since two tasks send at the same time
static void read(KafkaConsumer<String, String> consumer, int count) {
List<String> lines = new ArrayList<>();
while (lines.size() < count) {
for (ConsumerRecord<String, String> r : consumer.poll(Duration.ofMillis(500))) {
lines.add(" key=" + r.key() + " value=" + r.value());
}
}
lines.stream().sorted().forEach(System.out::println);
}
static KafkaConsumer<String, String> consumer(String bootstrap) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
"group.id", "reader", "auto.offset.reset", "earliest"),
new StringDeserializer(), new StringDeserializer());
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// logging is off: the worker logs some normal events, such as creating the
// dead letter topic, at ERROR. Logback's Logger is named in full because
// org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
task 0 got regions=eu,us
task 1 got regions=apac
key=apac value=apac event 1
key=apac value=apac event 2
key=eu value=eu event 1
key=eu value=eu event 2
key=us value=us event 1
key=us value=us event 2
restart with events.per.region=3
key=apac value=apac event 3
key=eu value=eu event 3
key=us value=us event 3
split three regions into two groups: task 0 gotConnectorUtils.groupPartitions and task 1 goteu,us . The connector caps the task count at the number of regions, since an extra task would have nothing to do.apac- Each record carries a source partition,
, and a source offset,{region=eu} . The worker stores the latest offset per partition, here in the standalone offset file.{seq=2} - After the restart, each region continued at event 3. In
, the task askedstart() for its last offsets and began after them. Without that lookup, a restart would send events 1 and 2 again.context.offsetStorageReader() - The two tasks sent at the same time, so the program sorts the records before printing. Within one region, the order is kept, because each region's records come from one task and go to one key.
A few rules apply to every source task. poll()nullLongoffset.flush.interval.mscommitRecord()
A sink connector and the errant record reporter
A sink task gets records in batches, writes them, and lets the worker commit consumer offsets once the writes are safe. The example writes account balances into a table, held in memory here, where a key with a null
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;
import org.apache.kafka.clients.admin.Admin;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.config.ConfigDef;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.kafka.common.serialization.StringSerializer;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Herder;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConnectorInfo;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.sink.ErrantRecordReporter;
import org.apache.kafka.connect.sink.SinkConnector;
import org.apache.kafka.connect.sink.SinkRecord;
import org.apache.kafka.connect.sink.SinkTask;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class BalanceSink {
// stands in for a database table: account to balance
static final Map<String, Long> TABLE = new ConcurrentSkipListMap<>();
public static class BalanceSinkConnector extends SinkConnector {
private Map<String, String> props;
@Override public void start(Map<String, String> props) { this.props = props; }
@Override public Class<? extends Task> taskClass() { return BalanceSinkTask.class; }
@Override public ConfigDef config() { return new ConfigDef(); }
@Override public void stop() { }
@Override public String version() { return "1.0"; }
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
return Collections.nCopies(maxTasks, props);
}
}
public static class BalanceSinkTask extends SinkTask {
private ErrantRecordReporter reporter;
@Override public String version() { return "1.0"; }
@Override
public void start(Map<String, String> props) {
reporter = context.errantRecordReporter(); // can be null: check before use
}
@Override
public void put(Collection<SinkRecord> records) {
for (SinkRecord r : records) {
String account = (String) r.key();
if (r.value() == null) {
TABLE.remove(account);
System.out.println(" offset " + r.kafkaOffset() + ": delete " + account);
continue;
}
try {
long balance = Long.parseLong((String) r.value());
TABLE.put(account, balance);
System.out.println(" offset " + r.kafkaOffset() + ": upsert " + account
+ " = " + balance);
} catch (NumberFormatException e) {
if (reporter == null) {
throw new DataException("bad balance at offset " + r.kafkaOffset(), e);
}
System.out.println(" offset " + r.kafkaOffset() + ": reported " + e);
reporter.report(r, e);
}
}
}
@Override
public void flush(Map<TopicPartition, OffsetAndMetadata> offsets) {
// a real sink makes its writes durable here, before Connect commits offsets
}
@Override public void stop() { }
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
String bootstrap = broker.getBrokersAsString();
try (KafkaProducer<String, String> producer = new KafkaProducer<>(
Map.of("bootstrap.servers", bootstrap),
new StringSerializer(), new StringSerializer())) {
String[][] data = {{"alice", "10"}, {"bob", "20"}, {"alice", "15"},
{"carol", "ten"}, {"bob", null}};
for (String[] d : data) {
producer.send(new ProducerRecord<>("balances", d[0], d[1]));
}
}
StandaloneHerder herder = startWorker(bootstrap, Files.createTempDirectory("connect"));
try {
Map<String, String> config = Map.of(
"name", "balances-sink",
"connector.class", BalanceSinkConnector.class.getName(),
"topics", "balances",
"value.converter", "org.apache.kafka.connect.storage.StringConverter",
"errors.tolerance", "all",
"errors.deadletterqueue.topic.name", "balances.dlq",
"errors.deadletterqueue.topic.replication.factor", "1",
"errors.deadletterqueue.context.headers.enable", "true");
System.out.println("put() calls on the task thread:");
FutureCallback<Herder.Created<ConnectorInfo>> created = new FutureCallback<>();
herder.putConnectorConfig("balances-sink", config, false, created);
created.get();
try (KafkaConsumer<String, String> dlq = consumer(bootstrap)) {
dlq.subscribe(List.of("balances.dlq"));
ConsumerRecord<String, String> bad = null;
while (bad == null) {
for (ConsumerRecord<String, String> r : dlq.poll(Duration.ofMillis(500))) {
bad = r;
}
}
String stage = new String(bad.headers().lastHeader("__connect.errors.stage")
.value(), StandardCharsets.UTF_8);
System.out.println("balances.dlq: key " + bad.key() + ", value " + bad.value()
+ ", stage " + stage);
}
Thread.sleep(1500); // the worker commits offsets every offset.flush.interval.ms
System.out.println("table: " + TABLE);
try (Admin admin = Admin.create(Map.of("bootstrap.servers", bootstrap))) {
System.out.println("committed offsets of group connect-balances-sink: "
+ admin.listConsumerGroupOffsets("connect-balances-sink")
.partitionsToOffsetAndMetadata().get());
}
} finally {
herder.stop();
broker.destroy();
}
}
static KafkaConsumer<String, String> consumer(String bootstrap) {
return new KafkaConsumer<>(Map.of("bootstrap.servers", bootstrap,
"group.id", "reader", "auto.offset.reset", "earliest"),
new StringDeserializer(), new StringDeserializer());
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// logging is off: the worker logs some normal events, such as creating the
// dead letter topic, at ERROR. Logback's Logger is named in full because
// org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
put() calls on the task thread:
offset 0: upsert alice = 10
offset 1: upsert bob = 20
offset 2: upsert alice = 15
offset 3: reported java.lang.NumberFormatException: For input string: "ten"
offset 4: delete bob
balances.dlq: key carol, value ten, stage TASK_PUT
table: {alice=15}
committed offsets of group connect-balances-sink: {balances-0=OffsetAndMetadata{offset=5, leaderEpoch=null, metadata=''}}
- The task handled the five records in order on its own thread: two upserts for alice, one for bob, then a delete for bob when the tombstone at offset 4 arrived. The table ends with only
.alice=15 - The record at offset 3 converted fine, because
accepts any text, but the task could not parseStringConverter . A converter-level dead letter queue cannot catch this; the task reported the record itself with"ten" .ErrantRecordReporter.report - The reported record landed in
with stagebalances.dlq , unlike theTASK_PUT stage on theVALUE_CONVERTERKafka Connect page, so whoever reads the dead letter queue can tell the two kinds of failure apart. - The worker committed offset 5 for the group
, the next record to read. The committed offset is the only progress a sink keeps: after a restart, the task starts there.connect-balances-sink
errantRecordReporter()nullDataExceptionput()RetriableExceptionput()context.timeout(ms)
The worker calls flush()preCommit()close()open()
Validating the configuration
A connector declares its settings in a ConfigDef
import ch.qos.logback.classic.Level;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.apache.kafka.common.config.Config;
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.ConfigValue;
import org.apache.kafka.common.utils.Time;
import org.apache.kafka.connect.connector.Task;
import org.apache.kafka.connect.connector.policy.AllConnectorClientConfigOverridePolicy;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.runtime.Worker;
import org.apache.kafka.connect.runtime.isolation.Plugins;
import org.apache.kafka.connect.runtime.rest.entities.ConfigInfo;
import org.apache.kafka.connect.runtime.rest.entities.ConfigInfos;
import org.apache.kafka.connect.runtime.standalone.StandaloneConfig;
import org.apache.kafka.connect.runtime.standalone.StandaloneHerder;
import org.apache.kafka.connect.source.SourceConnector;
import org.apache.kafka.connect.storage.FileOffsetBackingStore;
import org.apache.kafka.connect.util.FutureCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.test.EmbeddedKafkaBroker;
import org.springframework.kafka.test.EmbeddedKafkaKraftBroker;
public class ValidateConnector {
public static class TablePollConnector extends SourceConnector {
static final ConfigDef CONFIG = new ConfigDef()
.define("url", Type.STRING, ConfigDef.NO_DEFAULT_VALUE,
new ConfigDef.NonEmptyString(), Importance.HIGH, "JDBC URL")
.define("mode", Type.STRING, "bulk",
ConfigDef.ValidString.in("bulk", "incrementing", "timestamp"),
Importance.HIGH, "How new rows are found")
.define("incrementing.column", Type.STRING, "", Importance.MEDIUM,
"Column for mode=incrementing")
.define("poll.interval.ms", Type.INT, 5000, ConfigDef.Range.atLeast(100),
Importance.LOW, "Time between polls")
.define("password", Type.PASSWORD, "", Importance.HIGH, "Database password");
// checks that involve more than one key
@Override
public Config validate(Map<String, String> props) {
Config config = super.validate(props);
if ("incrementing".equals(props.get("mode"))
&& props.getOrDefault("incrementing.column", "").isBlank()) {
for (ConfigValue v : config.configValues()) {
if (v.name().equals("incrementing.column")) {
v.addErrorMessage("required when mode=incrementing");
}
}
}
return config;
}
@Override public void start(Map<String, String> props) { }
@Override public Class<? extends Task> taskClass() { return null; }
@Override public List<Map<String, String>> taskConfigs(int maxTasks) { return List.of(); }
@Override public void stop() { }
@Override public ConfigDef config() { return CONFIG; }
@Override public String version() { return "1.0"; }
}
public static void main(String[] args) throws Exception {
EmbeddedKafkaBroker broker = startBroker();
StandaloneHerder herder = startWorker(broker.getBrokersAsString(),
Files.createTempDirectory("connect"));
try {
String type = TablePollConnector.class.getName();
validate(herder, "valid", Map.of("name", "a", "connector.class", type,
"url", "jdbc:h2:mem:shop", "mode", "incrementing",
"incrementing.column", "id", "password", "s3cret"));
validate(herder, "invalid", Map.of("name", "b", "connector.class", type,
"url", "", "mode", "incrementing", "poll.interval.ms", "10",
"tasks.max", "0", "transforms", "mask"));
} finally {
herder.stop();
broker.destroy();
}
}
// PUT /connector-plugins/{type}/config/validate runs the same check
static void validate(StandaloneHerder herder, String label, Map<String, String> props)
throws Exception {
FutureCallback<ConfigInfos> result = new FutureCallback<>();
herder.validateConnectorConfig(props, result);
ConfigInfos infos = result.get();
System.out.println(label + ": " + infos.errorCount() + " error(s), groups "
+ infos.groups());
for (ConfigInfo info : infos.configs()) {
var value = info.configValue();
if (!value.errors().isEmpty()) {
System.out.println(" " + value.name() + " = " + value.value() + ": "
+ String.join("; ", value.errors()));
} else if (value.name().equals("password")) {
System.out.println(" password = " + value.value() + " (type "
+ info.configKey().type() + ")");
}
}
}
// Starts a standalone Connect worker in this JVM, the way connect-standalone.sh
// does, but without its REST server
static StandaloneHerder startWorker(String bootstrap, Path dir) {
Map<String, String> props = Map.of(
"bootstrap.servers", bootstrap,
"offset.storage.file.filename", dir.resolve("connect.offsets").toString(),
"offset.flush.interval.ms", "500",
"key.converter", "org.apache.kafka.connect.storage.StringConverter",
"value.converter", "org.apache.kafka.connect.json.JsonConverter");
Plugins plugins = new Plugins(props);
StandaloneConfig config = new StandaloneConfig(props);
var policy = new AllConnectorClientConfigOverridePolicy();
var offsetStore = new FileOffsetBackingStore(plugins.newInternalConverter(
true, JsonConverter.class.getName(), Map.of("schemas.enable", "false")));
offsetStore.configure(config);
Worker worker = new Worker("worker-1", Time.SYSTEM, plugins, config, offsetStore,
policy);
StandaloneHerder herder = new StandaloneHerder(worker, config.kafkaClusterId(), policy);
herder.start();
return herder;
}
// Starts a one-node KRaft broker inside this JVM, from spring-kafka-test
static EmbeddedKafkaBroker startBroker() {
// logging is off: the worker logs some normal events, such as creating the
// dead letter topic, at ERROR. Logback's Logger is named in full because
// org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.OFF);
PrintStream stdout = System.out;
System.setOut(new PrintStream(OutputStream.nullOutputStream()));
try {
EmbeddedKafkaBroker broker = new EmbeddedKafkaKraftBroker(1, 1);
broker.afterPropertiesSet();
return broker;
} finally {
System.setOut(stdout);
}
}
}
valid: 0 error(s), groups [Common, Transforms, Predicates, Error Handling, Topic Creation, Exactly Once Support, offsets.topic]
password = [hidden] (type PASSWORD)
invalid: 5 error(s), groups [Common, Transforms, Predicates, Error Handling, Topic Creation, Exactly Once Support, offsets.topic, Transforms: mask]
tasks.max = 0: Invalid value 0 for configuration tasks.max: Value must be at least 1
transforms.mask.type = null: Missing required configuration "transforms.mask.type" which has no default value.
url = : Invalid value for configuration url: String must be non-empty
incrementing.column = : required when mode=incrementing
poll.interval.ms = 10: Invalid value 10 for configuration poll.interval.ms: Value must be at least 100
password = [hidden] (type PASSWORD)
- The valid configuration had 0 errors. The
list shows that the worker also checked its own settings: transforms, predicates, error handling, topic creation, exactly-once support and the offsets topic.groups - The invalid one had 5 errors, two from the worker and three from the connector.
broke the framework's minimum of 1, and the transform aliastasks.max=0 had nomask .transforms.mask.type failedurl , andNonEmptyString failed thepoll.interval.ms=10 validator with its minimum of 100. These came from theRange without any code.ConfigDef failed the rule in the overriddenincrementing.column . Avalidate() validator sees one value at a time, so cross-field checks belong there.ConfigDef- The
type made the value appear asPASSWORD , in the validation result as in the worker's logs. Use it for every secret.[hidden]
Validation runs again when a connector is created or updated, and a failure there returns HTTP 400 with the same messages. Better still, keep secrets out of the configuration altogether: with a ConfigProviderFileConfigProviderconfig.providers=file${file:/etc/secrets/db.properties:password}
A custom single message transform
A transform is the smallest plugin: one class with configureapplyconfigcloseR extends ConnectRecord<R>
import ch.qos.logback.classic.Level;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.kafka.common.config.AbstractConfig;
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 org.apache.kafka.connect.connector.ConnectRecord;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaBuilder;
import org.apache.kafka.connect.data.Struct;
import org.apache.kafka.connect.errors.DataException;
import org.apache.kafka.connect.source.SourceRecord;
import org.apache.kafka.connect.transforms.Transformation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EmailMaskTransform {
// Masks the local part of e-mail addresses in the configured value fields
public static class EmailMask<R extends ConnectRecord<R>> implements Transformation<R> {
static final ConfigDef CONFIG = new ConfigDef().define("fields", Type.LIST,
ConfigDef.NO_DEFAULT_VALUE, ConfigDef.ValidList.anyNonDuplicateValues(false, false),
Importance.HIGH, "Value fields that hold e-mail addresses");
private List<String> fields;
@Override
public void configure(Map<String, ?> props) {
fields = new AbstractConfig(CONFIG, props).getList("fields");
}
@Override
public R apply(R record) {
Object value = record.value();
if (value == null) {
return record; // tombstones pass through unchanged
}
Object masked;
if (value instanceof Struct struct) {
Struct copy = new Struct(struct.schema());
for (var field : struct.schema().fields()) {
Object v = struct.get(field);
copy.put(field, fields.contains(field.name()) ? mask(v) : v);
}
masked = copy;
} else if (value instanceof Map<?, ?> map) {
Map<Object, Object> copy = new HashMap<>(map);
fields.forEach(f -> copy.computeIfPresent(f, (k, v) -> mask(v)));
masked = copy;
} else {
throw new DataException("EmailMask needs a Struct or Map value, got "
+ value.getClass().getSimpleName());
}
return record.newRecord(record.topic(), record.kafkaPartition(),
record.keySchema(), record.key(), record.valueSchema(), masked,
record.timestamp());
}
static Object mask(Object v) {
if (!(v instanceof String s) || s.indexOf('@') < 1) {
return v;
}
return s.charAt(0) + "***" + s.substring(s.indexOf('@'));
}
@Override public ConfigDef config() { return CONFIG; }
@Override public void close() { }
}
public static void main(String[] args) {
// AbstractConfig logs every parsed config at INFO. Logback's Logger is named
// in full because org.slf4j.Logger, imported, has no setLevel
((ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME))
.setLevel(Level.WARN);
EmailMask<SourceRecord> smt = new EmailMask<>();
smt.configure(Map.of("fields", "email,backup"));
Schema schema = SchemaBuilder.struct().name("Customer")
.field("id", Schema.INT32_SCHEMA)
.field("email", Schema.STRING_SCHEMA)
.field("backup", Schema.OPTIONAL_STRING_SCHEMA)
.build();
Struct struct = new Struct(schema).put("id", 7).put("email", "alice@example.com");
System.out.println("struct: " + smt.apply(record(schema, struct)).value());
System.out.println("original: " + struct);
Map<String, Object> map = Map.of("id", 8, "email", "bob@example.org", "note", "x@y");
System.out.println("map: " + new TreeMap<>(
(Map<?, ?>) smt.apply(record(null, map)).value()));
System.out.println("tombstone: " + smt.apply(record(null, null)).value());
try {
smt.apply(record(Schema.STRING_SCHEMA, "carol@example.com"));
} catch (DataException e) {
System.out.println("string: " + e.getMessage());
}
try {
new EmailMask<SourceRecord>().configure(Map.of("fields", ""));
} catch (ConfigException e) {
System.out.println("bad config: " + e.getMessage());
}
}
static SourceRecord record(Schema schema, Object value) {
return new SourceRecord(Map.of(), Map.of(), "customers", 0, null, null, schema, value);
}
}
struct: Struct{id=7,email=a***@example.com}
original: Struct{id=7,email=alice@example.com}
map: {email=b***@example.org, id=8, note=x@y}
tombstone: null
string: EmailMask needs a Struct or Map value, got String
bad config: Configuration 'fields' must not be empty. Valid values include: any non-empty value
- For a
value, the transform built a new struct with the same schema and maskedStruct . The optionalemail field wasbackup and stayed so.null - The original struct still holds
. Records may be shared, so a transform must return a new record throughalice@example.com instead of changing the old one.newRecord - For a schemaless
, it maskedMap and leftemail alone, becausenote was not configured. Values without a schema come fromnote withJsonConverter , so a transform should handle both shapes.schemas.enable=false - A tombstone passed through untouched. Dropping or changing tombstones would break compacted topics and deletes in sinks.
- A plain string value was rejected with a
, which the worker treats like a conversion error, soDataException applies to it.errors.tolerance - An empty
list failed infields , through theconfigure validator, before any record was seen.ValidList
To use it, put the class in a plugin jar and add transforms=masktransforms.mask.type=com.example.EmailMasktransforms.mask.fields=emailapply
Packaging and installing a plugin
Workers load plugins from the directories in plugin.path
/opt/connect/plugins/
balance-sink/
balance-sink-1.0.jar
postgresql-42.7.4.jar
email-mask/
email-mask-1.0.jar
Do not put the Kafka jars, such as connect-apikafka-clientsServiceLoader
META-INF/services/org.apache.kafka.connect.sink.SinkConnector
com.example.BalanceSinkConnector
META-INF/services/org.apache.kafka.connect.transforms.Transformation
com.example.EmailMask
The worker setting plugin.discoveryhybrid_warnservice_loadconnect-plugin-path.shlistsync-manifests
Two more methods matter for source connectors in distributed clusters. The first is exactlyOnceSupport()SUPPORTEDalterOffsets()PATCH /connectors/{name}/offsets
Choosing what to build
| Need | Build |
|---|---|
| Read a system that has positions you can store, such as ids, timestamps or file offsets | SourceConnectorSourceTask |
| Read a system with independent streams in parallel | One source partition per stream, split across tasks in taskConfigs |
| Write topics to a system | SinkConnectorSinkTaskflush |
| Bad records the task itself detects | ErrantRecordReporter |
| Cross-field configuration rules | Override Connector.validate |
| Change single records in existing connectors | A Transformation |
| Joins, aggregations or calls to other services per record | No plugin: a |
| Something an existing connector already does | Use the existing connector and configure it |
The worker settings, converters and REST operations that every plugin depends on are on