org.testcontainers.containers.FixedHostPortGenericContainer Java Examples

The following examples show how to use org.testcontainers.containers.FixedHostPortGenericContainer. 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: InfinispanServerTestResource.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> start() {
    if (INFINISPAN_IMAGE == null) {
        throw new RuntimeException("Please define a valid Infinispan image in system property container.image.infinispan");
    }
    LOGGER.info("Using Infinispan image: {}", INFINISPAN_IMAGE);
    infinispan = new FixedHostPortGenericContainer(INFINISPAN_IMAGE)
            .withFixedExposedPort(11232, 11222)
            //wait for the server to be  fully started
            .waitingFor(Wait.forLogMessage(".*\\bstarted\\b.*", 1))
            .withEnv("USER", "admin")
            .withEnv("PASS", "admin")
            .withLogConsumer(new Slf4jLogConsumer(LOGGER));
    infinispan.start();
    return Collections.emptyMap();
}
 
Example #2
Source File: InfinispanServerContainer.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    if (INFINISPAN_IMAGE == null) {
        throw new RuntimeException("Please define a valid Infinispan image in system property container.image.infinispan");
    }
    LOGGER.info("Using Infinispan image: {}", INFINISPAN_IMAGE);
    infinispan = new FixedHostPortGenericContainer(INFINISPAN_IMAGE)
            .withFixedExposedPort(11222, 11222)
            //wait for the server to be  fully started
            .waitingFor(Wait.forLogMessage(".*\\bstarted\\b.*", 1))
            .withEnv("USER", "admin")
            .withEnv("PASS", "admin")
            .withLogConsumer(new Slf4jLogConsumer(LOGGER));
    infinispan.start();
}
 
Example #3
Source File: BaseIntegrationTest.java    From eventeum with Apache License 2.0 5 votes vote down vote up
protected static void startParity() {
    parityContainer = new FixedHostPortGenericContainer("kauriorg/parity-docker:latest");
    parityContainer.waitingFor(Wait.forListeningPort());
    parityContainer.withFixedExposedPort(8545, 8545);
    parityContainer.withFixedExposedPort(8546, 8546);
    parityContainer.withFileSystemBind(PARITY_VOLUME_PATH,
            "/root/.local/share/io.parity.ethereum/", BindMode.READ_WRITE);
    parityContainer.addEnv("NO_BLOCKS", "true");
    parityContainer.start();

    waitForParityToStart(10000, Web3j.build(new HttpService("http://localhost:8545")));
}
 
Example #4
Source File: ServiceRestartRecoveryTests.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startMongo() {
    mongoContainer = new FixedHostPortGenericContainer("mongo:3.5.5");
    mongoContainer.waitingFor(Wait.forListeningPort());
    mongoContainer.withFixedExposedPort(MONGO_PORT, MONGO_PORT);
    mongoContainer.start();

    waitForMongoDBToStart(30000);
}
 
Example #5
Source File: RabbitBroadcasterDBEventStoreIT.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@PostConstruct
void initRabbit() {
    if (RabbitBroadcasterDBEventStoreIT.rabbitContainer == null) {
        RabbitBroadcasterDBEventStoreIT.rabbitContainer = new FixedHostPortGenericContainer("rabbitmq:3.6.14-management");
        RabbitBroadcasterDBEventStoreIT.rabbitContainer.waitingFor(Wait.forListeningPort());
        RabbitBroadcasterDBEventStoreIT.rabbitContainer.withFixedExposedPort(5672, 5672);
        RabbitBroadcasterDBEventStoreIT.rabbitContainer.start();
    }

}
 
Example #6
Source File: KeycloakServer.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext extensionContext) {
    keycloak = new FixedHostPortGenericContainer("quay.io/keycloak/keycloak:" + System.getProperty("keycloak.version"))
            .withFixedExposedPort(8180, 8080)
            .withEnv("KEYCLOAK_USER", "admin")
            .withEnv("KEYCLOAK_PASSWORD", "admin")
            .withEnv("KEYCLOAK_IMPORT", "/tmp/default-tenant-realm.json,/tmp/tenant-a-realm.json")
            .withClasspathResourceMapping("default-tenant-realm.json", "/tmp/default-tenant-realm.json", BindMode.READ_ONLY)
            .withClasspathResourceMapping("tenant-a-realm.json", "/tmp/tenant-a-realm.json", BindMode.READ_ONLY)
            .waitingFor(Wait.forHttp("/auth"));
    keycloak.start();
}
 
