- Move most of the stuff for backwards compatibility support into one class

- Added random port logic
- Updated wait wtrategies
- API alignments to make it similar to other official implementations
- ...
This commit is contained in:
Sergei Shitikov
2024-09-06 19:08:37 +02:00
parent a956794279
commit f05ea0020d
43 changed files with 1191 additions and 601 deletions
+147 -2
View File
@@ -6,9 +6,154 @@ namespace Testcontainers\Container;
/**
* Added for backward compatibility.
* Just a wrapper for GenericContainer.
* @deprecated Use GenericContainer instead.
* TODO: Remove in next major release.
*/
class Container extends GenericContainer
final class Container extends GenericContainer
{
protected ?StartedTestContainer $startedContainer = null;
protected ?StoppedTestContainer $stoppedContainer = null;
public static function make(string $image): self
{
return new self($image);
}
/**
* @deprecated Use `withPrivilegedMode` instead
*/
public function withPrivileged(bool $privileged = true): self
{
return $this->withPrivilegedMode($privileged);
}
/**
* @deprecated Use `withExposedPorts` instead
*/
public function withPort(string $localPort, string $containerPort): self
{
return $this->withExposedPorts($containerPort);
}
/**
* @deprecated there will be no replacement
*/
public function withImage(string $image): self
{
$this->image = $image;
return $this;
}
/**
* @deprecated Use `start` instead
*/
public function run(): self
{
$this->startedContainer = $this->start();
return $this;
}
/**
* @param array<string> $commandAsArray
* @deprecated Use 'exec' from StartedTestContainer instead
*/
public function execute(array $commandAsArray): string
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
return $this->startedContainer->exec($commandAsArray);
}
/**
* @deprecated Use 'logs' from StartedTestContainer instead
*/
public function logs(): string
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
return $this->startedContainer->logs();
}
/**
* @deprecated Use 'getHost' from StartedTestContainer instead
*/
public function getAddress(): string
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
return $this->startedContainer->getHost();
}
/**
* @deprecated Use 'getFirstMappedPort' from StartedTestContainer instead
*/
public function getPort(): int
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
return $this->startedContainer->getFirstMappedPort();
}
/**
* @deprecated Use 'stop' from StartedTestContainer instead
*/
public function kill(): self
{
$this->dockerClient->containerKill($this->id);
return $this;
}
/**
* @deprecated Use `stop` from StartedTestContainer instead
*/
public function stop(): self
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
$this->stoppedContainer = $this->startedContainer->stop();
return $this;
}
/**
* @deprecated Use 'restart' method from StartedTestContainer instead
*/
public function restart(): self
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
$restartedTestContainer = $this->startedContainer->restart();
$this->startedContainer = $restartedTestContainer;
return $this;
}
/**
* @deprecated Use 'stop' method from StartedTestContainer instead
*/
public function remove(): self
{
if($this->startedContainer === null) {
throw new \RuntimeException('Container is not started');
}
$this->startedContainer->stop();
return $this;
}
}
+63 -174
View File
@@ -4,39 +4,28 @@ declare(strict_types=1);
namespace Testcontainers\Container;
use Docker\API\Client;
use Docker\API\Exception\ContainerCreateNotFoundException;
use Docker\API\Model\ContainersCreatePostBody;
use Docker\API\Model\ContainersIdExecPostBody;
use Docker\API\Model\HealthConfig;
use Docker\API\Model\HostConfig;
use Docker\API\Model\Mount;
use Docker\API\Model\PortBinding;
use Docker\Docker;
use Psr\Http\Message\ResponseInterface;
use Testcontainers\ContainerRuntime\ContainerRuntimeClient;
use Testcontainers\Wait\WaitForContainerRunning;
use Testcontainers\Wait\WaitInterface;
use InvalidArgumentException;
use Testcontainers\ContainerClient\DockerContainerClient;
use Testcontainers\Utils\PortGenerator\RandomUniquePortGenerator;
use Testcontainers\Wait\WaitForContainer;
use Testcontainers\Wait\WaitStrategy;
/**
* @phpstan-type ContainerInspectSingleNetwork array<int, array{'NetworkSettings': array{'IPAddress': string}}>
* @phpstan-type ContainerInspectMultipleNetworks array<int, array{'NetworkSettings': array{'Networks': array<string, array{'IPAddress': string}>}}>
* @phpstan-type ContainerInspect ContainerInspectSingleNetwork|ContainerInspectMultipleNetworks
* @phpstan-type DockerNetwork array{CreatedAt: string, Driver: string, ID: string, IPv6: string, Internal: string, Labels: string, Name: string, Scope: string}
*/
class GenericContainer
class GenericContainer implements TestContainer
{
protected Docker $dockerClient;
protected ContainersCreatePostBody $containerConfig;
protected string $image;
protected string $containerName;
protected string $id;
/** @var array<string> */
/** @var list<string> */
protected array $command = [];
protected ?string $entryPoint = null;
@@ -48,7 +37,7 @@ class GenericContainer
*/
protected array $env = [];
protected WaitInterface $wait;
protected WaitStrategy $waitStrategy;
protected bool $isPrivileged = false;
protected ?string $networkName = null;
@@ -64,16 +53,7 @@ class GenericContainer
public function __construct(string $image)
{
$this->image = $image;
$this->dockerClient = ContainerRuntimeClient::getDockerClient();
}
/**
* @deprecated Use constructor instead
* Left for backward compatibility
*/
public static function make(string $image): self
{
return new GenericContainer($image);
$this->dockerClient = DockerContainerClient::getDockerClient();
}
public function getId(): string
@@ -81,58 +61,56 @@ class GenericContainer
return $this->id;
}
public function withCommand(array $command): self
/**
* @param list<string> $command
*/
public function withCommand(array $command): static
{
$this->command = $command;
return $this;
}
public function exec(array $command): string
{
$execConfig = (new ContainersIdExecPostBody())
->setCmd($command)
->setAttachStdout(true)
->setAttachStderr(true);
// Create and start the exec command
$exec = $this->dockerClient->containerExec($this->id, $execConfig);
$contents = $this->dockerClient
->execStart($exec->getId(), null, Client::FETCH_RESPONSE)
?->getBody()
->getContents() ?? '';
return preg_replace('/[\x00-\x1F\x7F]/u', '', $contents);
}
public function withEntryPoint(string $entryPoint): self
public function withEntryPoint(string $entryPoint): static
{
$this->entryPoint = $entryPoint;
return $this;
}
public function withEnvironment(string $name, string $value): self
/**
* To support temporarily backwards compatibility, the method supports two formats:
* 1. A single key-value pair (deprecated): $object->withEnvironment('key', 'value');
* 2. An array of key-value pairs: $object->withEnvironment(['key1' => 'value1', 'key2' => 'value2']);
*
* @param string | array<string, string> $env An array of environment variables or the name of a single variable.
* @param string|null $value The value of the environment variable if a single variable is passed.
* @return static Returns itself for chaining purposes.
*/
public function withEnvironment(string | array $env, ?string $value = null): static
{
$this->env[$name] = $value;
if (is_array($env)) {
foreach ($env as $key => $val) {
$this->env[$key] = $val;
}
} else {
if ($value === null) {
throw new InvalidArgumentException("Value cannot be null when setting a single environment variable.");
}
$this->env[$env] = $value;
}
return $this;
}
public function withImage(string $image): self
public function withWait(WaitStrategy $waitStrategy): static
{
$this->image = $image;
$this->waitStrategy = $waitStrategy;
return $this;
}
public function withWait(WaitInterface $wait): self
{
$this->wait = $wait;
return $this;
}
public function withHealthCheckCommand(string $command, int $healthCheckIntervalInMS = 1000): self
public function withHealthCheckCommand(string $command, int $healthCheckIntervalInMS = 1000): static
{
$this->healthConfig = new HealthConfig([
'Test' => ['CMD', $command],
@@ -142,33 +120,22 @@ class GenericContainer
return $this;
}
public function withMount(string $localPath, string $containerPath): self
public function withMount(string $localPath, string $containerPath): static
{
$this->mounts[] = new Mount(['type' => 'bind', 'source' => $localPath, 'target' => $containerPath]);
return $this;
}
/**
* @deprecated Use `withExposedPorts` instead
*/
public function withPort(string $localPort, string $containerPort): self
{
return $this->withExposedPorts($containerPort);
}
/**
* @psalm-param string|int|array<string|int> $port
*/
/**
* Add ports to be exposed by the Docker container.
* This method accepts multiple inputs: single port, multiple ports, or ports with specific protocols
* to attempt to align with other language implementations.
*
* @psalm-param int|string|array<int|string> $ports One or more ports to expose.
* @return self Fluent interface for chaining.
* @return static Fluent interface for chaining.
*/
public function withExposedPorts(...$ports): self
public function withExposedPorts(...$ports): static
{
foreach ($ports as $port) {
if (is_array($port)) {
@@ -207,46 +174,51 @@ class GenericContainer
return $port;
}
public function withPrivileged(bool $privileged = true): self
public function withPrivilegedMode(bool $privileged = true): static
{
$this->isPrivileged = $privileged;
return $this;
}
public function withNetwork(string $networkName): self
//TODO: not yet implemented
public function withNetwork(string $networkName): static
{
$this->networkName = $networkName;
return $this;
}
public function stop(): self
{
$this->dockerClient->containerStop($this->id);
return $this;
}
public function start(): self
//TODO: needs refactoring
public function start(): StartedGenericContainer
{
try {
$containerCreatePostBody = new ContainersCreatePostBody();
//setup only if we need to expose ports
//handle withExposedPorts
if(!empty($this->exposedPorts)) {
$portGenerator = new RandomUniquePortGenerator();
$portMap = new \ArrayObject();
foreach ($this->exposedPorts as $port) {
$portBinding = new PortBinding();
$portBinding->setHostPort(explode('/', $port)[0]);
$portBinding->setHostPort((string) $portGenerator->generatePort());
$portBinding->setHostIp('0.0.0.0');
$portMap[$port] = [$portBinding];
}
$hostConfig = new HostConfig();
$hostConfig->setPortBindings($portMap);
//handle withPrivilegedMode
if($this->isPrivileged) {
$hostConfig->setPrivileged($this->isPrivileged);
}
$containerCreatePostBody->setHostConfig($hostConfig);
}
//handle withPrivilegedMode
if($this->isPrivileged) {
$hostConfig = new HostConfig();
$hostConfig->setPrivileged($this->isPrivileged);
}
$containerCreatePostBody->setImage($this->image);
$containerCreatePostBody->setCmd($this->command);
$envs = [];
@@ -267,96 +239,13 @@ class GenericContainer
$this->dockerClient->containerStart($this->id);
if(!isset($this->wait)) {
$this->withWait(new WaitForContainerRunning());
if(!isset($this->waitStrategy)) {
$this->withWait(new WaitForContainer());
}
$this->wait->wait($this->id);
$startedContainer = new StartedGenericContainer($this->id);
$this->waitStrategy->wait($startedContainer);
return $this;
}
public function restart(): self
{
$this->dockerClient->containerRestart($this->id);
return $this;
}
public function remove(): self
{
$this->dockerClient->containerStop($this->id);
$this->dockerClient->containerDelete($this->id);
return $this;
}
public function kill(): self
{
$this->dockerClient->containerKill($this->id);
return $this;
}
/**
* @deprecated Use `start` instead
* Left for backward compatibility
*/
public function run(): self
{
return $this->start();
}
/**
* @param array<string> $commandAsArray
*/
public function execute(array $commandAsArray): ResponseInterface
{
$command = new ContainersIdExecPostBody();
$command->setCmd($commandAsArray);
return $this->dockerClient->containerExec($this->id, $command);
}
public function logs(): string
{
return $this->dockerClient->containerLogs($this->id)?->getBody()?->getContents() ?? '';
}
public function getAddress(): string
{
$inspection = $this->inspect();
return $inspection['gateway'];
// foreach ($containerNetworks as $network) {
// var_dump($network->getNetworkID(), $this->id, $network->getIPAddress());
// if($network->getNetworkID() === $this->id) {
// $containerAddress = $network->getIpAddress();
// break;
// }
// }
// return $containerAddress;
}
/**
* @return array{gateway: string, ports: array<string, int>}
*/
public function inspect(): array
{
$response = $this->dockerClient->containerInspect($this->id);
$settings = $response->getNetworkSettings();
//var_dump($settings);
$ports = [];
foreach ($settings->getPorts() as $port => $value) {
if ($value === null) {
continue;
}
$ports[$port] = (int) $value[0]->getHostPort();
}
return [
'gateway' => $settings->getGateway(),
'ports' => $ports,
];
return $startedContainer;
}
}
+7 -34
View File
@@ -4,39 +4,12 @@ declare(strict_types=1);
namespace Testcontainers\Container;
use Testcontainers\Wait\WaitForLog;
class MariaDBContainer extends GenericContainer
/**
* Left for namespace backward compatibility
* @deprecated Use \Testcontainers\Modules\MariaDBContainer instead.
* TODO: Remove in next major release.
*/
class MariaDBContainer extends \Testcontainers\Modules\MariaDBContainer
{
public function __construct(string $version = 'latest', string $mysqlRootPassword = 'root')
{
parent::__construct('mariadb:' . $version);
$this->withExposedPorts(3306);
$this->withWait(new WaitForLog('ready for connections'));
$this->withEnvironment('MARIADB_ROOT_PASSWORD', $mysqlRootPassword);
}
/**
* @deprecated Use constructor instead
* Left for backward compatibility
*/
public static function make(string $version = 'latest', string $mysqlRootPassword = 'root'): self
{
return new self($version, $mysqlRootPassword);
}
public function withMariaDBUser(string $username, string $password): self
{
$this->withEnvironment('MARIADB_USER', $username);
$this->withEnvironment('MARIADB_PASSWORD', $password);
return $this;
}
public function withMariaDBDatabase(string $database): self
{
$this->withEnvironment('MARIADB_DATABASE', $database);
return $this;
}
}
}
+7 -34
View File
@@ -4,39 +4,12 @@ declare(strict_types=1);
namespace Testcontainers\Container;
use Testcontainers\Wait\WaitForLog;
class MySQLContainer extends GenericContainer
/**
* Left for namespace backward compatibility
* @deprecated Use \Testcontainers\Modules\MySQLContainer instead.
* TODO: Remove in next major release.
*/
class MySQLContainer extends \Testcontainers\Modules\MySQLContainer
{
public function __construct(string $version = 'latest', string $mysqlRootPassword = 'root')
{
parent::__construct('mysql:' . $version);
$this->withExposedPorts(3306);
$this->withEnvironment('MYSQL_ROOT_PASSWORD', $mysqlRootPassword);
$this->withWait(new WaitForLog('ready for connections'));
}
/**
* @deprecated Use constructor instead
* Left for backward compatibility
*/
public static function make(string $version = 'latest', string $mysqlRootPassword = 'root'): self
{
return new self($version, $mysqlRootPassword);
}
public function withMySQLUser(string $username, string $password): self
{
$this->withEnvironment('MYSQL_USER', $username);
$this->withEnvironment('MYSQL_PASSWORD', $password);
return $this;
}
public function withMySQLDatabase(string $database): self
{
$this->withEnvironment('MYSQL_DATABASE', $database);
return $this;
}
}
}
+7 -40
View File
@@ -4,45 +4,12 @@ declare(strict_types=1);
namespace Testcontainers\Container;
use Testcontainers\Wait\WaitForHttp;
use Testcontainers\Wait\WaitForLog;
class OpenSearchContainer extends GenericContainer
/**
* Left for namespace backward compatibility
* @deprecated Use \Testcontainers\Modules\OpenSearchContainer instead.
* TODO: Remove in next major release.
*/
class OpenSearchContainer extends \Testcontainers\Modules\OpenSearchContainer
{
public function __construct(string $version = 'latest')
{
parent::__construct('opensearchproject/opensearch:' . $version);
$this->withExposedPorts(9200);
$this->withEnvironment('discovery.type', 'single-node');
$this->withEnvironment('OPENSEARCH_INITIAL_ADMIN_PASSWORD', 'c3o_ZPHo!');
$this->withWait(new WaitForLog(
'/\]\s+started\?\[/',
true,
30000
));
}
/**
* @deprecated Use constructor instead
* Left for backward compatibility
*/
public static function make(string $version = 'latest'): self
{
return new self($version);
}
public function withDisabledSecurityPlugin(): self
{
$this->withEnvironment('plugins.security.disabled', 'true');
return $this;
}
/**
* @deprecated Use withDisabledSecurityPlugin instead
*/
public function disableSecurityPlugin(): self
{
return $this->withDisabledSecurityPlugin();
}
}
}
+7 -42
View File
@@ -4,47 +4,12 @@ declare(strict_types=1);
namespace Testcontainers\Container;
use Testcontainers\Wait\WaitForExec;
class PostgresContainer extends GenericContainer
/**
* Left for namespace backward compatibility
* @deprecated Use \Testcontainers\Modules\PostgresContainer instead.
* TODO: Remove in next major release.
*/
class PostgresContainer extends \Testcontainers\Modules\PostgresContainer
{
public function __construct(
string $version = 'latest',
public readonly string $username = 'test',
public readonly string $password = 'test',
public readonly string $database = 'test'
) {
parent::__construct('postgres:' . $version);
$this->withExposedPorts(5432);
$this->withEnvironment('POSTGRES_USER', $this->username);
$this->withEnvironment('POSTGRES_PASSWORD', $this->password);
$this->withEnvironment('POSTGRES_DB', $this->database);
$this->withWait(new WaitForExec(["pg_isready", "-h", "127.0.0.1", "-U", $this->username]));
}
/**
* @deprecated Use constructor instead
* Left for backward compatibility
*/
public static function make(string $version = 'latest', string $dbPassword = 'root'): self
{
return new self(
version: $version,
password: $dbPassword
);
}
public function withPostgresUser(string $username): self
{
$this->withEnvironment('POSTGRES_USER', $username);
return $this;
}
public function withPostgresDatabase(string $database): self
{
$this->withEnvironment('POSTGRES_DB', $database);
return $this;
}
}
}
+7 -18
View File
@@ -4,23 +4,12 @@ declare(strict_types=1);
namespace Testcontainers\Container;
use Testcontainers\Wait\WaitForLog;
class RedisContainer extends GenericContainer
/**
* Left for namespace backward compatibility
* @deprecated Use \Testcontainers\Modules\RedisContainer instead.
* TODO: Remove in next major release.
*/
class RedisContainer extends \Testcontainers\Modules\RedisContainer
{
public function __construct(string $version = 'latest')
{
parent::__construct('redis:' . $version);
$this->withExposedPorts(6379);
$this->withWait(new WaitForLog('Ready to accept connections'));
}
/**
* @deprecated Use constructor instead
* Left for backward compatibility
*/
public static function make(string $version = 'latest'): self
{
return new self($version);
}
}
}
+152
View File
@@ -0,0 +1,152 @@
<?php
declare(strict_types=1);
namespace Testcontainers\Container;
use Docker\API\Client;
use Docker\API\Model\ContainersIdExecPostBody;
use Docker\API\Model\IdResponse;
use Docker\API\Runtime\Client\Client as DockerRuntimeClient;
use Docker\Docker;
use Testcontainers\ContainerClient\DockerContainerClient;
class StartedGenericContainer implements StartedTestContainer
{
protected Docker $dockerClient;
protected ?string $lastExecId = null;
public function __construct(protected readonly string $id)
{
$this->dockerClient = DockerContainerClient::getDockerClient();
}
public function getId(): string
{
return $this->id;
}
public function getLastExecId(): ?string
{
return $this->lastExecId;
}
public function getClient(): Docker
{
return $this->dockerClient;
}
/**
* @param list<string> $command
*/
public function exec(array $command): string
{
$execConfig = (new ContainersIdExecPostBody())
->setCmd($command)
->setAttachStdout(true)
->setAttachStderr(true);
// Create and start the exec command
/** @var IdResponse | null $exec */
$exec = $this->dockerClient->containerExec($this->id, $execConfig);
if($exec === null || $exec->getId() === null) {
throw new \RuntimeException('Failed to create exec command');
}
$this->lastExecId = $exec->getId();
$contents = $this->dockerClient
->execStart($this->lastExecId, null, Client::FETCH_RESPONSE)
?->getBody()
->getContents() ?? '';
return preg_replace('/[\x00-\x1F\x7F]/u', '', $contents) ?? '';
}
public function stop(): StoppedTestContainer
{
$this->dockerClient->containerStop($this->id);
$this->dockerClient->containerDelete($this->id);
return new StoppedGenericContainer($this->id);
}
public function restart(): self
{
$this->dockerClient->containerRestart($this->id);
return $this;
}
public function logs(): string
{
$output = $this->dockerClient
->containerLogs(
$this->id,
['stdout' => true, 'stderr' => true],
DockerRuntimeClient::FETCH_RESPONSE
)
?->getBody()
->getContents() ?? '';
return preg_replace('/[\x00-\x1F\x7F]/u', '', mb_convert_encoding($output, 'UTF-8', 'UTF-8')) ?? '';
}
//TODO: replace with the proper implementation
public function getHost(): string
{
return '127.0.0.1';
}
//TODO: not ready yet
public function getMappedPort(int $port): int
{
return $this->inspect()->ports[$port];
}
//TODO: not ready yet
public function getFirstMappedPort(): int
{
$containerInspectResponse = $this->dockerClient->containerInspect($this->id);
$settings = $containerInspectResponse->getNetworkSettings();
$ports = (array)$settings->getPorts();
$port = array_key_first($ports);
return (int) $ports[$port][0]->getHostPort();
}
public function getName(): string
{
// TODO: Implement getName() method.
return '';
}
public function getLabels(): array
{
// TODO: Implement getLabels() method.
return [];
}
public function getNetworkNames(): array
{
// TODO: Implement getNetworkNames() method.
return [];
}
public function getNetworkId(string $networkName): string
{
// TODO: Implement getNetworkId() method.
return '';
}
public function getIpAddress(string $networkName): string
{
// TODO: Implement getIpAddress() method.
return '';
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Testcontainers\Container;
use Docker\Docker;
interface StartedTestContainer
{
public function stop(): StoppedTestContainer;
public function restart(): self;
public function getClient(): Docker;
public function getHost(): string;
public function getFirstMappedPort(): int;
public function getMappedPort(int $port): int;
public function getName(): string;
public function getLabels(): array;
public function getId(): string;
public function getLastExecId(): string | null;
public function getNetworkNames(): array;
public function getNetworkId(string $networkName): string;
public function getIpAddress(string $networkName): string;
/**
* @param list<string> $command
*/
public function exec(array $command): string;
public function logs(): string;
}
+17
View File
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Testcontainers\Container;
class StoppedGenericContainer implements StoppedTestContainer
{
public function __construct(protected readonly string $id)
{
}
public function getId(): string
{
return $this->id;
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
namespace Testcontainers\Container;
interface StoppedTestContainer
{
public function getId(): string;
}
+34
View File
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Testcontainers\Container;
use Testcontainers\Wait\WaitStrategy;
interface TestContainer
{
public function start(): StartedGenericContainer;
/**
* TODO: replace with array after deprecated implementation is removed
* @param array<string, string>|string $env
*/
public function withEnvironment(array | string $env, ?string $value): static;
/**
* @param array<string> $command
*/
public function withCommand(array $command): static;
public function withEntrypoint(string $entryPoint): static;
/** @param int|string|array<int|string> $ports One or more ports to expose. */
public function withExposedPorts(...$ports): static;
public function withWait(WaitStrategy $waitStrategy): static;
public function withNetwork(string $networkName): static;
public function withPrivilegedMode(): static;
}