Skip to content

An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.

2.4 KB
Raw Blame
<?php

namespace App\Livewire\Server;

use App\Models\Server;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Component;

class Swarm extends Component
{
    use AuthorizesRequests;

    public Server $server;

    public array $parameters = [];

    public bool $isSwarmManager;

    public bool $isSwarmWorker;

    #[Locked]
    public bool $canUseSwarm;

    public function mount(string $server_uuid)
    {
        try {
            $this->server = Server::ownedByCurrentTeam()->whereUuid($server_uuid)->firstOrFail();
            $this->parameters = get_route_parameters();
            $this->canUseSwarm = $this->server->team->usesSwarm();
            $this->syncData();
        } catch (\Throwable) {
            return redirect()->route('server.index');
        }
    }

    private function syncData(bool $toModel = false): void
    {
        if ($toModel) {
            if (! $this->server->team->usesSwarm()) {
                throw new \Exception('Docker Swarm is deprecated and cannot be enabled for new teams.');
            }
            $this->server->settings->is_swarm_manager = $this->isSwarmManager;
            $this->server->settings->is_swarm_worker = $this->isSwarmWorker;
            $changedFields = auditChangedFields($this->server->settings);
            $this->server->settings->save();
            $this->auditSettingsUpdate($changedFields);
        } else {
            $this->isSwarmManager = $this->server->settings->is_swarm_manager;
            $this->isSwarmWorker = $this->server->settings->is_swarm_worker;
        }
    }

    public function instantSave()
    {
        try {
            $this->authorize('update', $this->server);
            $this->syncData(true);
            $this->dispatch('success', 'Swarm settings updated.');
        } catch (\Throwable $e) {
            return handleError($e, $this);
        }
    }

    public function render()
    {
        return view('livewire.server.swarm');
    }

    /**
     * @param  array<int, string>  $changedFields
     */
    private function auditSettingsUpdate(array $changedFields): void
    {
        if ($changedFields === []) {
            return;
        }

        auditLog('ui.server.settings_updated', [
            'team_id' => $this->server->team_id,
            'server_uuid' => $this->server->uuid,
            'server_name' => $this->server->name,
            'changed_fields' => $changedFields,
        ]);
    }
}