Search in sources :

Example 1 with StateListener

use of org.apache.kafka.streams.KafkaStreams.StateListener in project kafka by apache.

the class IntegrationTestUtils method startApplicationAndWaitUntilRunning.

/**
 * Starts the given {@link KafkaStreams} instances and waits for all of them to reach the
 * {@link State#RUNNING} state at the same time. Note that states may change between the time
 * that this method returns and the calling function executes its next statement.<p>
 *
 * If the application is already started, use {@link #waitForApplicationState(List, State, Duration)}
 * to wait for instances to reach {@link State#RUNNING} state.
 *
 * @param streamsList the list of streams instances to run.
 * @param timeout the time to wait for the streams to all be in {@link State#RUNNING} state.
 */
public static void startApplicationAndWaitUntilRunning(final List<KafkaStreams> streamsList, final Duration timeout) throws Exception {
    final Lock stateLock = new ReentrantLock();
    final Condition stateUpdate = stateLock.newCondition();
    final Map<KafkaStreams, State> stateMap = new HashMap<>();
    for (final KafkaStreams streams : streamsList) {
        stateMap.put(streams, streams.state());
        final StateListener prevStateListener = getStateListener(streams);
        final StateListener newStateListener = (newState, oldState) -> {
            stateLock.lock();
            try {
                stateMap.put(streams, newState);
                if (newState == State.RUNNING) {
                    if (stateMap.values().stream().allMatch(state -> state == State.RUNNING)) {
                        stateUpdate.signalAll();
                    }
                }
            } finally {
                stateLock.unlock();
            }
        };
        streams.setStateListener(prevStateListener != null ? new CompositeStateListener(prevStateListener, newStateListener) : newStateListener);
    }
    for (final KafkaStreams streams : streamsList) {
        streams.start();
    }
    final long expectedEnd = System.currentTimeMillis() + timeout.toMillis();
    stateLock.lock();
    try {
        // timeout has expired
        while (true) {
            final Map<KafkaStreams, State> nonRunningStreams = new HashMap<>();
            for (final Entry<KafkaStreams, State> entry : stateMap.entrySet()) {
                if (entry.getValue() != State.RUNNING) {
                    nonRunningStreams.put(entry.getKey(), entry.getValue());
                }
            }
            if (nonRunningStreams.isEmpty()) {
                return;
            }
            final long millisRemaining = expectedEnd - System.currentTimeMillis();
            if (millisRemaining <= 0) {
                fail("Application did not reach a RUNNING state for all streams instances. " + "Non-running instances: " + nonRunningStreams);
            }
            stateUpdate.await(millisRemaining, TimeUnit.MILLISECONDS);
        }
    } finally {
        stateLock.unlock();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) TestCondition(org.apache.kafka.test.TestCondition) TestUtils.waitForCondition(org.apache.kafka.test.TestUtils.waitForCondition) Condition(java.util.concurrent.locks.Condition) KafkaStreamsNamedTopologyWrapper(org.apache.kafka.streams.processor.internals.namedtopology.KafkaStreamsNamedTopologyWrapper) LoggerFactory(org.slf4j.LoggerFactory) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) TestCondition(org.apache.kafka.test.TestCondition) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) Metric(org.apache.kafka.common.Metric) Assert.fail(org.junit.Assert.fail) Request(kafka.api.Request) Consumer(org.apache.kafka.clients.consumer.Consumer) TopicPartition(org.apache.kafka.common.TopicPartition) Time(org.apache.kafka.common.utils.Time) TestUtils(org.apache.kafka.test.TestUtils) Collection(java.util.Collection) KeyValue(org.apache.kafka.streams.KeyValue) FailureReason(org.apache.kafka.streams.query.FailureReason) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ConsumerConfig(org.apache.kafka.clients.consumer.ConsumerConfig) RecordMetadata(org.apache.kafka.clients.producer.RecordMetadata) State(org.apache.kafka.streams.KafkaStreams.State) StateRestoreListener(org.apache.kafka.streams.processor.StateRestoreListener) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) StateQueryResult(org.apache.kafka.streams.query.StateQueryResult) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Entry(java.util.Map.Entry) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) InvalidStateStoreException(org.apache.kafka.streams.errors.InvalidStateStoreException) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) StreamsConfig(org.apache.kafka.streams.StreamsConfig) QueryableStoreType(org.apache.kafka.streams.state.QueryableStoreType) ProducerRecord(org.apache.kafka.clients.producer.ProducerRecord) Headers(org.apache.kafka.common.header.Headers) ConsumerGroupDescription(org.apache.kafka.clients.admin.ConsumerGroupDescription) HashMap(java.util.HashMap) AssignmentListener(org.apache.kafka.streams.processor.internals.assignment.AssignorConfiguration.AssignmentListener) ArrayList(java.util.ArrayList) TestUtils.retryOnExceptionWithTimeout(org.apache.kafka.test.TestUtils.retryOnExceptionWithTimeout) StateQueryRequest(org.apache.kafka.streams.query.StateQueryRequest) KafkaProducer(org.apache.kafka.clients.producer.KafkaProducer) TestName(org.junit.rules.TestName) UpdateMetadataPartitionState(org.apache.kafka.common.message.UpdateMetadataRequestData.UpdateMetadataPartitionState) Admin(org.apache.kafka.clients.admin.Admin) KafkaServer(kafka.server.KafkaServer) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) LinkedList(java.util.LinkedList) QueryResult(org.apache.kafka.streams.query.QueryResult) Utils(org.apache.kafka.common.utils.Utils) StreamsBuilder(org.apache.kafka.streams.StreamsBuilder) TimeoutException(org.apache.kafka.common.errors.TimeoutException) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Logger(org.slf4j.Logger) Properties(java.util.Properties) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Producer(org.apache.kafka.clients.producer.Producer) StreamThread(org.apache.kafka.streams.processor.internals.StreamThread) TestUtils.waitForCondition(org.apache.kafka.test.TestUtils.waitForCondition) ThreadStateTransitionValidator(org.apache.kafka.streams.processor.internals.ThreadStateTransitionValidator) IOException(java.io.IOException) Option(scala.Option) Field(java.lang.reflect.Field) KeyValueTimestamp(org.apache.kafka.streams.KeyValueTimestamp) File(java.io.File) StateListener(org.apache.kafka.streams.KafkaStreams.StateListener) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Condition(java.util.concurrent.locks.Condition) Lock(java.util.concurrent.locks.Lock) Paths(java.nio.file.Paths) MetadataCache(kafka.server.MetadataCache) StoreQueryParameters(org.apache.kafka.streams.StoreQueryParameters) Utils.sleep(org.apache.kafka.common.utils.Utils.sleep) KafkaStreams(org.apache.kafka.streams.KafkaStreams) Collections(java.util.Collections) KafkaStreams(org.apache.kafka.streams.KafkaStreams) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) State(org.apache.kafka.streams.KafkaStreams.State) UpdateMetadataPartitionState(org.apache.kafka.common.message.UpdateMetadataRequestData.UpdateMetadataPartitionState) StateListener(org.apache.kafka.streams.KafkaStreams.StateListener) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Example 2 with StateListener

