Skip to content
Merged
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
1 change: 0 additions & 1 deletion app/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
84 changes: 83 additions & 1 deletion composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions src/Event/CliExecuteEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/**
Expand Down Expand Up @@ -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.
*
Expand Down
8 changes: 2 additions & 6 deletions src/ExerciseDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(),
) {}

/**
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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);

Expand Down
4 changes: 2 additions & 2 deletions src/ExerciseRunner/CliRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();

Expand Down
10 changes: 1 addition & 9 deletions src/ExerciseRunner/Context/ExecutionContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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();

Expand All @@ -27,7 +25,6 @@ public static function fromInputAndExercise(Input $input, ExerciseInterface $exe
System::randomTempDir(),
$exercise,
$input,
$sandboxHost,
);
}

Expand Down Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions src/Process/DockerExecution.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ final class DockerExecution implements SandboxExecution
/**
* @param list<Process> $before
* @param list<Process> $after
* @param string $host the docker host's address that ports are published on, eg. 10.0.0.5
* @param array<int, int> $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 string $host = '127.0.0.1',
private array $ports = [],
) {}

public function start(): void
Expand Down Expand Up @@ -65,6 +69,15 @@ public function getErrorOutput(): string
return $this->process->getErrorOutput();
}

public function getAddress(int $port): string
{
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
{
foreach ($this->after as $step) {
Expand Down
18 changes: 10 additions & 8 deletions src/Process/DockerSandbox.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,22 +21,26 @@ final class DockerSandbox implements Sandbox
private string $projectName;
private string $portsNetwork;
private string $portsHost;
private PortPicker $portPicker;

public function __construct(
string $basePath,
string $projectName,
?ExecutableFinder $executableFinder = null,
string $portsNetwork = 'bridge',
string $portsHost = '127.0.0.1',
?PortPicker $portPicker = null,
) {
$this->executableFinder = $executableFinder ?? new ExecutableFinder();
$this->basePath = $basePath;
$this->projectName = $projectName;
//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 FreePortPicker();
}

public function getImageName(): string
Expand All @@ -58,19 +62,17 @@ public function createBuildProcess(): Process
);
}

public function getHost(): SandboxHost
{
return new SandboxHost($this->portsHost);
}

public function create(ProcessInput $processInput): DockerExecution
{
$network = ['--network', 'none'];
$ports = [];
if (count($processInput->getExposedPorts()) > 0) {
$network = ['--network', $this->portsNetwork];
foreach ($processInput->getExposedPorts() as $port) {
$hostPort = $this->portPicker->pick();
$network[] = '-p';
$network[] = $this->portsHost . ':' . $port . ':' . $port;
$network[] = $this->portsHost . ':' . $hostPort . ':' . $port;
$ports[$port] = $hostPort;
}
}

Expand Down Expand Up @@ -124,7 +126,7 @@ public function create(ProcessInput $processInput): DockerExecution
null,
$processInput->getInput(),
self::TIMEOUT + 5,
));
), [], [], $this->portsHost, $ports);
}

private function findDocker(): string
Expand Down
29 changes: 29 additions & 0 deletions src/Process/FreePortPicker.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Process;

use PhpSchool\PhpWorkshop\Exception\RuntimeException;

/**
* A port nothing listens on, on this machine. Inside a sandbox container every port is free, so exercises use it for
* the port their code listens on.
*/
final class FreePortPicker implements PortPicker
{
public function pick(): 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);
}
}
5 changes: 5 additions & 0 deletions src/Process/HostExecution.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@ public function getErrorOutput(): string
{
return $this->process->getErrorOutput();
}

public function getAddress(int $port): string
{
return '127.0.0.1:' . $port;
}
}
6 changes: 0 additions & 6 deletions src/Process/HostSandbox.php
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
Loading
Loading