ddns.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. // ddns.go — módulo de orquestación "DDNS" (Fase 17.3).
  2. //
  3. // Instala ddns-scripts (apk/opkg según el router) y configura el servicio de
  4. // DNS dinámico (service_name, dominio, usuario/contraseña) en /etc/config/ddns,
  5. // luego arranca el servicio ddns. Reutiliza los Kinds de 17.1 (apk_install /
  6. // install para opkg) y el patrón de secciones del 17.2.
  7. package orchestr
  8. import (
  9. "fmt"
  10. "strings"
  11. "time"
  12. "github.com/gnacho/netpulse/agent/executor"
  13. )
  14. // ddnsSection es la sección UCI del servicio DDNS que gestiona este módulo.
  15. // El probe detecta si ya existe una sección activa; si no, se usa esta.
  16. const ddnsSection = "myddns"
  17. // DdnsDesired es el estado deseado del módulo DDNS.
  18. type DdnsDesired struct {
  19. Enabled bool `json:"enabled"`
  20. ServiceName string `json:"serviceName"` // proveedor (duckdns.org, dyndns.org...)
  21. Domain string `json:"domain"`
  22. Username string `json:"username"`
  23. Password string `json:"password"`
  24. // AllowNonGateway: gateway-only por defecto (patrón #120).
  25. AllowNonGateway bool `json:"allowNonGateway,omitempty"`
  26. }
  27. // DdnsScenario describe el estado del DDNS en el router.
  28. type DdnsScenario struct {
  29. // Manager: "apk" | "opkg" (gestor de paquetes del router).
  30. Manager string
  31. // Installed: /etc/init.d/ddns existe (ddns-scripts instalado).
  32. Installed bool
  33. // ActiveSection: hay una sección ddns con enabled='1'.
  34. ActiveSection bool
  35. // SectionExists: existe la sección ddnsSection en uci.
  36. SectionExists bool
  37. }
  38. // probeDdnsCmd detecta gestor, instalación y sección activa.
  39. const probeDdnsCmd = `echo '===PKG_MGR==='
  40. [ -x /usr/bin/apk ] && echo apk || echo opkg
  41. echo '===INSTALLED==='
  42. [ -x /etc/init.d/ddns ] && echo yes || echo no
  43. echo '===DDNS_UCI==='
  44. uci show ddns 2>/dev/null
  45. echo '===END==='`
  46. // DetectDdns ejecuta el probe y devuelve el escenario.
  47. func DetectDdns(run CommandRunner, host string) (DdnsScenario, error) {
  48. out, err := run.Run(host, probeDdnsCmd, 8*time.Second)
  49. if err != nil {
  50. return DdnsScenario{}, err
  51. }
  52. return parseDdns(out), nil
  53. }
  54. // parseDdns extrae el escenario del output del probe. Función pura.
  55. func parseDdns(out string) DdnsScenario {
  56. sc := DdnsScenario{}
  57. sections := splitSections(out)
  58. sc.Manager = strings.TrimSpace(firstNonEmpty(sections["PKG_MGR"]))
  59. sc.Installed = strings.TrimSpace(firstNonEmpty(sections["INSTALLED"])) == "yes"
  60. uci := strings.Join(sections["DDNS_UCI"], "\n")
  61. sc.SectionExists = strings.Contains(uci, "ddns."+ddnsSection+"=service")
  62. if strings.Contains(uci, "ddns."+ddnsSection+".enabled='1'") {
  63. sc.ActiveSection = true
  64. }
  65. return sc
  66. }
  67. // DdnsOps genera las Ops para activar/desactivar DDNS.
  68. func DdnsOps(desired DdnsDesired, sc DdnsScenario) []executor.Op {
  69. if !desired.Enabled {
  70. return ddnsDisableOps(sc)
  71. }
  72. // Si no hay sección, crearla (uci_set_named → sección nombrada).
  73. var ops []executor.Op
  74. if !sc.Installed {
  75. if sc.Manager == "apk" {
  76. ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "ddns-scripts"}, Desc: "Install ddns-scripts (apk)"})
  77. } else {
  78. ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "ddns-scripts"}, Desc: "Install ddns-scripts (opkg)"})
  79. }
  80. }
  81. // Configurar la sección service.
  82. if !sc.SectionExists {
  83. ops = append(ops, executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "ddns", "section": ddnsSection, "type": "service"}, Desc: "Create ddns service section"})
  84. }
  85. svcName := desired.ServiceName
  86. if svcName == "" {
  87. svcName = "duckdns.org"
  88. }
  89. ops = append(ops,
  90. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "enabled", "value": "1"}, Desc: "Enable ddns service"},
  91. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "service_name", "value": svcName}, Desc: "Set ddns provider"},
  92. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "domain", "value": desired.Domain}, Desc: "Set ddns domain"},
  93. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "username", "value": desired.Username}, Desc: "Set ddns username"},
  94. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "password", "value": desired.Password}, Desc: "Set ddns password"},
  95. executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "ddns"}, Desc: "Commit ddns config"},
  96. executor.Op{Kind: "service", Args: map[string]string{"name": "ddns", "action": "enable"}, Desc: "Enable ddns on boot"},
  97. executor.Op{Kind: "service", Args: map[string]string{"name": "ddns", "action": "start"}, Desc: "Start ddns service"},
  98. )
  99. return ops
  100. }
  101. // ddnsDisableOps desactiva el servicio sin desinstalar el paquete.
  102. func ddnsDisableOps(sc DdnsScenario) []executor.Op {
  103. if !sc.SectionExists && !sc.Installed {
  104. // No hay nada que desactivar.
  105. return []executor.Op{}
  106. }
  107. return []executor.Op{
  108. {Kind: "uci_set", Args: map[string]string{"config": "ddns", "section": ddnsSection, "option": "enabled", "value": "0"}, Desc: "Disable ddns service"},
  109. {Kind: "uci_commit", Args: map[string]string{"config": "ddns"}, Desc: "Commit ddns config"},
  110. {Kind: "service", Args: map[string]string{"name": "ddns", "action": "stop"}, Desc: "Stop ddns service"},
  111. {Kind: "service", Args: map[string]string{"name": "ddns", "action": "disable"}, Desc: "Disable ddns on boot"},
  112. }
  113. }
  114. // validateDdnsOps valida cada op contra el executor (usado en tests).
  115. func validateDdnsOps(ops []executor.Op) error {
  116. for _, op := range ops {
  117. if err := executor.Validate(op); err != nil {
  118. return fmt.Errorf("%s: %w", op.Desc, err)
  119. }
  120. }
  121. return nil
  122. }