feat(servers): add cross-instance server migration (#11075)

This commit is contained in:
Andras Bacsai authored and GitHub committed 2026-08-07 23:07:55 +02:00
1 parent c15e3b35fd
commit f9caa5250d
36 files changed
+7675 -15

No files matched your search

+9
View File
@@ -327,6 +327,15 @@ class Show extends Component
{
try {
$this->authorize('update', $this->server);
if (! $this->server->canBeValidated()) {
$this->dispatch(
'error',
'Cannot revalidate',
'This server was transferred to another Coolify instance. Manage it from the target instance instead.'
);
return;
}
if ($this->server->vultr_instance_id) {
$status = $this->server->refreshVultrState();
$this->server->refresh();
+198
View File
@@ -0,0 +1,198 @@
<?php
namespace App\Livewire\Server;
use App\Models\Server;
use App\Services\ServerTransfer\ServerTransferBundle;
use App\Services\ServerTransfer\ServerTransferClaimer;
use App\Services\ServerTransfer\ServerTransferExporter;
use App\Services\ServerTransfer\ServerTransferMigrator;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Throwable;
class Transfer extends Component
{
use AuthorizesRequests;
public Server $server;
/** Primary one-click migrate fields */
public string $targetUrl = '';
public string $targetToken = '';
public bool $writeRemote = false;
/** Advanced */
public bool $showAdvanced = false;
public string $passphrase = '';
public bool $encryptBundle = false;
public bool $writeRemoteOnClaim = false;
public bool $rebindSentinelOnClaim = true;
public ?string $exportId = null;
/** @var list<string> */
public array $lastWarnings = [];
public ?string $lastResultJson = null;
public function mount(string $server_uuid): void
{
$this->ensureDevelopmentAvailability();
try {
$this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
$this->authorize('view', $this->server);
$this->exportId = data_get($this->server->server_metadata, 'transfer.export_id');
} catch (Throwable $e) {
handleError($e, $this);
$this->redirect(route('server.index'), navigate: true);
}
}
public function getTransferStatusProperty(): ?string
{
return data_get($this->server->fresh()->server_metadata, 'transfer.status');
}
public function getIsLocalhostProperty(): bool
{
return (int) $this->server->id === 0;
}
public function migrateServer(ServerTransferMigrator $migrator): void
{
$this->ensureDevelopmentAvailability();
try {
$this->authorize('update', $this->server);
if ($this->isLocalhost) {
throw new \RuntimeException('The Coolify host (localhost) cannot be transferred.');
}
$result = $migrator->migrate(
server: $this->server,
targetUrl: $this->targetUrl,
targetToken: $this->targetToken,
writeRemote: $this->writeRemote,
);
$this->server->refresh();
$this->exportId = $result['export_id'] ?? $this->exportId;
$this->lastWarnings = array_values((array) data_get($result, 'warnings', []));
// Never echo the target token in the result dump.
$safe = $result;
unset($safe['target_token']);
$this->lastResultJson = json_encode($safe, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$this->targetToken = '';
$this->dispatch('success', $result['message'] ?? 'Server transferred.');
} catch (Throwable $e) {
handleError($e, $this);
}
}
public function exportBundle(ServerTransferExporter $exporter)
{
$this->ensureDevelopmentAvailability();
try {
$this->authorize('view', $this->server);
if ($this->isLocalhost) {
throw new \RuntimeException('The Coolify host (localhost) cannot be transferred.');
}
$bundle = $exporter->export($this->server, includeSensitive: true);
$this->exportId = data_get($bundle, 'export_id');
$this->lastWarnings = array_values((array) data_get($bundle, 'warnings', []));
$this->lastResultJson = null;
$payload = $bundle;
$fileName = 'server-transfer-'.$this->server->uuid.'.json';
if ($this->encryptBundle) {
if (blank($this->passphrase)) {
throw new \RuntimeException('Passphrase is required to encrypt the bundle.');
}
$payload = ServerTransferBundle::encryptWithPassphrase($bundle, $this->passphrase);
$fileName = 'server-transfer-'.$this->server->uuid.'.encrypted.json';
}
$json = json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($json === false) {
throw new \RuntimeException('Failed to encode transfer bundle.');
}
$this->dispatch('success', 'Transfer bundle ready for download.');
return response()->streamDownload(function () use ($json) {
echo $json;
}, $fileName, [
'Content-Type' => 'application/json',
]);
} catch (Throwable $e) {
return handleError($e, $this);
}
}
public function completeTransfer(ServerTransferClaimer $claimer): void
{
$this->ensureDevelopmentAvailability();
try {
$this->authorize('update', $this->server);
if ($this->isLocalhost) {
throw new \RuntimeException('The Coolify host cannot be marked as transferred.');
}
$result = $claimer->markTransferred(
$this->server,
exportId: $this->exportId ?: data_get($this->server->server_metadata, 'transfer.export_id'),
targetInstanceUrl: filled($this->targetUrl) ? rtrim($this->targetUrl, '/') : null,
);
$this->server->refresh();
$this->lastResultJson = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$this->dispatch('success', $result['message'] ?? 'Server marked as transferred.');
} catch (Throwable $e) {
handleError($e, $this);
}
}
public function claimServer(ServerTransferClaimer $claimer): void
{
$this->ensureDevelopmentAvailability();
try {
$this->authorize('update', $this->server);
if ($this->isLocalhost) {
throw new \RuntimeException('The Coolify host cannot be claimed.');
}
$result = $claimer->claim(
$this->server,
writeRemote: $this->writeRemoteOnClaim,
rebindSentinel: $this->rebindSentinelOnClaim,
);
$this->server->refresh();
$this->lastResultJson = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$this->lastWarnings = [];
$this->dispatch('success', $result['message'] ?? 'Server claimed.');
} catch (Throwable $e) {
handleError($e, $this);
}
}
public function render()
{
return view('livewire.server.transfer');
}
private function ensureDevelopmentAvailability(): void
{
abort_unless(isDev(), 404);
}
}
+147
View File
@@ -0,0 +1,147 @@
<?php
namespace App\Livewire\Server;
use App\Models\Server;
use App\Services\ServerTransfer\ServerTransferBundle;
use App\Services\ServerTransfer\ServerTransferImporter;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Livewire\WithFileUploads;
use Throwable;
class TransferImport extends Component
{
use AuthorizesRequests;
use WithFileUploads;
public string $bundleJson = '';
public string $passphrase = '';
public bool $preserveUuids = true;
public bool $adoptMode = true;
/** Write ownership file on the host via SSH when claiming after import. */
public bool $writeRemote = false;
/** @var TemporaryUploadedFile|null */
public $bundleFile = null;
/** @var array<string, mixed>|null */
public ?array $lastResult = null;
/** @var list<string> */
public array $lastWarnings = [];
public ?string $importedServerUuid = null;
public function mount(): void
{
$this->ensureDevelopmentAvailability();
$this->authorize('create', Server::class);
}
public function updatedBundleFile(): void
{
$this->ensureDevelopmentAvailability();
if (! $this->bundleFile) {
return;
}
try {
$contents = $this->bundleFile->get();
if (! is_string($contents) || blank($contents)) {
throw new \RuntimeException('Uploaded file is empty.');
}
$this->bundleJson = $contents;
$this->dispatch('success', 'Bundle file loaded into the form.');
} catch (Throwable $e) {
handleError($e, $this);
}
}
/**
* @return array<string, mixed>
*/
private function resolveBundle(): array
{
$raw = trim($this->bundleJson);
if ($raw === '') {
throw new \RuntimeException('Paste a transfer bundle JSON or upload a file.');
}
$decoded = json_decode($raw, true);
if (! is_array($decoded)) {
throw new \RuntimeException('Bundle is not valid JSON.');
}
if (data_get($decoded, 'encrypted')) {
if (blank($this->passphrase)) {
throw new \RuntimeException('Passphrase is required for encrypted bundles.');
}
return ServerTransferBundle::decryptWithPassphrase($decoded, $this->passphrase);
}
return $decoded;
}
public function dryRun(ServerTransferImporter $importer): void
{
$this->ensureDevelopmentAvailability();
$this->runImport($importer, dryRun: true);
}
public function importBundle(ServerTransferImporter $importer): void
{
$this->ensureDevelopmentAvailability();
$this->runImport($importer, dryRun: false);
}
private function runImport(ServerTransferImporter $importer, bool $dryRun): void
{
try {
$this->authorize('create', Server::class);
$teamId = currentTeam()->id;
$bundle = $this->resolveBundle();
$result = $importer->import(
bundle: $bundle,
teamId: $teamId,
dryRun: $dryRun,
preserveUuids: $this->preserveUuids,
adoptMode: $this->adoptMode,
claim: ! $dryRun,
writeRemote: $this->writeRemote,
rebindSentinel: true,
);
$this->lastResult = $result;
$this->lastWarnings = array_values((array) data_get($result, 'warnings', []));
$this->importedServerUuid = $dryRun ? null : data_get($result, 'server_uuid');
if ($dryRun) {
$this->dispatch('success', 'Dry run completed — nothing was written.');
} elseif (data_get($result, 'claimed')) {
$this->dispatch('success', 'Server imported and claimed for this instance.');
} else {
$this->dispatch('success', 'Server imported. Claim did not complete — check warnings or re-claim from the server Transfer page.');
}
} catch (Throwable $e) {
handleError($e, $this);
}
}
public function render()
{
return view('livewire.server.transfer-import');
}
private function ensureDevelopmentAvailability(): void
{
abort_unless(isDev(), 404);
}
}
@@ -53,6 +53,21 @@ class ValidateAndInstall extends Component
public function init(int $data = 0)
{
if (! $this->server->canBeValidated()) {
$this->error = 'This server was transferred to another Coolify instance and cannot be revalidated here.';
$this->server->update([
'validation_logs' => $this->error,
'is_validating' => false,
]);
$this->dispatch(
'error',
'Cannot revalidate',
$this->error
);
return;
}
$this->isInstalling = false;
$this->uptime = null;
$this->supported_os_type = null;