Java Code Examples for org.testcontainers.containers.GenericContainer#stop()

The following examples show how to use org.testcontainers.containers.GenericContainer#stop() . 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: ContainersProvider.java    From replicator with Apache License 2.0 6 votes vote down vote up
@Override
public ServicesControl startZookeeper() {
    GenericContainer<?> zookeeper = this.getZookeeper(
            null, VersionedPipelines.defaultTags.zookeeperTag);

    zookeeper.start();


    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return zookeeper; }

        @Override
        public void close() {
            zookeeper.stop();
        }

        @Override
        public int getPort() {
            return zookeeper.getMappedPort(ContainersProvider.ZOOKEEPER_PORT);
        }

    };
}
 
Example 2
Source File: ContainersProvider.java    From replicator with Apache License 2.0 6 votes vote down vote up
@Override
public ServicesControl startZookeeper(Network network, String networkAlias) {
    GenericContainer<?> zookeeper = this.getZookeeper(network, VersionedPipelines.defaultTags.zookeeperTag);
    zookeeper.withNetworkAliases(networkAlias);

    zookeeper.start();
    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return zookeeper; }

        @Override
        public void close() {
            zookeeper.stop();
        }

        @Override
        public int getPort() {
            return zookeeper.getMappedPort(ContainersProvider.ZOOKEEPER_PORT);
        }

    };
}
 
Example 3
Source File: StatefulFunctionsAppContainers.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
/**
 * Restarts a single worker of this Stateful Functions application.
 *
 * @param workerIndex the index of the worker to restart.
 */
public void restartWorker(int workerIndex) {
  if (workerIndex >= workers.size()) {
    throw new IndexOutOfBoundsException(
        "Invalid worker index; valid values are 0 to " + (workers.size() - 1));
  }

  final GenericContainer<?> worker = workers.get(workerIndex);
  worker.stop();
  worker.start();
}
 
Example 4
Source File: DcpIntegrationTestBase.java    From java-dcp-client with Apache License 2.0 5 votes vote down vote up
protected static void stop(GenericContainer first, GenericContainer... others) {
  if (first != null) {
    first.stop();
  }
  for (GenericContainer c : others) {
    if (c != null) {
      c.stop();
    }
  }
}
 
Example 5
Source File: ContainersProvider.java    From replicator with Apache License 2.0 5 votes vote down vote up
@Override
public ServicesControl startSchemaRegistry(Network network) {

    GenericContainer<?> schemaRegistry = this.getContainer(System.getProperty(
            ContainersProvider.SCHEMA_REGISTRY_IMAGE_KEY,
            VersionedPipelines.defaultTags.schemaRegistryTag
            ),
            ContainersProvider.SCHEMA_REGISTRY_PORT,
            network,
            ContainersProvider.SCHEMA_REGISTRY_WAIT_REGEX,
            1,
            true
    ).withEnv(
            ContainersProvider.SCHEMA_REGISTRY_KAFKASTORE_CONNECTION_URL_KEY,
            String.format("%s:%d", "kafkaZk", ContainersProvider.ZOOKEEPER_PORT)
    ).withEnv(
            ContainersProvider.SCHEMA_REGISTRY_HOST_NAME_KEY,
            "localhost"
    );

    schemaRegistry.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return schemaRegistry; }

        @Override
        public void close() {
            schemaRegistry.stop();
        }

        @Override
        public int getPort() {
            return schemaRegistry.getMappedPort(ContainersProvider.SCHEMA_REGISTRY_PORT);
        }
    };
}
 
Example 6
Source File: ContainersProvider.java    From replicator with Apache License 2.0 5 votes vote down vote up
@Override
public ServicesControl startHbase() {

    Network network = Network.newNetwork();

    GenericContainer<?> hbase = this.getContainerHBase(
            VersionedPipelines.defaultTags.hbase,
            network,
            "",
            0,
            true
    );

    hbase.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return hbase; }

        @Override
        public void close() {
            hbase.stop();
        }

        @Override
        public int getPort() {
            return hbase.getMappedPort(ContainersProvider.HBASE_ZK_PORT);
        }
    };
}
 
