a73x

internal/agent/run/guestcidr.go

Ref:   Size: 1.3 KiB   History

package run

import (
	"log/slog"

	"github.com/a73x/eitri/internal/agent/state"
)

// resolveGuestCIDR decides which subnet this host's guests are on, and persists
// the answer the first time it produces one the identity lacks.
//
// join and serve both call this, which is the point: they are separate
// processes that used to source the subnet differently — join never had one and
// serve read the identity — so `eitri-agent join --bridge-cidr X` followed by a
// plain `eitri-agent` could silently re-home the host on the next start.
func resolveGuestCIDR(st *state.Store, cfg Config, suggestion string) string {
	if id, ok := st.Identity(); ok && id.BridgeCIDR != "" {
		return id.BridgeCIDR
	}
	for _, candidate := range []string{cfg.BridgeCIDR, suggestion} {
		if candidate == "" {
			continue
		}
		persistGuestCIDR(st, candidate)
		return candidate
	}
	return ""
}

// Best-effort: a failed write leaves the agent running on the value it
// resolved, and the next start resolves the same way from the same inputs.
func persistGuestCIDR(st *state.Store, cidr string) {
	id, ok := st.Identity()
	if !ok || id.BridgeCIDR == cidr {
		return
	}
	id.BridgeCIDR = cidr
	if err := st.SaveIdentity(id); err != nil {
		slog.Warn("persist guest cidr", "cidr", cidr, "err", err)
	}
}