Example #7
Source File: KeycloakServer.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {

    keycloak = new FixedHostPortGenericContainer("quay.io/keycloak/keycloak:" + System.getProperty("keycloak.version"))
            .withFixedExposedPort(8180, 8080)
            .withEnv("KEYCLOAK_USER", "admin")
            .withEnv("KEYCLOAK_PASSWORD", "admin")
            .withEnv("KEYCLOAK_IMPORT", "/tmp/realm.json")
            .withClasspathResourceMapping("quarkus-realm.json", "/tmp/realm.json", BindMode.READ_ONLY)
            .waitingFor(Wait.forHttp("/auth"));
    keycloak.start();
    return Collections.emptyMap();
}
 
Example #8
Source File: KeycloakServer.java    From quarkus-quickstarts with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeAll(ExtensionContext extensionContext) {
    keycloak = new FixedHostPortGenericContainer("quay.io/keycloak/keycloak:7.0.1")
            .withFixedExposedPort(8180, 8080)
            .withEnv("KEYCLOAK_USER", "admin")
            .withEnv("KEYCLOAK_PASSWORD", "admin")
            .withEnv("KEYCLOAK_IMPORT", "/tmp/realm.json")
            .withClasspathResourceMapping("quarkus-realm.json", "/tmp/realm.json", BindMode.READ_ONLY)
            .waitingFor(Wait.forHttp("/auth"));
    keycloak.start();
}
 
Example #9
Source File: TransactionalWalletServiceTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
private static GenericContainer initMongoNode(int exposePort) {
   GenericContainer node = new FixedHostPortGenericContainer("mongo:4.0.1")
      .withFixedExposedPort(exposePort, 27017)
      .waitingFor(Wait.forListeningPort().withStartupTimeout(Duration.ofSeconds(10)))
      .withLogConsumer(new Consumer<OutputFrame>() {
         @Override
         public void accept(OutputFrame outputFrame) {
            log.debug("[Mongo-{}]: {}", exposePort, outputFrame.getUtf8String().trim());
         }
      })
      .withCommand("mongod --storageEngine wiredTiger --replSet reactive");
   node.start();

   return node;
}
 
Example #10
Source File: FixedHostPortContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void testFixedHostPortMapping() throws IOException {
    // first find a free port on the docker host that will work for testing
    final Integer unusedHostPort;
    try (
        final GenericContainer echoServer = new GenericContainer<>(TEST_IMAGE)
            .withExposedPorts(TEST_PORT)
            .withCommand("/bin/sh", "-c", HTTP_ECHO_CMD)
    ) {
        echoServer.start();
        unusedHostPort = echoServer.getMappedPort(TEST_PORT);
    }

    // now starting echo server container mapped to known-as-free host port
    try (
        final GenericContainer echoServer = new FixedHostPortGenericContainer(TEST_IMAGE)
        // using workaround for port bind+expose
        .withFixedExposedPort(unusedHostPort, TEST_PORT)
        .withExposedPorts(TEST_PORT)
        .withCommand("/bin/sh", "-c", HTTP_ECHO_CMD)
    ) {
        echoServer.start();

        assertThat("Port mapping does not seem to match given fixed port",
            echoServer.getMappedPort(TEST_PORT), equalTo(unusedHostPort));

        final String content = this.readResponse(echoServer, unusedHostPort);
        assertThat("Returned echo from fixed port does not match expected", content, equalTo(TEST_RESPONSE));
    }
}
 
