v0.143.0 — guest RAM resize UI (R-24) — MinAgent: 0.90.0
The customer sees the guest's current memory + allowed range on the Rendszer settings page and resizes it. The controller proxies + maps the agent's machine code to Hungarian; the agent (felhom-agent v0.90.0) enforces every bound and applies live (no reboot). agentapi: GuestMemory + ResizeMemory; ruled 412 -> *MemoryRefusedError (code+bounds); pre-0.90 agent 404 -> typed *StatusError. Capability: FeatureGuestMemoryResize + featureMinAgent 0.90.0 + a featureProbes row (type-asserts GuestMemory so the shared SupportProber/netAgent are untouched). UI (internal/web/system_memory_handlers.go, settings_system.html): "Szerver memoria (RAM)" card + number input; POST /api/system/memory/resize -> capability gate -> agent -> flash. JS confirm only on shrink. Code->Hungarian map; agent-outdated hides the control; agent-unreachable falls back to the guest's /proc/meminfo. Agent English never shown raw. Tests: agentapi (decode, 404, refusal-code, capability table) + web handler (success/ below_usage_floor/agent_outdated). Gates + go build/vet/test all pass.
This commit is contained in:
@@ -1198,6 +1198,8 @@ func (s *Server) systemPageData() map[string]interface{} {
|
||||
// to. Empty = none set by the operator.
|
||||
data["ControllerFloor"] = s.updater.GetFloor()
|
||||
}
|
||||
// Guest RAM resize card (v0.143.0, R-24): current allocation + bounds + capability/reachability.
|
||||
s.memoryCardData(data)
|
||||
return data
|
||||
}
|
||||
|
||||
|
||||
@@ -109,6 +109,11 @@ type Server struct {
|
||||
// semantics — the add gate + the settings-page banner read it. Zero value ready.
|
||||
netFeatures agentapi.SupportCache
|
||||
|
||||
// memFeatures caches the guest-memory-resize capability probe (agent v0.90.0, R-24) — the resize
|
||||
// handler gate + the settings-page render read it. Zero value ready. memAgentFn is the test seam.
|
||||
memFeatures agentapi.SupportCache
|
||||
memAgentFn func() (memAgent, error)
|
||||
|
||||
// Asset syncer for Hub-managed assets (optional)
|
||||
assetsSyncer *assets.Syncer
|
||||
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/logx"
|
||||
)
|
||||
|
||||
// Guest RAM resize UI (v0.143.0, R-24; coupled to agent ≥ 0.90.0). The customer sees the guest's
|
||||
// current memory + the allowed range on the Rendszer settings page and resizes it; the request goes
|
||||
// to the agent's self-scoped /guest/memory, which enforces every bound. The controller only maps the
|
||||
// agent's machine `code` to a Hungarian message — the agent's English text is never shown raw.
|
||||
|
||||
// memAgent is the agent surface the memory UI needs (seam — tests inject a fake; production is the
|
||||
// shared *agentapi.Client). It carries NetVerifyStatus + AgentVersion so it satisfies the shared
|
||||
// SupportProber / version fast-path used by the capability cache (the agent has them anyway).
|
||||
type memAgent interface {
|
||||
GuestMemory(ctx context.Context) (agentapi.GuestMemoryInfo, error)
|
||||
ResizeMemory(ctx context.Context, memoryMB int64) (agentapi.MemoryResizeResult, error)
|
||||
NetVerifyStatus(ctx context.Context) (agentapi.NetVerifyStatus, error) // to satisfy SupportProber
|
||||
AgentVersion() string // version fast-path
|
||||
}
|
||||
|
||||
func (s *Server) memAgentForResize() (memAgent, error) {
|
||||
if s.memAgentFn != nil {
|
||||
return s.memAgentFn()
|
||||
}
|
||||
c, err := s.agentClient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// memUpdateNeededMsg is shown when the agent predates the resize endpoints (pre-0.90).
|
||||
const memUpdateNeededMsg = "A memória átméretezéséhez a kiszolgáló rendszerfrissítése szükséges."
|
||||
|
||||
// memAgentDownMsg is shown when the agent is unreachable — the value falls back to /proc/meminfo.
|
||||
const memAgentDownMsg = "A kiszolgáló ügynök jelenleg nem elérhető — próbáld meg később."
|
||||
|
||||
// memoryResizeMessage maps the agent's machine code (or success) to the customer's Hungarian line.
|
||||
func memoryResizeMessage(code string, res agentapi.MemoryResizeResult, bounds agentapi.GuestMemoryInfo) string {
|
||||
switch code {
|
||||
case "": // success
|
||||
if res.Unchanged {
|
||||
return fmt.Sprintf("A memória változatlan maradt: %d MB.", res.NewMB)
|
||||
}
|
||||
return fmt.Sprintf("A memória átméretezése megtörtént: %d MB → %d MB.", res.OldMB, res.NewMB)
|
||||
case "below_usage_floor":
|
||||
return fmt.Sprintf("A kért méret túl közel van a jelenlegi felhasználáshoz (%d MB). Állíts le néhány alkalmazást, majd próbáld újra.", bounds.UsageMB)
|
||||
case "below_min":
|
||||
return fmt.Sprintf("A minimális memória %d MB.", bounds.MinMB)
|
||||
case "above_max":
|
||||
return fmt.Sprintf("A megengedett maximum %d MB (a gazdagép tartaléka miatt).", bounds.MaxMB)
|
||||
default:
|
||||
return "A memória átméretezése nem sikerült. Próbáld meg később."
|
||||
}
|
||||
}
|
||||
|
||||
// memoryCardData fills the settings-page memory card. It never returns an error — every failure mode
|
||||
// degrades to an honest, render-safe state (supported=false, reachable=false + /proc/meminfo value).
|
||||
func (s *Server) memoryCardData(data map[string]interface{}) {
|
||||
data["MemorySupported"] = true // default; flipped to false only on a definite SupportNo
|
||||
data["MemoryReachable"] = false
|
||||
data["MemoryProcMB"] = procMemTotalMB() // in-guest fallback (this container's own /proc/meminfo)
|
||||
|
||||
agent, err := s.memAgentForResize()
|
||||
if err != nil {
|
||||
return // agent not configured/reachable → reachable=false, proc fallback rendered
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Capability gate: only a DEFINITE SupportNo hides the control (SupportUnknown from a down agent
|
||||
// keeps it, with the honest unreachable note).
|
||||
if s.memFeatures.Supports(ctx, agent, agentapi.FeatureGuestMemoryResize) == agentapi.SupportNo {
|
||||
data["MemorySupported"] = false
|
||||
return
|
||||
}
|
||||
info, err := agent.GuestMemory(ctx)
|
||||
if err != nil {
|
||||
logx.Debugf(s.logger, "[web] memory card: GuestMemory failed: %v", err)
|
||||
return // reachable=false; the proc fallback shows the current size
|
||||
}
|
||||
data["MemoryReachable"] = true
|
||||
data["MemoryAllocatedMB"] = info.AllocatedMB
|
||||
data["MemoryUsageMB"] = info.UsageMB
|
||||
data["MemoryMinMB"] = info.MinMB
|
||||
data["MemoryMaxMB"] = info.MaxMB
|
||||
data["MemoryFloorMB"] = info.FloorMB
|
||||
data["MemoryHostTotalMB"] = info.HostTotalMB
|
||||
}
|
||||
|
||||
// ServeSystemAPI dispatches /api/system/* (currently the guest-memory resize surface).
|
||||
func (s *Server) ServeSystemAPI(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/system/memory" && r.Method == http.MethodGet:
|
||||
s.handleMemoryGet(w, r)
|
||||
case r.URL.Path == "/api/system/memory/resize" && r.Method == http.MethodPost:
|
||||
s.handleMemoryResize(w, r)
|
||||
default:
|
||||
writeDiskJSON(w, http.StatusNotFound, false, "ismeretlen végpont", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// handleMemoryGet returns the current allocation + bounds (the JS refreshes the card after a resize).
|
||||
func (s *Server) handleMemoryGet(w http.ResponseWriter, r *http.Request) {
|
||||
agent, err := s.memAgentForResize()
|
||||
if err != nil {
|
||||
writeDiskJSON(w, http.StatusBadGateway, false, memAgentDownMsg, nil)
|
||||
return
|
||||
}
|
||||
if s.memFeatures.Supports(r.Context(), agent, agentapi.FeatureGuestMemoryResize) == agentapi.SupportNo {
|
||||
writeDiskJSON(w, http.StatusPreconditionFailed, false, memUpdateNeededMsg, map[string]any{"code": "agent_outdated"})
|
||||
return
|
||||
}
|
||||
info, err := agent.GuestMemory(r.Context())
|
||||
if err != nil {
|
||||
writeDiskJSON(w, http.StatusBadGateway, false, memAgentDownMsg, nil)
|
||||
return
|
||||
}
|
||||
writeDiskJSON(w, http.StatusOK, true, "", info)
|
||||
}
|
||||
|
||||
// handleMemoryResize validates nothing itself (the agent is the authority) beyond parsing, gates on
|
||||
// capability, calls the agent, and maps the outcome to a Hungarian message + machine code.
|
||||
func (s *Server) handleMemoryResize(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
MemoryMB int64 `json:"memory_mb"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.MemoryMB <= 0 {
|
||||
writeDiskJSON(w, http.StatusBadRequest, false, "érvénytelen memória érték", nil)
|
||||
return
|
||||
}
|
||||
agent, err := s.memAgentForResize()
|
||||
if err != nil {
|
||||
writeDiskJSON(w, http.StatusBadGateway, false, memAgentDownMsg, nil)
|
||||
return
|
||||
}
|
||||
// Capability gate (publish-train backstop): refuse honestly on an agent that predates the resize.
|
||||
support, source := s.memFeatures.SupportsWithSource(r.Context(), agent, agentapi.FeatureGuestMemoryResize)
|
||||
logx.Debugf(s.logger, "[web] memory resize gate: %s=%s (source=%s)", agentapi.FeatureGuestMemoryResize, support, source)
|
||||
if support == agentapi.SupportNo {
|
||||
writeDiskJSON(w, http.StatusPreconditionFailed, false, memUpdateNeededMsg, map[string]any{"code": "agent_outdated"})
|
||||
return
|
||||
}
|
||||
|
||||
res, err := agent.ResizeMemory(r.Context(), req.MemoryMB)
|
||||
if err != nil {
|
||||
var refused *agentapi.MemoryRefusedError
|
||||
if errors.As(err, &refused) {
|
||||
s.logger.Printf("[INFO] [web] memory resize refused: code=%s target=%d", refused.Code, req.MemoryMB)
|
||||
writeDiskJSON(w, http.StatusPreconditionFailed, false,
|
||||
memoryResizeMessage(refused.Code, agentapi.MemoryResizeResult{}, refused.Bounds),
|
||||
map[string]any{"code": refused.Code})
|
||||
return
|
||||
}
|
||||
logx.Debugf(s.logger, "[web] memory resize agent error: %v", err)
|
||||
writeDiskJSON(w, http.StatusBadGateway, false, "A memória átméretezése nem sikerült — próbáld meg később.", nil)
|
||||
return
|
||||
}
|
||||
s.logger.Printf("[INFO] [web] memory resized: %d MB -> %d MB (unchanged=%v)", res.OldMB, res.NewMB, res.Unchanged)
|
||||
writeDiskJSON(w, http.StatusOK, true, memoryResizeMessage("", res, agentapi.GuestMemoryInfo{}),
|
||||
map[string]any{"old_mb": res.OldMB, "new_mb": res.NewMB, "unchanged": res.Unchanged})
|
||||
}
|
||||
|
||||
// procMemTotalMB reads MemTotal from this container's /proc/meminfo (the agent-unreachable fallback).
|
||||
// Returns 0 if unreadable (the template renders "n/a" then).
|
||||
func procMemTotalMB() int64 {
|
||||
raw, err := os.ReadFile("/proc/meminfo")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
if strings.HasPrefix(line, "MemTotal:") {
|
||||
f := strings.Fields(line)
|
||||
if len(f) >= 2 {
|
||||
if kb, err := strconv.ParseInt(f[1], 10, 64); err == nil {
|
||||
return kb / 1024 // kB → MB
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
|
||||
)
|
||||
|
||||
// fakeMemAgent is the memAgent seam for handler tests. AgentVersion drives the capability gate
|
||||
// (version fast-path); NetVerifyStatus is the SupportProber stub.
|
||||
type fakeMemAgent struct {
|
||||
info agentapi.GuestMemoryInfo
|
||||
resizeRes agentapi.MemoryResizeResult
|
||||
resizeErr error
|
||||
ver string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeMemAgent) GuestMemory(context.Context) (agentapi.GuestMemoryInfo, error) {
|
||||
return f.info, nil
|
||||
}
|
||||
func (f *fakeMemAgent) ResizeMemory(_ context.Context, _ int64) (agentapi.MemoryResizeResult, error) {
|
||||
f.calls++
|
||||
return f.resizeRes, f.resizeErr
|
||||
}
|
||||
func (f *fakeMemAgent) NetVerifyStatus(context.Context) (agentapi.NetVerifyStatus, error) {
|
||||
return agentapi.NetVerifyStatus{Phase: "none"}, nil
|
||||
}
|
||||
func (f *fakeMemAgent) AgentVersion() string { return f.ver }
|
||||
|
||||
func postResize(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/system/memory/resize", strings.NewReader(body))
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeSystemAPI(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
// Success → 200 with the Hungarian old→new message.
|
||||
func TestMemoryResize_Success(t *testing.T) {
|
||||
s := testServer(t)
|
||||
agent := &fakeMemAgent{ver: "0.90.0", resizeRes: agentapi.MemoryResizeResult{OldMB: 8192, NewMB: 12288}}
|
||||
s.memAgentFn = func() (memAgent, error) { return agent, nil }
|
||||
|
||||
w := postResize(t, s, `{"memory_mb":12288}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("resize = %d (%s), want 200", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "A memória átméretezése megtörtént: 8192 MB → 12288 MB.") {
|
||||
t.Errorf("success message missing: %s", w.Body.String())
|
||||
}
|
||||
if agent.calls != 1 {
|
||||
t.Errorf("ResizeMemory calls = %d, want 1", agent.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// below_usage_floor refusal → 412, the mapped Hungarian message, and the machine code (agent English
|
||||
// never shown raw).
|
||||
func TestMemoryResize_BelowUsageFloor(t *testing.T) {
|
||||
s := testServer(t)
|
||||
agent := &fakeMemAgent{
|
||||
ver: "0.90.0",
|
||||
resizeErr: &agentapi.MemoryRefusedError{
|
||||
Code: "below_usage_floor",
|
||||
Bounds: agentapi.GuestMemoryInfo{UsageMB: 3000, FloorMB: 3512, MinMB: 2048, MaxMB: 14336},
|
||||
Msg: "requested 3300 MB is too close to current usage 3000 MB (floor 3512 MB)",
|
||||
},
|
||||
}
|
||||
s.memAgentFn = func() (memAgent, error) { return agent, nil }
|
||||
|
||||
w := postResize(t, s, `{"memory_mb":3300}`)
|
||||
if w.Code != http.StatusPreconditionFailed {
|
||||
t.Fatalf("below_usage_floor = %d (%s), want 412", w.Code, w.Body.String())
|
||||
}
|
||||
body := w.Body.String()
|
||||
if !strings.Contains(body, `"code":"below_usage_floor"`) {
|
||||
t.Errorf("machine code missing: %s", body)
|
||||
}
|
||||
if !strings.Contains(body, "túl közel van a jelenlegi felhasználáshoz (3000 MB)") {
|
||||
t.Errorf("mapped Hungarian message missing: %s", body)
|
||||
}
|
||||
// The agent's raw English must NEVER surface.
|
||||
if strings.Contains(body, "requested 3300 MB is too close") {
|
||||
t.Errorf("agent English leaked to the customer: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
// A pre-0.90 agent (version < MinAgent) → the capability gate refuses up front with agent_outdated,
|
||||
// and ResizeMemory is NEVER called.
|
||||
func TestMemoryResize_AgentOutdated(t *testing.T) {
|
||||
s := testServer(t)
|
||||
agent := &fakeMemAgent{ver: "0.89.0"}
|
||||
s.memAgentFn = func() (memAgent, error) { return agent, nil }
|
||||
|
||||
w := postResize(t, s, `{"memory_mb":12288}`)
|
||||
if w.Code != http.StatusPreconditionFailed {
|
||||
t.Fatalf("outdated agent = %d (%s), want 412", w.Code, w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), `"code":"agent_outdated"`) {
|
||||
t.Errorf("agent_outdated code missing: %s", w.Body.String())
|
||||
}
|
||||
if !strings.Contains(w.Body.String(), "rendszerfrissítése szükséges") {
|
||||
t.Errorf("outdated Hungarian note missing: %s", w.Body.String())
|
||||
}
|
||||
if agent.calls != 0 {
|
||||
t.Errorf("ResizeMemory called %d times on a gated request — must be 0", agent.calls)
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card">
|
||||
<h3>Szerver memória (RAM)</h3>
|
||||
{{if .MemorySupported}}
|
||||
{{if .MemoryReachable}}
|
||||
<div class="settings-grid">
|
||||
<div class="settings-row">
|
||||
<span class="settings-label">Jelenlegi memória</span>
|
||||
<span class="settings-value mono">{{.MemoryAllocatedMB}} MB</span>
|
||||
</div>
|
||||
<div class="settings-row">
|
||||
<span class="settings-label">Felhasznált</span>
|
||||
<span class="settings-value mono">{{.MemoryUsageMB}} MB</span>
|
||||
</div>
|
||||
<div class="settings-row">
|
||||
<span class="settings-label">Megengedett tartomány</span>
|
||||
<span class="settings-value mono">{{.MemoryMinMB}} MB – {{.MemoryMaxMB}} MB</span>
|
||||
</div>
|
||||
<div class="settings-row" style="padding-top: 0.5em;">
|
||||
<span class="settings-label">Új méret (MB)</span>
|
||||
<span class="settings-value">
|
||||
<input type="number" id="mem-input" class="input mono" style="width:8em;"
|
||||
value="{{.MemoryAllocatedMB}}" min="{{.MemoryMinMB}}" max="{{.MemoryMaxMB}}" step="256"
|
||||
data-current="{{.MemoryAllocatedMB}}">
|
||||
<button class="btn btn-primary btn-sm" id="btn-mem-resize" onclick="resizeMemory()" style="margin-left:0.5em;">Átméretezés</button>
|
||||
<span id="mem-status-msg" style="margin-left:0.5em; display:none;"></span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{{else}}
|
||||
<div class="settings-grid">
|
||||
<div class="settings-row">
|
||||
<span class="settings-label">Jelenlegi memória</span>
|
||||
<span class="settings-value mono">{{if .MemoryProcMB}}{{.MemoryProcMB}} MB{{else}}n/a{{end}}</span>
|
||||
</div>
|
||||
</div>
|
||||
<p class="settings-card-desc">A kiszolgáló ügynök jelenleg nem elérhető — próbáld meg később.</p>
|
||||
{{end}}
|
||||
{{else}}
|
||||
<p class="settings-card-desc">A memória átméretezéséhez a kiszolgáló rendszerfrissítése szükséges.</p>
|
||||
{{end}}
|
||||
</div>
|
||||
|
||||
<div id="dialog-root"></div>
|
||||
<script>
|
||||
// Light overlay dialog (D1) — replaces the native blocking browser dialogs (same texts).
|
||||
@@ -220,6 +262,55 @@ function doTriggerUpdate() {
|
||||
});
|
||||
}
|
||||
|
||||
function resizeMemory() {
|
||||
var input = document.getElementById('mem-input');
|
||||
var target = parseInt(input.value, 10);
|
||||
var current = parseInt(input.getAttribute('data-current'), 10);
|
||||
if (isNaN(target) || target <= 0) {
|
||||
showMemMsg('Érvénytelen memória érték', true);
|
||||
return;
|
||||
}
|
||||
if (target < current) {
|
||||
openDialog({title:'Memória csökkentése', confirmLabel:'Csökkentés',
|
||||
message:'A memória csökkentése hatással lehet a futó alkalmazások teljesítményére. Biztosan folytatod?',
|
||||
onConfirm:function(){ doResizeMemory(target); }});
|
||||
return;
|
||||
}
|
||||
doResizeMemory(target);
|
||||
}
|
||||
function doResizeMemory(target) {
|
||||
var btn = document.getElementById('btn-mem-resize');
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'Átméretezés...';
|
||||
fetch('/api/system/memory/resize', {
|
||||
method:'POST', headers: Object.assign({'Content-Type':'application/json'}, csrfHeaders()),
|
||||
body: JSON.stringify({memory_mb: target})
|
||||
})
|
||||
.then(function(r) { return r.json(); })
|
||||
.then(function(data) {
|
||||
if (data.ok) {
|
||||
showMemMsg(data.error || data.message || 'Kész.', false);
|
||||
setTimeout(function(){ location.reload(); }, 1200);
|
||||
} else {
|
||||
showMemMsg(data.error || 'A művelet nem sikerült', true);
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Átméretezés';
|
||||
}
|
||||
})
|
||||
.catch(function() {
|
||||
showMemMsg('Kapcsolódási hiba', true);
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'Átméretezés';
|
||||
});
|
||||
}
|
||||
function showMemMsg(text, isErr) {
|
||||
var msg = document.getElementById('mem-status-msg');
|
||||
if (!msg) return;
|
||||
msg.textContent = text;
|
||||
msg.style.color = isErr ? 'var(--danger, #c0392b)' : 'var(--text-2)';
|
||||
msg.style.display = 'inline';
|
||||
}
|
||||
|
||||
function pollUntilBack() {
|
||||
var iv = setInterval(function() {
|
||||
fetch('/api/health')
|
||||
|
||||
Reference in New Issue
Block a user