Skip to content

Create daemons on initial site provisioning #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 28, 2025
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
23 changes: 23 additions & 0 deletions app/Actions/LineBreaksToArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace App\Actions;

use Illuminate\Support\Str;
use Lorisleiva\Actions\Concerns\AsAction;

class LineBreaksToArray
{
use AsAction;

public function handle(?string $content): ?array
{
return str($content)
->explode("\n")
->map(Str::squish(...))
->filter()
->values()
->all();
}
}
44 changes: 44 additions & 0 deletions app/Actions/ParseDaemonCommands.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

namespace App\Actions;

use App\Services\Syntax\CommandParser;
use App\Traits\CommandSyntax;
use App\Traits\CommandSyntaxParser;
use App\Traits\Outputifier;
use Lorisleiva\Actions\Concerns\AsAction;

class ParseDaemonCommands
{
use AsAction,
Outputifier,
CommandSyntax;

protected string $signature = '{command* : The command you want to run}
{--directory= : Working directory}
{--user= : User to run the command under}
{--processes=1 : How many processes to run}
{--startsecs= : The total number of seconds the program must stay running in order to consider the start successful}
{--stopwaitsecs=10 : The number of seconds Supervisor will allow for the daemon to gracefully stop before forced termination}
{--stopsignal=SIGTERM : The signal used to kill the program when a stop is requested}';

public function handle(array $commands): array
{
$definition = $this->definition($this->signature);

return array_map(function (string $command) use ($definition) {
$input = $this->input($command, $definition);

if (blank($input->getArgument('command'))) {
$this->failCommand("No command was specified for daemon creation: {$command}");

return [];
}

return array_filter([
'command' => implode(' ', $input->getArgument('command')),
...$input->getOptions(),
], fn ($value) => ! is_null($value));
}, $commands);
}
}
26 changes: 7 additions & 19 deletions app/Actions/ParseQueueCommands.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

namespace App\Actions;

use App\Services\Syntax\CommandParser;
use App\Traits\CommandSyntax;
use App\Traits\Outputifier;
use Illuminate\Console\Parser;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\StringInput;

class ParseQueueCommands
{
use AsAction,
Outputifier;
Outputifier,
CommandSyntax;

protected string $signature = '{connection : The name of the queue connection to work}
{--queue= : The names of the queues to work}
Expand All @@ -30,11 +30,10 @@ class ParseQueueCommands

public function handle(array $commands): array
{
$definition = $this->definition();
$definition = $this->definition($this->signature);

return array_map(function ($command) use ($definition) {
$input = new StringInput($command);
$input->bind($definition);
return array_map(function (string $command) use ($definition) {
$input = $this->input($command, $definition);

if (blank($input->getArgument('connection'))) {
$this->failCommand("No queue connection was specified for command: {$command}");
Expand All @@ -48,15 +47,4 @@ public function handle(array $commands): array
], fn ($value) => ! is_null($value));
}, $commands);
}

protected function definition(): InputDefinition
{
[, $arguments, $options] = Parser::parse($this->signature);

$definition = new InputDefinition();
$definition->setArguments($arguments);
$definition->setOptions($options);

return $definition;
}
}
2 changes: 2 additions & 0 deletions app/Commands/ProvisionCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

use App\Services\Forge\ForgeService;
use App\Services\Forge\Pipeline\AnnounceSiteOnSlack;
use App\Services\Forge\Pipeline\CreateDaemons;
use App\Services\Forge\Pipeline\CreateDatabase;
use App\Services\Forge\Pipeline\CreateQueueWorkers;
use App\Services\Forge\Pipeline\CreateWebhook;
Expand Down Expand Up @@ -62,6 +63,7 @@ public function handle(ForgeService $service): void
CreateWebhook::class,
RunOptionalCommands::class,
EnsureJobScheduled::class,
CreateDaemons::class,
CreateQueueWorkers::class,
PutCommentOnPullRequest::class,
AnnounceSiteOnSlack::class,
Expand Down
2 changes: 2 additions & 0 deletions app/Commands/TearDownCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
use App\Services\Forge\Pipeline\DestroySite;
use App\Services\Forge\Pipeline\FindServer;
use App\Services\Forge\Pipeline\FindSiteOrFail;
use App\Services\Forge\Pipeline\RemoveDaemons;
use App\Services\Forge\Pipeline\RemoveDatabaseUser;
use App\Services\Forge\Pipeline\RemoveExistingDeployKey;
use App\Services\Forge\Pipeline\RemoveInertiaSupport;
Expand All @@ -43,6 +44,7 @@ public function handle(ForgeService $service): void
RunOptionalCommands::class,
RemoveDatabaseUser::class,
RemoveExistingDeployKey::class,
RemoveDaemons::class,
DestroySite::class,
])
->then(fn () => $this->success('Environment teardown successful! All provisioned resources have been removed.'));
Expand Down
5 changes: 4 additions & 1 deletion app/Services/Forge/ForgeService.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ public function getSiteLink(): string

public function siteDirectory(): string
{
return sprintf('/home/%s/%s', $this->site->username, $this->site->name);
return Str::chopEnd(
subject: $this->site->attributes['web_directory'],
needle: $this->site->directory // usually only contains /public
);
}
}
6 changes: 6 additions & 0 deletions app/Services/Forge/ForgeSetting.php
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,11 @@ class ForgeSetting
*/
public ?string $queueWorkers;

