Java Code Examples for org.rnorth.ducttape.unreliables.Unreliables#retryUntilTrue()

The following examples show how to use org.rnorth.ducttape.unreliables.Unreliables#retryUntilTrue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StartupCheckStrategy.java    From testcontainers-java with MIT License 6 votes vote down vote up
public boolean waitUntilStartupSuccessful(DockerClient dockerClient, String containerId) {
    final Boolean[] startedOK = {null};
    Unreliables.retryUntilTrue((int) timeout.toMillis(), TimeUnit.MILLISECONDS, () -> {
        //noinspection CodeBlock2Expr
        return DOCKER_CLIENT_RATE_LIMITER.getWhenReady(() -> {
            StartupStatus state = checkStartupState(dockerClient, containerId);
            switch (state) {
                case SUCCESSFUL:    startedOK[0] = true;
                                    return true;
                case FAILED:        startedOK[0] = false;
                                    return true;
                default:            return false;
            }
        });
    });
    return startedOK[0];
}
 
Example 2
Source File: GenericContainerTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Override
@SneakyThrows
protected void waitUntilReady() {
    Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, () -> {
        ContainerState state = waitStrategyTarget.getCurrentContainerInfo().getState();

        log.debug("Current state: {}", state);
        if (!"exited".equalsIgnoreCase(state.getStatus())) {
            Thread.sleep(100);
            return false;
        }
        return predicate.test(state);
    });

    throw new IllegalStateException("Nope!");
}
 
Example 3
Source File: KafkaConnectConverterIT.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
private <T> List<ConsumerRecord<T, T>> drain(KafkaConsumer<T, T> consumer, int expectedRecordCount) {
    LOGGER.info("Waiting for consumer to receive {} records", expectedRecordCount);
    List<ConsumerRecord<T, T>> allRecords = new ArrayList<>();

    Unreliables.retryUntilTrue(20, TimeUnit.SECONDS, () -> {
        consumer.poll(Duration.ofMillis(50))
            .iterator()
            .forEachRemaining(allRecords::add);

        return allRecords.size() == expectedRecordCount;
    });

    LOGGER.info("All {} records received", expectedRecordCount);
    return allRecords;
}
 
Example 4
Source File: HostPortWaitStrategy.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Override
protected void waitUntilReady() {
    final Set<Integer> externalLivenessCheckPorts = getLivenessCheckPorts();
    if (externalLivenessCheckPorts.isEmpty()) {
        if (log.isDebugEnabled()) {
            log.debug("Liveness check ports of {} is empty. Not waiting.", waitStrategyTarget.getContainerInfo().getName());
        }
        return;
    }

    @SuppressWarnings("unchecked")
    List<Integer> exposedPorts = waitStrategyTarget.getExposedPorts();

    final Set<Integer> internalPorts = getInternalPorts(externalLivenessCheckPorts, exposedPorts);

    Callable<Boolean> internalCheck = new InternalCommandPortListeningCheck(waitStrategyTarget, internalPorts);

    Callable<Boolean> externalCheck = new ExternalPortListeningCheck(waitStrategyTarget, externalLivenessCheckPorts);

    try {
        Unreliables.retryUntilTrue((int) startupTimeout.getSeconds(), TimeUnit.SECONDS,
            () -> getRateLimiter().getWhenReady(() -> internalCheck.call() && externalCheck.call()));

    } catch (TimeoutException e) {
        throw new ContainerLaunchException("Timed out waiting for container port to open (" +
                waitStrategyTarget.getHost() +
                " ports: " +
                externalLivenessCheckPorts +
                " should be listening)");
    }
}
 
Example 5
Source File: DockerHealthcheckWaitStrategy.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Override
protected void waitUntilReady() {

    try {
        Unreliables.retryUntilTrue((int) startupTimeout.getSeconds(), TimeUnit.SECONDS, waitStrategyTarget::isHealthy);
    } catch (TimeoutException e) {
        throw new ContainerLaunchException("Timed out waiting for container to become healthy");
    }
}
 
Example 6
Source File: DockerComposeOverridesTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void test() {
    try (DockerComposeContainer compose =
             new DockerComposeContainer(composeFiles)
                 .withLocalCompose(localMode)
                 .withExposedService(SERVICE_NAME, SERVICE_PORT)) {

        compose.start();

        BufferedReader br = Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS, () -> {
            Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);

            Socket socket = new Socket(compose.getServiceHost(SERVICE_NAME, SERVICE_PORT), compose.getServicePort(SERVICE_NAME, SERVICE_PORT));
            return new BufferedReader(new InputStreamReader(socket.getInputStream()));
        });

        Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> {
            while (br.ready()) {
                String line = br.readLine();
                if (line.contains(expectedEnvVar)) {
                    pass("Mapped environment variable was found");
                    return true;
                }
            }
            info("Mapped environment variable was not found yet - process probably not ready");
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
            return false;
        });
    }
}
 
