org.testcontainers.containers.ContainerLaunchException Java Examples

The following examples show how to use org.testcontainers.containers.ContainerLaunchException. 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: EtcdContainer.java    From etcd4j with Apache License 2.0 7 votes vote down vote up
private WaitStrategy waitStrategy() {
    return new AbstractWaitStrategy() {
        @Override
        protected void waitUntilReady() {
            final DockerClient client = DockerClientFactory.instance().client();
            final WaitingConsumer waitingConsumer = new WaitingConsumer();

            LogUtils.followOutput(client, waitStrategyTarget.getContainerId(), waitingConsumer);

            try {
                waitingConsumer.waitUntil(
                    f -> f.getUtf8String().contains("etcdserver: published"),
                    startupTimeout.getSeconds(),
                    TimeUnit.SECONDS,
                    1
                );
            } catch (TimeoutException e) {
                throw new ContainerLaunchException("Timed out");
            }
        }
    };
}
 
Example #2
Source File: CassandraQueryWaitStrategy.java    From testcontainers-java with MIT License 6 votes vote down vote up
@Override
protected void waitUntilReady() {
    // execute select version query until success or timeout
    try {
        retryUntilSuccess((int) startupTimeout.getSeconds(), TimeUnit.SECONDS, () -> {
            getRateLimiter().doWhenReady(() -> {
                try (DatabaseDelegate databaseDelegate = getDatabaseDelegate()) {
                    databaseDelegate.execute(SELECT_VERSION_QUERY, "", 1, false, false);
                }
            });
            return true;
        });
    } catch (TimeoutException e) {
        throw new ContainerLaunchException(TIMEOUT_ERROR);
    }
}
 
Example #3
Source File: ImagePullPolicyTest.java    From testcontainers-java with MIT License 6 votes vote down vote up
private void expectToFailWithNotFoundException(GenericContainer<?> container) {
    try {
        container.start();
        fail("Should fail");
    } catch (ContainerLaunchException e) {
        Throwable throwable = e;
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
            if (throwable.getCause() instanceof NotFoundException) {
                VisibleAssertions.pass("Caused by NotFoundException");
                return;
            }
        }
        VisibleAssertions.fail("Caused by NotFoundException");
    }
}
 
Example #4
Source File: SelectedPortWaitStrategy.java    From presto with Apache License 2.0 6 votes vote down vote up
@Override
protected void waitUntilReady()
{
    Callable<Boolean> internalCheck = new InternalCommandPortListeningCheck(waitStrategyTarget, exposedPorts);

    Set<Integer> externalPorts = exposedPorts.stream()
            .map(waitStrategyTarget::getMappedPort)
            .collect(toImmutableSet());
    Callable<Boolean> externalCheck = new ExternalPortListeningCheck(waitStrategyTarget, externalPorts);

    Failsafe.with(new RetryPolicy<>()
            .withMaxDuration(startupTimeout)
            .withMaxAttempts(Integer.MAX_VALUE) // limited by MaxDuration
            .abortOn(e -> getExitCode().isPresent()))
            .run(() -> {
                if (!getRateLimiter().getWhenReady(() -> internalCheck.call() && externalCheck.call())) {
                    // We say "timed out" immediately. Failsafe will propagate this only when timeout reached.
                    throw new ContainerLaunchException(format(
                            "Timed out waiting for container port to open (%s ports: %s should be listening)",
                            waitStrategyTarget.getContainerIpAddress(),
                            exposedPorts));
                }
            });
}
 
Example #5
Source File: CassandraStorageExtension.java    From zipkin-dependencies with Apache License 2.0 6 votes vote down vote up
@Override protected void waitUntilContainerStarted() {
  Unreliables.retryUntilSuccess(2, TimeUnit.MINUTES, () -> {
    if (!isRunning()) {
      throw new ContainerLaunchException("Container failed to start");
    }

    InetSocketAddress address =
      new InetSocketAddress(getContainerIpAddress(), getMappedPort(9042));

    try (Cluster cluster = getCluster(address); Session session = cluster.newSession()) {
      session.execute("SELECT now() FROM system.local");
      logger().info("Obtained a connection to container ({})", cluster.getClusterName());
      return null; // unused value
    }
  });
}
 
Example #6
Source File: CassandraStorageExtension.java    From zipkin-dependencies with Apache License 2.0 6 votes vote down vote up
@Override protected void waitUntilContainerStarted() {
  Unreliables.retryUntilSuccess(2, TimeUnit.MINUTES, () -> {
    if (!isRunning()) {
      throw new ContainerLaunchException("Container failed to start");
    }

    InetSocketAddress address =
      new InetSocketAddress(getContainerIpAddress(), getMappedPort(9042));

    try (Cluster cluster = getCluster(address); Session session = cluster.newSession()) {
      session.execute("SELECT now() FROM system.local");
      logger().info("Obtained a connection to container ({})", cluster.getClusterName());
      return null; // unused value
    }
  });
}
 
Example #7
Source File: JaegerTestDriverContainer.java    From spark-dependencies with Apache License 2.0 6 votes vote down vote up
protected Callable<Boolean> containerStartedCondition(String statusUrl) {
  return () -> {
    if (!isRunning()) {
      throw new ContainerLaunchException("Container failed to start");
    }

    Request request = new Request.Builder()
        .url(statusUrl)
        .head()
        .build();
    try (Response response = okHttpClient.newCall(request).execute()) {
      return response.code() == 200;
    } catch (ConnectException ex) {
      return false;
    }
  };
}
 
