Search in sources :

Example 1 with CompletionCallback

use of io.debezium.embedded.EmbeddedEngine.CompletionCallback in project debezium by debezium.

the class ConnectorOutputTest method runConnector.

/**
 * Run the connector described by the supplied test specification.
 *
 * @param spec the test specification
 * @param callback the function that should be called when the connector is stopped
 */
protected void runConnector(TestSpecification spec, CompletionCallback callback) {
    PreviousContext preRunContext = LoggingContext.forConnector(getClass().getSimpleName(), "runner", spec.name());
    final Configuration environmentConfig = Configuration.copy(spec.environment()).build();
    final Configuration connectorConfig = spec.config();
    String[] ignorableFieldNames = environmentConfig.getString(ENV_IGNORE_FIELDS, "").split(",");
    final Set<String> ignorableFields = Arrays.stream(ignorableFieldNames).map(String::trim).collect(Collectors.toSet());
    String[] globallyIgnorableFieldNames = globallyIgnorableFieldNames();
    if (globallyIgnorableFieldNames != null && globallyIgnorableFieldNames.length != 0) {
        ignorableFields.addAll(Arrays.stream(globallyIgnorableFieldNames).map(String::trim).collect(Collectors.toSet()));
    }
    final SchemaAndValueConverter keyConverter = new SchemaAndValueConverter(environmentConfig, true);
    final SchemaAndValueConverter valueConverter = new SchemaAndValueConverter(environmentConfig, false);
    final TestData testData = spec.testData();
    // Get any special comparators ...
    final Map<String, RecordValueComparator> comparatorsByFieldName = new HashMap<>();
    addValueComparatorsByFieldPath(comparatorsByFieldName::put);
    final Map<String, RecordValueComparator> comparatorsBySchemaName = new HashMap<>();
    addValueComparatorsBySchemaName(comparatorsBySchemaName::put);
    RuntimeException runError = null;
    CompletionResult problem = new CompletionResult(callback);
    try {
        // Set up the test data ...
        final PreviewIterator<Document> expectedRecords = Iterators.preview(testData.read());
        final Consumer<Document> recorder = testData::write;
        // We need something that will measure the amount of time since our consumer has seen a record ...
        TimeSince timeSinceLastRecord = Threads.timeSince(Clock.SYSTEM);
        // We'll keep the last 10 expected and actual records so that there is some context if they don't match ...
        Queue<SourceRecord> actualRecordHistory = fixedSizeQueue(10);
        Queue<SourceRecord> expectedRecordHistory = fixedSizeQueue(10);
        // Define what happens for each record ...
        ConsumerCompletion result = new ConsumerCompletion();
        Consumer<SourceRecord> consumer = (actualRecord) -> {
            PreviousContext prev = LoggingContext.forConnector(getClass().getSimpleName(), "runner", spec.name());
            try {
                Testing.debug("actual record:    " + SchemaUtil.asString(actualRecord));
                timeSinceLastRecord.reset();
                // Record the actual in the history ...
                actualRecordHistory.add(actualRecord);
                // And possibly hand it to the test's recorder ...
                try {
                    Document jsonRecord = serializeSourceRecord(actualRecord, keyConverter, valueConverter);
                    if (jsonRecord != null)
                        recorder.accept(jsonRecord);
                } catch (IOException e) {
                    String msg = "Error converting JSON to SourceRecord";
                    Testing.debug(msg);
                    throw new ConnectException(msg, e);
                }
                if (expectedRecords != null) {
                    // Get the test's next expected record ...
                    if (!expectedRecords.hasNext()) {
                        // We received an actual record but don't have or expect one ...
                        String msg = "Source record found but nothing expected";
                        result.error();
                        Testing.debug(msg);
                        throw new MismatchRecordException(msg, actualRecordHistory, expectedRecordHistory);
                    }
                    Document expected = expectedRecords.next();
                    if (isEndCommand(expected)) {
                        result.error();
                        String msg = "Source record was found but not expected: " + SchemaUtil.asString(actualRecord);
                        Testing.debug(msg);
                        throw new MismatchRecordException(msg, actualRecordHistory, expectedRecordHistory);
                    } else if (isCommand(expected)) {
                        Testing.debug("applying command: " + SchemaUtil.asString(expected));
                        applyCommand(expected, result);
                    } else {
                        try {
                            // Otherwise, build a record from the expected and add it to the history ...
                            SourceRecord expectedRecord = rehydrateSourceRecord(expected, keyConverter, valueConverter);
                            expectedRecordHistory.add(expectedRecord);
                            Testing.debug("expected record:  " + SchemaUtil.asString(expectedRecord));
                            // And compare the records ...
                            try {
                                assertSourceRecordMatch(actualRecord, expectedRecord, ignorableFields::contains, comparatorsByFieldName, comparatorsBySchemaName);
                            } catch (AssertionError e) {
                                result.error();
                                String msg = "Source record with key " + SchemaUtil.asString(actualRecord.key()) + " did not match expected record: " + e.getMessage();
                                Testing.debug(msg);
                                throw new MismatchRecordException(e, msg, actualRecordHistory, expectedRecordHistory);
                            }
                        } catch (IOException e) {
                            result.exception();
                            String msg = "Error converting JSON to SourceRecord";
                            Testing.debug(msg);
                            throw new ConnectException(msg, e);
                        }
                    }
                    if (!expectedRecords.hasNext()) {
                        // We expect no more records, so stop the connector ...
                        result.stop();
                        String msg = "Stopping connector after no more expected records found";
                        Testing.debug(msg);
                        throw new StopConnectorException(msg);
                    }
                    // Peek at the next record to see if it is a command ...
                    Document nextExpectedRecord = expectedRecords.peek();
                    if (isCommand(nextExpectedRecord)) {
                        // consume it and apply it ...
                        applyCommand(expectedRecords.next(), result);
                    }
                }
            } finally {
                prev.restore();
            }
        };
        // Set up the configuration for the engine to include the connector configuration and apply as defaults
        // the environment and engine parameters ...
        Configuration engineConfig = Configuration.copy(connectorConfig).withDefault(environmentConfig).withDefault(EmbeddedEngine.ENGINE_NAME, spec.name()).withDefault(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG, OFFSET_STORE_PATH).withDefault(EmbeddedEngine.OFFSET_FLUSH_INTERVAL_MS, 0).build();
        // Create the engine ...
        EmbeddedEngine engine = EmbeddedEngine.create().using(engineConfig).notifying(consumer).using(this.getClass().getClassLoader()).using(problem).build();
        long connectorTimeoutInSeconds = environmentConfig.getLong(ENV_CONNECTOR_TIMEOUT_IN_SECONDS, 10);
        // Get ready to run the connector one or more times ...
        do {
            // Each time create a thread that will stop our connector if we don't get enough results
            Thread timeoutThread = Threads.timeout(spec.name() + "-connector-output", connectorTimeoutInSeconds, TimeUnit.SECONDS, timeSinceLastRecord, engine::stop);
            // But plan to stop our timeout thread as soon as the connector completes ...
            result.uponCompletion(timeoutThread::interrupt);
            timeoutThread.start();
            // Run the connector and block until the connector is stopped by the timeout thread or until
            // an exception is thrown within the connector (perhaps by the consumer) ...
            Testing.debug("Starting connector");
            result.reset();
            engine.run();
        } while (result.get() == ExecutionResult.RESTART_REQUESTED);
    } catch (IOException e) {
        runError = new RuntimeException("Error reading test data: " + e.getMessage(), e);
    } catch (RuntimeException t) {
        runError = t;
    } finally {
        // And clean up everything ...
        try {
            testData.close();
        } catch (IOException e) {
            if (runError != null) {
                runError = new RuntimeException("Error closing test data: " + e.getMessage(), e);
            }
        } finally {
            try {
                keyConverter.close();
            } finally {
                try {
                    valueConverter.close();
                } finally {
                    preRunContext.restore();
                }
            }
        }
    }
    if (runError != null) {
        throw runError;
    }
    if (problem.hasError()) {
        Throwable error = problem.error();
        if (error instanceof AssertionError) {
            fail(problem.message());
        } else if (error instanceof MismatchRecordException) {
            MismatchRecordException mismatch = (MismatchRecordException) error;
            LinkedList<SourceRecord> actualHistory = mismatch.getActualRecords();
            LinkedList<SourceRecord> expectedHistory = mismatch.getExpectedRecords();
            Testing.print("");
            Testing.print("FAILURE in connector integration test '" + spec.name() + "' in class " + getClass());
            Testing.print(" actual record:   " + SchemaUtil.asString(actualHistory.getLast()));
            Testing.print(" expected record: " + SchemaUtil.asString(expectedHistory.getLast()));
            Testing.print(mismatch.getMessage());
            Testing.print("");
            AssertionError cause = ((MismatchRecordException) error).getError();
            if (cause != null) {
                throw cause;
            }
            fail(problem.message());
        } else if (error instanceof RuntimeException) {
            throw (RuntimeException) error;
        } else {
            throw new RuntimeException(error);
        }
    }
}
Also used : Arrays(java.util.Arrays) PreviewIterator(io.debezium.util.Iterators.PreviewIterator) Threads(io.debezium.util.Threads) Schema(org.apache.kafka.connect.data.Schema) LoggingContext(io.debezium.util.LoggingContext) JsonDeserializer(org.apache.kafka.connect.json.JsonDeserializer) Map(java.util.Map) After(org.junit.After) Assert.fail(org.junit.Assert.fail) JsonNode(com.fasterxml.jackson.databind.JsonNode) Path(java.nio.file.Path) DocumentReader(io.debezium.document.DocumentReader) Predicate(java.util.function.Predicate) Set(java.util.Set) Collectors(java.util.stream.Collectors) SourceRecord(org.apache.kafka.connect.source.SourceRecord) ArrayReader(io.debezium.document.ArrayReader) StandardCharsets(java.nio.charset.StandardCharsets) List(java.util.List) Queue(java.util.Queue) JsonConverter(org.apache.kafka.connect.json.JsonConverter) SchemaUtil(io.debezium.data.SchemaUtil) Value(io.debezium.document.Value) CompletionResult(io.debezium.embedded.EmbeddedEngine.CompletionResult) Array(io.debezium.document.Array) RecordValueComparator(io.debezium.data.VerifyRecord.RecordValueComparator) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) PreviousContext(io.debezium.util.LoggingContext.PreviousContext) ArrayList(java.util.ArrayList) StandaloneConfig(org.apache.kafka.connect.runtime.standalone.StandaloneConfig) Document(io.debezium.document.Document) BiConsumer(java.util.function.BiConsumer) ArrayWriter(io.debezium.document.ArrayWriter) LinkedList(java.util.LinkedList) Strings(io.debezium.util.Strings) Before(org.junit.Before) OutputStream(java.io.OutputStream) Properties(java.util.Properties) Iterators(io.debezium.util.Iterators) Iterator(java.util.Iterator) SchemaAndValue(org.apache.kafka.connect.data.SchemaAndValue) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) Configuration(io.debezium.config.Configuration) FileInputStream(java.io.FileInputStream) CompletionCallback(io.debezium.embedded.EmbeddedEngine.CompletionCallback) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonSerializer(org.apache.kafka.connect.json.JsonSerializer) Testing(io.debezium.util.Testing) Paths(java.nio.file.Paths) Collect(io.debezium.util.Collect) ConnectException(org.apache.kafka.connect.errors.ConnectException) VerifyRecord(io.debezium.data.VerifyRecord) Clock(io.debezium.util.Clock) TimeSince(io.debezium.util.Threads.TimeSince) IoUtil(io.debezium.util.IoUtil) InputStream(java.io.InputStream) Configuration(io.debezium.config.Configuration) HashMap(java.util.HashMap) Document(io.debezium.document.Document) SourceRecord(org.apache.kafka.connect.source.SourceRecord) ConnectException(org.apache.kafka.connect.errors.ConnectException) CompletionResult(io.debezium.embedded.EmbeddedEngine.CompletionResult) IOException(java.io.IOException) LinkedList(java.util.LinkedList) RecordValueComparator(io.debezium.data.VerifyRecord.RecordValueComparator) PreviousContext(io.debezium.util.LoggingContext.PreviousContext) TimeSince(io.debezium.util.Threads.TimeSince)

