feat: module viewServices — gestion services systemd via systemctl

- module.json : métadonnées du module (nav_href, nav_icon, nav_color, nav_label_key)
- backend/go.mod : dépendance sur core/backend via replace directive
- backend/services.go : implémente modules.Module, routes /api/services et /api/services/{name}/*
  - Utilise r.RunOnTarget du Registry (pas d'accès internal)
  - Liste services, statut détaillé, actions start/stop/restart/reload/enable/disable
  - Enregistrement du nav item via r.RegisterNavItem
- frontend/services.html : page de gestion des services systemd
  - Composant servicePage Alpine.js inline (autonome, indépendant de core app.js)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
enzo 2026-03-22 04:01:59 +01:00
commit f1d475c7e5
4 changed files with 408 additions and 0 deletions

10
backend/go.mod Normal file
View file

@ -0,0 +1,10 @@
module git.geronzi.fr/proxmoxPanel/viewServices/backend
go 1.26
require (
git.geronzi.fr/proxmoxPanel/core/backend v0.0.0
github.com/go-chi/chi/v5 v5.2.5
)
replace git.geronzi.fr/proxmoxPanel/core/backend => ../../core/backend

163
backend/services.go Normal file
View file

@ -0,0 +1,163 @@
// Module viewServices — gestion des services systemd via systemctl.
// Dépôt indépendant : https://git.geronzi.fr/proxmoxPanel/viewServices
package viewservices
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"git.geronzi.fr/proxmoxPanel/core/backend/modules"
"github.com/go-chi/chi/v5"
)
// ServicesModule gère les opérations systemctl sur le host et les LXC.
type ServicesModule struct{}
// New crée un ServicesModule.
func New() *ServicesModule { return &ServicesModule{} }
func (m *ServicesModule) ID() string { return "viewServices" }
// Register enregistre les routes du module dans le CORE.
func (m *ServicesModule) Register(r modules.Registry) error {
r.RegisterNavItem(modules.NavItemDef{
ID: "viewServices",
Href: "/viewServices/services.html",
Icon: "lnid-gear-2",
Color: "#fb923c",
LabelKey: "nav.services",
})
r.RegisterRoute("GET", "/api/services", m.listServices(r), false)
r.RegisterRoute("GET", "/api/services/{name}/status", m.serviceStatus(r), false)
r.RegisterRoute("POST", "/api/services/{name}/{action}", m.serviceAction(r), true)
return nil
}
// ServiceEntry représente un service systemd dans la liste.
type ServiceEntry struct {
Name string `json:"name"`
LoadState string `json:"load_state"`
ActiveState string `json:"active_state"`
SubState string `json:"sub_state"`
Description string `json:"description"`
}
// listServices retourne la liste des services systemd d'une cible.
// GET /api/services?target=host|lxc:ID
func (m *ServicesModule) listServices(r modules.Registry) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
target := req.URL.Query().Get("target")
if target == "" {
target = "host"
}
out, err := r.RunOnTarget(target, "systemctl list-units --type=service --all --no-legend --plain --no-pager 2>/dev/null")
if err != nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "Erreur commande SSH : " + err.Error()})
return
}
services := parseServiceList(out)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(services)
}
}
// parseServiceList parse la sortie de systemctl list-units.
func parseServiceList(output string) []ServiceEntry {
var services []ServiceEntry
for _, line := range strings.Split(output, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "UNIT") || strings.HasPrefix(line, "Legend") ||
strings.HasPrefix(line, "To show") || strings.HasPrefix(line, "Pass") {
continue
}
line = strings.TrimPrefix(line, "● ")
line = strings.TrimPrefix(line, " ")
fields := strings.Fields(line)
if len(fields) < 4 {
continue
}
name := strings.TrimSuffix(fields[0], ".service")
desc := ""
if len(fields) >= 5 {
desc = strings.Join(fields[4:], " ")
}
services = append(services, ServiceEntry{
Name: name,
LoadState: fields[1],
ActiveState: fields[2],
SubState: fields[3],
Description: desc,
})
}
return services
}
// serviceStatus retourne le statut détaillé d'un service.
// GET /api/services/{name}/status?target=host|lxc:ID
func (m *ServicesModule) serviceStatus(r modules.Registry) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
name := chi.URLParam(req, "name")
target := req.URL.Query().Get("target")
if target == "" {
target = "host"
}
out, _ := r.RunOnTarget(target, fmt.Sprintf("systemctl status %s --no-pager 2>&1", name))
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"output": out})
}
}
// serviceAction exécute une action (start/stop/restart/reload) sur un service.
// POST /api/services/{name}/{action}
// Body: { "target": "host" | "lxc:ID" }
func (m *ServicesModule) serviceAction(r modules.Registry) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
name := chi.URLParam(req, "name")
action := chi.URLParam(req, "action")
// Valider l'action pour éviter l'injection de commandes
allowed := map[string]bool{
"start": true, "stop": true, "restart": true,
"reload": true, "enable": true, "disable": true,
}
if !allowed[action] {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"error": "Action invalide"})
return
}
var body struct {
Target string `json:"target"`
}
if err := json.NewDecoder(req.Body).Decode(&body); err != nil || body.Target == "" {
body.Target = "host"
}
out, err := r.RunOnTarget(body.Target, fmt.Sprintf("systemctl %s %s 2>&1", action, name))
w.Header().Set("Content-Type", "application/json")
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": fmt.Sprintf("Erreur action %s sur %s : %v", action, name, err),
"output": out,
})
return
}
json.NewEncoder(w).Encode(map[string]string{
"message": fmt.Sprintf("Action « %s » exécutée sur %s", action, name),
"output": out,
})
}
}

223
frontend/services.html Normal file
View file

@ -0,0 +1,223 @@
<!DOCTYPE html>
<html lang="fr">
<head>
<script>(function(){document.documentElement.setAttribute("data-theme",localStorage.getItem("pxp_theme")||"dark");document.documentElement.setAttribute("data-sidebar",localStorage.getItem("pxp_sidebar_pos")||"left")})()</script>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ProxmoxPanel — Services</title>
<link rel="stylesheet" href="/css/neu.css" />
<link rel="stylesheet" href="/css/dark.css" />
<link rel="stylesheet" href="/css/light.css" />
<link rel="stylesheet" href="/css/pages.css" />
<link rel="stylesheet" href="/css/lineicons-duotone.css" />
<link rel="manifest" href="/manifest.json" />
<script src="/js/vendors/htmx.min.js"></script>
<script src="/js/vendors/swup.iife.js"></script>
<script src="/js/app.js"></script>
<script>
// Composant servicePage — fourni par le module viewServices
document.addEventListener('alpine:init', () => {
Alpine.data('servicePage', () => ({
services: [],
loading: false,
target: 'host',
targets: [{ value: 'host', label: 'Host Proxmox' }],
filter: '',
actioning: {},
get filtered() {
const q = this.filter.toLowerCase()
if (!q) return this.services
return this.services.filter(s =>
s.name.toLowerCase().includes(q) || (s.description || '').toLowerCase().includes(q)
)
},
async init() {
await this.loadTargets()
await this.load()
},
async loadTargets() {
try {
const res = await apiFetch('/api/proxmox/lxc')
if (res.ok) {
const lxc = await res.json() || []
this.targets = [
{ value: 'host', label: 'Host Proxmox' },
...lxc.map(c => ({ value: `lxc:${c.vmid}`, label: `LXC ${c.vmid} — ${c.name || 'CT'+c.vmid}` }))
]
}
} catch(e) {}
},
async load() {
this.loading = true
try {
const res = await apiFetch(`/api/services?target=${this.target}`)
if (res.ok) this.services = await res.json() || []
} finally {
this.loading = false
}
},
async action(name, act) {
this.actioning[name] = act
try {
const res = await apiFetch(`/api/services/${name}/${act}`, {
method: 'POST',
body: JSON.stringify({ target: this.target })
})
if (res.ok) {
Alpine.store('toasts').success(`${act} ${name}`)
await this.load()
} else {
const b = await res.json().catch(() => ({}))
Alpine.store('toasts').error(b.error || `Erreur ${act}`)
}
} catch(e) {
Alpine.store('toasts').error(e.message)
} finally {
this.actioning[name] = false
}
},
stateClass(svc) {
if (svc.active_state === 'active') return 'state-active'
if (svc.active_state === 'failed') return 'state-failed'
if (svc.active_state === 'inactive') return 'state-inactive'
return 'state-other'
},
t(key) { return Alpine.store('i18n').t(key) },
}))
})
</script>
<script src="/js/vendors/alpine.min.js" defer></script>
</head>
<body x-data x-init="$store.ui.init()">
<aside class="sidebar" x-data="sidebar()" :class="{ collapsed: collapsed }" x-cloak>
<div class="sidebar-header" @click="toggle()">
<i class="sidebar-logo lnid-layout-1"></i>
<span class="sidebar-title" x-show="!collapsed">ProxmoxPanel</span>
</div>
<nav class="sidebar-nav">
<template x-for="item in navItems" :key="item.id">
<a class="sidebar-link" :class="{ active: isActive(item.id) }" :href="item.href" @click.prevent="navigate(item.href)">
<i class="sidebar-icon" :class="item.iconClass" :style="iconStyle(item)"></i>
<span class="sidebar-label" x-show="!collapsed" x-text="t(item.labelKey)"></span>
</a>
</template>
</nav>
<div class="sidebar-footer">
<a class="sidebar-link" href="/profile.html" @click.prevent="navigate('/profile.html')">
<i class="sidebar-icon lnid-user-circle-1"></i>
<span class="sidebar-label" x-show="!collapsed" x-text="$store.auth.user?.username || t('nav.profile')"></span>
</a>
</div>
</aside>
<div class="main-layout">
<nav class="navbar" x-data="navbar()" x-cloak>
<h2 class="navbar-title" x-text="t('nav.services')"></h2>
<div class="navbar-actions">
<button class="neu-btn neu-btn--sm neu-btn--icon-sm" @click="toggleTheme()" :title="theme==='dark'?t('navbar.lightMode'):t('navbar.darkMode')">
<i :class="theme==='dark' ? 'lnid-sun-1' : 'lnid-moon-half-left-1'"></i>
</button>
<button class="neu-btn neu-btn--sm neu-btn--icon-sm" @click="logout()" :title="t('navbar.logout')">
<i class="lnid-power-button"></i>
</button>
</div>
</nav>
<main id="swup" class="page-content transition-fade">
<div x-data="servicePage()" x-cloak>
<!-- Barre de contrôle -->
<div class="services-toolbar">
<select class="neu-input services-target-sel" x-model="target" @change="load()">
<template x-for="tgt in targets" :key="tgt.value">
<option :value="tgt.value" x-text="tgt.label"></option>
</template>
</select>
<div class="services-search">
<i class="lnid-search-1"></i>
<input class="neu-input" type="text" x-model="filter"
:placeholder="t('services.filter')" />
</div>
<button class="neu-btn neu-btn--sm" @click="load()" :disabled="loading">
<i :class="loading ? 'spinner-sm' : 'lnid-refresh-circle-1-clockwise'"></i>
<span x-text="t('common.refresh')"></span>
</button>
</div>
<!-- Chargement -->
<div class="loading-state" x-show="loading && services.length === 0">
<div class="spinner-lg"></div>
<span>Chargement…</span>
</div>
<!-- Tableau des services -->
<div class="neu-card services-table-wrap" x-show="!loading || services.length > 0">
<table class="services-table">
<thead>
<tr>
<th x-text="t('services.status')"></th>
<th x-text="t('services.name')"></th>
<th x-text="t('services.substate')"></th>
<th x-text="t('services.description')"></th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<template x-for="svc in filtered" :key="svc.name">
<tr>
<td>
<span class="svc-state-dot" :class="stateClass(svc)"></span>
<span class="svc-state-label" x-text="svc.active_state"></span>
</td>
<td class="svc-name" x-text="svc.name"></td>
<td class="svc-sub" x-text="svc.sub_state"></td>
<td class="svc-desc" x-text="svc.description"></td>
<td class="svc-actions">
<button class="neu-btn neu-btn--sm neu-btn--success neu-btn--icon-sm"
@click="action(svc.name, 'start')"
:disabled="actioning[svc.name] || svc.active_state === 'active'"
:title="t('services.start')">
<span x-show="actioning[svc.name] === 'start'" class="spinner-sm"></span>
<i x-show="actioning[svc.name] !== 'start'" class="lnid-play"></i>
</button>
<button class="neu-btn neu-btn--sm neu-btn--danger neu-btn--icon-sm"
@click="action(svc.name, 'stop')"
:disabled="actioning[svc.name] || svc.active_state !== 'active'"
:title="t('services.stop')">
<span x-show="actioning[svc.name] === 'stop'" class="spinner-sm"></span>
<i x-show="actioning[svc.name] !== 'stop'" class="lnid-stop"></i>
</button>
<button class="neu-btn neu-btn--sm neu-btn--icon-sm"
@click="action(svc.name, 'restart')"
:disabled="actioning[svc.name]"
:title="t('services.restart')">
<span x-show="actioning[svc.name] === 'restart'" class="spinner-sm"></span>
<i x-show="actioning[svc.name] !== 'restart'" class="lnid-refresh-circle-1-clockwise"></i>
</button>
</td>
</tr>
</template>
<tr x-show="!loading && filtered.length === 0">
<td colspan="5" class="empty-state" style="text-align:center;padding:1.5rem"
x-text="t('services.noServices')"></td>
</tr>
</tbody>
</table>
</div>
</div>
</main>
</div>
</body>
</html>

12
module.json Normal file
View file

@ -0,0 +1,12 @@
{
"id": "viewServices",
"name": "Services",
"description": "Gestion des services systemd via systemctl",
"version": "1.0.0",
"author": "proxmoxPanel",
"core_min_version": "1.0.0",
"nav_href": "/viewServices/services.html",
"nav_icon": "lnid-gear-2",
"nav_color": "#fb923c",
"nav_label_key": "nav.services"
}