Example 7
Source File: DaemonTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    Thread mainThread = Thread.currentThread();

    GenericContainer genericContainer = null;

    try {
        genericContainer = new GenericContainer().withCommand("top");
        genericContainer.start();

        Set<Thread> threads = new HashSet<>(Thread.getAllStackTraces().keySet());
        threads.remove(mainThread);

        Set<Thread> nonDaemonThreads = threads.stream().filter(it -> !it.isDaemon()).collect(Collectors.toSet());

        if (nonDaemonThreads.isEmpty()) {
            VisibleAssertions.pass("All threads marked as daemon");
        } else {
            String nonDaemonThreadNames = nonDaemonThreads.stream()
                .map(Thread::getName)
                .collect(Collectors.joining("\n", "\n", ""));

            VisibleAssertions.fail("Expected all threads to be daemons but the following are not:\n" + nonDaemonThreadNames);
        }
    } finally {
        if (genericContainer != null) {
            genericContainer.stop();
        }
    }
}
 
Example 8
Source File: DockerfileTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
protected void verifyImage(ImageFromDockerfile image) {
    GenericContainer container = new GenericContainer(image);

    try {
        container.start();

        pass("Should start from Dockerfile");
    } finally {
        container.stop();
    }
}
 
Example 9
Source File: GenericContainerRuleTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test @Ignore //TODO investigate intermittent failures
public void failFastWhenContainerHaltsImmediately() throws Exception {

    long startingTimeMs = System.currentTimeMillis();
    final GenericContainer failsImmediately = new GenericContainer("alpine:3.2")
          .withCommand("/bin/sh", "-c", "return false")
          .withMinimumRunningDuration(Duration.ofMillis(100));

    try {
        assertThrows(
              "When we start a container that halts immediately, an exception is thrown",
              RetryCountExceededException.class,
              () -> {
                  failsImmediately.start();
                  return null;
              });

        // Check how long it took, to verify that we ARE bailing out early.
        // Want to strike a balance here; too short and this test will fail intermittently
        // on slow systems and/or due to GC variation, too long and we won't properly test
        // what we're intending to test.
        int allowedSecondsToFailure =
            GenericContainer.CONTAINER_RUNNING_TIMEOUT_SEC / 2;
        long completedTimeMs = System.currentTimeMillis();
        assertTrue("container should not take long to start up",
              completedTimeMs - startingTimeMs < 1000L * allowedSecondsToFailure);
    } finally {
        failsImmediately.stop();
    }
}
 
Example 10
Source File: ContainersProvider.java    From replicator with Apache License 2.0 4 votes vote down vote up
public ServicesControl startCustomTagMySQL(
        String mysqlImageTag,
        String schema,
        String username,
        String password,
        String... initScripts) {
    GenericContainer<?> mysql = this.getContainer(
            System.getProperty(
                    ContainersProvider.MYSQL_DOCKER_IMAGE_KEY,
                    mysqlImageTag
            ),
            ContainersProvider.MYSQL_PORT,
            null,
            ContainersProvider.MYSQL_STARTUP_WAIT_REGEX,
            ContainersProvider.MYSQL_STARTUP_WAIT_TIMES,
            false
    ).withEnv(ContainersProvider.MYSQL_ROOT_PASSWORD_KEY, password
    ).withEnv(ContainersProvider.MYSQL_DATABASE_KEY, schema
    ).withEnv(ContainersProvider.MYSQL_USER_KEY, username
    ).withEnv(ContainersProvider.MYSQL_PASSWORD_KEY, password
    ).withClasspathResourceMapping(ContainersProvider.MYSQL_CONFIGURATION_FILE, ContainersProvider.MYSQL_CONFIGURATION_PATH, BindMode.READ_ONLY
    );

    for (String initScript : initScripts) {
        mysql.withClasspathResourceMapping(initScript, String.format(ContainersProvider.MYSQL_INIT_SCRIPT_PATH, initScript), BindMode.READ_ONLY);
    }

    mysql.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return mysql; }

        @Override
        public void close() {
            mysql.stop();
        }

        @Override
        public int getPort() {
            return mysql.getMappedPort(ContainersProvider.MYSQL_PORT);
        }
    };
}
 