Example 7
Source File: InternalCommandPortListeningCheckTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void nonListening() {
    final InternalCommandPortListeningCheck check = new InternalCommandPortListeningCheck(container, ImmutableSet.of(8080, 1234));

    try {
        Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, check);
    } catch (TimeoutException e) {
        // we expect it to timeout
    }

    final Boolean result = check.call();

    assertFalse("InternalCommandPortListeningCheck detects a non-listening port among many", result);
}
 
Example 8
Source File: CassandraWaitStrategy.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void waitUntilReady(WaitStrategyTarget waitStrategyTarget) {
    Unreliables.retryUntilTrue(Ints.checkedCast(timeout.getSeconds()), TimeUnit.SECONDS, () -> {
            try {
                return cassandraContainer
                    .execInContainer("cqlsh", "-u", "cassandra", "-p", "cassandra", "-e", "show host")
                    .getStdout()
                    .contains("Connected to Test Cluster");
            } catch (IOException | InterruptedException e) {
                return false;
            }
        }
    );
}
 
Example 9
Source File: SpamAssassinWaitStrategy.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public void waitUntilReady(WaitStrategyTarget waitStrategyTarget) {
    Unreliables.retryUntilTrue(Ints.checkedCast(timeout.getSeconds()), TimeUnit.SECONDS, () -> {
            try {
                return spamAssassinContainer
                    .execInContainer("spamassassin", "-V")
                    .getStdout()
                    .contains("SpamAssassin version 3.4.2");
            } catch (IOException | InterruptedException e) {
                return false;
            }
        }
    );
}
 
Example 10
Source File: JaegerTestDriverContainer.java    From spark-dependencies with Apache License 2.0 4 votes vote down vote up
@Override
protected void waitUntilContainerStarted() {
  String statusUrl = String.format("http://localhost:%d/", this.getMappedPort(8080));
  Unreliables.retryUntilTrue((int)waitUntilReady.toMillis(), TimeUnit.MILLISECONDS, containerStartedCondition(statusUrl));
}
 
Example 11
Source File: KafkaContainerTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
protected void testKafkaFunctionality(String bootstrapServers) throws Exception {
    try (
        KafkaProducer<String, String> producer = new KafkaProducer<>(
            ImmutableMap.of(
                ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers,
                ProducerConfig.CLIENT_ID_CONFIG, UUID.randomUUID().toString()
            ),
            new StringSerializer(),
            new StringSerializer()
        );

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(
            ImmutableMap.of(
                ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers,
                ConsumerConfig.GROUP_ID_CONFIG, "tc-" + UUID.randomUUID(),
                ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"
            ),
            new StringDeserializer(),
            new StringDeserializer()
        );
    ) {
        String topicName = "messages";
        consumer.subscribe(Arrays.asList(topicName));

        producer.send(new ProducerRecord<>(topicName, "testcontainers", "rulezzz")).get();

        Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));

            if (records.isEmpty()) {
                return false;
            }

            assertThat(records)
                .hasSize(1)
                .extracting(ConsumerRecord::topic, ConsumerRecord::key, ConsumerRecord::value)
                .containsExactly(tuple(topicName, "testcontainers", "rulezzz"));

            return true;
        });

        consumer.unsubscribe();
    }
}
 
Example 12
Source File: RabbitMQWaitStrategy.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public void waitUntilReady(WaitStrategyTarget waitStrategyTarget) {
    int seconds = Ints.checkedCast(this.timeout.getSeconds());

    Unreliables.retryUntilTrue(seconds, TimeUnit.SECONDS, this::isConnected);
}
 
Example 13
Source File: InternalCommandPortListeningCheckTest.java    From testcontainers-java with MIT License 3 votes vote down vote up
@Test
public void singleListening() {
    final InternalCommandPortListeningCheck check = new InternalCommandPortListeningCheck(container, ImmutableSet.of(8080));

    Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, check);

    final Boolean result = check.call();

    assertTrue("InternalCommandPortListeningCheck identifies a single listening port", result);
}
 
Example 14
Source File: InternalCommandPortListeningCheckTest.java    From testcontainers-java with MIT License 3 votes vote down vote up
@Test
public void lowAndHighPortListening() {
    final InternalCommandPortListeningCheck check = new InternalCommandPortListeningCheck(container, ImmutableSet.of(100, 8080));

    Unreliables.retryUntilTrue(5, TimeUnit.SECONDS, check);

    final Boolean result = check.call();

    assertTrue("InternalCommandPortListeningCheck identifies a low and a high port", result);
}