config.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. // config.go: carga de config del agente desde el entorno del proceso y el
  2. // env file (KEY=VALUE), extraída de cmd/netpulse-agent para que los
  3. // embedders reutilicen el mismo formato y validación.
  4. package runtime
  5. import (
  6. "log/slog"
  7. "os"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/gnacho/netpulse/agent/internal/tlspin"
  12. "github.com/gnacho/netpulse/agent/probe"
  13. )
  14. // DefaultEnvFile: env file por defecto del agente standalone.
  15. const DefaultEnvFile = "/etc/netpulse-agent.env"
  16. // ConfigError: falta una key obligatoria (env o env file).
  17. type ConfigError struct{ Key string }
  18. func (e *ConfigError) Error() string {
  19. return "falta " + e.Key + " (env o " + DefaultEnvFile + ")"
  20. }
  21. // LoadConfigFromEnv lee la config del entorno del proceso y del env file
  22. // (el env del proceso gana). envFile vacío respeta NETPULSE_ENV_FILE y, en
  23. // su defecto, DefaultEnvFile. Fail-fast si falta lo obligatorio.
  24. func LoadConfigFromEnv(envFile string) (Options, error) {
  25. if envFile == "" {
  26. envFile = os.Getenv("NETPULSE_ENV_FILE")
  27. if envFile == "" {
  28. envFile = DefaultEnvFile
  29. }
  30. }
  31. fromFile := loadEnvFile(envFile)
  32. get := func(key string) string {
  33. if v := os.Getenv(key); v != "" {
  34. return v
  35. }
  36. return fromFile[key]
  37. }
  38. opts := Options{
  39. Server: strings.TrimRight(get("NETPULSE_SERVER"), "/"),
  40. Token: get("NETPULSE_TOKEN"),
  41. Slug: get("NETPULSE_SLUG"),
  42. ServerFP: tlspin.Normalize(get("NETPULSE_SERVER_FP")),
  43. PairingToken: get("NETPULSE_PAIRING_TOKEN"),
  44. Interval: DefaultInterval,
  45. WanTarget: get("NETPULSE_WAN_TARGET"),
  46. GwTarget: get("NETPULSE_GW_TARGET"),
  47. HeartbeatFile: get("NETPULSE_HEARTBEAT_FILE"),
  48. EnvFile: envFile,
  49. }
  50. if v := get("NETPULSE_INTERVAL"); v != "" {
  51. if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
  52. opts.Interval = time.Duration(sec) * time.Second
  53. } else if d, err := time.ParseDuration(v); err == nil && d > 0 {
  54. opts.Interval = d
  55. } else {
  56. slog.Warn("[netpulse-agent] NETPULSE_INTERVAL inválido, usando 30s", "value", v)
  57. }
  58. }
  59. // NETPULSE_SCAN_INTERVAL (#699): mínimo entre scans de vecinos. "0" =
  60. // sin scans periódicos (solo on-demand vía refresh del server); número
  61. // en segundos o duración Go ("15m"). Sin valor: DefaultScanInterval.
  62. opts.ScanInterval = probe.DefaultScanInterval
  63. if v := get("NETPULSE_SCAN_INTERVAL"); v != "" {
  64. if v == "0" {
  65. opts.ScanInterval = probe.ScanDisabled
  66. } else if sec, err := strconv.Atoi(v); err == nil && sec > 0 {
  67. opts.ScanInterval = time.Duration(sec) * time.Second
  68. } else if d, err := time.ParseDuration(v); err == nil && d > 0 {
  69. opts.ScanInterval = d
  70. } else {
  71. slog.Warn("[netpulse-agent] NETPULSE_SCAN_INTERVAL inválido, usando 30m", "value", v)
  72. }
  73. }
  74. if err := opts.Validate(); err != nil {
  75. return Options{}, err
  76. }
  77. return opts, nil
  78. }
  79. // Validate comprueba lo obligatorio: SERVER y SLUG siempre; TOKEN salvo en
  80. // modo pairing (donde PAIRING_TOKEN lo sustituye).
  81. func (o Options) Validate() error {
  82. for _, kv := range [][2]string{
  83. {"NETPULSE_SERVER", o.Server},
  84. {"NETPULSE_SLUG", o.Slug},
  85. } {
  86. if strings.TrimSpace(kv[1]) == "" {
  87. return &ConfigError{kv[0]}
  88. }
  89. }
  90. if o.Token == "" && o.PairingToken == "" {
  91. return &ConfigError{"NETPULSE_TOKEN (o NETPULSE_PAIRING_TOKEN para bootstrap)"}
  92. }
  93. return nil
  94. }
  95. // loadEnvFile lee KEY=VALUE de un fichero env. Soporta líneas de comentario
  96. // completas (# al inicio) y comentarios inline (" #" tras el valor); estos
  97. // últimos se recortan antes de quitar comillas y espacios. Los valores que
  98. // genera el server (URL, token, FP SPKI) nunca contienen " #", así que
  99. // recortar en el primero es seguro.
  100. func loadEnvFile(path string) map[string]string {
  101. out := map[string]string{}
  102. data, err := os.ReadFile(path)
  103. if err != nil {
  104. return out
  105. }
  106. for _, line := range strings.Split(string(data), "\n") {
  107. line = strings.TrimSpace(line)
  108. if line == "" || strings.HasPrefix(line, "#") {
  109. continue
  110. }
  111. k, v, ok := strings.Cut(line, "=")
  112. if !ok {
  113. continue
  114. }
  115. if before, _, found := strings.Cut(v, " #"); found {
  116. v = before
  117. }
  118. out[strings.TrimSpace(k)] = strings.Trim(strings.TrimSpace(v), `"'`)
  119. }
  120. return out
  121. }