Example #8
Source File: EtcdContainer.java    From jetcd with Apache License 2.0 5 votes vote down vote up
private static Path createDataDirectory(String name) {
    try {
        final String prefix = "jetcd_test_" + name + "_";
        final FileAttribute<?> attribute = PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class));

        // https://github.com/etcd-io/jetcd/issues/489
        // Resolve symlink (/var -> /private/var) to don't fail for Mac OS because of docker thing with /var/folders
        return Files.createTempDirectory(prefix, attribute).toRealPath();
    } catch (IOException e) {
        throw new ContainerLaunchException("Error creating data directory", e);
    }
}
 
Example #9
Source File: CassandraContainer.java    From spark-dependencies with Apache License 2.0 5 votes vote down vote up
@Override
protected void waitUntilContainerStarted() {
  Unreliables.retryUntilSuccess(120, TimeUnit.SECONDS, () -> {
    if (!isRunning()) {
      throw new ContainerLaunchException("Container failed to start");
    }

    try (Cluster cluster = getCluster(); Session session = cluster.newSession()) {
      session.execute("SELECT now() FROM system.local");
      logger().info("Obtained a connection to container ({})", cluster.getClusterName());
      return null; // unused value
    }
  });
}
 
Example #10
Source File: VertxMySqlContainer.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void await(CountDownLatch latch) {
  	try {
  		latch.await( getStartupTimeoutSeconds(), TimeUnit.SECONDS );
} catch (InterruptedException e) {
	throw new ContainerLaunchException("Container startup wait was interrupted", e);
}
  }
 
Example #11
Source File: SimpleMySQLTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test(expected = ContainerLaunchException.class)
public void testEmptyPasswordWithNonRootUser() {
    try (MySQLContainer<?> container = new MySQLContainer<>("mysql:5.5")
                .withDatabaseName("TEST")
                .withUsername("test")
                .withPassword("")
                .withEnv("MYSQL_ROOT_HOST", "%")){
        container.start();
        fail("ContainerLaunchException expected to be thrown");
    }
}
 
Example #12
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 #13
Source File: LogMessageWaitStrategy.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Override
@SneakyThrows(IOException.class)
protected void waitUntilReady() {
    WaitingConsumer waitingConsumer = new WaitingConsumer();

    LogContainerCmd cmd = DockerClientFactory.instance().client().logContainerCmd(waitStrategyTarget.getContainerId())
        .withFollowStream(true)
        .withSince(0)
        .withStdOut(true)
        .withStdErr(true);

    try (FrameConsumerResultCallback callback = new FrameConsumerResultCallback()) {
        callback.addConsumer(STDOUT, waitingConsumer);
        callback.addConsumer(STDERR, waitingConsumer);

        cmd.exec(callback);

        Predicate<OutputFrame> waitPredicate = outputFrame ->
            // (?s) enables line terminator matching (equivalent to Pattern.DOTALL)
            outputFrame.getUtf8String().matches("(?s)" + regEx);

        try {
            waitingConsumer.waitUntil(waitPredicate, startupTimeout.getSeconds(), TimeUnit.SECONDS, times);
        } catch (TimeoutException e) {
            throw new ContainerLaunchException("Timed out waiting for log output matching '" + regEx + "'");
        }
    }
}
 
Example #14
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 #15
Source File: AbstractWaitStrategyTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Expects that the WaitStrategy throws a {@link RetryCountExceededException} after unsuccessful connection
 * to a container with a listening port.
 *
 * @param container the container to start
 */
protected void waitUntilReadyAndTimeout(GenericContainer container) {
    // start() blocks until successful or timeout
    VisibleAssertions.assertThrows("an exception is thrown when timeout occurs (" + WAIT_TIMEOUT_MILLIS + "ms)",
            ContainerLaunchException.class,
            container::start);

}
 
Example #16
Source File: VertxMySqlContainer.java    From hibernate-reactive with GNU Lesser General Public License v2.1 5 votes vote down vote up
public SqlConnection createVertxConnection() {
	String url = getVertxUrl();
	CountDownLatch countDown = new CountDownLatch( 1 );
	AtomicReference<AsyncResult<SqlConnection>> result = new AtomicReference<>();
	MySQLPool.pool( url ).getConnection( ar -> {
		result.set( ar );
		countDown.countDown();
	});
	await(countDown);
	SqlConnection con = result.get().result();
	if (con != null)
		return con;
	else
		throw new ContainerLaunchException( "Failed to obtain a connection", result.get().cause() );
}
 
Example #17
Source File: MongoDBContainer.java    From hazelcast-jet-contrib with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the replicaSet by calling `rs.initialize()` in mongo shell.
 */
public int initializeReplicaSet() {
    ExecResult execResult;
    try {
        execResult = execInContainer("mongo", "--eval", "rs.initiate()");
        return execResult.getExitCode();
    } catch (Exception e) {
        throw new ContainerLaunchException("Error during initialization of replicaSet for container: " + self(), e);
    }
}
 
Example #18
Source File: DockerHealthcheckWaitStrategyTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Test
public void containerStartFailsIfContainerIsUnhealthy() {
    container.withCommand("tail", "-f", "/dev/null");
    assertThrows("Container launch fails when unhealthy", ContainerLaunchException.class, container::start);
}