From 58ec8abbcad2d3a2b39ee4504c6e89c75ff44904 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 08:56:22 +0100 Subject: [PATCH 1/8] Exercises pick their port up front, docker picks where it is published A port free on this machine is free in a sandbox container too, so exercises pick it once with System::freePort() and docker publishes it on a free host port. Checks ask the execution where to connect, from the executing event. SandboxHost goes, so nothing asks this machine about ports on the docker host. --- app/config.php | 1 - src/Event/CliExecuteEvent.php | 12 ++++++ src/ExerciseDispatcher.php | 8 +--- src/ExerciseRunner/CliRunner.php | 4 +- .../Context/ExecutionContext.php | 10 +---- src/Process/DockerExecution.php | 11 +++++ src/Process/DockerSandbox.php | 38 +++++++++++++---- src/Process/HostExecution.php | 5 +++ src/Process/HostSandbox.php | 6 --- src/Process/Sandbox.php | 2 - src/Process/SandboxExecution.php | 7 ++++ src/Process/SandboxHost.php | 41 ------------------- src/Utils/System.php | 18 ++++++++ test/ExerciseRunner/CliRunnerTest.php | 28 ++++++++++--- .../Context/ExecutionContextTest.php | 5 +-- test/Process/DockerSandboxTest.php | 39 ++++++++++++++---- test/Process/HostSandboxTest.php | 7 ++++ test/Process/SandboxHostTest.php | 26 ------------ test/Utils/SystemTest.php | 7 ++++ 19 files changed, 157 insertions(+), 118 deletions(-) delete mode 100644 src/Process/SandboxHost.php delete mode 100644 test/Process/SandboxHostTest.php diff --git a/app/config.php b/app/config.php index bc02fbcf..cb047456 100644 --- a/app/config.php +++ b/app/config.php @@ -138,7 +138,6 @@ $c->get(ResultAggregator::class), $c->get(EventDispatcher::class), $c->get(CheckRepository::class), - $c->get(Sandbox::class), ); }, ResultAggregator::class => create(ResultAggregator::class), diff --git a/src/Event/CliExecuteEvent.php b/src/Event/CliExecuteEvent.php index b9ea0277..2ce351c9 100644 --- a/src/Event/CliExecuteEvent.php +++ b/src/Event/CliExecuteEvent.php @@ -6,6 +6,7 @@ use PhpSchool\PhpWorkshop\Exercise\Scenario\CliScenario; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; +use PhpSchool\PhpWorkshop\Process\SandboxExecution; use PhpSchool\PhpWorkshop\Utils\Collection; /** @@ -56,6 +57,17 @@ public function appendArg(string $arg): void $this->args = $this->args->append($arg); } + /** + * The running program, eg. to connect to a port it listens on with getAddress(). Only on the executing events. + */ + public function getExecution(): SandboxExecution + { + /** @var SandboxExecution $execution */ + $execution = $this->getParameter('execution'); + + return $execution; + } + /** * Get the arguments to be passed to the program. * diff --git a/src/ExerciseDispatcher.php b/src/ExerciseDispatcher.php index 8570fc2d..7afa33d0 100644 --- a/src/ExerciseDispatcher.php +++ b/src/ExerciseDispatcher.php @@ -15,8 +15,6 @@ use PhpSchool\PhpWorkshop\Exception\InvalidArgumentException; use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; -use PhpSchool\PhpWorkshop\Process\HostSandbox; -use PhpSchool\PhpWorkshop\Process\Sandbox; use PhpSchool\PhpWorkshop\ExerciseRunner\RunnerManager; use PhpSchool\PhpWorkshop\Input\Input; use PhpSchool\PhpWorkshop\Output\OutputInterface; @@ -45,14 +43,12 @@ class ExerciseDispatcher * @param ResultAggregator $results * @param EventDispatcher $eventDispatcher * @param CheckRepository $checkRepository - * @param Sandbox $sandbox Where the code runs, exercises get its host from the context. */ public function __construct( private RunnerManager $runnerManager, private ResultAggregator $results, private EventDispatcher $eventDispatcher, private CheckRepository $checkRepository, - private Sandbox $sandbox = new HostSandbox(), ) {} /** @@ -110,7 +106,7 @@ public function requireCheck(string $requiredCheck): void */ public function verify(ExerciseInterface $exercise, Input $input): ResultAggregator { - $context = ExecutionContext::fromInputAndExercise($input, $exercise, $this->sandbox->getHost()); + $context = ExecutionContext::fromInputAndExercise($input, $exercise); $runner = $this->runnerManager->getRunner($exercise); @@ -165,7 +161,7 @@ public function verify(ExerciseInterface $exercise, Input $input): ResultAggrega */ public function run(ExerciseInterface $exercise, Input $input, OutputInterface $output): bool { - $context = ExecutionContext::fromInputAndExercise($input, $exercise, $this->sandbox->getHost()); + $context = ExecutionContext::fromInputAndExercise($input, $exercise); $runner = $this->runnerManager->getRunner($exercise); diff --git a/src/ExerciseRunner/CliRunner.php b/src/ExerciseRunner/CliRunner.php index 0dab8b1b..76a3a7b6 100644 --- a/src/ExerciseRunner/CliRunner.php +++ b/src/ExerciseRunner/CliRunner.php @@ -229,7 +229,7 @@ public function run(ExecutionContext $context, OutputInterface $output): bool $execution->start(); $this->eventDispatcher->dispatch( - new CliExecuteEvent('cli.run.student.executing', $context, $scenario, $args, ['output' => $output]), + new CliExecuteEvent('cli.run.student.executing', $context, $scenario, $args, ['output' => $output, 'execution' => $execution]), ); $execution->wait(function ($outputType, $outputBuffer) use ($output) { $output->write($outputBuffer); @@ -262,7 +262,7 @@ private function executePhpFile(ExecutionContext $context, CliScenario $scenario $execution->start(); $this->eventDispatcher->dispatch( - new CliExecuteEvent(sprintf('cli.verify.%s.executing', $type), $context, $scenario, $args), + new CliExecuteEvent(sprintf('cli.verify.%s.executing', $type), $context, $scenario, $args, ['execution' => $execution]), ); $execution->wait(); diff --git a/src/ExerciseRunner/Context/ExecutionContext.php b/src/ExerciseRunner/Context/ExecutionContext.php index c1852ccc..ba1c300c 100644 --- a/src/ExerciseRunner/Context/ExecutionContext.php +++ b/src/ExerciseRunner/Context/ExecutionContext.php @@ -4,7 +4,6 @@ use PhpSchool\PhpWorkshop\Exercise\ExerciseInterface; use PhpSchool\PhpWorkshop\Input\Input; -use PhpSchool\PhpWorkshop\Process\SandboxHost; use PhpSchool\PhpWorkshop\Utils\Path; use PhpSchool\PhpWorkshop\Utils\System; @@ -15,10 +14,9 @@ public function __construct( private string $referenceExecutionDirectory, private ExerciseInterface $exercise, private Input $input, - private SandboxHost $sandboxHost = new SandboxHost(), ) {} - public static function fromInputAndExercise(Input $input, ExerciseInterface $exercise, SandboxHost $sandboxHost): ExecutionContext + public static function fromInputAndExercise(Input $input, ExerciseInterface $exercise): ExecutionContext { $program = $input->hasArgument('program') ? dirname($input->getRequiredArgument('program')) : (string) getcwd(); @@ -27,7 +25,6 @@ public static function fromInputAndExercise(Input $input, ExerciseInterface $exe System::randomTempDir(), $exercise, $input, - $sandboxHost, ); } @@ -63,11 +60,6 @@ public function getStudentExecutionDirectory(): string return $this->studentExecutionDirectory; } - public function getSandboxHost(): SandboxHost - { - return $this->sandboxHost; - } - public function getReferenceExecutionDirectory(): string { return $this->referenceExecutionDirectory; diff --git a/src/Process/DockerExecution.php b/src/Process/DockerExecution.php index d7ea71a8..c4cafee5 100644 --- a/src/Process/DockerExecution.php +++ b/src/Process/DockerExecution.php @@ -15,11 +15,13 @@ final class DockerExecution implements SandboxExecution /** * @param list $before * @param list $after + * @param \Closure(int): string $address finds where docker published a port, see getAddress() */ public function __construct( public readonly Process $process, public readonly array $before = [], public readonly array $after = [], + private ?\Closure $address = null, ) {} public function start(): void @@ -65,6 +67,15 @@ public function getErrorOutput(): string return $this->process->getErrorOutput(); } + public function getAddress(int $port): string + { + if ($this->address === null) { + throw new \RuntimeException(sprintf('Port %d is not published', $port)); + } + + return ($this->address)($port); + } + private function runAfter(): void { foreach ($this->after as $step) { diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 8c0bff1d..f85dbbe4 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -58,19 +58,17 @@ public function createBuildProcess(): Process ); } - public function getHost(): SandboxHost - { - return new SandboxHost($this->portsHost); - } - public function create(ProcessInput $processInput): DockerExecution { + $container = 'php-school-' . bin2hex(random_bytes(8)); + $network = ['--network', 'none']; if (count($processInput->getExposedPorts()) > 0) { $network = ['--network', $this->portsNetwork]; foreach ($processInput->getExposedPorts() as $port) { + //no host port, docker picks a free one, see getAddress() $network[] = '-p'; - $network[] = $this->portsHost . ':' . $port . ':' . $port; + $network[] = $this->portsHost . '::' . $port; } } @@ -86,6 +84,8 @@ public function create(ProcessInput $processInput): DockerExecution $this->findDocker(), 'run', '--rm', + '--name', + $container, '-i', '--init', '--user', @@ -124,7 +124,31 @@ public function create(ProcessInput $processInput): DockerExecution null, $processInput->getInput(), self::TIMEOUT + 5, - )); + ), [], [], fn(int $port) => $this->getAddress($container, $port)); + } + + /** + * Asks docker which host port it published a container's port on. Waits a little, as the container may still be + * starting. + */ + private function getAddress(string $container, int $port): string + { + for ($try = 0; $try < 20; $try++) { + //eg. 127.0.0.1:54321 + $process = new Process([$this->findDocker(), 'port', $container, (string) $port], $this->basePath); + $process->run(); + + if ($process->isSuccessful() && trim($process->getOutput()) !== '') { + $published = strtok(trim($process->getOutput()), "\n"); + $host = str_contains($this->portsHost, ':') ? '[' . $this->portsHost . ']' : $this->portsHost; + + return $host . ':' . substr((string) $published, (int) strrpos((string) $published, ':') + 1); + } + + usleep(100000); + } + + throw new \RuntimeException(sprintf('Port %d of the sandbox was not published', $port)); } private function findDocker(): string diff --git a/src/Process/HostExecution.php b/src/Process/HostExecution.php index 9694349c..9e4b3799 100644 --- a/src/Process/HostExecution.php +++ b/src/Process/HostExecution.php @@ -39,4 +39,9 @@ public function getErrorOutput(): string { return $this->process->getErrorOutput(); } + + public function getAddress(int $port): string + { + return '127.0.0.1:' . $port; + } } diff --git a/src/Process/HostSandbox.php b/src/Process/HostSandbox.php index fce86247..8351e2fa 100644 --- a/src/Process/HostSandbox.php +++ b/src/Process/HostSandbox.php @@ -21,12 +21,6 @@ public function __construct(?ExecutableFinder $executableFinder = null) $this->executableFinder = $executableFinder ?? new ExecutableFinder(); } - - public function getHost(): SandboxHost - { - return new SandboxHost(); - } - public function create(ProcessInput $processInput): HostExecution { $executablePath = $this->executableFinder->find($processInput->getExecutable()); diff --git a/src/Process/Sandbox.php b/src/Process/Sandbox.php index b2c054bc..784281f4 100644 --- a/src/Process/Sandbox.php +++ b/src/Process/Sandbox.php @@ -7,6 +7,4 @@ interface Sandbox { public function create(ProcessInput $processInput): SandboxExecution; - - public function getHost(): SandboxHost; } diff --git a/src/Process/SandboxExecution.php b/src/Process/SandboxExecution.php index f0638945..cc45c046 100644 --- a/src/Process/SandboxExecution.php +++ b/src/Process/SandboxExecution.php @@ -26,4 +26,11 @@ public function isSuccessful(): bool; public function getOutput(): string; public function getErrorOutput(): string; + + /** + * Where to connect to a port the code listens on, once it has started. + * + * @return string eg. '127.0.0.1:54321' + */ + public function getAddress(int $port): string; } diff --git a/src/Process/SandboxHost.php b/src/Process/SandboxHost.php deleted file mode 100644 index 8a086157..00000000 --- a/src/Process/SandboxHost.php +++ /dev/null @@ -1,41 +0,0 @@ -address; - } - - /** - * A port that is free to publish. Asks this machine, so it needs another way when the host is remote. - */ - public function getFreePort(): int - { - $server = @stream_socket_server('tcp://127.0.0.1:0'); - - if ($server === false) { - throw new RuntimeException('Cannot create socket'); - } - - //eg. 127.0.0.1:54321 - $name = (string) stream_socket_get_name($server, false); - fclose($server); - - return (int) substr($name, (int) strrpos($name, ':') + 1); - } -} diff --git a/src/Utils/System.php b/src/Utils/System.php index 8664dead..bd0676ec 100644 --- a/src/Utils/System.php +++ b/src/Utils/System.php @@ -29,6 +29,24 @@ public static function tempDir(string $path = ''): string return Path::join(self::realpath(sys_get_temp_dir()), 'php-school', $path); } + /** + * A port nothing listens on, on this machine. Inside a sandbox container every port is free, so it works there too. + */ + public static function freePort(): int + { + $server = @stream_socket_server('tcp://127.0.0.1:0'); + + if ($server === false) { + throw new RuntimeException('Cannot create socket'); + } + + //eg. 127.0.0.1:54321 + $name = (string) stream_socket_get_name($server, false); + fclose($server); + + return (int) substr($name, (int) strrpos($name, ':') + 1); + } + public static function randomTempDir(): string { return Path::join(self::realpath(sys_get_temp_dir()), 'php-school', bin2hex(random_bytes(4))); diff --git a/test/ExerciseRunner/CliRunnerTest.php b/test/ExerciseRunner/CliRunnerTest.php index 46ff49d5..f3418d81 100644 --- a/test/ExerciseRunner/CliRunnerTest.php +++ b/test/ExerciseRunner/CliRunnerTest.php @@ -10,7 +10,6 @@ use PhpSchool\PhpWorkshop\Listener\OutputRunInfoListener; use PhpSchool\PhpWorkshop\Process\HostSandbox; use PhpSchool\PhpWorkshop\Process\SandboxExecution; -use PhpSchool\PhpWorkshop\Process\SandboxHost; use PhpSchool\PhpWorkshop\Output\NullOutput; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\Sandbox; @@ -87,6 +86,28 @@ public function testVerifyReturnsSuccessIfSolutionOutputMatchesUserOutput(): voi $this->assertTrue($result->isSuccessful()); } + public function testExecutingEventsHaveTheExecution(): void + { + $solution = SingleFileSolution::fromFile(realpath(__DIR__ . '/../res/cli/solution.php')); + $this->exercise->setSolution($solution); + $this->exercise->setScenario((new CliScenario())->withExecution([1, 2, 3])); + + $executions = []; + $this->eventDispatcher->listen( + ['cli.verify.reference.executing', 'cli.verify.student.executing', 'cli.run.student.executing'], + function (CliExecuteEvent $event) use (&$executions) { + $executions[] = $event->getExecution(); + }, + ); + + $context = TestContext::fromExerciseAndStudentSolution($this->exercise, __DIR__ . '/../res/cli/user.php'); + $this->runner->verify($context); + $this->runner->run($context, new NullOutput()); + + $this->assertCount(3, $executions); + $this->assertContainsOnlyInstancesOf(SandboxExecution::class, $executions); + } + public function testSuccessWithSingleSetOfArgsForBC(): void { $solution = SingleFileSolution::fromFile(realpath(__DIR__ . '/../res/cli/solution.php')); @@ -184,11 +205,6 @@ public function create(ProcessInput $processInput): SandboxExecution return (new HostSandbox())->create($processInput); } - - public function getHost(): SandboxHost - { - return new SandboxHost(); - } }; $runner = new CliRunner($this->exercise, $this->eventDispatcher, $sandbox, new EnvironmentManager(new Filesystem(), $this->eventDispatcher)); diff --git a/test/ExerciseRunner/Context/ExecutionContextTest.php b/test/ExerciseRunner/Context/ExecutionContextTest.php index ad0ea33b..09a0e291 100644 --- a/test/ExerciseRunner/Context/ExecutionContextTest.php +++ b/test/ExerciseRunner/Context/ExecutionContextTest.php @@ -6,7 +6,6 @@ use PhpSchool\PhpWorkshop\ExerciseRunner\Context\ExecutionContext; use PhpSchool\PhpWorkshop\ExerciseRunner\Context\NoEntryPoint; use PhpSchool\PhpWorkshop\Input\Input; -use PhpSchool\PhpWorkshop\Process\SandboxHost; use PhpSchool\PhpWorkshop\Utils\System; use PHPUnit\Framework\TestCase; @@ -91,7 +90,7 @@ public function testFactory(): void $input = new Input('test', ['program' => $temporaryDirectory . '/solution.php']); $exercise = new MockExercise(); - $context = ExecutionContext::fromInputAndExercise($input, $exercise, new SandboxHost('10.0.0.1')); + $context = ExecutionContext::fromInputAndExercise($input, $exercise); //check that student execution directory uses the parent directory of the program from the input static::assertSame($temporaryDirectory, $context->getStudentExecutionDirectory()); @@ -99,7 +98,5 @@ public function testFactory(): void //check that reference execution directory is a random temporary directory static::assertTrue(str_starts_with($context->getReferenceExecutionDirectory(), System::tempDir())); - - static::assertSame('10.0.0.1', $context->getSandboxHost()->getAddress()); } } diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index 3a523190..dd7875d1 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -22,14 +22,18 @@ private function factory(string $portsNetwork = 'bridge', string $portsHost = '1 } /** + * @param string $commandLine the actual one, for the container name * @param list $network * @param list $extra env and mount args * @param list $command */ - private function expectedCommand(array $network, array $extra, array $command): string + private function expectedCommand(string $commandLine, array $network, array $extra, array $command): string { + //each container gets its own name + preg_match('/php-school-[0-9a-f]{16}/', $commandLine, $container); + $parts = [ - '/usr/local/bin/docker', 'run', '--rm', '-i', '--init', '--user', getmyuid() . ':' . getmygid(), + '/usr/local/bin/docker', 'run', '--rm', '--name', $container[0] ?? '', '-i', '--init', '--user', getmyuid() . ':' . getmygid(), ...$network, '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '64', '--memory', '256m', '--memory-swap', '256m', @@ -63,6 +67,7 @@ public function testCreateIsIsolatedWithNoNetwork(): void $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], []))->process; $expected = $this->expectedCommand( + $process->getCommandLine(), ['--network', 'none'], ['-v', __DIR__ . ':/solution'], ['php', 'one', 'two'], @@ -77,7 +82,8 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '127.0.0.1:8000:8000'], + $process->getCommandLine(), + ['--network', 'bridge', '-p', '127.0.0.1::8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -89,7 +95,8 @@ public function testExposedPortsUseTheGivenNetwork(): void $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - ['--network', 'php-school-sandbox', '-p', '127.0.0.1:8000:8000'], + $process->getCommandLine(), + ['--network', 'php-school-sandbox', '-p', '127.0.0.1::8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -101,18 +108,33 @@ public function testExposedPortsArePublishedOnTheGivenHost(): void $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - ['--network', 'bridge', '-p', '172.19.0.2:8000:8000'], + $process->getCommandLine(), + ['--network', 'bridge', '-p', '172.19.0.2::8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); } - public function testHostIsWherePortsArePublished(): void + public function testAddressIsThePortDockerPublishedOnTheGivenHost(): void { - $sandbox = new DockerSandbox('/docker-dir', 'php8appreciate', null, 'bridge', '172.19.0.2'); + //stands in for `docker port 8000` + $docker = tempnam(sys_get_temp_dir(), 'docker'); + file_put_contents($docker, "#!/bin/sh\necho 172.19.0.2:54321\n"); + chmod($docker, 0755); - static::assertSame('172.19.0.2', $sandbox->getHost()->getAddress()); + $finder = $this->createMock(ExecutableFinder::class); + $finder->method('find')->with('docker')->willReturn($docker); + + $execution = (new DockerSandbox(__DIR__, 'php8appreciate', $finder, 'bridge', '172.19.0.2')) + ->create(new ProcessInput('php', [], __DIR__, [], [8000])); + static::assertSame('172.19.0.2:54321', $execution->getAddress(8000)); + + $execution = (new DockerSandbox(__DIR__, 'php8appreciate', $finder, 'bridge', 'fdaa::2')) + ->create(new ProcessInput('php', [], __DIR__, [], [8000])); + static::assertSame('[fdaa::2]:54321', $execution->getAddress(8000)); + + unlink($docker); } public function testCreateWithEnv(): void @@ -120,6 +142,7 @@ public function testCreateWithEnv(): void $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], []))->process; $expected = $this->expectedCommand( + $process->getCommandLine(), ['--network', 'none'], ['-e', 'SOME_VAR=value', '-v', __DIR__ . ':/solution'], ['php'], diff --git a/test/Process/HostSandboxTest.php b/test/Process/HostSandboxTest.php index 191ec899..bc0ecbc0 100644 --- a/test/Process/HostSandboxTest.php +++ b/test/Process/HostSandboxTest.php @@ -41,6 +41,13 @@ public function testCreate(): void static::assertSame("'/usr/local/bin/composer'", $process->getCommandLine()); } + public function testAddressIsThePortOnThisMachine(): void + { + $execution = (new HostSandbox())->create(new ProcessInput('php', [], __DIR__, [], [54321])); + + static::assertSame('127.0.0.1:54321', $execution->getAddress(54321)); + } + public function testCreateWithArgs(): void { $finder = $this->createMock(ExecutableFinder::class); diff --git a/test/Process/SandboxHostTest.php b/test/Process/SandboxHostTest.php deleted file mode 100644 index d9e72138..00000000 --- a/test/Process/SandboxHostTest.php +++ /dev/null @@ -1,26 +0,0 @@ -getAddress()); - static::assertSame('10.0.0.1', (new SandboxHost('10.0.0.1'))->getAddress()); - } - - public function testGetFreePortCanBeListenedOn(): void - { - $port = (new SandboxHost())->getFreePort(); - - $server = stream_socket_server('tcp://127.0.0.1:' . $port); - static::assertNotFalse($server); - fclose($server); - } -} diff --git a/test/Utils/SystemTest.php b/test/Utils/SystemTest.php index 69fd2a0a..4acbaaec 100644 --- a/test/Utils/SystemTest.php +++ b/test/Utils/SystemTest.php @@ -34,6 +34,13 @@ public function testTempDirWithPath(): void self::assertSame($expect, System::tempDir('test')); } + public function testFreePortCanBeListenedOn(): void + { + $server = stream_socket_server('tcp://127.0.0.1:' . System::freePort()); + self::assertNotFalse($server); + fclose($server); + } + public function testRandomTempDir(): void { self::assertTrue(str_starts_with(System::randomTempDir(), realpath(sys_get_temp_dir()) . '/php-school')); From 18789d5ef4136831d1386d29372c01438a83c2ae Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 09:46:02 +0100 Subject: [PATCH 2/8] Pick the docker host port with a PortPicker instead of asking docker DockerSandbox picks the published port itself, random by default, so it knows the address without a docker port lookup. A shared docker host can pass a picker that remembers ports in use. --- src/Process/DockerExecution.php | 10 ++---- src/Process/DockerSandbox.php | 42 ++++++---------------- test/Process/DockerSandboxTest.php | 57 ++++++++++++++---------------- 3 files changed, 41 insertions(+), 68 deletions(-) diff --git a/src/Process/DockerExecution.php b/src/Process/DockerExecution.php index c4cafee5..562fad86 100644 --- a/src/Process/DockerExecution.php +++ b/src/Process/DockerExecution.php @@ -15,13 +15,13 @@ final class DockerExecution implements SandboxExecution /** * @param list $before * @param list $after - * @param \Closure(int): string $address finds where docker published a port, see getAddress() + * @param array $addresses where each port is published, eg. [54321 => '10.0.0.5:47213'] */ public function __construct( public readonly Process $process, public readonly array $before = [], public readonly array $after = [], - private ?\Closure $address = null, + private array $addresses = [], ) {} public function start(): void @@ -69,11 +69,7 @@ public function getErrorOutput(): string public function getAddress(int $port): string { - if ($this->address === null) { - throw new \RuntimeException(sprintf('Port %d is not published', $port)); - } - - return ($this->address)($port); + return $this->addresses[$port] ?? throw new \RuntimeException(sprintf('Port %d is not published', $port)); } private function runAfter(): void diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index f85dbbe4..e6c0107a 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -21,6 +21,7 @@ final class DockerSandbox implements Sandbox private string $projectName; private string $portsNetwork; private string $portsHost; + private PortPicker $portPicker; public function __construct( string $basePath, @@ -28,6 +29,7 @@ public function __construct( ?ExecutableFinder $executableFinder = null, string $portsNetwork = 'bridge', string $portsHost = '127.0.0.1', + ?PortPicker $portPicker = null, ) { $this->executableFinder = $executableFinder ?? new ExecutableFinder(); $this->basePath = $basePath; @@ -37,6 +39,7 @@ public function __construct( $this->portsNetwork = $portsNetwork; //the address ports are published on, the docker host's private address when it is remote $this->portsHost = $portsHost; + $this->portPicker = $portPicker ?? new RandomPortPicker(); } public function getImageName(): string @@ -60,15 +63,18 @@ public function createBuildProcess(): Process public function create(ProcessInput $processInput): DockerExecution { - $container = 'php-school-' . bin2hex(random_bytes(8)); - $network = ['--network', 'none']; + $addresses = []; if (count($processInput->getExposedPorts()) > 0) { $network = ['--network', $this->portsNetwork]; + //eg. [fdaa::2] for an IPv6 address + $host = str_contains($this->portsHost, ':') ? '[' . $this->portsHost . ']' : $this->portsHost; + foreach ($processInput->getExposedPorts() as $port) { - //no host port, docker picks a free one, see getAddress() + $hostPort = $this->portPicker->pick(); $network[] = '-p'; - $network[] = $this->portsHost . '::' . $port; + $network[] = $host . ':' . $hostPort . ':' . $port; + $addresses[$port] = $host . ':' . $hostPort; } } @@ -84,8 +90,6 @@ public function create(ProcessInput $processInput): DockerExecution $this->findDocker(), 'run', '--rm', - '--name', - $container, '-i', '--init', '--user', @@ -124,31 +128,7 @@ public function create(ProcessInput $processInput): DockerExecution null, $processInput->getInput(), self::TIMEOUT + 5, - ), [], [], fn(int $port) => $this->getAddress($container, $port)); - } - - /** - * Asks docker which host port it published a container's port on. Waits a little, as the container may still be - * starting. - */ - private function getAddress(string $container, int $port): string - { - for ($try = 0; $try < 20; $try++) { - //eg. 127.0.0.1:54321 - $process = new Process([$this->findDocker(), 'port', $container, (string) $port], $this->basePath); - $process->run(); - - if ($process->isSuccessful() && trim($process->getOutput()) !== '') { - $published = strtok(trim($process->getOutput()), "\n"); - $host = str_contains($this->portsHost, ':') ? '[' . $this->portsHost . ']' : $this->portsHost; - - return $host . ':' . substr((string) $published, (int) strrpos((string) $published, ':') + 1); - } - - usleep(100000); - } - - throw new \RuntimeException(sprintf('Port %d of the sandbox was not published', $port)); + ), [], [], $addresses); } private function findDocker(): string diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index dd7875d1..bdb71568 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -3,6 +3,8 @@ namespace PhpSchool\PhpWorkshopTest\Process; use PhpSchool\PhpWorkshop\Process\DockerSandbox; +use PhpSchool\PhpWorkshop\Process\PortPicker; +use PhpSchool\PhpWorkshop\Process\RandomPortPicker; use PhpSchool\PhpWorkshop\Process\ProcessInput; use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException; use PHPUnit\Framework\TestCase; @@ -12,28 +14,31 @@ class DockerSandboxTest extends TestCase { private function factory(string $portsNetwork = 'bridge', string $portsHost = '127.0.0.1'): DockerSandbox { + $ports = new class implements PortPicker { + public function pick(): int + { + return 47213; + } + }; + $finder = $this->createMock(ExecutableFinder::class); $finder->expects($this->once()) ->method('find') ->with('docker') ->willReturn('/usr/local/bin/docker'); - return new DockerSandbox('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost); + return new DockerSandbox('/docker-dir', 'PHP8Appreciate', $finder, $portsNetwork, $portsHost, $ports); } /** - * @param string $commandLine the actual one, for the container name * @param list $network * @param list $extra env and mount args * @param list $command */ - private function expectedCommand(string $commandLine, array $network, array $extra, array $command): string + private function expectedCommand(array $network, array $extra, array $command): string { - //each container gets its own name - preg_match('/php-school-[0-9a-f]{16}/', $commandLine, $container); - $parts = [ - '/usr/local/bin/docker', 'run', '--rm', '--name', $container[0] ?? '', '-i', '--init', '--user', getmyuid() . ':' . getmygid(), + '/usr/local/bin/docker', 'run', '--rm', '-i', '--init', '--user', getmyuid() . ':' . getmygid(), ...$network, '--read-only', '--tmpfs', '/tmp:rw,nosuid,nodev,size=64m', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges', '--pids-limit', '64', '--memory', '256m', '--memory-swap', '256m', @@ -67,7 +72,6 @@ public function testCreateIsIsolatedWithNoNetwork(): void $process = $this->factory()->create(new ProcessInput('php', ['one', 'two'], __DIR__, [], []))->process; $expected = $this->expectedCommand( - $process->getCommandLine(), ['--network', 'none'], ['-v', __DIR__ . ':/solution'], ['php', 'one', 'two'], @@ -82,8 +86,7 @@ public function testExposedPortsArePublishedOnLoopbackOnly(): void $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - $process->getCommandLine(), - ['--network', 'bridge', '-p', '127.0.0.1::8000'], + ['--network', 'bridge', '-p', '127.0.0.1:47213:8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -95,8 +98,7 @@ public function testExposedPortsUseTheGivenNetwork(): void $process = $this->factory('php-school-sandbox')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - $process->getCommandLine(), - ['--network', 'php-school-sandbox', '-p', '127.0.0.1::8000'], + ['--network', 'php-school-sandbox', '-p', '127.0.0.1:47213:8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); @@ -108,33 +110,29 @@ public function testExposedPortsArePublishedOnTheGivenHost(): void $process = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000]))->process; $expected = $this->expectedCommand( - $process->getCommandLine(), - ['--network', 'bridge', '-p', '172.19.0.2::8000'], + ['--network', 'bridge', '-p', '172.19.0.2:47213:8000'], ['-v', __DIR__ . ':/solution'], ['php'], ); static::assertSame($expected, $process->getCommandLine()); } - public function testAddressIsThePortDockerPublishedOnTheGivenHost(): void + public function testAddressIsThePickedPortOnTheGivenHost(): void { - //stands in for `docker port 8000` - $docker = tempnam(sys_get_temp_dir(), 'docker'); - file_put_contents($docker, "#!/bin/sh\necho 172.19.0.2:54321\n"); - chmod($docker, 0755); + $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000])); + static::assertSame('172.19.0.2:47213', $execution->getAddress(8000)); - $finder = $this->createMock(ExecutableFinder::class); - $finder->method('find')->with('docker')->willReturn($docker); - - $execution = (new DockerSandbox(__DIR__, 'php8appreciate', $finder, 'bridge', '172.19.0.2')) - ->create(new ProcessInput('php', [], __DIR__, [], [8000])); - static::assertSame('172.19.0.2:54321', $execution->getAddress(8000)); + $execution = $this->factory('bridge', 'fdaa::2')->create(new ProcessInput('php', [], __DIR__, [], [8000])); + static::assertStringContainsString("'-p' '[fdaa::2]:47213:8000'", $execution->process->getCommandLine()); + static::assertSame('[fdaa::2]:47213', $execution->getAddress(8000)); + } - $execution = (new DockerSandbox(__DIR__, 'php8appreciate', $finder, 'bridge', 'fdaa::2')) - ->create(new ProcessInput('php', [], __DIR__, [], [8000])); - static::assertSame('[fdaa::2]:54321', $execution->getAddress(8000)); + public function testRandomPortIsHigh(): void + { + $port = (new RandomPortPicker())->pick(); - unlink($docker); + static::assertGreaterThanOrEqual(20000, $port); + static::assertLessThanOrEqual(59999, $port); } public function testCreateWithEnv(): void @@ -142,7 +140,6 @@ public function testCreateWithEnv(): void $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], []))->process; $expected = $this->expectedCommand( - $process->getCommandLine(), ['--network', 'none'], ['-e', 'SOME_VAR=value', '-v', __DIR__ . ':/solution'], ['php'], From 6153392f4a7d99b633e8b3cc23991d3baed69566 Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 09:48:35 +0100 Subject: [PATCH 3/8] Pass an IPv6 ports host in brackets instead of adding them --- src/Process/DockerSandbox.php | 10 ++++------ test/Process/DockerSandboxTest.php | 2 +- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index e6c0107a..78604cd9 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -37,7 +37,8 @@ public function __construct( //for exercises that expose ports, eg a server the check connects to. Pass a network without internet access //to stop student code reaching out, the published ports still work $this->portsNetwork = $portsNetwork; - //the address ports are published on, the docker host's private address when it is remote + //the address ports are published on, the docker host's private address when it is remote. IPv6 in brackets, + //eg. [fdaa::2] $this->portsHost = $portsHost; $this->portPicker = $portPicker ?? new RandomPortPicker(); } @@ -67,14 +68,11 @@ public function create(ProcessInput $processInput): DockerExecution $addresses = []; if (count($processInput->getExposedPorts()) > 0) { $network = ['--network', $this->portsNetwork]; - //eg. [fdaa::2] for an IPv6 address - $host = str_contains($this->portsHost, ':') ? '[' . $this->portsHost . ']' : $this->portsHost; - foreach ($processInput->getExposedPorts() as $port) { $hostPort = $this->portPicker->pick(); $network[] = '-p'; - $network[] = $host . ':' . $hostPort . ':' . $port; - $addresses[$port] = $host . ':' . $hostPort; + $network[] = $this->portsHost . ':' . $hostPort . ':' . $port; + $addresses[$port] = $this->portsHost . ':' . $hostPort; } } diff --git a/test/Process/DockerSandboxTest.php b/test/Process/DockerSandboxTest.php index bdb71568..bbb1b499 100644 --- a/test/Process/DockerSandboxTest.php +++ b/test/Process/DockerSandboxTest.php @@ -122,7 +122,7 @@ public function testAddressIsThePickedPortOnTheGivenHost(): void $execution = $this->factory('bridge', '172.19.0.2')->create(new ProcessInput('php', [], __DIR__, [], [8000])); static::assertSame('172.19.0.2:47213', $execution->getAddress(8000)); - $execution = $this->factory('bridge', 'fdaa::2')->create(new ProcessInput('php', [], __DIR__, [], [8000])); + $execution = $this->factory('bridge', '[fdaa::2]')->create(new ProcessInput('php', [], __DIR__, [], [8000])); static::assertStringContainsString("'-p' '[fdaa::2]:47213:8000'", $execution->process->getCommandLine()); static::assertSame('[fdaa::2]:47213', $execution->getAddress(8000)); } From a184d0c3e796eb3c91cdefcabb3d48a3f4dcf3fe Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 09:52:06 +0100 Subject: [PATCH 4/8] Add the PortPicker files missed from the last commits --- src/Process/PortPicker.php | 14 ++++++++++++++ src/Process/RandomPortPicker.php | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/Process/PortPicker.php create mode 100644 src/Process/RandomPortPicker.php diff --git a/src/Process/PortPicker.php b/src/Process/PortPicker.php new file mode 100644 index 00000000..eb64d453 --- /dev/null +++ b/src/Process/PortPicker.php @@ -0,0 +1,14 @@ + Date: Sun, 1 Nov 2026 10:53:10 +0100 Subject: [PATCH 5/8] FreePortPicker and LockPortPicker instead of System::freePort and RandomPortPicker FreePortPicker is a port free on this machine: exercises use it, and DockerSandbox by default. LockPortPicker claims a random port with a symfony/lock lock, for a docker host shared by many runs. --- composer.json | 3 +- composer.lock | 84 ++++++++++++++++++++++++++++- src/Process/DockerSandbox.php | 2 +- src/Process/FreePortPicker.php | 29 ++++++++++ src/Process/LockPortPicker.php | 34 ++++++++++++ src/Process/PortPicker.php | 4 +- src/Process/RandomPortPicker.php | 16 ------ src/Utils/System.php | 18 ------- test/Process/DockerSandboxTest.php | 9 ---- test/Process/FreePortPickerTest.php | 18 +++++++ test/Process/LockPortPickerTest.php | 25 +++++++++ test/Utils/SystemTest.php | 7 --- 12 files changed, 194 insertions(+), 55 deletions(-) create mode 100644 src/Process/FreePortPicker.php create mode 100644 src/Process/LockPortPicker.php delete mode 100644 src/Process/RandomPortPicker.php create mode 100644 test/Process/FreePortPickerTest.php create mode 100644 test/Process/LockPortPickerTest.php diff --git a/composer.json b/composer.json index 46b37bf3..098600a2 100644 --- a/composer.json +++ b/composer.json @@ -31,7 +31,8 @@ "nikic/php-parser": "^5.0", "guzzlehttp/guzzle": "^7.9 | ^8.0", "psr/log": "^1.1 | ^2.0 | ^3.0", - "ext-json": "*" + "ext-json": "*", + "symfony/lock": "^6.4 | ^7.0 | ^8.0" }, "require-dev": { "phpunit/phpunit": "^11.5", diff --git a/composer.lock b/composer.lock index 664f8eed..e028e70a 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "e56e46a1cfc2be6b0655246c48614d85", + "content-hash": "504c9387f09dcb02dcf5932b79f46deb", "packages": [ { "name": "beberlei/assert", @@ -1920,6 +1920,88 @@ ], "time": "2026-10-06T20:05:19+00:00" }, + { + "name": "symfony/lock", + "version": "v8.1.10", + "source": { + "type": "git", + "url": "https://github.com/symfony/lock.git", + "reference": "86767bf6c112741d39118cc4c946f1a7ee98fa6d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/lock/zipball/86767bf6c112741d39118cc4c946f1a7ee98fa6d", + "reference": "86767bf6c112741d39118cc4c946f1a7ee98fa6d", + "shasum": "" + }, + "require": { + "php": ">=8.4.1", + "psr/log": "^1|^2|^3" + }, + "conflict": { + "doctrine/dbal": "<4.3" + }, + "require-dev": { + "doctrine/dbal": "^4.3", + "predis/predis": "^1.1|^2.0", + "symfony/serializer": "^6.4|^7.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Symfony\\Component\\Lock\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jérémy Derussé", + "email": "jeremy@derusse.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Creates and manages locks, a mechanism to provide exclusive access to a shared resource", + "homepage": "https://symfony.com", + "keywords": [ + "cas", + "flock", + "locking", + "mutex", + "redlock", + "semaphore" + ], + "support": { + "source": "https://github.com/symfony/lock/tree/v8.1.10" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-10-25T14:40:25+00:00" + }, { "name": "symfony/polyfill-ctype", "version": "v1.37.0", diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 78604cd9..2d1fd2fb 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -40,7 +40,7 @@ public function __construct( //the address ports are published on, the docker host's private address when it is remote. IPv6 in brackets, //eg. [fdaa::2] $this->portsHost = $portsHost; - $this->portPicker = $portPicker ?? new RandomPortPicker(); + $this->portPicker = $portPicker ?? new FreePortPicker(); } public function getImageName(): string diff --git a/src/Process/FreePortPicker.php b/src/Process/FreePortPicker.php new file mode 100644 index 00000000..1ace14f4 --- /dev/null +++ b/src/Process/FreePortPicker.php @@ -0,0 +1,29 @@ +locks->createLock('php-school-port-' . $port, self::LOCK_SECONDS, false)->acquire()) { + return $port; + } + } + + throw new RuntimeException('No free port to publish on'); + } +} diff --git a/src/Process/PortPicker.php b/src/Process/PortPicker.php index eb64d453..0b25171b 100644 --- a/src/Process/PortPicker.php +++ b/src/Process/PortPicker.php @@ -5,8 +5,8 @@ namespace PhpSchool\PhpWorkshop\Process; /** - * Picks the port on the docker host that a container's port is published on. Swap it for one that remembers ports in - * use when verifies run at the same time on a shared docker host. + * Picks a port, eg. the one an exercise's code listens on, or the one DockerSandbox publishes it on. FreePortPicker + * when the code runs on this machine, LockPortPicker for a docker host shared by many runs. */ interface PortPicker { diff --git a/src/Process/RandomPortPicker.php b/src/Process/RandomPortPicker.php deleted file mode 100644 index 3648447d..00000000 --- a/src/Process/RandomPortPicker.php +++ /dev/null @@ -1,16 +0,0 @@ -getAddress(8000)); } - public function testRandomPortIsHigh(): void - { - $port = (new RandomPortPicker())->pick(); - - static::assertGreaterThanOrEqual(20000, $port); - static::assertLessThanOrEqual(59999, $port); - } - public function testCreateWithEnv(): void { $process = $this->factory()->create(new ProcessInput('php', [], __DIR__, ['SOME_VAR' => 'value'], []))->process; diff --git a/test/Process/FreePortPickerTest.php b/test/Process/FreePortPickerTest.php new file mode 100644 index 00000000..7ead740e --- /dev/null +++ b/test/Process/FreePortPickerTest.php @@ -0,0 +1,18 @@ +pick()); + static::assertNotFalse($server); + fclose($server); + } +} diff --git a/test/Process/LockPortPickerTest.php b/test/Process/LockPortPickerTest.php new file mode 100644 index 00000000..3d05075e --- /dev/null +++ b/test/Process/LockPortPickerTest.php @@ -0,0 +1,25 @@ +pick(); + + static::assertGreaterThanOrEqual(20000, $port); + static::assertLessThanOrEqual(59999, $port); + //another run can not take it + static::assertFalse($locks->createLock('php-school-port-' . $port)->acquire()); + } +} diff --git a/test/Utils/SystemTest.php b/test/Utils/SystemTest.php index 4acbaaec..69fd2a0a 100644 --- a/test/Utils/SystemTest.php +++ b/test/Utils/SystemTest.php @@ -34,13 +34,6 @@ public function testTempDirWithPath(): void self::assertSame($expect, System::tempDir('test')); } - public function testFreePortCanBeListenedOn(): void - { - $server = stream_socket_server('tcp://127.0.0.1:' . System::freePort()); - self::assertNotFalse($server); - fclose($server); - } - public function testRandomTempDir(): void { self::assertTrue(str_starts_with(System::randomTempDir(), realpath(sys_get_temp_dir()) . '/php-school')); From b2d7baef4b3a37997bf84b2f1cdc5eeba7d54dcb Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 11:26:53 +0100 Subject: [PATCH 6/8] DockerExecution keeps the host once and a port map --- src/Process/DockerExecution.php | 12 +++++++++--- src/Process/DockerSandbox.php | 6 +++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Process/DockerExecution.php b/src/Process/DockerExecution.php index 562fad86..bee68a6c 100644 --- a/src/Process/DockerExecution.php +++ b/src/Process/DockerExecution.php @@ -15,13 +15,15 @@ final class DockerExecution implements SandboxExecution /** * @param list $before * @param list $after - * @param array $addresses where each port is published, eg. [54321 => '10.0.0.5:47213'] + * @param string $host the docker host's address that ports are published on, eg. 10.0.0.5 + * @param array $ports container port => published port on the host, eg. [54321 => 47213] */ public function __construct( public readonly Process $process, public readonly array $before = [], public readonly array $after = [], - private array $addresses = [], + private string $host = '127.0.0.1', + private array $ports = [], ) {} public function start(): void @@ -69,7 +71,11 @@ public function getErrorOutput(): string public function getAddress(int $port): string { - return $this->addresses[$port] ?? throw new \RuntimeException(sprintf('Port %d is not published', $port)); + if (!isset($this->ports[$port])) { + throw new \RuntimeException(sprintf('Port %d is not published', $port)); + } + + return $this->host . ':' . $this->ports[$port]; } private function runAfter(): void diff --git a/src/Process/DockerSandbox.php b/src/Process/DockerSandbox.php index 2d1fd2fb..82a09cc3 100644 --- a/src/Process/DockerSandbox.php +++ b/src/Process/DockerSandbox.php @@ -65,14 +65,14 @@ public function createBuildProcess(): Process public function create(ProcessInput $processInput): DockerExecution { $network = ['--network', 'none']; - $addresses = []; + $ports = []; if (count($processInput->getExposedPorts()) > 0) { $network = ['--network', $this->portsNetwork]; foreach ($processInput->getExposedPorts() as $port) { $hostPort = $this->portPicker->pick(); $network[] = '-p'; $network[] = $this->portsHost . ':' . $hostPort . ':' . $port; - $addresses[$port] = $this->portsHost . ':' . $hostPort; + $ports[$port] = $hostPort; } } @@ -126,7 +126,7 @@ public function create(ProcessInput $processInput): DockerExecution null, $processInput->getInput(), self::TIMEOUT + 5, - ), [], [], $addresses); + ), [], [], $this->portsHost, $ports); } private function findDocker(): string From ccd87753edd6f8b30c6f8dc141e50eb1eea5aafb Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 11:29:37 +0100 Subject: [PATCH 7/8] LockPortPicker gives up after 5 tries --- src/Process/LockPortPicker.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Process/LockPortPicker.php b/src/Process/LockPortPicker.php index 55297860..018a65db 100644 --- a/src/Process/LockPortPicker.php +++ b/src/Process/LockPortPicker.php @@ -20,7 +20,7 @@ public function __construct(private LockFactory $locks) {} public function pick(): int { - for ($try = 0; $try < 100; $try++) { + for ($try = 0; $try < 5; $try++) { $port = random_int(20000, 59999); //not released when this object goes, it expires From 06ef5ad3f77e37b4fcea390e151bd50e2cab0b4d Mon Sep 17 00:00:00 2001 From: Aydin Hassan Date: Sun, 1 Nov 2026 11:31:25 +0100 Subject: [PATCH 8/8] PortPicker docs: no implementations --- src/Process/PortPicker.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Process/PortPicker.php b/src/Process/PortPicker.php index 0b25171b..97e3fb89 100644 --- a/src/Process/PortPicker.php +++ b/src/Process/PortPicker.php @@ -5,8 +5,7 @@ namespace PhpSchool\PhpWorkshop\Process; /** - * Picks a port, eg. the one an exercise's code listens on, or the one DockerSandbox publishes it on. FreePortPicker - * when the code runs on this machine, LockPortPicker for a docker host shared by many runs. + * Picks a port, eg. the one an exercise's code listens on, or the one DockerSandbox publishes it on. */ interface PortPicker {