feat: module viewLogs — streaming journalctl via WebSocket

- 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/logs.go : implémente modules.Module, routes /api/logs/units et /ws/logs
  - Utilise r.RunOnTarget et r.StreamOnTarget du Registry (pas d'accès internal)
  - Streaming journalctl -f via WebSocket
  - Enregistrement du nav item via r.RegisterNavItem
- frontend/logs.html : page de visualisation des journaux
  - Composant logsPage 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 03:42:15 +01:00
commit 15e1a32a7b
4 changed files with 349 additions and 0 deletions

11
backend/go.mod Normal file
View file

@ -0,0 +1,11 @@
module git.geronzi.fr/proxmoxPanel/viewLogs/backend
go 1.26
require (
git.geronzi.fr/proxmoxPanel/core/backend v0.0.0
github.com/gorilla/websocket v1.5.3
golang.org/x/crypto v0.49.0
)
replace git.geronzi.fr/proxmoxPanel/core/backend => ../../core/backend

126
backend/logs.go Normal file
View file

@ -0,0 +1,126 @@
// Module viewLogs — streaming journalctl via WebSocket.
// Dépôt indépendant : https://git.geronzi.fr/proxmoxPanel/viewLogs
package viewlogs
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"git.geronzi.fr/proxmoxPanel/core/backend/modules"
gorillaws "github.com/gorilla/websocket"
)
// LogsModule gère la lecture des journaux systemd via journalctl.
type LogsModule struct{}
// New crée un LogsModule.
func New() *LogsModule { return &LogsModule{} }
func (m *LogsModule) ID() string { return "viewLogs" }
// Register enregistre les routes du module dans le CORE.
func (m *LogsModule) Register(r modules.Registry) error {
r.RegisterNavItem(modules.NavItemDef{
ID: "viewLogs",
Href: "/viewLogs/logs.html",
Icon: "lnid-scroll-angular-1",
Color: "#38bdf8",
LabelKey: "nav.logs",
})
r.RegisterRoute("GET", "/api/logs/units", m.listUnits(r), false)
r.RegisterRoute("GET", "/ws/logs", m.streamLogs(r), false)
return nil
}
// listUnits retourne la liste des unités systemd présentes dans les journaux.
func (m *LogsModule) listUnits(r modules.Registry) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
target := req.URL.Query().Get("target")
if target == "" {
target = "host"
}
out, _ := r.RunOnTarget(target, "journalctl --field=_SYSTEMD_UNIT --no-pager 2>/dev/null | sort -u | head -300")
units := []string{}
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSpace(line)
if line != "" {
units = append(units, line)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(units)
}
}
// wsUpgrader pour les WebSockets du module.
var wsUpgrader = gorillaws.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}
// streamLogs ouvre un WebSocket et stream journalctl via SSH.
func (m *LogsModule) streamLogs(r modules.Registry) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
target := req.URL.Query().Get("target")
if target == "" {
target = "host"
}
unit := sanitizeUnit(req.URL.Query().Get("unit"))
linesStr := req.URL.Query().Get("lines")
lines := 100
if n, err := strconv.Atoi(linesStr); err == nil && n > 0 && n <= 2000 {
lines = n
}
conn, err := wsUpgrader.Upgrade(w, req, nil)
if err != nil {
return
}
defer conn.Close()
args := fmt.Sprintf("-f --no-pager -n %d", lines)
if unit != "" {
args += " -u " + unit
}
// Pour les cibles LXC, StreamOnTarget wrappera via pct exec
// On passe la commande journalctl directement ; buildTargetCmd dans le registry gère le wrapping
cmd := "journalctl " + args
output := make(chan string, 100)
if err := r.StreamOnTarget(target, cmd, output); err != nil {
conn.WriteMessage(gorillaws.TextMessage, []byte("Erreur : "+err.Error()))
return
}
done := make(chan struct{})
go func() {
defer close(done)
for chunk := range output {
if err := conn.WriteMessage(gorillaws.TextMessage, []byte(chunk)); err != nil {
break
}
}
}()
// Attendre fermeture WS
for {
_, _, err := conn.ReadMessage()
if err != nil {
break
}
}
<-done
}
}
func sanitizeUnit(unit string) string {
for _, c := range unit {
ok := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '-' || c == '.' || c == '_' || c == '@' || c == ':'
if !ok {
return ""
}
}
return unit
}

