Просмотр исходного кода

fix(agent): delete the config backup from the unit once uploaded (#1897) (#1905)

* fix(agent): delete the config backup from the unit once uploaded (#1897)

* docs(changelog): cover the config backup cleanup (#1897)
Nacho 4 недель назад
Родитель
Сommit
dff6ce1acb
3 измененных файлов с 100 добавлено и 1 удалено
  1. 2 0
      CHANGELOG.md
  2. 9 1
      agent/runtime/config_backup.go
  3. 89 0
      agent/runtime/config_backup_test.go

+ 2 - 0
CHANGELOG.md

@@ -9,6 +9,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Fixed
 
+- A config backup no longer stays on the unit after it is uploaded (#1897). Every manual or scheduled backup wrote its tarball under `/tmp` and left it there, and on a router `/tmp` is RAM, so each snapshot took memory away until the next reboot. The agent now deletes the local file once the operation ends, whether the upload succeeded or not, since the copy that matters is the one the server keeps with retention. The firmware flow keeps its local backup on purpose: that one is reported in the result so it can be recovered by hand when sysupgrade fails.
+
 - The target version chosen on a firmware card stays where it was left (#1898). The selection lived only in the local state of the page, so a refresh, leaving and coming back, or the ten second auto-refresh that runs while an upgrade is in flight put the dropdown back to whatever the server had stored, and nothing was saved unless the separate Save button was pressed. Choosing a version now saves it, a reload no longer overwrites an edit that is still local, and scheduling a recurrence saves the target shown in the dialog before saving the schedule. That last case mattered beyond the dropdown: a scheduled run flashes the target stored on the server, and a unit with none had its recurrence disabled when it fired, with "no firmware target saved" as the only explanation.
 
 - A client is tagged with the VLAN its bridge actually sees (#1757). The forwarding table was read from one bridge only and every port carrying a dot was thrown away, so a router that segments with 802.1Q subinterfaces, where the real ports are `eth0.777` and `eth0.999`, lost its wired clients altogether: no port, no VLAN and no line in the topology. Every bridge the unit has is read now, a subinterface counts as a port, and each MAC carries the VLAN the bridge learned it on, which is the only evidence of where a client lives. A forwarding table without that field leaves the client without a VLAN instead of guessing one from the default of the port.

+ 9 - 1
agent/runtime/config_backup.go

@@ -12,6 +12,7 @@ package runtime
 import (
 	"fmt"
 	"net/http"
+	"os"
 	"path/filepath"
 	"time"
 )
@@ -23,9 +24,16 @@ func handleConfigBackup(opts Options, transport http.RoundTripper) {
 		log.Error("[netpulse-agent] config_backup: snapshot falló", "err", err)
 		return
 	}
+	// #1897: el tar.gz se borra siempre al terminar, suba o no. En el router
+	// /tmp es tmpfs (RAM), así que cada backup manual o programado se quedaba
+	// ocupando memoria hasta el próximo reinicio; la copia que importa es la
+	// que el server guarda con retención. El flujo de firmware NO hace esto:
+	// ahí el backup local se conserva a propósito para recuperarlo a mano si
+	// sysupgrade falla, y su ruta se reporta en el resultado.
+	defer os.Remove(backupPath)
 	if err := uploadBackup(opts, transport, backupPath); err != nil {
 		log.Error("[netpulse-agent] config_backup: subida falló", "err", err)
 		return
 	}
-	log.Info("[netpulse-agent] config_backup: backup subido", "path", backupPath)
+	log.Info("[netpulse-agent] config_backup: backup subido y temporal local eliminado")
 }

+ 89 - 0
agent/runtime/config_backup_test.go

@@ -0,0 +1,89 @@
+package runtime
+
+// #1897: el backup standalone de config dejaba el tar.gz en el dispositivo
+// tras subirlo. En un router /tmp es tmpfs, o sea RAM, así que cada backup
+// manual o programado restaba memoria hasta el reboot. Estos tests fijan que
+// el fichero local desaparece tanto si la subida va bien como si falla.
+
+import (
+	"net/http"
+	"net/http/httptest"
+	"os"
+	"path/filepath"
+	"sync"
+	"testing"
+)
+
+// stubConfigBackup apunta el tmp del firmware a un dir temporal y sustituye
+// sysupgrade por un script que crea el tar.gz que el handler espera.
+func stubConfigBackup(t *testing.T) string {
+	t.Helper()
+	dir := t.TempDir()
+	oldTmp := firmwareTmpDir
+	firmwareTmpDir = dir
+	t.Cleanup(func() { firmwareTmpDir = oldTmp })
+
+	fake := filepath.Join(dir, "sysupgrade")
+	// sysupgrade -b <dest>: el segundo argumento es el fichero a crear.
+	if err := os.WriteFile(fake, []byte("#!/bin/sh\nprintf 'tar' > \"$2\"\n"), 0o755); err != nil {
+		t.Fatalf("WriteFile sysupgrade fake: %v", err)
+	}
+	oldBin := sysupgradeBin
+	sysupgradeBin = fake
+	t.Cleanup(func() { sysupgradeBin = oldBin })
+	return dir
+}
+
+func leftoverConfigBackups(t *testing.T, dir string) []string {
+	t.Helper()
+	left, err := filepath.Glob(filepath.Join(dir, "netpulse-config-backup-*.tar.gz"))
+	if err != nil {
+		t.Fatalf("Glob: %v", err)
+	}
+	return left
+}
+
+func TestConfigBackupDeletesTheLocalTarball(t *testing.T) {
+	dir := stubConfigBackup(t)
+
+	var mu sync.Mutex
+	uploads := 0
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		if r.URL.Path != "/api/agents/patio/firmware-backup" {
+			w.WriteHeader(http.StatusNotFound)
+			return
+		}
+		mu.Lock()
+		uploads++
+		mu.Unlock()
+		w.WriteHeader(http.StatusOK)
+	}))
+	defer srv.Close()
+
+	handleConfigBackup(Options{Server: srv.URL, Slug: "patio", Token: "tok"}, nil)
+
+	mu.Lock()
+	if uploads != 1 {
+		t.Fatalf("subidas = %d, quiero 1", uploads)
+	}
+	mu.Unlock()
+	if left := leftoverConfigBackups(t, dir); len(left) != 0 {
+		t.Fatalf("quedan backups en el dispositivo tras subir: %v", left)
+	}
+}
+
+func TestConfigBackupDeletesTheLocalTarballWhenUploadFails(t *testing.T) {
+	dir := stubConfigBackup(t)
+
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.WriteHeader(http.StatusInternalServerError)
+	}))
+	defer srv.Close()
+
+	handleConfigBackup(Options{Server: srv.URL, Slug: "patio", Token: "tok"}, nil)
+
+	// Sin reintento posterior, un fichero huérfano solo sirve para gastar RAM.
+	if left := leftoverConfigBackups(t, dir); len(left) != 0 {
+		t.Fatalf("quedan backups en el dispositivo tras una subida fallida: %v", left)
+	}
+}