CluPilotCloud/app/Provisioning/Jobs/ApplyVpnPeer.php

55 lines
1.6 KiB
PHP

<?php
namespace App\Provisioning\Jobs;
use App\Models\VpnPeer;
use App\Services\Wireguard\WireguardHub;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
/**
* Push one peer's desired state onto the hub. Runs on the provisioning queue
* because that is the only worker whose container owns wg0.
*
* Takes the public key rather than the model for the removal case: the row is
* already gone by then, and the hub still has to be told.
*/
class ApplyVpnPeer implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public function __construct(
public string $publicKey,
public ?string $allowedIp,
public bool $enabled,
) {
$this->onQueue('provisioning');
}
public static function for(VpnPeer $peer): self
{
return new self($peer->public_key, $peer->allowed_ip, $peer->enabled);
}
public function handle(WireguardHub $hub): void
{
if ($this->enabled && $this->allowedIp !== null) {
$hub->addPeer($this->publicKey, $this->allowedIp);
} else {
$hub->removePeer($this->publicKey);
}
// Reflect the change immediately instead of waiting for the next sync,
// so the console does not sit on "wird angewendet" for a whole minute.
VpnPeer::query()->where('public_key', $this->publicKey)->update([
'present' => $this->enabled,
'observed_at' => now(),
]);
}
}