feat: add one pull plug and play feature

This commit is contained in:
2026-05-18 11:28:38 +02:00
parent ad64766cd6
commit fc498379f6
11 changed files with 290 additions and 42 deletions

View File

@ -1,14 +0,0 @@
# Mot de passe Gitea (optionnel — si absent, le script le demande interactivement)
GITEA_PASSWORD=ton-mot-de-passe
# Serveur
JWT_SECRET=change-me-to-a-random-secret
ADMIN_USER=admin
ADMIN_PASSWORD=change-me
# Token pour l'agent local (même VM que le serveur)
LOCAL_AGENT_TOKEN=change-me-to-a-random-token
# Agents distants uniquement (docker-compose.agent.yml)
CONTAINARR_SERVER_URL=http://<ip-du-serveur>:9090
CONTAINARR_AGENT_TOKEN=<token-généré-par-le-serveur>

1
.gitignore vendored
View File

@ -29,7 +29,6 @@ push.sh
*.db-shm *.db-shm
.env .env
.env.* .env.*
!.env.example
# ── OS ──────────────────────────────────────────────────────────────────────── # ── OS ────────────────────────────────────────────────────────────────────────
.DS_Store .DS_Store

View File

@ -5,6 +5,6 @@ services:
volumes: volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro - /var/run/docker.sock:/var/run/docker.sock:ro
environment: environment:
CONTAINARR_SERVER_URL: "${CONTAINARR_SERVER_URL}" CONTAINARR_SERVER_URL: "http://<ip-du-serveur>:9090"
CONTAINARR_AGENT_TOKEN: "${CONTAINARR_AGENT_TOKEN}" CONTAINARR_AGENT_TOKEN: "<token-généré-depuis-l-interface-admin>"
RUST_LOG: "info" RUST_LOG: "info"

View File

@ -11,22 +11,9 @@ services:
DB_PATH: /data/containarr.db DB_PATH: /data/containarr.db
HTTP_ADDR: ":8080" HTTP_ADDR: ":8080"
GRPC_ADDR: ":9090" GRPC_ADDR: ":9090"
JWT_SECRET: "${JWT_SECRET}" JWT_SECRET: "change-me-to-a-random-secret"
ADMIN_USER: "${ADMIN_USER}" ADMIN_USER: "admin"
ADMIN_PASSWORD: "${ADMIN_PASSWORD}" ADMIN_PASSWORD: "change-me"
BOOTSTRAP_TOKENS: "local:${LOCAL_AGENT_TOKEN}"
agent:
image: gitea.anthonybouteiller.ovh/blomios/containarr-agent:latest
restart: unless-stopped
depends_on:
- server
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
environment:
CONTAINARR_SERVER_URL: "http://server:9090"
CONTAINARR_AGENT_TOKEN: "${LOCAL_AGENT_TOKEN}"
RUST_LOG: "info"
volumes: volumes:
containarr-data: containarr-data:

View File

