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
66 changes: 53 additions & 13 deletions src/Environments/DockerEnvironment.php
Original file line number Diff line number Diff line change
Expand Up @@ -564,25 +564,50 @@
}

protected function startDocker(InstallCommand $command): bool
{
return $this->startServices($command) && $this->ensureWebPortPublished($command);
}

/**
* Not the queue and SSR: until the app is migrated and built they crash and restart.
* startWorkers() starts them once it is.
*/
protected function startServices(InstallCommand $command): bool
{
$command->info('Starting Docker services (this may take a few minutes while pulling images and starting containers)...');

// No `docker compose restart` first: it stop/starts the existing containers, and
// a container that comes back up can lose its host port bindings. `up` then sees
// an unchanged config hash, considers it up to date, and never repairs it.
// `up -d` alone already creates what is missing and recreates what changed.
$up = Process::path($command->targetPath())
->timeout(30 * 60) // 30 minutes — first run pulls images + builds layers
->run(['docker', 'compose', 'up', '-d', '--wait', '--build'], fn ($_type, $buffer) => $command->line(trim($buffer)));
$command->newLine();

if (! $up->successful()) {
$command->error('Docker failed to start: '.$up->errorOutput());
if (! $this->runQuietly($command, ['docker', 'compose', 'up', '-d', '--wait', '--build', 'app', 'nginx', 'mysql', 'redis', 'mailpit'], 30 * 60)) {

Check warning on line 583 in src/Environments/DockerEnvironment.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 154 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_installer&issues=AaFz82RQPtVSnfJO90rN&open=AaFz82RQPtVSnfJO90rN&pullRequest=36
$command->error('Docker failed to start.');

return false;
}

return $this->ensureWebPortPublished($command);
return true;
}

/** The SSR container serves the bundle this builds, so the workers start after it. */
protected function buildFrontend(InstallCommand $command): bool
{
$built = parent::buildFrontend($command);
$this->startWorkers($command, $built);

return $built;
}

/** Without a build, SSR has no bundle to serve: nextSteps() says to start it after one. */
protected function startWorkers(InstallCommand $command, bool $built): void
{
$services = $built ? ['queue', 'ssr'] : ['queue'];
$command->info('Starting '.implode(' and ', $services).'...');

// Not fatal: the app serves pages without them.
if (! $this->runQuietly($command, ['docker', 'compose', 'up', '-d', ...$services], 300)) {
$command->warn('They did not start. Start them with `docker compose up -d '.implode(' ', $services).'`.');
}
}

/**
Expand Down Expand Up @@ -641,12 +666,26 @@
protected function runComposerInContainer(InstallCommand $command): bool
{
$command->info('Installing PHP dependencies...');
$result = Process::path($command->targetPath())
->timeout(300)
->run(['docker', 'compose', 'exec', '-T', 'app', 'composer', 'install'], fn ($_type, $buffer) => $command->line(trim($buffer)));

if (! $result->successful()) {
if (! $this->runQuietly($command, ['docker', 'compose', 'exec', '-T', 'app', 'composer', 'install'], 300)) {
$command->error('composer install failed inside container.');

return false;
}

return true;
}

/** Prints the output only when the command fails, or as it runs with -v. */
protected function runQuietly(InstallCommand $command, array $args, int $timeout): bool
{
$verbose = (bool) $command->getOutput()?->isVerbose();
$result = Process::path($command->targetPath())
->timeout($timeout)
->run($args, $verbose ? fn ($_type, $buffer) => $command->line(trim($buffer)) : null);

if (! $verbose && ! $result->successful()) {
$command->line(trim($result->output().$result->errorOutput()));
}

return $result->successful();
Expand Down Expand Up @@ -773,9 +812,10 @@
$mailpit = $this->readEnvValue($command, 'FORWARD_MAILPIT_DASHBOARD_PORT') ?? '8025';

return [
...($this->frontendBuilt ? [] : ['Compile frontend assets: `npm install && npm run dev`']),
...($this->frontendBuilt ? [] : ['Compile frontend assets: `npm install && npm run dev`', 'After `npm run build`, start SSR: `docker compose up -d ssr`']),

Check warning on line 815 in src/Environments/DockerEnvironment.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 167 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_installer&issues=AaFz_dFVrSoZWpziou4n&open=AaFz_dFVrSoZWpziou4n&pullRequest=36
'Open your app: `'.$appUrl.'`',
'Email testing (Mailpit): `http://localhost:'.$mailpit.'`',
'Run artisan in the container: `docker compose exec app php artisan …`',
];
}

Expand Down
125 changes: 125 additions & 0 deletions tests/Feature/Environments/DockerStartTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
<?php

namespace Saucebase\Installer\Tests\Feature\Environments;

use Illuminate\Support\Facades\Process;
use Saucebase\Installer\Console\Commands\InstallCommand;
use Saucebase\Installer\Environments\DockerEnvironment;
use Saucebase\Installer\Tests\Feature\TestableInstallCommand;
use Saucebase\Installer\Tests\TestCase;

/**
* Docker's own logs (BuildKit, Composer) stay out of the install unless a step fails, and
* the queue and SSR containers start last: before the app is migrated and built they crash.
*/
class DockerStartTest extends TestCase
{
private TestableInstallCommand $command;

private DockerEnvironment $docker;

protected function setUp(): void
{
parent::setUp();

$this->command = new class extends TestableInstallCommand
{
/** @var string[] */
public array $printed = [];

public function line($string, $style = null, $verbosity = null): void
{
$this->printed[] = $string;
}

public function warn($string, $verbosity = null): void
{
$this->printed[] = $string;
}
};
$this->command->fakeOptions = ['path' => sys_get_temp_dir()];

$this->docker = new class extends DockerEnvironment
{
public function start(InstallCommand $command): bool
{
return $this->startServices($command);
}

public function composer(InstallCommand $command): bool
{
return $this->runComposerInContainer($command);
}

public function workers(InstallCommand $command, bool $built): void
{
$this->startWorkers($command, $built);
}

public function steps(InstallCommand $command): array
{
return $this->nextSteps($command);
}
};
}

public function test_it_starts_every_service_but_the_queue_and_ssr_without_printing_dockers_log(): void
{
Process::fake(['*' => Process::result('#1 [internal] load build definition')]);

$this->assertTrue($this->docker->start($this->command));

Process::assertRan(fn ($p) => $p->command === ['docker', 'compose', 'up', '-d', '--wait', '--build', 'app', 'nginx', 'mysql', 'redis', 'mailpit']);
$this->assertStringNotContainsString('#1', implode("\n", $this->command->printed));
}

public function test_dockers_log_is_shown_when_the_services_fail_to_start(): void
{
Process::fake(['*' => Process::result('#1 [internal] load build definition', 'pull access denied', 1)]);

$this->assertFalse($this->docker->start($this->command));

$this->assertStringContainsString('pull access denied', implode("\n", $this->command->printed));
}

public function test_composer_install_in_the_container_prints_nothing_when_it_succeeds(): void
{
Process::fake(['*' => Process::result('Generating optimized autoload files')]);

$this->assertTrue($this->docker->composer($this->command));

$this->assertStringNotContainsString('autoload', implode("\n", $this->command->printed));
}

public function test_the_queue_and_ssr_start_last(): void
{
Process::fake();

$this->docker->workers($this->command, built: true);

Process::assertRan(fn ($p) => $p->command === ['docker', 'compose', 'up', '-d', 'queue', 'ssr']);
}

public function test_without_a_frontend_build_only_the_queue_starts(): void
{
Process::fake();

$this->docker->workers($this->command, built: false);

Process::assertRan(fn ($p) => $p->command === ['docker', 'compose', 'up', '-d', 'queue']);
}

public function test_a_failed_worker_start_says_how_to_start_them(): void
{
Process::fake(['*' => Process::result(errorOutput: 'no such service', exitCode: 1)]);

$this->docker->workers($this->command, built: true);

$this->assertStringContainsString('Start them with `docker compose up -d queue ssr`', implode("\n", $this->command->printed));
}

public function test_the_summary_says_artisan_runs_in_the_container(): void
{
$this->assertContains('Run artisan in the container: `docker compose exec app php artisan …`', $this->docker->steps($this->command));
}
}
Loading