Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PostgreSQLWaitStrategy #5368

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package org.testcontainers.containers;

import com.github.dockerjava.api.command.LogContainerCmd;
import lombok.SneakyThrows;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.output.FrameConsumerResultCallback;
import org.testcontainers.containers.output.OutputFrame;
import org.testcontainers.containers.output.WaitingConsumer;
import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;

import static org.testcontainers.containers.output.OutputFrame.OutputType.STDERR;
import static org.testcontainers.containers.output.OutputFrame.OutputType.STDOUT;

public class MultiLogMessageWaitStrategy extends AbstractWaitStrategy {

private List<List<String>> regExs = new ArrayList<>();

private final int times = 1;

private final long limit = 15;

@Override
@SneakyThrows(IOException.class)
protected void waitUntilReady() {
boolean success = true;
for (List<String> ex : this.regExs) {
WaitingConsumer waitingConsumer = new WaitingConsumer();
try (FrameConsumerResultCallback callback = new FrameConsumerResultCallback()) {
callback.addConsumer(STDOUT, waitingConsumer);
callback.addConsumer(STDERR, waitingConsumer);
success = true;

try {
for (String regEx : ex) {
LogContainerCmd cmd = DockerClientFactory.instance().client().logContainerCmd(waitStrategyTarget.getContainerId())
.withFollowStream(true)
.withSince(0)
.withStdOut(true)
.withStdErr(true);
cmd.exec(callback);

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

waitingConsumer.waitUntil(waitPredicate, limit, TimeUnit.SECONDS, times);
}
} catch (TimeoutException e) {
success = false;
}
if (success) {
break;
}
}
}
if (!success) {
throw new ContainerLaunchException("Timed out waiting for log output matching '" + "." + "'");
}
}

public MultiLogMessageWaitStrategy withRegEx(List<String> regExs) {
this.regExs.add(regExs);
return this;
}

}
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
package org.testcontainers.containers;

import org.jetbrains.annotations.NotNull;
import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy;
import org.testcontainers.utility.DockerImageName;

import java.time.Duration;
import java.util.Set;

import static java.time.temporal.ChronoUnit.SECONDS;
import static java.util.Collections.singleton;

/**
Expand Down Expand Up @@ -49,10 +46,7 @@ public PostgreSQLContainer(final DockerImageName dockerImageName) {

dockerImageName.assertCompatibleWith(DEFAULT_IMAGE_NAME);

this.waitStrategy = new LogMessageWaitStrategy()
.withRegEx(".*database system is ready to accept connections.*\\s")
.withTimes(2)
.withStartupTimeout(Duration.of(60, SECONDS));
this.waitStrategy = new PostgreSQLWaitStrategy();
this.setCommand("postgres", "-c", FSYNC_OFF_OPTION);

addExposedPort(POSTGRESQL_PORT);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package org.testcontainers.containers;

import org.testcontainers.containers.wait.strategy.AbstractWaitStrategy;
import org.testcontainers.utility.ComparableVersion;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PostgreSQLWaitStrategy extends AbstractWaitStrategy {

private final Pattern pattern = Pattern.compile("(?s)(?:\\d\\S*)");

@Override
protected void waitUntilReady() {
try {
String postgresVersion = this.waitStrategyTarget.execInContainer("postgres", "-V").getStdout();
Matcher matcher = this.pattern.matcher(postgresVersion);
if (matcher.find()) {
String version = matcher.group();
boolean isAtLeastMajorVersion94 = new ComparableVersion(version).isGreaterThanOrEqualTo("9.4");

List<String> firstAttempt = new ArrayList<>();
firstAttempt.add(".*PostgreSQL init process complete.*$");
firstAttempt.add(".*database system is ready to accept connections.*$");

List<String> secondAttempt = new ArrayList<>();
if (isAtLeastMajorVersion94) {
secondAttempt.add(".*PostgreSQL Database directory appears to contain a database.*$");
}
secondAttempt.add(".*database system is ready to accept connections.*$");

new MultiLogMessageWaitStrategy()
.withRegEx(firstAttempt)
.withRegEx(secondAttempt)
.waitUntilReady(this.waitStrategyTarget);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException(e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@
import org.junit.Test;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.db.AbstractContainerDatabaseTest;
import org.testcontainers.images.builder.ImageFromDockerfile;
import org.testcontainers.utility.DockerImageName;

import java.nio.file.Paths;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.LogManager;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.rnorth.visibleassertions.VisibleAssertions.assertEquals;
import static org.rnorth.visibleassertions.VisibleAssertions.assertNotEquals;
import static org.testcontainers.PostgreSQLTestImages.POSTGRES_TEST_IMAGE;
Expand Down Expand Up @@ -79,4 +82,37 @@ public void testWithAdditionalUrlParamInJdbcUrl() {
assertThat(jdbcUrl, containsString("charSet=UNICODE"));
}
}

@Test
public void test92WithDataAlreadyInTheContainer() throws SQLException {
ImageFromDockerfile image = new ImageFromDockerfile("postgres-with-data:9.2")
.withDockerfile(Paths.get("src/test/resources/Dockerfile-92"));

DockerImageName postgresImage = DockerImageName.parse(image.get()).asCompatibleSubstituteFor("postgres");
try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(postgresImage)) {
postgres.start();

ResultSet resultSet = performQuery(postgres, "SELECT foo FROM bar");

String firstColumnValue = resultSet.getString(1);
assertEquals("Value from init script should equal real value", "hello world", firstColumnValue);
}
}

@Test
public void test142WithDataAlreadyInTheContainer() throws SQLException {
ImageFromDockerfile image = new ImageFromDockerfile("postgres-with-data:14.2")
.withDockerfile(Paths.get("src/test/resources/Dockerfile-142"));

DockerImageName postgresImage = DockerImageName.parse(image.get()).asCompatibleSubstituteFor("postgres");
try (PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>(postgresImage)) {
postgres.start();

ResultSet resultSet = performQuery(postgres, "SELECT foo FROM bar");

String firstColumnValue = resultSet.getString(1);
assertEquals("Value from init script should equal real value", "hello world", firstColumnValue);
}
}

}
15 changes: 15 additions & 0 deletions modules/postgresql/src/test/resources/Dockerfile-142
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM postgres:14.2 AS dumper

COPY somepath/init_postgresql.sql /docker-entrypoint-initdb.d

RUN ["sed", "-i", "s/exec \"$@\"/echo \"skipping...\"/", "/usr/local/bin/docker-entrypoint.sh"]

ENV POSTGRES_USER=test
ENV POSTGRES_PASSWORD=test
ENV PGDATA=/data

RUN ["/usr/local/bin/docker-entrypoint.sh", "postgres"]

FROM postgres:14.2

COPY --from=dumper /data $PGDATA
15 changes: 15 additions & 0 deletions modules/postgresql/src/test/resources/Dockerfile-92
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM postgres:9.2 AS dumper

COPY somepath/init_postgresql.sql /docker-entrypoint-initdb.d

RUN ["sed", "-i", "s/exec \"$@\"/echo \"skipping...\"/", "/usr/local/bin/docker-entrypoint.sh"]

ENV POSTGRES_USER=test
ENV POSTGRES_PASSWORD=test
ENV PGDATA=/data

RUN ["/usr/local/bin/docker-entrypoint.sh", "postgres"]

FROM postgres:9.2

COPY --from=dumper /data $PGDATA