@ -488,6 +488,77 @@ func TestListContainers_WithData(t *testing.T) {
} }
} }
// ── DeleteAgent ───────────────────────────────────────────────────────────────
func TestDeleteAgent_Success(t *testing.T) {
h, s, reg, _ := newTestHandler(t)
_ = s.CreateAgentToken("a1", "t1", "host1")
reg.Register("a1", "host1", "", "ip", "arch", "os")
router := chi.NewRouter()
router.Delete("/api/v1/agents/{agentID}", h.DeleteAgent)
req, _ := http.NewRequest(http.MethodDelete, "/api/v1/agents/a1", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNoContent {
t.Fatalf("expected 204, got %d — body: %s", w.Code, w.Body.String())
}
// Agent must be gone from store
_, err := s.GetAgent("a1")
if err == nil {
t.Error("expected store error after deletion, got nil")
}
// Agent must be gone from registry
_, ok := reg.Get("a1")
if ok {
t.Error("expected agent to be deregistered from registry")
}
}
func TestDeleteAgent_NotInRegistry(t *testing.T) {
h, s, _, _ := newTestHandler(t)
_ = s.CreateAgentToken("a1", "t1", "host1")
// Agent not registered in registry (offline agent)
router := chi.NewRouter()
router.Delete("/api/v1/agents/{agentID}", h.DeleteAgent)
req, _ := http.NewRequest(http.MethodDelete, "/api/v1/agents/a1", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusNoContent {
t.Fatalf("expected 204 even when not in registry, got %d — body: %s", w.Code, w.Body.String())
}
_, err := s.GetAgent("a1")
if err == nil {
t.Error("expected store error after deletion, got nil")
}
}
func TestDeleteAgent_NonExistent(t *testing.T) {
h, _, _, _ := newTestHandler(t)
router := chi.NewRouter()
router.Delete("/api/v1/agents/{agentID}", h.DeleteAgent)
req, _ := http.NewRequest(http.MethodDelete, "/api/v1/agents/ghost", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
// DELETE on a non-existent ID is still 204 (idempotent)
if w.Code != http.StatusNoContent {
t.Fatalf("expected 204 for non-existent agent, got %d — body: %s", w.Code, w.Body.String())
}
}
// ── ContainerAction ─────────────────────────────────────────────────────────── // ── ContainerAction ───────────────────────────────────────────────────────────
func TestContainerAction_AgentNotConnected(t *testing.T) { func TestContainerAction_AgentNotConnected(t *testing.T) {

View File

@ -72,6 +72,16 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {
jsonOK(w, out) jsonOK(w, out)
} }
func (h *Handler) DeleteAgent(w http.ResponseWriter, r *http.Request) {
agentID := chi.URLParam(r, "agentID")
if err := h.store.DeleteAgent(agentID); err != nil {
http.Error(w, "store error", http.StatusInternalServerError)
return
}
h.registry.Deregister(agentID)
w.WriteHeader(http.StatusNoContent)
}
func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) { func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
agentID := chi.URLParam(r, "agentID") agentID := chi.URLParam(r, "agentID")
var body struct { var body struct {

View File

@ -44,6 +44,7 @@ func NewRouter(h *Handler) http.Handler {
r.Get("/agents", h.ListAgents) r.Get("/agents", h.ListAgents)
r.Post("/agents/token", h.CreateAgentToken) r.Post("/agents/token", h.CreateAgentToken)
r.Patch("/agents/{agentID}", h.UpdateAgent) r.Patch("/agents/{agentID}", h.UpdateAgent)
r.Delete("/agents/{agentID}", h.DeleteAgent)
r.Get("/containers", h.ListContainers) r.Get("/containers", h.ListContainers)
r.Post("/agents/{agentID}/containers/{containerID}/action", h.ContainerAction) r.Post("/agents/{agentID}/containers/{containerID}/action", h.ContainerAction)
r.Get("/agents/{agentID}/containers/{containerID}/logs", h.LogsWS) r.Get("/agents/{agentID}/containers/{containerID}/logs", h.LogsWS)

View File

@ -138,6 +138,11 @@ func (s *Store) UpdateAgentAlias(id, alias string) error {
return err return err
} }
func (s *Store) DeleteAgent(id string) error {
_, err := s.db.Exec(`DELETE FROM agents WHERE id = ?`, id)
return err
}
// ── Users ───────────────────────────────────────────────────────────────────── // ── Users ─────────────────────────────────────────────────────────────────────
func (s *Store) GetUserHash(username string) (string, error) { func (s *Store) GetUserHash(username string) (string, error) {

View File

@ -195,6 +195,54 @@ func TestUpdateAgentAlias(t *testing.T) {
} }
} }
func TestDeleteAgent(t *testing.T) {
s := newTestStore(t)
if err := s.CreateAgentToken("a1", "t1", "host1"); err != nil {
t.Fatalf("CreateAgentToken: %v", err)
}
if err := s.DeleteAgent("a1"); err != nil {
t.Fatalf("DeleteAgent: %v", err)
}
_, err := s.GetAgent("a1")
if err == nil {
t.Error("expected error after deletion, got nil")
}
}
func TestDeleteAgent_NotFound(t *testing.T) {
s := newTestStore(t)
// Deleting a non-existent agent should not error (DELETE is idempotent at SQL level)
if err := s.DeleteAgent("nonexistent"); err != nil {
t.Fatalf("DeleteAgent on missing id: %v", err)
}
}
func TestDeleteAgent_RemovesFromList(t *testing.T) {
s := newTestStore(t)
_ = s.CreateAgentToken("a1", "t1", "host1")
_ = s.CreateAgentToken("a2", "t2", "host2")
if err := s.DeleteAgent("a1"); err != nil {
t.Fatalf("DeleteAgent: %v", err)
}
agents, err := s.ListAgents()
if err != nil {
t.Fatalf("ListAgents: %v", err)
}
if len(agents) != 1 {
t.Fatalf("expected 1 agent after deletion, got %d", len(agents))
}
if agents[0].ID != "a2" {
t.Errorf("expected remaining agent to be a2, got %q", agents[0].ID)
}
}
func TestCreateAgentToken_IdempotentIgnore(t *testing.T) { func TestCreateAgentToken_IdempotentIgnore(t *testing.T) {
s := newTestStore(t) s := newTestStore(t)

View File

@ -58,6 +58,21 @@ async function apiFetch(input: string, init: RequestInit = {}): Promise<Response
return r; return r;
} }
export async function createAgentToken(hostname: string): Promise<{ agent_id: string; token: string }> {
const r = await apiFetch(`${BASE}/agents/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ hostname }),
});
if (!r.ok) throw new Error(`create token: ${r.status}`);
return r.json();
}
export async function deleteAgent(id: string): Promise<void> {
const r = await apiFetch(`${BASE}/agents/${id}`, { method: "DELETE" });
if (!r.ok) throw new Error(`delete agent: ${r.status}`);
}
export async function fetchAgents(): Promise<Agent[]> { export async function fetchAgents(): Promise<Agent[]> {
const r = await apiFetch(`${BASE}/agents`); const r = await apiFetch(`${BASE}/agents`);
if (!r.ok) throw new Error(`agents: ${r.status}`); if (!r.ok) throw new Error(`agents: ${r.status}`);

View File

@ -1,6 +1,6 @@
<script lang="ts"> <script lang="ts">
import { onMount } from "svelte"; import { onMount } from "svelte";
import { fetchAgents, updateAgent, type Agent } from "$lib/api"; import { fetchAgents, updateAgent, createAgentToken, deleteAgent, type Agent } from "$lib/api";
import { getToken } from "$lib/auth"; import { getToken } from "$lib/auth";
let agents = $state<Agent[]>([]); let agents = $state<Agent[]>([]);
@ -36,6 +36,52 @@
setTimeout(() => (toast = null), 3000); setTimeout(() => (toast = null), 3000);
} }
// ── Agent token creation ─────────────────────────────────────────────────
let tokenHostname = $state("");
let tokenResult = $state<{ agent_id: string; token: string } | null>(null);
let tokenCreating = $state(false);
let tokenError = $state<string | null>(null);
let tokenCopied = $state(false);
async function generateToken(e: SubmitEvent) {
e.preventDefault();
tokenError = null;
tokenResult = null;
tokenCreating = true;
try {
tokenResult = await createAgentToken(tokenHostname.trim());
tokenHostname = "";
} catch (err: any) {
tokenError = err.message;
} finally {
tokenCreating = false;
}
}
async function copyToken() {
if (!tokenResult) return;
await navigator.clipboard.writeText(tokenResult.token);
tokenCopied = true;
setTimeout(() => (tokenCopied = false), 2000);
}
// ── Agent deletion ────────────────────────────────────────────────────────
let deleting = $state<string | null>(null);
async function removeAgent(agent: Agent) {
if (!confirm(`Supprimer l'agent "${agent.alias || agent.hostname}" ? Cette action est irréversible.`)) return;
deleting = agent.id;
try {
await deleteAgent(agent.id);
agents = agents.filter(a => a.id !== agent.id);
showToast("Agent supprimé", true);
} catch (err: any) {
showToast(err.message, false);
} finally {
deleting = null;
}
}
// ── Password change ────────────────────────────────────────────────────── // ── Password change ──────────────────────────────────────────────────────
let pwCurrent = $state(""); let pwCurrent = $state("");
let pwNew = $state(""); let pwNew = $state("");
@ -144,6 +190,77 @@
<section> <section>
<h2 class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-4">Agents</h2> <h2 class="text-xs font-semibold text-slate-500 uppercase tracking-widest mb-4">Agents</h2>
<!-- Créer un token d'agent -->
<div class="card p-5 max-w-sm mb-6">
<h3 class="text-sm font-semibold text-slate-200 mb-1">Créer un token d'agent</h3>
<p class="text-xs text-slate-500 mb-4">
Génère un token d'authentification pour enregistrer un nouvel agent.
</p>
<form onsubmit={generateToken} class="space-y-3">
{#if tokenError}
<p class="text-xs text-signal-red bg-signal-red/10 border border-signal-red/20
rounded-lg px-3 py-2">{tokenError}</p>
{/if}
<div>
<label class="block text-xs text-slate-500 mb-1" for="token-hostname">Hostname de l'agent</label>
<input
id="token-hostname"
type="text"
required
bind:value={tokenHostname}
placeholder="ex: server-01"
class="w-full bg-abyss-700 border border-white/[0.08] rounded-lg px-3 py-2 text-sm
text-slate-100 placeholder-slate-600 outline-none focus:border-emerald/60
focus:ring-1 focus:ring-emerald/30 transition-all"
/>
</div>
<button
type="submit"
disabled={tokenCreating}
class="w-full bg-emerald hover:bg-emerald-bright disabled:opacity-50 text-white
text-sm font-medium py-2 rounded-lg transition-colors">
{tokenCreating ? "Génération…" : "Générer"}
</button>
</form>
{#if tokenResult}
<div class="mt-4 p-3 rounded-lg bg-signal-green/5 border border-signal-green/20 space-y-2">
<div class="flex items-center gap-1.5 text-xs font-semibold text-signal-green">
<svg class="w-3.5 h-3.5 shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
</svg>
Token généré — notez-le, il ne sera plus affiché !
</div>
<p class="text-xs text-slate-500 font-mono break-all select-all bg-abyss-800 rounded px-2 py-1.5 border border-white/[0.06]">
{tokenResult.token}
</p>
<button
onclick={copyToken}
class="w-full flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-lg text-xs
font-medium transition-all
{tokenCopied
? 'bg-signal-green/20 text-signal-green border border-signal-green/30'
: 'bg-abyss-700 hover:bg-abyss-600 text-slate-300 border border-white/[0.08]'}">
{#if tokenCopied}
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
</svg>
Copié !
{:else}
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"/>
</svg>
Copier le token
{/if}
</button>
</div>
{/if}
</div>
<!-- Liste des agents -->
<h3 class="text-xs font-semibold text-slate-600 uppercase tracking-wider mb-3">Agents enregistrés</h3>
{#if loadError} {#if loadError}
<p class="text-signal-red text-sm">{loadError}</p> <p class="text-signal-red text-sm">{loadError}</p>
{:else if agents.length === 0} {:else if agents.length === 0}
@ -158,7 +275,7 @@
<th class="px-4 py-3 text-left font-medium">IP</th> <th class="px-4 py-3 text-left font-medium">IP</th>
<th class="px-4 py-3 text-left font-medium">Arch / OS</th> <th class="px-4 py-3 text-left font-medium">Arch / OS</th>
<th class="px-4 py-3 text-left font-medium">Alias</th> <th class="px-4 py-3 text-left font-medium">Alias</th>
<th class="px-4 py-3 text-right font-medium"></th> <th class="px-4 py-3 text-right font-medium">Actions</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@ -186,6 +303,7 @@
/> />
</td> </td>
<td class="px-4 py-3 text-right"> <td class="px-4 py-3 text-right">
<div class="flex items-center justify-end gap-2">
<button <button
onclick={() => saveAlias(agent)} onclick={() => saveAlias(agent)}
disabled={saving === agent.id || editing[agent.id] === agent.alias} disabled={saving === agent.id || editing[agent.id] === agent.alias}
@ -193,6 +311,14 @@
bg-emerald/10 hover:bg-emerald/20 text-emerald border border-emerald/20"> bg-emerald/10 hover:bg-emerald/20 text-emerald border border-emerald/20">
{saving === agent.id ? "…" : "Sauvegarder"} {saving === agent.id ? "…" : "Sauvegarder"}
</button> </button>
<button
onclick={() => removeAgent(agent)}
disabled={deleting === agent.id}
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-all disabled:opacity-30
bg-signal-red/10 hover:bg-signal-red/20 text-signal-red border border-signal-red/20">
{deleting === agent.id ? "…" : "Supprimer"}
</button>
</div>
</td> </td>
</tr> </tr>
{/each} {/each}