| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137 |
- // config.go: carga de config del agente desde el entorno del proceso y el
- // env file (KEY=VALUE), extraída de cmd/netpulse-agent para que los
- // embedders reutilicen el mismo formato y validación.
- package runtime
- import (
- "log/slog"
- "os"
- "strconv"
- "strings"
- "time"
- "github.com/gnacho/netpulse/agent/internal/tlspin"
- "github.com/gnacho/netpulse/agent/probe"
- )
- // DefaultEnvFile: env file por defecto del agente standalone.
- const DefaultEnvFile = "/etc/netpulse-agent.env"
- // ConfigError: falta una key obligatoria (env o env file).
- type ConfigError struct{ Key string }
- func (e *ConfigError) Error() string {
- return "falta " + e.Key + " (env o " + DefaultEnvFile + ")"
- }
- // LoadConfigFromEnv lee la config del entorno del proceso y del env file
- // (el env del proceso gana). envFile vacío respeta NETPULSE_ENV_FILE y, en
- // su defecto, DefaultEnvFile. Fail-fast si falta lo obligatorio.
- func LoadConfigFromEnv(envFile string) (Options, error) {
- if envFile == "" {
- envFile = os.Getenv("NETPULSE_ENV_FILE")
- if envFile == "" {
- envFile = DefaultEnvFile
- }
- }
- fromFile := loadEnvFile(envFile)
- get := func(key string) string {
- if v := os.Getenv(key); v != "" {
- return v
- }
- return fromFile[key]
- }
- opts := Options{
- Server: strings.TrimRight(get("NETPULSE_SERVER"), "/"),
- Token: get("NETPULSE_TOKEN"),
- Slug: get("NETPULSE_SLUG"),
- ServerFP: tlspin.Normalize(get("NETPULSE_SERVER_FP")),
- PairingToken: get("NETPULSE_PAIRING_TOKEN"),
- Interval: DefaultInterval,
- WanTarget: get("NETPULSE_WAN_TARGET"),
- GwTarget: get("NETPULSE_GW_TARGET"),
- HeartbeatFile: get("NETPULSE_HEARTBEAT_FILE"),
- EnvFile: envFile,
- }
- switch strings.ToLower(strings.TrimSpace(get("NETPULSE_ALLOW_INSECURE_COMMANDS"))) {
- case "1", "true", "yes", "on":
- opts.AllowInsecureCommands = true
- case "", "0", "false", "no", "off":
- default:
- slog.Warn("[netpulse-agent] NETPULSE_ALLOW_INSECURE_COMMANDS invalid, ignoring it",
- "value", get("NETPULSE_ALLOW_INSECURE_COMMANDS"))
- }
- if v := get("NETPULSE_INTERVAL"); v != "" {
- if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
- opts.Interval = time.Duration(sec) * time.Second
- } else if d, err := time.ParseDuration(v); err == nil && d > 0 {
- opts.Interval = d
- } else {
- slog.Warn("[netpulse-agent] NETPULSE_INTERVAL invalid, using 30s", "value", v)
- }
- }
- // NETPULSE_SCAN_INTERVAL (#699): mínimo entre scans de vecinos. "0" =
- // sin scans periódicos (solo on-demand vía refresh del server); número
- // en segundos o duración Go ("15m"). Sin valor: DefaultScanInterval.
- opts.ScanInterval = probe.DefaultScanInterval
- if v := get("NETPULSE_SCAN_INTERVAL"); v != "" {
- if v == "0" {
- opts.ScanInterval = probe.ScanDisabled
- } else if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
- opts.ScanInterval = time.Duration(sec) * time.Second
- } else if d, err := time.ParseDuration(v); err == nil && d > 0 {
- opts.ScanInterval = d
- } else {
- slog.Warn("[netpulse-agent] NETPULSE_SCAN_INTERVAL invalid, using 30m", "value", v)
- }
- }
- if err := opts.Validate(); err != nil {
- return Options{}, err
- }
- return opts, nil
- }
- // Validate comprueba lo obligatorio: SERVER y SLUG siempre; TOKEN salvo en
- // modo pairing (donde PAIRING_TOKEN lo sustituye).
- func (o Options) Validate() error {
- for _, kv := range [][2]string{
- {"NETPULSE_SERVER", o.Server},
- {"NETPULSE_SLUG", o.Slug},
- } {
- if strings.TrimSpace(kv[1]) == "" {
- return &ConfigError{kv[0]}
- }
- }
- if o.Token == "" && o.PairingToken == "" {
- return &ConfigError{"NETPULSE_TOKEN (o NETPULSE_PAIRING_TOKEN para bootstrap)"}
- }
- return nil
- }
- // loadEnvFile lee KEY=VALUE de un fichero env. Soporta líneas de comentario
- // completas (# al inicio) y comentarios inline (" #" tras el valor); estos
- // últimos se recortan antes de quitar comillas y espacios. Los valores que
- // genera el server (URL, token, FP SPKI) nunca contienen " #", así que
- // recortar en el primero es seguro.
- func loadEnvFile(path string) map[string]string {
- out := map[string]string{}
- data, err := os.ReadFile(path)
- if err != nil {
- return out
- }
- for _, line := range strings.Split(string(data), "\n") {
- line = strings.TrimSpace(line)
- if line == "" || strings.HasPrefix(line, "#") {
- continue
- }
- k, v, ok := strings.Cut(line, "=")
- if !ok {
- continue
- }
- if before, _, found := strings.Cut(v, " #"); found {
- v = before
- }
- out[strings.TrimSpace(k)] = strings.Trim(strings.TrimSpace(v), `"'`)
- }
- return out
- }
|