Example #11
Source File: ContainersProvider.java    From replicator with Apache License 2.0 4 votes vote down vote up
private GenericContainer<?> getContainerHBase(String image, Network network, String logWaitRegex, int logWaitTimes, boolean matchExposedPort) {

        FixedHostPortGenericContainer<?> container = new FixedHostPortGenericContainer<>(image);

        container.withNetwork(network);
        container.withNetworkAliases("hbase_alias");

        container.withFixedExposedPort(HBASE_ZK_PORT, HBASE_ZK_PORT);
        container.withFixedExposedPort(16201, HBASE_REGION_SERVER_PORT);
        container.withFixedExposedPort(16000, HBASE_MASTER_PORT);

        container.withCreateContainerCmdModifier(cmd -> cmd.withName(HBASE_CONTAINER_NAME));
        container.withCreateContainerCmdModifier(cmd -> cmd.withHostName(HBASE_HOST_NAME));

        return container;
    }
 
Example #12
Source File: EtcdContainer.java    From jetcd with Apache License 2.0 4 votes vote down vote up
public EtcdContainer(Network network, LifecycleListener listener, boolean ssl, String clusterName, String endpoint,
    List<String> endpoints, String image, List<String> additionalArgs) {

    this.endpoint = endpoint;
    this.ssl = ssl;
    this.listener = listener;
    this.dataDirectory = createDataDirectory(endpoint);

    this.container = new FixedHostPortGenericContainer<>(image);
    this.container.withExposedPorts(ETCD_PEER_PORT);
    this.container.withFixedExposedPort(getAvailablePort(), ETCD_CLIENT_PORT);
    this.container.withNetwork(network);
    this.container.withNetworkAliases(endpoint);
    this.container.waitingFor(Wait.forLogMessage(".*ready to serve client requests.*", 1));
    this.container.withLogConsumer(new Slf4jLogConsumer(LOGGER).withPrefix(endpoint));
    this.container.addFileSystemBind(dataDirectory.toString(), ETCD_DATA_DIR, BindMode.READ_WRITE, SelinuxContext.SHARED);

    List<String> cmd = new ArrayList<>();
    cmd.add("etcd");
    cmd.add("--name");
    cmd.add(endpoint);
    cmd.add("--advertise-client-urls");
    cmd.add((ssl ? "https" : "http") + "://0.0.0.0:" + ETCD_CLIENT_PORT);
    cmd.add("--listen-client-urls");
    cmd.add((ssl ? "https" : "http") + "://0.0.0.0:" + ETCD_CLIENT_PORT);
    cmd.add("--data-dir");
    cmd.add(ETCD_DATA_DIR);

    if (ssl) {
        this.container.withClasspathResourceMapping(
            "ssl/cert/" + endpoint + ".pem", "/etc/ssl/etcd/server.pem",
            BindMode.READ_ONLY,
            SelinuxContext.SHARED);

        this.container.withClasspathResourceMapping(
            "ssl/cert/" + endpoint + "-key.pem", "/etc/ssl/etcd/server-key.pem",
            BindMode.READ_ONLY,
            SelinuxContext.SHARED);

        cmd.add("--cert-file");
        cmd.add("/etc/ssl/etcd/server.pem");
        cmd.add("--key-file");
        cmd.add("/etc/ssl/etcd/server-key.pem");
    }

    if (endpoints.size() > 1) {
        cmd.add("--initial-advertise-peer-urls");
        cmd.add("http://" + endpoint + ":" + ETCD_PEER_PORT);
        cmd.add("--listen-peer-urls");
        cmd.add("http://0.0.0.0:" + ETCD_PEER_PORT);
        cmd.add("--initial-cluster-token");
        cmd.add(clusterName);
        cmd.add("--initial-cluster");
        cmd.add(endpoints.stream().map(e -> e + "=http://" + e + ":" + ETCD_PEER_PORT).collect(Collectors.joining(",")));
        cmd.add("--initial-cluster-state");
        cmd.add("new");
    }

    cmd.addAll(additionalArgs);

    if (!cmd.isEmpty()) {
        this.container.withCommand(cmd.toArray(new String[0]));
    }
}
 
