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

feat(agent): publish the uplink's global IPv6 in data.wan.ipv6 (#2275) (#2276)

Nacho 1 день назад
Родитель
Сommit
37999277fe
4 измененных файлов с 157 добавлено и 7 удалено
  1. 2 1
      CHANGELOG.md
  2. 1 1
      agent/VERSION
  3. 72 5
      agent/probe/probe.go
  4. 82 0
      agent/probe/probe_test.go

+ 2 - 1
CHANGELOG.md

@@ -9,7 +9,8 @@ y este proyecto se adhiere a [Versionado Semántico](https://semver.org/lang/es/
 
 ### Added
 
-- The WAN section accepts an optional `ipv6` field, so an external pusher that reads the uplink's global IPv6 (the gfiber pusher does) can push it instead of journalling it. The server passes it through to the WAN panel and to the WAN port tile, and a unit that reports only IPv6 keeps its address instead of being treated as having no WAN data. The native agent does not probe it yet, so nothing changes for routers on their own agent (#2226). Thanks to @brainnoms for the contract.
+- The native agent fills the WAN IPv6 it already had in hand: `ipv6-address` comes in the same ubus dump as the IPv4, and the parser now publishes the first global address (link-local and ULA skipped, a deprecated address only when nothing else is left) in `data.wan.ipv6`. A modem uplink gets it from the child netifd creates for it, and an uplink with no IPv4 still reports its v6. The SSH poller shares the parser, so both paths gain it at once, and a router without v6 keeps the field absent (#2275).
+- The WAN section accepts an optional `ipv6` field, so an external pusher that reads the uplink's global IPv6 (the gfiber pusher does) can push it instead of journalling it. The server passes it through to the WAN panel and to the WAN port tile, and a unit that reports only IPv6 keeps its address instead of being treated as having no WAN data (#2226). Thanks to @brainnoms for the contract.
 - The vendor catalog accepts a third mode, `node`, for pushers that must run on the monitored host itself: a Kubernetes node that reads its own kubelet and `/proc`, a Docker host, a storage box. The Integrations page registers the row, issues the token and shows the environment to set, and the server never downloads, installs, starts or stops anything there. Start and stop answer `not_managed`, update only refreshes the published version so the page can point at the download, edit keeps to the label and the interval, and the row stays `pending` until the pusher's first push makes it live (#2272).
 - A host that runs other machines - an RKE2 node, a PVE box, a Docker host - can report the guests nested inside it through an optional `workloads` section in the push: stable id, name, kind and state per guest. The server keeps the census as reported and shows it on the unit's detail page, a count and a list with each workload's state. It is detail data, not graph data: a node with a hundred pods does not draw a hundred clients (#2227). Thanks to @brainnoms for the contract.
 - A unit that is not the gateway can keep the neighbours of its uplink out of its client list. The agent reports its logical networks with their Linux devices, the router detail page shows a Client discovery panel with Automatic, On or Off per network, and Automatic ignores the network that carries the unit's uplink (`br-*` bridges excepted, where an AP's uplink is its own LAN). Only devices attributed from ARP alone are filtered: a wireless association or an FDB entry still wins (#2235).

+ 1 - 1
agent/VERSION

@@ -1 +1 @@
-3.0.52
+3.0.53

+ 72 - 5
agent/probe/probe.go

@@ -12,6 +12,7 @@ import (
 	"encoding/json"
 	"fmt"
 	"net"
+	"net/netip"
 	"os"
 	"regexp"
 	"sort"
@@ -750,11 +751,12 @@ type ifaceStatus struct {
 	// a modem uplink, the DHCPv6 side of a PPPoE one. It holds the address
 	// and the route its parent has none of, and cannot be configured or
 	// named in a policy, so it is only ever read through its parent.
-	Dynamic bool `json:"dynamic"`
-	IPV4    []struct {
-		Address    string `json:"address"`
-		PtpAddress string `json:"ptpaddress"`
-	} `json:"ipv4-address"`
+	Dynamic bool       `json:"dynamic"`
+	IPV4    []ubusIPv4 `json:"ipv4-address"`
+	// IPV6 es `ipv6-address` del dump: netifd lista ahí todas las
+	// direcciones del lado v6 (la global del ISP, la ULA del router y la
+	// link-local), así que elegir una no es quedarse con la primera.
+	IPV6  []ubusIPv6 `json:"ipv6-address"`
 	Route []struct {
 		Target  string `json:"target"`
 		Mask    int    `json:"mask"`
@@ -763,6 +765,21 @@ type ifaceStatus struct {
 	DNS []string `json:"dns-server"`
 }
 
+// ubusIPv4 es una entrada de `ipv4-address`.
+type ubusIPv4 struct {
+	Address    string `json:"address"`
+	PtpAddress string `json:"ptpaddress"`
+}
+
+// ubusIPv6 es una entrada de `ipv6-address`. Preferred llega crudo porque
+// netifd lo escribe de varias formas: segundos de vida, `true` cuando no
+// caduca, o ausente. Decodificarlo a int64 abortaría el parseo entero del
+// dump con un solo `true`, y con él el estado WAN completo.
+type ubusIPv6 struct {
+	Address   string          `json:"address"`
+	Preferred json.RawMessage `json:"preferred"`
+}
+
 func (s ifaceStatus) defaultNexthop() string {
 	for _, r := range s.Route {
 		if r.Target == "0.0.0.0" && r.Mask == 0 && r.Nexthop != "" {
@@ -829,6 +846,9 @@ func withChildFacts(parent ifaceStatus, ifaces []ifaceStatus) ifaceStatus {
 		if len(parent.IPV4) == 0 {
 			parent.IPV4 = c.IPV4
 		}
+		if len(parent.IPV6) == 0 {
+			parent.IPV6 = c.IPV6
+		}
 		if len(parent.Route) == 0 {
 			parent.Route = c.Route
 		}
@@ -847,6 +867,9 @@ func wanInfoFrom(s ifaceStatus) WanInfo {
 			info.Gateway = s.IPV4[0].PtpAddress
 		}
 	}
+	// #2275: la dirección global del lado v6, si el uplink tiene una. El
+	// campo es opcional en el payload y vacío en un router sin v6.
+	info.IPv6 = globalIPv6(s.IPV6)
 	// El gateway real es el nexthop de la ruta por defecto (0.0.0.0/0).
 	if nh := s.defaultNexthop(); nh != "" {
 		info.Gateway = nh
@@ -854,6 +877,50 @@ func wanInfoFrom(s ifaceStatus) WanInfo {
 	return info
 }
 
+// globalIPv6 elige la dirección que se publica como IPv6 del uplink: la
+// primera global, saltando link-local (fe80::/10), ULA (fc00::/7) y loopback.
+// Una dirección deprecada (`preferred` a cero) solo se usa cuando no queda
+// ninguna otra, de modo que un router en medio de un cambio de prefijo sigue
+// reportando algo en vez de nada.
+func globalIPv6(addrs []ubusIPv6) string {
+	fallback := ""
+	for _, a := range addrs {
+		raw := strings.TrimSpace(a.Address)
+		if i := strings.IndexByte(raw, '/'); i >= 0 {
+			raw = raw[:i]
+		}
+		addr, err := netip.ParseAddr(raw)
+		if err != nil || !addr.Is6() || addr.IsLinkLocalUnicast() || addr.IsPrivate() || addr.IsLoopback() || addr.IsUnspecified() {
+			continue
+		}
+		if deprecatedIPv6(a.Preferred) {
+			if fallback == "" {
+				fallback = addr.String()
+			}
+			continue
+		}
+		return addr.String()
+	}
+	return fallback
+}
+
+// deprecatedIPv6 dice si la vida preferida del dump marca la dirección como
+// deprecada: cero segundos o `false`. Ausente, `null` o `true` significan
+// "sin caducidad conocida", que no es lo mismo que deprecada.
+func deprecatedIPv6(raw json.RawMessage) bool {
+	switch strings.TrimSpace(string(raw)) {
+	case "", "null":
+		return false
+	case "false":
+		return true
+	}
+	var seconds int64
+	if err := json.Unmarshal(raw, &seconds); err == nil {
+		return seconds == 0
+	}
+	return false
+}
+
 // ParseWanStatus parsea el estado de la WAN (issue #276). Acepta las dos
 // formas: `ubus call network.interface dump` (y entonces elige el uplink
 // activo, ver pickUplink) y el status de una sola interfaz. Extrae proto,

+ 82 - 0
agent/probe/probe_test.go

@@ -1820,3 +1820,85 @@ func TestParseArpDevs(t *testing.T) {
 		t.Fatalf("devs %v, want 2 (la incompleta se descarta)", devs)
 	}
 }
+
+// #2275: la direccion global del uplink viaja en el WanInfo. netifd lista en
+// `ipv6-address` la link-local, la ULA del router y la global del ISP a la
+// vez, asi que quedarse con la primera seria publicar la interfaz equivocada.
+func TestParseWanStatusIPv6(t *testing.T) {
+	raw := `{"up":true,"proto":"dhcp","l3_device":"wan","device":"eth0.2",` +
+		`"ipv4-address":[{"address":"84.122.5.9","mask":24}],` +
+		`"ipv6-address":[` +
+		`{"address":"fe80::1","mask":64,"preferred":true,"valid":true},` +
+		`{"address":"fd00::1","mask":64,"preferred":9000,"valid":9000},` +
+		`{"address":"2a0c:5a80:1234::9","mask":64,"preferred":7200,"valid":7200}],` +
+		`"route":[{"target":"0.0.0.0","mask":0,"nexthop":"84.122.5.1"}]}`
+	info := ParseWanStatus([]byte(raw))
+	if info.IPv6 != "2a0c:5a80:1234::9" {
+		t.Fatalf("ipv6=%q, esperaba la global del SP", info.IPv6)
+	}
+	// Un `preferred` booleano en el dump no puede tirar el resto del parseo.
+	if info.IP != "84.122.5.9" || info.Gateway != "84.122.5.1" {
+		t.Fatalf("el dump con preferred booleano perdio el lado v4: %+v", info)
+	}
+}
+
+func TestParseWanStatusIPv6SoloNoGlobales(t *testing.T) {
+	raw := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
+		`"ipv4-address":[{"address":"192.168.9.7","mask":24}],` +
+		`"ipv6-address":[{"address":"fe80::1","mask":64},` +
+		`{"address":"fc00::1","mask":64,"preferred":3600}]}`
+	info := ParseWanStatus([]byte(raw))
+	if info.IPv6 != "" {
+		t.Fatalf("ipv6=%q, sin global el campo debe quedar vacio", info.IPv6)
+	}
+	if info.IP != "192.168.9.7" {
+		t.Fatalf("ip=%q, el lado v4 no cambia", info.IP)
+	}
+}
+
+// Una unidad solo v6 (o un ISP con CGNAT y sin v4) conserva la direccion.
+func TestParseWanStatusSoloIPv6(t *testing.T) {
+	raw := `{"interface":"wan","up":true,"proto":"dhcpv6","l3_device":"eth0.2",` +
+		`"ipv6-address":[{"address":"2a0c:5a80:1234::9","mask":64,"preferred":7200}]}`
+	info := ParseWanStatusPreferring([]byte(raw), "wan")
+	if info.IPv6 != "2a0c:5a80:1234::9" {
+		t.Fatalf("ipv6=%q", info.IPv6)
+	}
+	if info.IP != "" {
+		t.Fatalf("ip=%q, no hay v4 que publicar", info.IP)
+	}
+}
+
+// Deprecada (preferred a cero) solo como ultimo recurso: primero se prefiere
+// una viva, y si no queda ninguna se publica la deprecada en vez de nada.
+func TestParseWanStatusIPv6Deprecada(t *testing.T) {
+	both := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
+		`"ipv6-address":[{"address":"2a0c:5a80:1111::1","mask":64,"preferred":0},` +
+		`{"address":"2a0c:5a80:2222::1","mask":64,"preferred":1800}]}`
+	if got := ParseWanStatus([]byte(both)).IPv6; got != "2a0c:5a80:2222::1" {
+		t.Fatalf("ipv6=%q, esperaba la viva y no la deprecada", got)
+	}
+	only := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
+		`"ipv6-address":[{"address":"2a0c:5a80:1111::1","mask":64,"preferred":0}]}`
+	if got := ParseWanStatus([]byte(only)).IPv6; got != "2a0c:5a80:1111::1" {
+		t.Fatalf("ipv6=%q, la deprecada se publica cuando no hay otra", got)
+	}
+	falsy := `{"interface":"wan","up":true,"proto":"dhcp","l3_device":"eth0.2",` +
+		`"ipv6-address":[{"address":"2a0c:5a80:1111::1","mask":64,"preferred":false},` +
+		`{"address":"2a0c:5a80:3333::1","mask":64,"preferred":true}]}`
+	if got := ParseWanStatus([]byte(falsy)).IPv6; got != "2a0c:5a80:3333::1" {
+		t.Fatalf("ipv6=%q, `preferred:false` no puede ganar a una viva", got)
+	}
+}
+
+// El hijo que netifd crea para un modem lleva las direcciones que el padre no
+// tiene: si no se copian, el uplink reporta v4 sin v6.
+func TestWithChildFactsCopiaIPv6(t *testing.T) {
+	parent := ifaceStatus{Interface: "wwan", Dynamic: true, L3Device: "wwan0"}
+	child := ifaceStatus{Interface: "wwan_6", Dynamic: true, L3Device: "wwan0",
+		IPV6: []ubusIPv6{{Address: "2a0c:5a80:1234::9", Preferred: []byte("7200")}}}
+	got := withChildFacts(child, []ifaceStatus{parent})
+	if len(got.IPV6) != 1 || got.IPV6[0].Address != "2a0c:5a80:1234::9" {
+		t.Fatalf("ipv6 no copiada del padre: %+v", got.IPV6)
+	}
+}