Skip to content

Instantly share code, notes, and snippets.

@osi
Created March 12, 2021 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osi/c73d97e680a74c58cb23cc71d125d98d to your computer and use it in GitHub Desktop.
Save osi/c73d97e680a74c58cb23cc71d125d98d to your computer and use it in GitHub Desktop.
a PostgreSQLContainer for use in TestContainer-integrated builds that allows simulating a restart of the database.
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.model.RestartPolicy;
import org.springframework.util.SocketUtils;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.containers.output.OutputFrame;
import org.testcontainers.utility.DockerImageName;
import java.io.IOException;
import java.util.Objects;
/**
* A variant of {@link PostgreSQLContainer} that exposes the ability to restart the instance.
*/
public class RestartablePostgreSQLContainer<SELF extends RestartablePostgreSQLContainer<SELF>> extends PostgreSQLContainer<SELF> {
public RestartablePostgreSQLContainer(DockerImageName dockerImageName) {
super(dockerImageName);
withCreateContainerCmdModifier(RestartablePostgreSQLContainer::alwaysRestartContainer);
addFixedExposedPort(SocketUtils.findAvailableTcpPort(), 5432);
withLogConsumer(of -> {
// When the container terminates, this is needed to re-follow it's output
if(of.getType() == OutputFrame.OutputType.END) {
getLogConsumers().forEach(this::followOutput);
}
});
}
private static void alwaysRestartContainer(CreateContainerCmd c) {
c.withHostConfig(Objects.requireNonNull(c.getHostConfig()).withRestartPolicy(RestartPolicy.alwaysRestart()));
}
public void restart() {
try {
var result = execInContainer("su", "postgres", "-c", "pg_ctl restart");
logger().debug("restarted database. {}", result);
if (result.getExitCode() != 137) {
throw new RuntimeException("Failed to restart database: " + result);
}
} catch (IOException | InterruptedException e) {
throw new RuntimeException("Failed to restart database", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment