Support for waiting on tcp port to open

This commit is contained in:
Nikola Petkanski
2024-07-16 02:34:24 +03:00
parent 3ddc75e717
commit 6c3c74c817
3 changed files with 98 additions and 0 deletions
+5
View File
@@ -56,6 +56,11 @@ class Container
return new Container($image);
}
public function getId(): string
{
return $this->id;
}
public function withEntryPoint(string $entryPoint): self
{
$this->entryPoint = $entryPoint;
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Testcontainer\Wait;
use JsonException;
use RuntimeException;
use Symfony\Component\Process\Process;
use Testcontainer\Exception\ContainerNotReadyException;
/**
* @phpstan-type ContainerInspect array<int, array{'NetworkSettings': array{'IPAddress': string}}>
*/
final class WaitForTcpPortOpen implements WaitInterface
{
public function __construct(private readonly int $port)
{
}
public static function make(int $port): self
{
return new self($port);
}
/**
* @throws JsonException
*/
public function wait(string $id): void
{
if (@fsockopen($this->findContainerAddress($id), $this->port) === false) {
throw new ContainerNotReadyException($id, new RuntimeException('Unable to connect to container TCP port'));
}
}
/**
* @throws JsonException
*/
private function findContainerAddress(string $id): string
{
$process = new Process(['docker', 'inspect', $id]);
$process->mustRun();
/** @var ContainerInspect $data */
$data = json_decode($process->getOutput(), true, 512, JSON_THROW_ON_ERROR);
$containerAddress = $data[0]['NetworkSettings']['IPAddress'] ?? null;
if (! is_string($containerAddress)) {
throw new ContainerNotReadyException($id, new RuntimeException('Unable to find container IP address'));
}
return $containerAddress;
}
}