80 lines
2.8 KiB
PHP
80 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace App\Actions\Registries;
|
|
|
|
use App\Enums\BuildArtifactStatus;
|
|
use App\Enums\OperationKind;
|
|
use App\Enums\OperationStatus;
|
|
use App\Models\BuildArtifact;
|
|
use App\Models\Operation;
|
|
use App\Models\Registry;
|
|
use App\Models\Server;
|
|
use App\Services\Registries\ManagedRegistryOperationScripts;
|
|
use App\Services\Registries\ManagedRegistryRetention;
|
|
use RuntimeException;
|
|
|
|
class CreateManagedRegistryMaintenanceOperation
|
|
{
|
|
public function __construct(
|
|
private readonly ManagedRegistryRetention $retention,
|
|
private readonly ManagedRegistryOperationScripts $scripts,
|
|
) {}
|
|
|
|
public function execute(Registry $registry): Operation
|
|
{
|
|
$server = $registry->controlServer;
|
|
|
|
if (! $server instanceof Server) {
|
|
throw new RuntimeException('A control/build server is required to prune the managed registry.');
|
|
}
|
|
|
|
$activeBuilds = $registry->organisation->applications()
|
|
->whereHas('environments.buildArtifacts', fn ($query) => $query
|
|
->where('status', BuildArtifactStatus::BUILDING)
|
|
->where('registry_ref', 'like', rtrim((string) $registry->url, '/').'/%'))
|
|
->exists();
|
|
|
|
if ($activeBuilds) {
|
|
throw new RuntimeException('Managed registry pruning cannot run while builds are active.');
|
|
}
|
|
|
|
$this->retention->markPrunable($registry);
|
|
$artifacts = $this->prunableArtifacts($registry);
|
|
$maintenance = $this->scripts->maintenance($registry, $artifacts);
|
|
|
|
$operation = $server->operations()->create([
|
|
'kind' => OperationKind::REGISTRY_MAINTENANCE,
|
|
'status' => OperationStatus::PENDING,
|
|
'metadata' => [
|
|
'registry_id' => $registry->id,
|
|
'artifact_ids' => $artifacts->pluck('id')->values()->all(),
|
|
],
|
|
]);
|
|
|
|
$operation->steps()->create([
|
|
'name' => 'Delete prunable manifests and run registry GC',
|
|
'order' => 1,
|
|
'status' => OperationStatus::PENDING,
|
|
'script' => $maintenance['script'],
|
|
'secrets' => $maintenance['secrets'],
|
|
]);
|
|
|
|
return $operation->refresh();
|
|
}
|
|
|
|
/**
|
|
* @return \Illuminate\Support\Collection<int, BuildArtifact>
|
|
*/
|
|
private function prunableArtifacts(Registry $registry): \Illuminate\Support\Collection
|
|
{
|
|
return $registry->organisation->applications()
|
|
->with(['environments.buildArtifacts' => fn ($query) => $query
|
|
->where('status', BuildArtifactStatus::PRUNABLE)
|
|
->where('registry_ref', 'like', rtrim((string) $registry->url, '/').'/%')])
|
|
->get()
|
|
->flatMap(fn ($application) => $application->environments)
|
|
->flatMap(fn ($environment) => $environment->buildArtifacts)
|
|
->values();
|
|
}
|
|
}
|