use of org.apache.kafka.streams.KafkaStreams.StateListener in project kafka by apache.

the class IntegrationTestUtils method getStateListener.

private static StateListener getStateListener(final KafkaStreams streams) {
    try {
        if (streams instanceof KafkaStreamsNamedTopologyWrapper) {
            final Field field = streams.getClass().getSuperclass().getDeclaredField("stateListener");
            field.setAccessible(true);
            return (StateListener) field.get(streams);
        } else {
            final Field field = streams.getClass().getDeclaredField("stateListener");
            field.setAccessible(true);
            return (StateListener) field.get(streams);
        }
    } catch (final IllegalAccessException | NoSuchFieldException e) {
        throw new RuntimeException("Failed to get StateListener through reflection", e);
    }
}
Also used : KafkaStreamsNamedTopologyWrapper(org.apache.kafka.streams.processor.internals.namedtopology.KafkaStreamsNamedTopologyWrapper) Field(java.lang.reflect.Field) StateListener(org.apache.kafka.streams.KafkaStreams.StateListener)

Aggregations

Field (java.lang.reflect.Field)2 File (java.io.File)1 IOException (java.io.IOException)1 Paths (java.nio.file.Paths)1 Duration (java.time.Duration)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Map (java.util.Map)1 Entry (java.util.Map.Entry)1 Objects (java.util.Objects)1 Optional (java.util.Optional)1 Properties (java.util.Properties)1 Set (java.util.Set)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CountDownLatch (java.util.concurrent.CountDownLatch)1