Example #13
Source File: EtcdContainer.java    From etcd4j with Apache License 2.0 4 votes vote down vote up
public EtcdContainer(Network network, LifecycleListener listener, boolean ssl, String clusterName, String endpoint, List<String> endpoints) {
    this.endpoint = endpoint;
    this.ssl = ssl;
    this.listener = listener;

    final String name = endpoint;
    final List<String> command = new ArrayList<>();

    this.container = new FixedHostPortGenericContainer<>(ETCD_DOCKER_IMAGE_NAME);
    this.container.withExposedPorts(ETCD_CLIENT_PORT, ETCD_PEER_PORT);
    this.container.withNetwork(network);
    this.container.withNetworkAliases(name);
    this.container.waitingFor(waitStrategy());
    this.container.withLogConsumer(logConsumer());

    command.add("--name");
    command.add(name);
    command.add("--advertise-client-urls");
    command.add((ssl ? "https" : "http") + "://0.0.0.0:" + ETCD_CLIENT_PORT);
    command.add("--listen-client-urls");
    command.add((ssl ? "https" : "http") + "://0.0.0.0:" + ETCD_CLIENT_PORT);

    if (ssl) {
        this.container.withClasspathResourceMapping(
            "ssl/cert/" + name + ".pem",
            "/etc/ssl/etcd/server.pem",
            BindMode.READ_ONLY,
            SelinuxContext.SHARED);

        this.container.withClasspathResourceMapping(
            "ssl/cert/" + name + "-key.pem",
            "/etc/ssl/etcd/server-key.pem",
            BindMode.READ_ONLY,
            SelinuxContext.SHARED);

        command.add("--cert-file");
        command.add("/etc/ssl/etcd/server.pem");
        command.add("--key-file");
        command.add("/etc/ssl/etcd/server-key.pem");
    }

    if (endpoints.size() > 1) {
        command.add("--initial-advertise-peer-urls");
        command.add("http://" + name + ":" + ETCD_PEER_PORT);
        command.add("--listen-peer-urls");
        command.add("http://0.0.0.0:" + ETCD_PEER_PORT);
        command.add("--initial-cluster-token");
        command.add(clusterName);
        command.add("--initial-cluster");
        command.add(endpoints.stream().map(e -> e + "=" + "http://" + e + ":" + ETCD_PEER_PORT).collect(Collectors.joining(",")));
        command.add("--initial-cluster-state");
        command.add("new");
    }

    if (!command.isEmpty()) {
        this.container.withCommand(command.toArray(new String[command.size()]));
    }
}
 
Example #14
Source File: GitLabIntegrationTest.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@BeforeClass
void before() throws Exception {
  SvnTestHelper.skipTestIfDockerUnavailable();

  String gitlabVersion = System.getenv("GITLAB_VERSION");
  if (gitlabVersion == null) {
    SvnTestHelper.skipTestIfRunningOnCI();

    gitlabVersion = "9.3.3-ce.0";
  }

  final int hostPort = 9999;
  // containerPort is supposed to be 80, but GitLab binds to port from external_url
  // See https://stackoverflow.com/questions/39351563/gitlab-docker-not-working-if-external-url-is-set
  final int containerPort = 9999;
  final String hostname = DockerClientFactory.instance().dockerHostIpAddress();

  gitlabUrl = String.format("http://%s:%s", hostname, hostPort);

  gitlab = new FixedHostPortGenericContainer<>("gitlab/gitlab-ce:" + gitlabVersion)
      // We have a chicken-and-egg problem here. In order to set external_url, we need to know container address,
      // but we do not know container address until container is started.
      // So, for now use fixed port :(
      .withFixedExposedPort(hostPort, containerPort)
      // This is kinda stupid that we need to do withExposedPorts even when we have withFixedExposedPort
      .withExposedPorts(containerPort)
      .withEnv("GITLAB_OMNIBUS_CONFIG", String.format("external_url '%s'", gitlabUrl))
      .withEnv("GITLAB_ROOT_PASSWORD", rootPassword)
      .waitingFor(Wait.forHttp("/users/sign_in")
          .withStartupTimeout(Duration.of(10, ChronoUnit.MINUTES)));

  gitlab.start();

  rootToken = createToken(root, rootPassword, true);

  final GitlabAPI rootAPI = GitLabContext.connect(gitlabUrl, rootToken);

  final CreateUserRequest createUserRequest = new CreateUserRequest(user, user, "git-as-svn@localhost")
      .setPassword(userPassword)
      .setSkipConfirmation(true);

  final GitlabUser gitlabUser = rootAPI.createUser(createUserRequest);
  Assert.assertNotNull(gitlabUser);

  final GitlabGroup group = rootAPI.createGroup(new CreateGroupRequest("testGroup").setVisibility(GitlabVisibility.PUBLIC), null);
  Assert.assertNotNull(group);

  Assert.assertNotNull(rootAPI.addGroupMember(group.getId(), gitlabUser.getId(), GitlabAccessLevel.Developer));

  gitlabProject = createGitlabProject(rootAPI, group, "test", GitlabVisibility.INTERNAL, Collections.singleton("git-as-svn:master"));
  gitlabPublicProject = createGitlabProject(rootAPI, group, "publik", GitlabVisibility.PUBLIC, Collections.singleton("git-as-svn:master"));
}
 
