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
7 changes: 3 additions & 4 deletions app/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
use PhpSchool\PhpWorkshop\Output\OutputInterface;
use PhpSchool\PhpWorkshop\Output\StdOutput;
use PhpSchool\PhpWorkshop\Patch;
use PhpSchool\PhpWorkshop\Process\Composer;
use PhpSchool\PhpWorkshop\Process\DockerSandbox;
use PhpSchool\PhpWorkshop\Process\HostSandbox;
use PhpSchool\PhpWorkshop\Process\Sandbox;
Expand Down Expand Up @@ -280,17 +281,15 @@
},

ReferencePackages::class => function (ContainerInterface $c) {
return new ReferencePackages($c->get(ExerciseRepository::class), $c->get(Sandbox::class));
return new ReferencePackages($c->get(ExerciseRepository::class), new Composer());
},

//Listeners
InitialCodeListener::class => function (ContainerInterface $c) {
return new InitialCodeListener($c->get('currentWorkingDirectory'), $c->get(LoggerInterface::class));
},
PrepareSolutionListener::class => function (ContainerInterface $c) {
return new PrepareSolutionListener(
$c->get(Sandbox::class),
);
return new PrepareSolutionListener(new Composer());
},
CodePatchListener::class => function (ContainerInterface $c) {
return new CodePatchListener(
Expand Down
16 changes: 5 additions & 11 deletions src/Listener/PrepareSolutionListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,15 @@
use PhpSchool\PhpWorkshop\Event\ExerciseRunnerEvent;
use PhpSchool\PhpWorkshop\Exercise\ProvidesSolution;
use PhpSchool\PhpWorkshop\Exception\RuntimeException;
use PhpSchool\PhpWorkshop\Process\Sandbox;
use PhpSchool\PhpWorkshop\Process\ProcessInput;
use PhpSchool\PhpWorkshop\Process\SandboxExecution;
use PhpSchool\PhpWorkshop\Process\Composer;
use Symfony\Component\Process\Process;

/**
* Listener to install composer deps for an exercise solution, offline when ReferencePackages has warmed the cache
*/
class PrepareSolutionListener
{
public function __construct(private Sandbox $sandbox)
{
$this->sandbox = $sandbox;
}
public function __construct(private Composer $composer) {}

/**
* @param ExerciseRunnerEvent $event
Expand Down Expand Up @@ -63,10 +59,8 @@ public function __invoke(ExerciseRunnerEvent $event): void
/**
* @param array<string, string> $env
*/
private function install(ExerciseRunnerEvent $event, array $env): SandboxExecution
private function install(ExerciseRunnerEvent $event, array $env): Process
{
return $this->sandbox->create(
new ProcessInput('composer', ['install', '--no-interaction'], $event->getContext()->getReferenceExecutionDirectory(), $env, []),
);
return $this->composer->create(['install'], $event->getContext()->getReferenceExecutionDirectory(), $env);
}
}
45 changes: 45 additions & 0 deletions src/Process/Composer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshop\Process;

use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;

/**
* Runs composer on this machine, not in the sandbox. Package plugins and scripts never run, so no package code does,
* and vendor is copied into the sandbox with the rest of the solution.
*/
final class Composer
{
//downloading packages can take a while
private const TIMEOUT = 120;

private ExecutableFinder $executableFinder;

public function __construct(?ExecutableFinder $executableFinder = null)
{
$this->executableFinder = $executableFinder ?? new ExecutableFinder();
}

/**
* @param list<string> $args eg. ['install']
* @param array<string, string> $env eg. ['COMPOSER_DISABLE_NETWORK' => '1']
*/
public function create(array $args, string $directory, array $env = []): Process
{
$composer = $this->executableFinder->find('composer');
if ($composer === null) {
throw ProcessNotFoundException::fromExecutable('composer');
}

return new Process(
[$composer, ...$args, '--no-interaction', '--no-plugins', '--no-scripts'],
$directory,
$env,
null,
self::TIMEOUT,
);
}
}
44 changes: 5 additions & 39 deletions src/Process/DockerSandbox.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,19 @@
final class DockerSandbox implements Sandbox
{
private const TIMEOUT = 30;
//a named volume, so it lives on the docker host, which may not be this machine
private const COMPOSER_CACHE_VOLUME = 'php-school-composer-cache';

private ExecutableFinder $executableFinder;
private string $basePath;
private string $projectName;
private string $portsNetwork;
private string $portsHost;

/**
* @var array<string, string>
*/
private array $vendorVolumes;

/**
* @param array<string, string> $vendorVolumes folder => volume, for runs in a folder directly inside it, so vendor
* stays on the docker host between runs, eg. ['/tmp/php-school/<student id>' => 'php-school-vendor-<student id>-<exercise>']
*/
public function __construct(
string $basePath,
string $projectName,
?ExecutableFinder $executableFinder = null,
string $portsNetwork = 'bridge',
string $portsHost = '127.0.0.1',
array $vendorVolumes = [],
) {
$this->executableFinder = $executableFinder ?? new ExecutableFinder();
$this->basePath = $basePath;
Expand All @@ -49,7 +37,6 @@ 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->vendorVolumes = $vendorVolumes;
}

public function getImageName(): string
Expand Down Expand Up @@ -78,30 +65,8 @@ public function getHost(): SandboxHost

public function create(ProcessInput $processInput): DockerExecution
{
$isComposer = $processInput->getExecutable() === 'composer';

$args = $processInput->getArgs();
$mounts = [$processInput->getWorkingDirectory() . ':/solution'];

$vendorVolume = $this->vendorVolumes[dirname($processInput->getWorkingDirectory())] ?? null;
if ($vendorVolume !== null) {
//only composer writes to it
$mounts[] = $vendorVolume . ':/solution/vendor' . ($isComposer ? '' : ':ro');
}

$env = ['COMPOSER_HOME' => '/composer'];

if ($isComposer) {
//we need to mount a volume for composer cache, and never run package plugins or scripts
$mounts[] = self::COMPOSER_CACHE_VOLUME . ':/composer';
$args = [...$args, '--no-plugins', '--no-scripts'];
}

$network = ['--network', 'none'];
if ($isComposer) {
//composer needs to download packages
$network = ['--network', 'bridge'];
} elseif (count($processInput->getExposedPorts()) > 0) {
if (count($processInput->getExposedPorts()) > 0) {
$network = ['--network', $this->portsNetwork];
foreach ($processInput->getExposedPorts() as $port) {
$network[] = '-p';
Expand All @@ -110,7 +75,7 @@ public function create(ProcessInput $processInput): DockerExecution
}

$envArgs = [];
foreach ([...$processInput->getEnv(), ...$env] as $key => $value) {
foreach ($processInput->getEnv() as $key => $value) {
$envArgs[] = '-e';
$envArgs[] = $key . '=' . $value;
}
Expand Down Expand Up @@ -142,7 +107,8 @@ public function create(ProcessInput $processInput): DockerExecution
'--cpus',
'1',
...$envArgs,
...array_merge(...array_map(fn($mount) => ['-v', $mount], $mounts)),
'-v',
$processInput->getWorkingDirectory() . ':/solution',
'-w',
'/solution',
$this->getImageName(),
Expand All @@ -152,7 +118,7 @@ public function create(ProcessInput $processInput): DockerExecution
'KILL',
(string) self::TIMEOUT,
$processInput->getExecutable(),
...$args,
...$processInput->getArgs(),
],
$this->basePath,
null,
Expand Down
11 changes: 3 additions & 8 deletions src/ReferencePackages.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@

use PhpSchool\PhpWorkshop\Exception\RuntimeException;
use PhpSchool\PhpWorkshop\Exercise\ProvidesSolution;
use PhpSchool\PhpWorkshop\Process\ProcessInput;
use PhpSchool\PhpWorkshop\Process\Sandbox;
use PhpSchool\PhpWorkshop\Process\Composer;
use Symfony\Component\Filesystem\Filesystem;

/**
Expand All @@ -18,7 +17,7 @@ class ReferencePackages
{
private Filesystem $filesystem;

public function __construct(private ExerciseRepository $exerciseRepository, private Sandbox $sandbox)
public function __construct(private ExerciseRepository $exerciseRepository, private Composer $composer)
{
$this->filesystem = new Filesystem();
}
Expand All @@ -36,12 +35,8 @@ public function warm(): void
$this->filesystem->remove($directory . '/vendor');

//keeps a committed composer.lock, or writes one next to the solution. It is copied with it on each verify
$execution = $this->sandbox->create(
new ProcessInput('composer', ['install', '--no-interaction'], $directory, [], []),
);

try {
$execution->mustRun();
$this->composer->create(['install'], $directory)->mustRun();
} catch (\Symfony\Component\Process\Exception\RuntimeException $e) {
throw new RuntimeException(sprintf('Composer packages for "%s" could not be installed', $exercise->getName()), 0, $e);
}
Expand Down
10 changes: 5 additions & 5 deletions test/Listener/PrepareSolutionListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use PhpSchool\PhpWorkshop\Event\ExerciseRunnerEvent;
use PhpSchool\PhpWorkshop\ExerciseRunner\Context\TestContext;
use PhpSchool\PhpWorkshop\Listener\PrepareSolutionListener;
use PhpSchool\PhpWorkshop\Process\HostSandbox;
use PhpSchool\PhpWorkshop\Process\Composer;
use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException;
use PhpSchool\PhpWorkshop\Solution\SolutionInterface;
use PhpSchool\PhpWorkshopTest\Asset\CliExerciseImpl;
Expand Down Expand Up @@ -33,7 +33,7 @@ public function testIfSolutionRequiresComposerButComposerCannotBeLocatedExceptio
$this->expectException(ProcessNotFoundException::class);
$this->expectExceptionMessage('Could not find executable: "composer"');
$event = new ExerciseRunnerEvent('event', $context);
(new PrepareSolutionListener(new HostSandbox($finder)))->__invoke($event);
(new PrepareSolutionListener(new Composer($finder)))->__invoke($event);
}

public function testIfSolutionRequiresComposerButVendorDirExistsNothingIsDone(): void
Expand All @@ -54,7 +54,7 @@ public function testIfSolutionRequiresComposerButVendorDirExistsNothingIsDone():
$exercise->setSolution($solution);

$event = new ExerciseRunnerEvent('event', $context);
(new PrepareSolutionListener(new HostSandbox()))->__invoke($event);
(new PrepareSolutionListener(new Composer()))->__invoke($event);

$this->assertFileExists(sprintf('%s/vendor', $context->getReferenceExecutionDirectory()));
//check for non existence of lock file, composer generates this when updating if it doesn't exist
Expand Down Expand Up @@ -84,7 +84,7 @@ public function testIfSolutionRequiresComposerComposerInstallIsExecuted(): void
$exercise->setSolution($solution);

$event = new ExerciseRunnerEvent('event', $context);
(new PrepareSolutionListener(new HostSandbox()))->__invoke($event);
(new PrepareSolutionListener(new Composer()))->__invoke($event);

$this->assertFileExists(sprintf('%s/vendor', $context->getReferenceExecutionDirectory()));
}
Expand Down Expand Up @@ -119,7 +119,7 @@ public function testExceptionIsThrownIfDependenciesCannotBeResolved(): void
->willReturn(true);

$event = new ExerciseRunnerEvent('event', $context);
(new PrepareSolutionListener(new HostSandbox()))->__invoke($event);
(new PrepareSolutionListener(new Composer()))->__invoke($event);

$this->assertFileExists(sprintf('%s/vendor', $context->getReferenceExecutionDirectory()));
}
Expand Down
38 changes: 38 additions & 0 deletions test/Process/ComposerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace PhpSchool\PhpWorkshopTest\Process;

use PhpSchool\PhpWorkshop\Process\Composer;
use PhpSchool\PhpWorkshop\Process\ProcessNotFoundException;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Process\ExecutableFinder;

class ComposerTest extends TestCase
{
public function testNeverRunsPackagePluginsOrScripts(): void
{
$finder = $this->createMock(ExecutableFinder::class);
$finder->method('find')->with('composer')->willReturn('/usr/local/bin/composer');

$process = (new Composer($finder))->create(['install'], __DIR__, ['COMPOSER_DISABLE_NETWORK' => '1']);

static::assertSame(
"'/usr/local/bin/composer' 'install' '--no-interaction' '--no-plugins' '--no-scripts'",
$process->getCommandLine(),
);
static::assertSame(__DIR__, $process->getWorkingDirectory());
static::assertSame(['COMPOSER_DISABLE_NETWORK' => '1'], $process->getEnv());
}

public function testThrowsIfComposerIsNotFound(): void
{
$finder = $this->createMock(ExecutableFinder::class);
$finder->method('find')->with('composer')->willReturn(null);

$this->expectException(ProcessNotFoundException::class);

(new Composer($finder))->create(['install'], __DIR__);
}
}
Loading
Loading