Example 11
Source File: ContainersProvider.java    From replicator with Apache License 2.0 4 votes vote down vote up
@Override
public ServicesControl startMySQL(MySQLConfiguration mySQLConfiguration) {

    Map<String, String> envConfigs = new HashMap<>();
    // Root password is mandatory for starting mysql docker instance
    envConfigs.put(ContainersProvider.MYSQL_ROOT_PASSWORD_KEY, mySQLConfiguration.getPassword());
    envConfigs.computeIfAbsent(ContainersProvider.MYSQL_DATABASE_KEY, val -> mySQLConfiguration.getSchema());
    envConfigs.computeIfAbsent(ContainersProvider.MYSQL_USER_KEY, val -> mySQLConfiguration.getUsername());
    envConfigs.computeIfAbsent(ContainersProvider.MYSQL_PASSWORD_KEY, val -> mySQLConfiguration.getPassword());

    GenericContainer<?> mysql = this.getContainer(
            System.getProperty(
                    ContainersProvider.MYSQL_DOCKER_IMAGE_KEY,
                    VersionedPipelines.defaultTags.mysqlReplicantTag
            ),
            ContainersProvider.MYSQL_PORT,
            mySQLConfiguration.getNetwork(),
            ContainersProvider.MYSQL_STARTUP_WAIT_REGEX,
            ContainersProvider.MYSQL_STARTUP_WAIT_TIMES,
            // Cannot match exposed port in mysql as it can have conflicts
            false)
            .withEnv(envConfigs)
            .withClasspathResourceMapping(mySQLConfiguration.getConfPath(), ContainersProvider.MYSQL_CONFIGURATION_PATH, BindMode.READ_ONLY
    );

    for (String initScript : mySQLConfiguration.getInitScripts()) {
        mysql.withClasspathResourceMapping(initScript, String.format(ContainersProvider.MYSQL_INIT_SCRIPT_PATH, initScript), BindMode.READ_ONLY);
    }

    mysql.withNetworkAliases(mySQLConfiguration.getNetworkAlias());

    mysql.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return mysql; }

        @Override
        public void close() {
            mysql.stop();
        }

        @Override
        public int getPort() {
            return mysql.getMappedPort(ContainersProvider.MYSQL_PORT);
        }
    };
}
 
Example 12
Source File: ContainersProvider.java    From replicator with Apache License 2.0 4 votes vote down vote up
@Override
public ServicesControl startKafka(String topic, int partitions, int replicas) {
    Network network = Network.newNetwork();

    GenericContainer<?> zookeeper = this.getZookeeper(network, VersionedPipelines.defaultTags.zookeeperTag);

    zookeeper.start();

    GenericContainer<?> kafka = this.getContainer(
            System.getProperty(
                    ContainersProvider.KAFKA_DOCKER_IMAGE_KEY,
                    VersionedPipelines.defaultTags.kafkaTag
            ),
            ContainersProvider.KAFKA_PORT,
            network,
            ContainersProvider.KAFKA_STARTUP_WAIT_REGEX,
            partitions,
            true
    ).withEnv(
            ContainersProvider.KAFKA_ZOOKEEPER_CONNECT_KEY,
            String.format("%s:%d", zookeeper.getContainerInfo().getConfig().getHostName(), ContainersProvider.ZOOKEEPER_PORT)
    ).withEnv(
            ContainersProvider.KAFKA_CREATE_TOPICS_KEY,
            String.format("%s:%d:%d", topic, partitions, replicas)
    ).withEnv(
            ContainersProvider.KAFKA_ADVERTISED_HOST_NAME_KEY,
            "localhost"
    );

    kafka.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return kafka; }

        @Override
        public void close() {
            kafka.stop();
            zookeeper.stop();
        }

        @Override
        public int getPort() {
            return kafka.getMappedPort(ContainersProvider.KAFKA_PORT);
        }
    };
}
 