Example #15
Source File: GiteaIntegrationTest.java    From git-as-svn with GNU General Public License v2.0 4 votes vote down vote up
@BeforeClass
void before() throws Exception {
  SvnTestHelper.skipTestIfDockerUnavailable();

  String giteaVersion = System.getenv("GITEA_VERSION");
  if (giteaVersion == null) {
    SvnTestHelper.skipTestIfRunningOnCI();

    giteaVersion = "latest";
  }

  final int hostPort = 9999;
  final int containerPort = 3000;
  final String hostname = DockerClientFactory.instance().dockerHostIpAddress();

  giteaUrl = String.format("http://%s:%s", hostname, hostPort);
  giteaApiUrl = giteaUrl + "/api/v1";

  gitea = new FixedHostPortGenericContainer<>("gitea/gitea:" + giteaVersion)
      .withFixedExposedPort(hostPort, containerPort)
      .withExposedPorts(containerPort)
      .withEnv("ROOT_URL", giteaUrl)
      .withEnv("INSTALL_LOCK", "true")
      .withEnv("SECRET_KEY", "CmjF5WBUNZytE2C80JuogljLs5enS0zSTlikbP2HyG8IUy15UjkLNvTNsyYW7wN")
      .withEnv("RUN_MODE", "prod")
      .withEnv("LFS_START_SERVER", "true")
      .waitingFor(Wait.forHttp("/user/login"))
      .withLogConsumer(new Slf4jLogConsumer(log));

  gitea.start();

  ExecResult createUserHelpResult = gitea.execInContainer("gitea", "admin", "create-user", "--help", "-c", "/data/gitea/conf/app.ini");
  boolean mustChangePassword = createUserHelpResult.getStdout().contains("--must-change-password");
  String mustChangePasswordString = mustChangePassword ? "--must-change-password=false" : "";
  {
    ExecResult result = gitea.execInContainer("gitea", "admin", "create-user", "--name", administrator,
        "--password", administratorPassword, "--email", "[email protected]", "--admin",
        mustChangePasswordString, "-c", "/data/gitea/conf/app.ini");
    System.out.println(result.getStdout());
    System.err.println(result.getStderr());
  }

  ApiClient apiClient = new ApiClient();
  apiClient.setBasePath(giteaApiUrl);
  apiClient.setUsername(administrator);
  apiClient.setPassword(administratorPassword);
  UserApi userApi = new UserApi(apiClient);
  AccessTokenName accessTokenName = new AccessTokenName();
  accessTokenName.setName("integration-test");
  AccessToken token = userApi.userCreateToken(administrator, accessTokenName);
  administratorToken = new GiteaToken(token.getSha1());

  // Switch to the GiteaContext approach
  // CreateTestUser
  final User testUser = createUser(user, userPassword);
  Assert.assertNotNull(testUser);

  final User collaboratorUser = createUser(collaborator, collaboratorPassword);
  Assert.assertNotNull(collaboratorUser);

  // Create a repository for the test user
  testPublicRepository = createRepository(user, "public-user-repo", "Public User Repository", false, true);
  Assert.assertNotNull(testPublicRepository);

  testPrivateRepository = createRepository(user, "private-user-repo", "Private User Repository", true, true);
  Assert.assertNotNull(testPrivateRepository);
}