Example 2 with CompletionCallback

use of io.debezium.embedded.EmbeddedEngine.CompletionCallback in project debezium by debezium.

the class AbstractConnectorTest method start.

/**
 * Start the connector using the supplied connector configuration.
 *
 * @param connectorClass the connector class; may not be null
 * @param connectorConfig the configuration for the connector; may not be null
 * @param isStopRecord the function that will be called to determine if the connector should be stopped before processing
 *            this record; may be null if not needed
 * @param callback the function that will be called when the engine fails to start the connector or when the connector
 *            stops running after completing successfully or due to an error; may be null
 */
protected void start(Class<? extends SourceConnector> connectorClass, Configuration connectorConfig, CompletionCallback callback, Predicate<SourceRecord> isStopRecord) {
    Configuration config = Configuration.copy(connectorConfig).with(EmbeddedEngine.ENGINE_NAME, "testing-connector").with(EmbeddedEngine.CONNECTOR_CLASS, connectorClass.getName()).with(StandaloneConfig.OFFSET_STORAGE_FILE_FILENAME_CONFIG, OFFSET_STORE_PATH).with(EmbeddedEngine.OFFSET_FLUSH_INTERVAL_MS, 0).build();
    latch = new CountDownLatch(1);
    CompletionCallback wrapperCallback = (success, msg, error) -> {
        try {
            if (callback != null)
                callback.handle(success, msg, error);
        } finally {
            if (!success) {
                // we only unblock if there was an error; in all other cases we're unblocking when a task has been started
                latch.countDown();
            }
        }
        Testing.debug("Stopped connector");
    };
    ConnectorCallback connectorCallback = new ConnectorCallback() {

        @Override
        public void taskStarted() {
            // if this is called, it means a task has been started successfully so we can continue
            latch.countDown();
        }
    };
    // Create the connector ...
    engine = EmbeddedEngine.create().using(config).notifying((record) -> {
        if (isStopRecord != null && isStopRecord.test(record)) {
            logger.error("Stopping connector after record as requested");
            throw new ConnectException("Stopping connector after record as requested");
        }
        try {
            consumedLines.put(record);
        } catch (InterruptedException e) {
            Thread.interrupted();
        }
    }).using(this.getClass().getClassLoader()).using(wrapperCallback).using(connectorCallback).build();
    // Submit the connector for asynchronous execution ...
    assertThat(executor).isNull();
    executor = Executors.newFixedThreadPool(1);
    executor.execute(() -> {
        LoggingContext.forConnector(getClass().getSimpleName(), "", "engine");
        engine.run();
    });
    try {
        if (!latch.await(10, TimeUnit.SECONDS)) {
            // maybe it takes more time to start up, so just log a warning and continue
            logger.warn("The connector did not finish starting its task(s) or complete in the expected amount of time");
        }
    } catch (InterruptedException e) {
        if (Thread.interrupted()) {
            fail("Interrupted while waiting for engine startup");
        }
    }
}
Also used : WorkerConfig(org.apache.kafka.connect.runtime.WorkerConfig) FileOffsetBackingStore(org.apache.kafka.connect.storage.FileOffsetBackingStore) Arrays(java.util.Arrays) BooleanConsumer(io.debezium.function.BooleanConsumer) LoggerFactory(org.slf4j.LoggerFactory) Schema(org.apache.kafka.connect.data.Schema) BigDecimal(java.math.BigDecimal) LoggingContext(io.debezium.util.LoggingContext) JsonDeserializer(org.apache.kafka.connect.json.JsonDeserializer) SourceConnector(org.apache.kafka.connect.source.SourceConnector) Assertions.assertThat(org.fest.assertions.Assertions.assertThat) Map(java.util.Map) Converter(org.apache.kafka.connect.storage.Converter) After(org.junit.After) Assert.fail(org.junit.Assert.fail) SkipTestRule(io.debezium.junit.SkipTestRule) Path(java.nio.file.Path) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) ConfigValue(org.apache.kafka.common.config.ConfigValue) SourceRecord(org.apache.kafka.connect.source.SourceRecord) Executors(java.util.concurrent.Executors) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) CountDownLatch(java.util.concurrent.CountDownLatch) HistoryRecord(io.debezium.relational.history.HistoryRecord) List(java.util.List) EmbeddedConfig(io.debezium.embedded.EmbeddedEngine.EmbeddedConfig) JsonConverter(org.apache.kafka.connect.json.JsonConverter) Delta(org.fest.assertions.Delta) SchemaUtil(io.debezium.data.SchemaUtil) OffsetStorageReaderImpl(org.apache.kafka.connect.storage.OffsetStorageReaderImpl) TestRule(org.junit.rules.TestRule) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Config(org.apache.kafka.common.config.Config) StandaloneConfig(org.apache.kafka.connect.runtime.standalone.StandaloneConfig) LinkedList(java.util.LinkedList) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) Logger(org.slf4j.Logger) Field(org.apache.kafka.connect.data.Field) SchemaAndValue(org.apache.kafka.connect.data.SchemaAndValue) Configuration(io.debezium.config.Configuration) CompletionCallback(io.debezium.embedded.EmbeddedEngine.CompletionCallback) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Rule(org.junit.Rule) Testing(io.debezium.util.Testing) Struct(org.apache.kafka.connect.data.Struct) ConnectException(org.apache.kafka.connect.errors.ConnectException) VerifyRecord(io.debezium.data.VerifyRecord) Collections(java.util.Collections) ConnectorCallback(io.debezium.embedded.EmbeddedEngine.ConnectorCallback) Configuration(io.debezium.config.Configuration) ConnectorCallback(io.debezium.embedded.EmbeddedEngine.ConnectorCallback) CompletionCallback(io.debezium.embedded.EmbeddedEngine.CompletionCallback) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectException(org.apache.kafka.connect.errors.ConnectException)

Aggregations

Configuration (io.debezium.config.Configuration)2 SchemaUtil (io.debezium.data.SchemaUtil)2 VerifyRecord (io.debezium.data.VerifyRecord)2 CompletionCallback (io.debezium.embedded.EmbeddedEngine.CompletionCallback)2 LoggingContext (io.debezium.util.LoggingContext)2 Testing (io.debezium.util.Testing)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 RecordValueComparator (io.debezium.data.VerifyRecord.RecordValueComparator)1 Array (io.debezium.document.Array)1 ArrayReader (io.debezium.document.ArrayReader)1 ArrayWriter (io.debezium.document.ArrayWriter)1 Document (io.debezium.document.Document)1 DocumentReader (io.debezium.document.DocumentReader)1