Example 13
Source File: ContainersProvider.java    From replicator with Apache License 2.0 4 votes vote down vote up
@Override
public ServicesControl startKafka(Network network, String topic, int partitions, int replicas, String networkAlias) {

    GenericContainer<?> kafka = this.getContainer(
            System.getProperty(
                    ContainersProvider.KAFKA_DOCKER_IMAGE_KEY,
                    VersionedPipelines.defaultTags.kafkaTag
            ),
            ContainersProvider.KAFKA_PORT,
            network,
            ContainersProvider.KAFKA_STARTUP_WAIT_REGEX,
            partitions,
            true
    ).withEnv(
            ContainersProvider.KAFKA_ZOOKEEPER_CONNECT_KEY,
            String.format("%s:%d", "kafkaZk", ContainersProvider.ZOOKEEPER_PORT)
    ).withEnv(
            ContainersProvider.KAFKA_CREATE_TOPICS_KEY,
            String.format("%s:%d:%d", topic, partitions, replicas)
    ).withEnv(KAFKA_LISTENERS_KEY, String.format("PLAINTEXT://%s:29092,OUTSIDE://0.0.0.0:%d", networkAlias, KAFKA_PORT)
    ).withEnv(KAFKA_LISTENER_SECURITY_PROTOCOL_MAP_KEY, "PLAINTEXT:PLAINTEXT,OUTSIDE:PLAINTEXT"
    ).withEnv(KAFKA_ADVERTISED_LISTENERS_KEY, String.format("PLAINTEXT://%s:29092,OUTSIDE://localhost:%d", networkAlias, KAFKA_PORT)
    ).withEnv(KAFKA_INTER_BROKER_LISTENER_NAME_KEY, "PLAINTEXT");
    //   https://rmoff.net/2018/08/02/kafka-listeners-explained/

    kafka.withNetworkAliases(networkAlias);

    kafka.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return kafka; }

        @Override
        public void close() {
            kafka.stop();
        }

        @Override
        public int getPort() {
            return kafka.getMappedPort(ContainersProvider.KAFKA_PORT);
        }
    };
}
 
Example 14
Source File: ContainersProvider.java    From replicator with Apache License 2.0 4 votes vote down vote up
public ServicesControl startKafka(String kafkaImageTag, String topic, int partitions, int replicas) {
    Network network = Network.newNetwork();

    GenericContainer<?> zookeeper = this.getZookeeper(
            network,
            VersionedPipelines.defaultTags.zookeeperTag
    );

    zookeeper.start();

    GenericContainer<?> kafka = this.getContainer(
            System.getProperty(
                    ContainersProvider.KAFKA_DOCKER_IMAGE_KEY,
                    kafkaImageTag
            ),
            ContainersProvider.KAFKA_PORT,
            network,
            ContainersProvider.KAFKA_STARTUP_WAIT_REGEX,
            partitions,
            true
    ).withEnv(
            ContainersProvider.KAFKA_ZOOKEEPER_CONNECT_KEY,
            String.format("%s:%d", zookeeper.getContainerInfo().getConfig().getHostName(), ContainersProvider.ZOOKEEPER_PORT)
    ).withEnv(
            ContainersProvider.KAFKA_CREATE_TOPICS_KEY,
            String.format("%s:%d:%d", topic, partitions, replicas)
    ).withEnv(
            ContainersProvider.KAFKA_ADVERTISED_HOST_NAME_KEY,
            "localhost"
    );

    kafka.start();

    return new ServicesControl() {
        @Override
        public GenericContainer<?> getContainer() { return kafka; }

        @Override
        public void close() {
            kafka.stop();
            zookeeper.stop();
        }

        @Override
        public int getPort() {
            return kafka.getMappedPort(ContainersProvider.KAFKA_PORT);
        }
    };
}
 
Example 15
Source File: PulsarCluster.java    From pulsar with Apache License 2.0 4 votes vote down vote up
public void stopService(String networkAlias,
                        GenericContainer<?> serviceContainer) {
    log.info("Stopping external service {} ...", networkAlias);
    serviceContainer.stop();
    log.info("Successfully stop external service {}", networkAlias);
}
 
Example 16
Source File: DockerfileTest.java    From testcontainers-java with MIT License 4 votes vote down vote up
@Test
public void filePermissions() throws TimeoutException {

    WaitingConsumer consumer = new WaitingConsumer();

    ImageFromDockerfile image = new ImageFromDockerfile()
            .withFileFromTransferable("/someFile.txt", new Transferable() {
                @Override
                public long getSize() {
                    return 0;
                }

                @Override
                public byte[] getBytes() {
                    return new byte[0];
                }

                @Override
                public String getDescription() {
                    return "test file";
                }

                @Override
                public int getFileMode() {
                    return 0123;
                }


            })
            .withDockerfileFromBuilder(builder -> builder
                    .from("alpine:3.2")
                    .copy("someFile.txt", "/someFile.txt")
                    .cmd("stat -c \"%a\" /someFile.txt")
            );

    GenericContainer container = new GenericContainer(image)
            .withStartupCheckStrategy(new OneShotStartupCheckStrategy())
            .withLogConsumer(consumer);

    try {
        container.start();

        consumer.waitUntil(frame -> frame.getType() == STDOUT && frame.getUtf8String().contains("123"), 5, TimeUnit.SECONDS);
    } finally {
        container.stop();
    }
}