Search in sources :

Example 1 with ConnectorContext

use of org.apache.kafka.connect.connector.ConnectorContext in project kafka by apache.

the class WorkerTest method testAddConnectorByAlias.

@Test
public void testAddConnectorByAlias() throws Exception {
    expectStartStorage();
    // Create
    Connector connector = PowerMock.createMock(Connector.class);
    ConnectorContext ctx = PowerMock.createMock(ConnectorContext.class);
    EasyMock.expect(connectorFactory.newConnector("WorkerTestConnector")).andReturn(connector);
    EasyMock.expect(connector.version()).andReturn("1.0");
    Map<String, String> props = new HashMap<>();
    props.put(SinkConnectorConfig.TOPICS_CONFIG, "foo,bar");
    props.put(ConnectorConfig.TASKS_MAX_CONFIG, "1");
    props.put(ConnectorConfig.NAME_CONFIG, CONNECTOR_ID);
    props.put(ConnectorConfig.CONNECTOR_CLASS_CONFIG, "WorkerTestConnector");
    connector.initialize(EasyMock.anyObject(ConnectorContext.class));
    EasyMock.expectLastCall();
    connector.start(props);
    EasyMock.expectLastCall();
    connectorStatusListener.onStartup(CONNECTOR_ID);
    EasyMock.expectLastCall();
    // Remove
    connector.stop();
    EasyMock.expectLastCall();
    connectorStatusListener.onShutdown(CONNECTOR_ID);
    EasyMock.expectLastCall();
    expectStopStorage();
    PowerMock.replayAll();
    worker = new Worker(WORKER_ID, new MockTime(), connectorFactory, config, offsetBackingStore);
    worker.start();
    assertEquals(Collections.emptySet(), worker.connectorNames());
    worker.startConnector(CONNECTOR_ID, props, ctx, connectorStatusListener, TargetState.STARTED);
    assertEquals(new HashSet<>(Arrays.asList(CONNECTOR_ID)), worker.connectorNames());
    worker.stopConnector(CONNECTOR_ID);
    assertEquals(Collections.emptySet(), worker.connectorNames());
    // Nothing should be left, so this should effectively be a nop
    worker.stop();
    PowerMock.verifyAll();
}
Also used : Connector(org.apache.kafka.connect.connector.Connector) HashMap(java.util.HashMap) ConnectorContext(org.apache.kafka.connect.connector.ConnectorContext) MockTime(org.apache.kafka.connect.util.MockTime) ThreadedTest(org.apache.kafka.connect.util.ThreadedTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 2 with ConnectorContext

use of org.apache.kafka.connect.connector.ConnectorContext in project kafka by apache.

the class DistributedHerder method startConnector.

// Helper for starting a connector with the given name, which will extract & parse the config, generate connector
// context and add to the worker. This needs to be called from within the main worker thread for this herder.
private boolean startConnector(String connectorName) {
    log.info("Starting connector {}", connectorName);
    final Map<String, String> configProps = configState.connectorConfig(connectorName);
    final ConnectorContext ctx = new HerderConnectorContext(this, connectorName);
    final TargetState initialState = configState.targetState(connectorName);
    boolean started = worker.startConnector(connectorName, configProps, ctx, this, initialState);
    // just restoring an existing connector.
    if (started && initialState == TargetState.STARTED)
        reconfigureConnectorTasksWithRetry(connectorName);
    return started;
}
Also used : TargetState(org.apache.kafka.connect.runtime.TargetState) HerderConnectorContext(org.apache.kafka.connect.runtime.HerderConnectorContext) ConnectorContext(org.apache.kafka.connect.connector.ConnectorContext) HerderConnectorContext(org.apache.kafka.connect.runtime.HerderConnectorContext)

Example 3 with ConnectorContext

use of org.apache.kafka.connect.connector.ConnectorContext in project apache-kafka-on-k8s by banzaicloud.

the class WorkerConnector method initialize.

public void initialize(ConnectorConfig connectorConfig) {
    try {
        this.config = connectorConfig.originalsStrings();
        log.debug("{} Initializing connector {} with config {}", this, connName, config);
        if (isSinkConnector()) {
            SinkConnectorConfig.validate(config);
        }
        connector.initialize(new ConnectorContext() {

            @Override
            public void requestTaskReconfiguration() {
                ctx.requestTaskReconfiguration();
            }

            @Override
            public void raiseError(Exception e) {
                log.error("{} Connector raised an error", this, e);
                onFailure(e);
                ctx.raiseError(e);
            }
        });
    } catch (Throwable t) {
        log.error("{} Error initializing connector", this, t);
        onFailure(t);
    }
}
Also used : ConnectorContext(org.apache.kafka.connect.connector.ConnectorContext)

Example 4 with ConnectorContext

use of org.apache.kafka.connect.connector.ConnectorContext in project apache-kafka-on-k8s by banzaicloud.

the class DistributedHerder method startConnector.

// Helper for starting a connector with the given name, which will extract & parse the config, generate connector
// context and add to the worker. This needs to be called from within the main worker thread for this herder.
private boolean startConnector(String connectorName) {
    log.info("Starting connector {}", connectorName);
    final Map<String, String> configProps = configState.connectorConfig(connectorName);
    final ConnectorContext ctx = new HerderConnectorContext(this, connectorName);
    final TargetState initialState = configState.targetState(connectorName);
    boolean started = worker.startConnector(connectorName, configProps, ctx, this, initialState);
    // just restoring an existing connector.
    if (started && initialState == TargetState.STARTED)
        reconfigureConnectorTasksWithRetry(connectorName);
    return started;
}
Also used : TargetState(org.apache.kafka.connect.runtime.TargetState) HerderConnectorContext(org.apache.kafka.connect.runtime.HerderConnectorContext) ConnectorContext(org.apache.kafka.connect.connector.ConnectorContext) HerderConnectorContext(org.apache.kafka.connect.runtime.HerderConnectorContext)

Example 5 with ConnectorContext

use of org.apache.kafka.connect.connector.ConnectorContext in project debezium by debezium.

the class EmbeddedEngine method run.

/**
 * Run this embedded connector and deliver database changes to the registered {@link Consumer}. This method blocks until
 * the connector is stopped.
 * <p>
 * First, the method checks to see if this instance is currently {@link #run() running}, and if so immediately returns.
 * <p>
 * If the configuration is valid, this method starts the connector and starts polling the connector for change events.
 * All messages are delivered in batches to the {@link Consumer} registered with this embedded connector. The batch size,
 * polling
 * frequency, and other parameters are controlled via configuration settings. This continues until this connector is
 * {@link #stop() stopped}.
 * <p>
 * Note that there are two ways to stop a connector running on a thread: calling {@link #stop()} from another thread, or
 * interrupting the thread (e.g., via {@link ExecutorService#shutdownNow()}).
 * <p>
 * This method can be called repeatedly as needed.
 */
@Override
public void run() {
    if (runningThread.compareAndSet(null, Thread.currentThread())) {
        final String engineName = config.getString(ENGINE_NAME);
        final String connectorClassName = config.getString(CONNECTOR_CLASS);
        final Optional<ConnectorCallback> connectorCallback = Optional.ofNullable(this.connectorCallback);
        // Only one thread can be in this part of the method at a time ...
        latch.countUp();
        try {
            if (!config.validateAndRecord(CONNECTOR_FIELDS, logger::error)) {
                fail("Failed to start connector with invalid configuration (see logs for actual errors)");
                return;
            }
            // Instantiate the connector ...
            SourceConnector connector = null;
            try {
                @SuppressWarnings("unchecked") Class<? extends SourceConnector> connectorClass = (Class<SourceConnector>) classLoader.loadClass(connectorClassName);
                connector = connectorClass.newInstance();
            } catch (Throwable t) {
                fail("Unable to instantiate connector class '" + connectorClassName + "'", t);
                return;
            }
            // Instantiate the offset store ...
            final String offsetStoreClassName = config.getString(OFFSET_STORAGE);
            OffsetBackingStore offsetStore = null;
            try {
                @SuppressWarnings("unchecked") Class<? extends OffsetBackingStore> offsetStoreClass = (Class<OffsetBackingStore>) classLoader.loadClass(offsetStoreClassName);
                offsetStore = offsetStoreClass.newInstance();
            } catch (Throwable t) {
                fail("Unable to instantiate OffsetBackingStore class '" + offsetStoreClassName + "'", t);
                return;
            }
            // Initialize the offset store ...
            try {
                offsetStore.configure(workerConfig);
                offsetStore.start();
            } catch (Throwable t) {
                fail("Unable to configure and start the '" + offsetStoreClassName + "' offset backing store", t);
                return;
            }
            // Set up the offset commit policy ...
            if (offsetCommitPolicy == null) {
                offsetCommitPolicy = config.getInstance(EmbeddedEngine.OFFSET_COMMIT_POLICY, OffsetCommitPolicy.class, config);
            }
            // Initialize the connector using a context that does NOT respond to requests to reconfigure tasks ...
            ConnectorContext context = new ConnectorContext() {

                @Override
                public void requestTaskReconfiguration() {
                // Do nothing ...
                }

                @Override
                public void raiseError(Exception e) {
                    fail(e.getMessage(), e);
                }
            };
            connector.initialize(context);
            OffsetStorageWriter offsetWriter = new OffsetStorageWriter(offsetStore, engineName, keyConverter, valueConverter);
            OffsetStorageReader offsetReader = new OffsetStorageReaderImpl(offsetStore, engineName, keyConverter, valueConverter);
            long commitTimeoutMs = config.getLong(OFFSET_COMMIT_TIMEOUT_MS);
            try {
                // Start the connector with the given properties and get the task configurations ...
                connector.start(config.asMap());
                connectorCallback.ifPresent(ConnectorCallback::connectorStarted);
                List<Map<String, String>> taskConfigs = connector.taskConfigs(1);
                Class<? extends Task> taskClass = connector.taskClass();
                SourceTask task = null;
                try {
                    task = (SourceTask) taskClass.newInstance();
                } catch (IllegalAccessException | InstantiationException t) {
                    fail("Unable to instantiate connector's task class '" + taskClass.getName() + "'", t);
                    return;
                }
                try {
                    SourceTaskContext taskContext = () -> offsetReader;
                    task.initialize(taskContext);
                    task.start(taskConfigs.get(0));
                    connectorCallback.ifPresent(ConnectorCallback::taskStarted);
                } catch (Throwable t) {
                    // Mask the passwords ...
                    Configuration config = Configuration.from(taskConfigs.get(0)).withMaskedPasswords();
                    String msg = "Unable to initialize and start connector's task class '" + taskClass.getName() + "' with config: " + config;
                    fail(msg, t);
                    return;
                }
                recordsSinceLastCommit = 0;
                Throwable handlerError = null;
                try {
                    timeOfLastCommitMillis = clock.currentTimeInMillis();
                    boolean keepProcessing = true;
                    List<SourceRecord> changeRecords = null;
                    while (runningThread.get() != null && handlerError == null && keepProcessing) {
                        try {
                            try {
                                logger.debug("Embedded engine is polling task for records on thread " + runningThread.get());
                                // blocks until there are values ...
                                changeRecords = task.poll();
                                logger.debug("Embedded engine returned from polling task for records");
                            } catch (InterruptedException e) {
                                // Interrupted while polling ...
                                logger.debug("Embedded engine interrupted on thread " + runningThread.get() + " while polling the task for records");
                                Thread.interrupted();
                                break;
                            }
                            try {
                                if (changeRecords != null && !changeRecords.isEmpty()) {
                                    logger.debug("Received {} records from the task", changeRecords.size());
                                    // First forward the records to the connector's consumer ...
                                    for (SourceRecord record : changeRecords) {
                                        try {
                                            consumer.accept(record);
                                            task.commitRecord(record);
                                        } catch (StopConnectorException e) {
                                            keepProcessing = false;
                                            // Stop processing any more but first record the offset for this record's
                                            // partition
                                            offsetWriter.offset(record.sourcePartition(), record.sourceOffset());
                                            recordsSinceLastCommit += 1;
                                            break;
                                        } catch (Throwable t) {
                                            handlerError = t;
                                            break;
                                        }
                                        // Record the offset for this record's partition
                                        offsetWriter.offset(record.sourcePartition(), record.sourceOffset());
                                        recordsSinceLastCommit += 1;
                                    }
                                    // Flush the offsets to storage if necessary ...
                                    maybeFlush(offsetWriter, offsetCommitPolicy, commitTimeoutMs, task);
                                } else {
                                    logger.debug("Received no records from the task");
                                }
                            } catch (Throwable t) {
                                // There was some sort of unexpected exception, so we should stop work
                                if (handlerError == null) {
                                    // make sure we capture the error first so that we can report it later
                                    handlerError = t;
                                }
                                break;
                            }
                        } finally {
                            // then try to commit the offsets, since we record them only after the records were handled
                            // by the consumer ...
                            maybeFlush(offsetWriter, offsetCommitPolicy, commitTimeoutMs, task);
                        }
                    }
                } finally {
                    if (handlerError != null) {
                        // There was an error in the handler so make sure it's always captured...
                        fail("Stopping connector after error in the application's handler method: " + handlerError.getMessage(), handlerError);
                    }
                    try {
                        // First stop the task ...
                        logger.debug("Stopping the task and engine");
                        task.stop();
                        connectorCallback.ifPresent(ConnectorCallback::taskStopped);
                        // Always commit offsets that were captured from the source records we actually processed ...
                        commitOffsets(offsetWriter, commitTimeoutMs, task);
                        if (handlerError == null) {
                            // We stopped normally ...
                            succeed("Connector '" + connectorClassName + "' completed normally.");
                        }
                    } catch (Throwable t) {
                        fail("Error while trying to stop the task and commit the offsets", t);
                    }
                }
            } catch (Throwable t) {
                fail("Error while trying to run connector class '" + connectorClassName + "'", t);
            } finally {
                // Close the offset storage and finally the connector ...
                try {
                    offsetStore.stop();
                } catch (Throwable t) {
                    fail("Error while trying to stop the offset store", t);
                } finally {
                    try {
                        connector.stop();
                        connectorCallback.ifPresent(ConnectorCallback::connectorStopped);
                    } catch (Throwable t) {
                        fail("Error while trying to stop connector class '" + connectorClassName + "'", t);
                    }
                }
            }
        } finally {
            latch.countDown();
            runningThread.set(null);
            // after we've "shut down" the engine, fire the completion callback based on the results we collected
            completionCallback.handle(completionResult.success(), completionResult.message(), completionResult.error());
        }
    }
}
Also used : OffsetStorageWriter(org.apache.kafka.connect.storage.OffsetStorageWriter) Configuration(io.debezium.config.Configuration) SourceRecord(org.apache.kafka.connect.source.SourceRecord) OffsetCommitPolicy(io.debezium.embedded.spi.OffsetCommitPolicy) FileOffsetBackingStore(org.apache.kafka.connect.storage.FileOffsetBackingStore) OffsetBackingStore(org.apache.kafka.connect.storage.OffsetBackingStore) KafkaOffsetBackingStore(org.apache.kafka.connect.storage.KafkaOffsetBackingStore) ConnectorContext(org.apache.kafka.connect.connector.ConnectorContext) SourceTaskContext(org.apache.kafka.connect.source.SourceTaskContext) TimeoutException(java.util.concurrent.TimeoutException) ExecutionException(java.util.concurrent.ExecutionException) OffsetStorageReaderImpl(org.apache.kafka.connect.storage.OffsetStorageReaderImpl) SourceConnector(org.apache.kafka.connect.source.SourceConnector) SourceTask(org.apache.kafka.connect.source.SourceTask) OffsetStorageReader(org.apache.kafka.connect.storage.OffsetStorageReader) Map(java.util.Map)

Aggregations

ConnectorContext (org.apache.kafka.connect.connector.ConnectorContext)9 HashMap (java.util.HashMap)4 Connector (org.apache.kafka.connect.connector.Connector)4 MockTime (org.apache.kafka.connect.util.MockTime)4 ThreadedTest (org.apache.kafka.connect.util.ThreadedTest)4 Test (org.junit.Test)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 Map (java.util.Map)2 ConnectException (org.apache.kafka.connect.errors.ConnectException)2 HerderConnectorContext (org.apache.kafka.connect.runtime.HerderConnectorContext)2 TargetState (org.apache.kafka.connect.runtime.TargetState)2 Configuration (io.debezium.config.Configuration)1 OffsetCommitPolicy (io.debezium.embedded.spi.OffsetCommitPolicy)1 ExecutionException (java.util.concurrent.ExecutionException)1 TimeoutException (java.util.concurrent.TimeoutException)1 SourceConnector (org.apache.kafka.connect.source.SourceConnector)1 SourceRecord (org.apache.kafka.connect.source.SourceRecord)1 SourceTask (org.apache.kafka.connect.source.SourceTask)1 SourceTaskContext (org.apache.kafka.connect.source.SourceTaskContext)1 FileOffsetBackingStore (org.apache.kafka.connect.storage.FileOffsetBackingStore)1