/**
* The daemons to create on new site installation
*/
public ?string $daemons;

public function __construct()
{
$this->init(config('forge'));
Expand Down Expand Up @@ -271,6 +276,7 @@ protected function validate(array $configurations): \Illuminate\Validation\Valid
'inertia_ssr_enabled' => ['required', 'boolean'],
'github_create_deploy_key' => ['required', 'boolean'],
'queue_workers' => ['nullable', 'string'],
'daemons' => ['nullable', 'string'],
])->sometimes('git_provider', 'in:custom', function (Fluent $input) {
return $input->github_create_deploy_key === true;
});
Expand Down
45 changes: 45 additions & 0 deletions app/Services/Forge/Pipeline/CreateDaemons.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace App\Services\Forge\Pipeline;

use App\Actions\LineBreaksToArray;
use App\Actions\ParseDaemonCommands;
use App\Services\Forge\ForgeService;
use App\Traits\Outputifier;
use Closure;

class CreateDaemons
{
use Outputifier;

public function __invoke(ForgeService $service, Closure $next)
{
if (! $service->setting->daemons || ! $service->siteNewlyMade) {
return $next($service);
}

$daemons = ParseDaemonCommands::run(
LineBreaksToArray::run($service->setting->daemons),
);

$this->information('Creating daemons.');

foreach ($daemons as $daemon) {
$service->forge->createDaemon(
serverId: $service->server->id,
data: array_merge(
[
// Defaults a daemon to run under the same user and directory as the current site.
'user' => $service->site->username,
'directory' => $service->siteDirectory(),
],
$daemon
)
);
}

return $next($service);
}
}
9 changes: 2 additions & 7 deletions app/Services/Forge/Pipeline/CreateQueueWorkers.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

namespace App\Services\Forge\Pipeline;

use App\Actions\LineBreaksToArray;
use App\Actions\ParseQueueCommands;
use App\Services\Forge\ForgeService;
use App\Traits\Outputifier;
use Closure;
use Illuminate\Support\Str;

class CreateQueueWorkers
{
Expand All @@ -21,12 +21,7 @@ public function __invoke(ForgeService $service, Closure $next)
}

$workers = ParseQueueCommands::run(
str($service->setting->queueWorkers)
->explode("\n")
->map(Str::squish(...))
->filter()
->values()
->all()
LineBreaksToArray::run($service->setting->queueWorkers),
);

$this->information('Creating queue workers.');
Expand Down
72 changes: 72 additions & 0 deletions app/Services/Forge/Pipeline/RemoveDaemons.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace App\Services\Forge\Pipeline;

use App\Actions\LineBreaksToArray;
use App\Actions\ParseDaemonCommands;
use App\Services\Forge\ForgeService;
use App\Services\Forge\ForgeSetting;
use App\Traits\Outputifier;
use Closure;
use Illuminate\Support\Str;
use Laravel\Forge\Resources\Daemon;

class RemoveDaemons
{
use Outputifier;

public function __invoke(ForgeService $service, Closure $next)
{
$daemons = $service->forge->daemons($service->server->id);

$this->information('Deleting daemons');

foreach ($daemons as $daemon) {
// If the daemon is running under the same user as the site in user isolation mode.
if ($service->setting->siteIsolationRequired && $daemon->user === $service->site->username) {
$service->forge->deleteDaemon($service->server->id, $daemon->id);
$this->information("--> Deleted daemon under user: {$daemon->command}");

continue;
}

// If the daemon is running from the same directory as the site.
if (Str::contains(haystack: $daemon->directory, needles: $service->siteDirectory())) {
$service->forge->deleteDaemon($service->server->id, $daemon->id);
$this->information("--> Deleted daemon under directory: {$daemon->command}");

continue;
}

// If a daemon can be detected as being one that was configured by us.
if ($this->daemonWasAddedForThisSite($daemon, $service->setting)) {
$service->forge->deleteDaemon($service->server->id, $daemon->id);
$this->information("--> Deleted daemon created with site: {$daemon->command}");
}
}

return $next($service);
}

protected function daemonWasAddedForThisSite(Daemon $daemon, ForgeSetting $setting): bool
{
if (empty($setting->daemons)) {
return false;
}

$configuredDaemons = ParseDaemonCommands::run(
LineBreaksToArray::run($setting->daemons),
);

return collect($configuredDaemons)
->whereNotNull('user')
->whereNotNull('directory')
->contains(
fn (array $configuredDaemon) => $configuredDaemon['command'] === $daemon->command
&& $configuredDaemon['user'] === $daemon->user
&& $configuredDaemon['directory'] === $daemon->directory
);
}
}
29 changes: 29 additions & 0 deletions app/Traits/CommandSyntax.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace App\Traits;

use Illuminate\Console\Parser;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\StringInput;

trait CommandSyntax
{
protected function input(string $command, InputDefinition $definition): StringInput
{
$input = new StringInput($command);
$input->bind($definition);

return $input;
}

protected function definition(string $signature): InputDefinition
{
[, $arguments, $options] = Parser::parse($signature);

$definition = new InputDefinition();
$definition->setArguments($arguments);
$definition->setOptions($options);

return $definition;
}
}
3 changes: 3 additions & 0 deletions config/forge.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,7 @@

// The queue workers to be added to Forge site
'queue_workers' => env('FORGE_QUEUE_WORKERS'),

// The daemons to create on a Forge server
'daemons' => env('FORGE_DAEMONS'),
];
Loading
Loading