200
frontend/logs.html Normal file
View file

@ -0,0 +1,200 @@
<!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 — Journaux</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 logsPage — fourni par le module viewLogs
document.addEventListener('alpine:init', () => {
Alpine.data('logsPage', () => ({
lines: [],
target: 'host',
targets: [{ value: 'host', label: 'Host Proxmox' }],
unit: '',
units: [],
linesCount: '100',
following: false,
ws: null,
async init() {
await this.loadTargets()
await this.loadUnits()
},
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 loadUnits() {
try {
const res = await apiFetch(`/api/logs/units?target=${this.target}`)
if (res.ok) this.units = await res.json() || []
} catch(e) {}
},
async onTargetChange() {
this.stopFollow()
this.unit = ''
await this.loadUnits()
},
toggleFollow() {
if (this.following) {
this.stopFollow()
} else {
this.startFollow()
}
},
startFollow() {
this.lines = []
const token = encodeURIComponent(localStorage.getItem('pxp_token') || '')
const proto = location.protocol === 'https:' ? 'wss' : 'ws'
const unit = this.unit ? `&unit=${encodeURIComponent(this.unit)}` : ''
const url = `${proto}://${location.host}/ws/logs?token=${token}&target=${this.target}&lines=${this.linesCount}${unit}`
this.ws = new WebSocket(url)
this.following = true
this.ws.onmessage = (e) => {
const incoming = e.data.split('\n').filter(l => l !== '')
this.lines.push(...incoming)
if (this.lines.length > 3000) this.lines = this.lines.slice(-3000)
this.$nextTick(() => {
const el = this.$refs.logOutput
if (el) el.scrollTop = el.scrollHeight
})
}
this.ws.onclose = () => { this.following = false; this.ws = null }
this.ws.onerror = () => { this.following = false; this.ws = null }
},
stopFollow() {
if (this.ws) {
this.ws.close()
this.ws = null
}
this.following = false
},
clearLog() {
this.lines = []
},
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.logs')"></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="logsPage()" x-cloak>
<!-- Barre de contrôle -->
<div class="logs-toolbar">
<select class="neu-input logs-sel" x-model="target" @change="onTargetChange()">
<template x-for="tgt in targets" :key="tgt.value">
<option :value="tgt.value" x-text="tgt.label"></option>
</template>
</select>
<select class="neu-input logs-sel" x-model="unit">
<option value="" x-text="t('logs.unitAll')"></option>
<template x-for="u in units" :key="u">
<option :value="u" x-text="u"></option>
</template>
</select>
<select class="neu-input logs-sel-sm" x-model="linesCount">
<option value="50">50</option>
<option value="100">100</option>
<option value="200">200</option>
<option value="500">500</option>
</select>
<button class="neu-btn neu-btn--sm"
:class="following ? 'neu-btn--danger' : 'neu-btn--primary'"
@click="toggleFollow()">
<i :class="following ? 'lnid-stop' : 'lnid-play'"></i>
<span x-text="following ? t('logs.stopFollow') : t('logs.follow')"></span>
</button>
<button class="neu-btn neu-btn--sm" @click="clearLog()" :disabled="lines.length === 0">
<i class="lnid-trash-1"></i>
<span x-text="t('logs.clear')"></span>
</button>
</div>
<!-- Indicateur de connexion -->
<div class="logs-status" x-show="following">
<span class="logs-status-dot"></span>
<span x-text="t('logs.connecting')"></span>
</div>
<!-- Sortie des logs -->
<div class="neu-card logs-output-wrap">
<pre class="logs-output" x-ref="logOutput" x-show="lines.length > 0"><template x-for="(line, idx) in lines" :key="idx"><span x-text="line + '\n'"></span></template></pre>
<p class="empty-state logs-empty" x-show="lines.length === 0" x-text="t('logs.noLogs')"></p>
</div>
</div>
</main>
</div>
</body>
</html>

12
module.json Normal file
View file

@ -0,0 +1,12 @@
{
"id": "viewLogs",
"name": "Journaux",
"description": "Consultation des journaux système via journalctl en temps réel",
"version": "1.0.0",
"author": "proxmoxPanel",
"core_min_version": "1.0.0",
"nav_href": "/viewLogs/logs.html",
"nav_icon": "lnid-scroll-angular-1",
"nav_color": "#38bdf8",
"nav_label_key": "nav.logs"
}