sqm.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. // sqm.go — módulo de orquestación "QoS / SQM" (Fase 17.4).
  2. //
  3. // Instala sqm-scripts (apk/opkg según el router) y configura Smart Queue
  4. // Management (SQM) en la interfaz elegida: sección UCI `queue` con download,
  5. // upload, qdisc y script, y arranca el servicio `sqm`. Reutiliza los Kinds de
  6. // 17.1 (apk_install / install) y el patrón de índices @queue[n] del 17.2.
  7. package orchestr
  8. import (
  9. "fmt"
  10. "strings"
  11. "time"
  12. "github.com/gnacho/netpulse/agent/executor"
  13. )
  14. // sqmDefaults: valores por defecto razonables para OpenWrt cuando el desired
  15. // no los trae (mismos que la UI LuCI de sqm-scripts).
  16. const (
  17. sqmDefaultQdisc = "cake"
  18. sqmDefaultScript = "piece_of_cake.qos"
  19. sqmDefaultLink = "ethernet"
  20. sqmDefaultOverhead = "44"
  21. )
  22. // SqmDesired es el estado deseado del módulo QoS.
  23. type SqmDesired struct {
  24. Enabled bool `json:"enabled"`
  25. // Interface: interfaz WAN/LAN a gestionar (p. ej. "eth1"). Obligatoria.
  26. Interface string `json:"interface"`
  27. // Download / Upload: ancho de banda en kbit/s (p. ej. "85000").
  28. Download string `json:"download"`
  29. Upload string `json:"upload"`
  30. // Qdisc / Script: disciplinas y script de SQM (defaults LuCI).
  31. Qdisc string `json:"qdisc"`
  32. Script string `json:"script"`
  33. Linklayer string `json:"linklayer"`
  34. Overhead string `json:"overhead"`
  35. // AllowNonGateway: gateway-only por defecto (patrón #120).
  36. AllowNonGateway bool `json:"allowNonGateway,omitempty"`
  37. }
  38. // SqmSection es una sección `queue` del config sqm.
  39. type SqmSection struct {
  40. // Idx: referencia UCI "@queue[n]" (o nombre si la sección es nombrada).
  41. Idx string
  42. // Interface: valor de option interface.
  43. Interface string
  44. // Enabled: option enabled == '1'.
  45. Enabled bool
  46. }
  47. // SqmScenario describe el estado del SQM en el router.
  48. type SqmScenario struct {
  49. // Manager: "apk" | "opkg" (gestor de paquetes del router).
  50. Manager string
  51. // Installed: /etc/init.d/sqm existe (sqm-scripts instalado).
  52. Installed bool
  53. // Sections: secciones queue existentes en uci.
  54. Sections []SqmSection
  55. }
  56. // probeSqmCmd detecta gestor, instalación y secciones sqm.
  57. const probeSqmCmd = `echo '===PKG_MGR==='
  58. [ -x /usr/bin/apk ] && echo apk || echo opkg
  59. echo '===INSTALLED==='
  60. [ -x /etc/init.d/sqm ] && echo yes || echo no
  61. echo '===SQM_UCI==='
  62. uci show sqm 2>/dev/null
  63. echo '===END==='`
  64. // DetectSqm ejecuta el probe y devuelve el escenario.
  65. func DetectSqm(run CommandRunner, host string) (SqmScenario, error) {
  66. out, err := run.Run(host, probeSqmCmd, 8*time.Second)
  67. if err != nil {
  68. return SqmScenario{}, err
  69. }
  70. return parseSqm(out), nil
  71. }
  72. // parseSqm extrae el escenario del output del probe. Función pura.
  73. //
  74. // Formato de `uci show sqm`:
  75. //
  76. // sqm.@queue[0]=queue
  77. // sqm.@queue[0].interface='eth1'
  78. // sqm.@queue[0].enabled='0'
  79. // sqm.@queue[0].download='85000'
  80. // ...
  81. func parseSqm(out string) SqmScenario {
  82. sc := SqmScenario{}
  83. sections := splitSections(out)
  84. sc.Manager = strings.TrimSpace(firstNonEmpty(sections["PKG_MGR"]))
  85. sc.Installed = strings.TrimSpace(firstNonEmpty(sections["INSTALLED"])) == "yes"
  86. uci := strings.Join(sections["SQM_UCI"], "\n")
  87. // Secciones: líneas "sqm.@queue[n]=queue" o "sqm.<nombre>=queue".
  88. for _, line := range strings.Split(uci, "\n") {
  89. line = strings.TrimSpace(line)
  90. if !strings.HasPrefix(line, "sqm.") || !strings.HasSuffix(line, "=queue") {
  91. continue
  92. }
  93. raw := strings.TrimSuffix(strings.TrimPrefix(line, "sqm."), "=queue")
  94. sec := SqmSection{Idx: raw}
  95. // Leer option interface y enabled de la sección.
  96. if v := sqmOptionValue(uci, raw, "interface"); v != "" {
  97. sec.Interface = v
  98. }
  99. if v := sqmOptionValue(uci, raw, "enabled"); v == "1" {
  100. sec.Enabled = true
  101. }
  102. sc.Sections = append(sc.Sections, sec)
  103. }
  104. return sc
  105. }
  106. // sqmOptionValue lee el valor de una option de una sección en el output de
  107. // `uci show sqm` ("sqm.@queue[0].interface='eth1'" → "eth1").
  108. func sqmOptionValue(uci, section, option string) string {
  109. prefix := "sqm." + section + "." + option + "="
  110. for _, line := range strings.Split(uci, "\n") {
  111. line = strings.TrimSpace(line)
  112. if strings.HasPrefix(line, prefix) {
  113. return strings.Trim(strings.TrimPrefix(line, prefix), "'")
  114. }
  115. }
  116. return ""
  117. }
  118. // SqmOps genera las Ops para activar/desactivar SQM.
  119. func SqmOps(desired SqmDesired, sc SqmScenario) []executor.Op {
  120. if !desired.Enabled {
  121. return sqmDisableOps(desired, sc)
  122. }
  123. iface := desired.Interface
  124. if iface == "" {
  125. if len(sc.Sections) > 0 {
  126. iface = sc.Sections[0].Interface
  127. }
  128. }
  129. if iface == "" {
  130. iface = "eth1" // fallback razonable (la mayoría de routers OpenWrt)
  131. }
  132. // Resolver la sección a gestionar: la que ya tenga esa interfaz, o la
  133. // primera existente, o crear una nueva (@queue[-1]).
  134. idx := sqmSectionFor(sc, iface)
  135. var ops []executor.Op
  136. if !sc.Installed {
  137. if sc.Manager == "apk" {
  138. ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "sqm-scripts"}, Desc: "Install sqm-scripts (apk)"})
  139. } else {
  140. ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "sqm-scripts"}, Desc: "Install sqm-scripts (opkg)"})
  141. }
  142. }
  143. if idx == "" {
  144. ops = append(ops, executor.Op{Kind: "uci_add", Args: map[string]string{"config": "sqm", "type": "queue"}, Desc: "Create sqm queue section"})
  145. idx = "@queue[-1]"
  146. }
  147. ops = append(ops,
  148. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "enabled", "value": "1"}, Desc: "Enable SQM"},
  149. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "interface", "value": iface}, Desc: "Set SQM interface " + iface},
  150. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "download", "value": sqmOrDefault(desired.Download, "100000")}, Desc: "Set download bandwidth"},
  151. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "upload", "value": sqmOrDefault(desired.Upload, "20000")}, Desc: "Set upload bandwidth"},
  152. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "qdisc", "value": sqmOrDefault(desired.Qdisc, sqmDefaultQdisc)}, Desc: "Set SQM qdisc"},
  153. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "script", "value": sqmOrDefault(desired.Script, sqmDefaultScript)}, Desc: "Set SQM script"},
  154. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "linklayer", "value": sqmOrDefault(desired.Linklayer, sqmDefaultLink)}, Desc: "Set SQM link layer"},
  155. executor.Op{Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "overhead", "value": sqmOrDefault(desired.Overhead, sqmDefaultOverhead)}, Desc: "Set SQM overhead"},
  156. executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "sqm"}, Desc: "Commit sqm config"},
  157. executor.Op{Kind: "service", Args: map[string]string{"name": "sqm", "action": "enable"}, Desc: "Enable sqm on boot"},
  158. executor.Op{Kind: "service", Args: map[string]string{"name": "sqm", "action": "start"}, Desc: "Start sqm service"},
  159. )
  160. return ops
  161. }
  162. // sqmDisableOps desactiva SQM sin desinstalar el paquete.
  163. func sqmDisableOps(desired SqmDesired, sc SqmScenario) []executor.Op {
  164. iface := desired.Interface
  165. if iface == "" && len(sc.Sections) > 0 {
  166. iface = sc.Sections[0].Interface
  167. }
  168. idx := sqmSectionFor(sc, iface)
  169. if idx == "" {
  170. // No hay sección que desactivar.
  171. return []executor.Op{}
  172. }
  173. return []executor.Op{
  174. {Kind: "uci_set", Args: map[string]string{"config": "sqm", "section": idx, "option": "enabled", "value": "0"}, Desc: "Disable SQM"},
  175. {Kind: "uci_commit", Args: map[string]string{"config": "sqm"}, Desc: "Commit sqm config"},
  176. {Kind: "service", Args: map[string]string{"name": "sqm", "action": "stop"}, Desc: "Stop sqm service"},
  177. {Kind: "service", Args: map[string]string{"name": "sqm", "action": "disable"}, Desc: "Disable sqm on boot"},
  178. }
  179. }
  180. // sqmSectionFor devuelve la referencia UCI de la sección a gestionar: la que
  181. // ya tiene la interfaz deseada, o la primera existente ("" si no hay ninguna).
  182. func sqmSectionFor(sc SqmScenario, iface string) string {
  183. if iface != "" {
  184. for _, s := range sc.Sections {
  185. if s.Interface == iface {
  186. return s.Idx
  187. }
  188. }
  189. }
  190. if len(sc.Sections) > 0 {
  191. return sc.Sections[0].Idx
  192. }
  193. return ""
  194. }
  195. // sqmOrDefault devuelve val si no está vacío, si no fallback.
  196. func sqmOrDefault(val, fallback string) string {
  197. if val == "" {
  198. return fallback
  199. }
  200. return val
  201. }
  202. // validateSqmOps valida cada op contra el executor (usado en tests).
  203. func validateSqmOps(ops []executor.Op) error {
  204. for _, op := range ops {
  205. if err := executor.Validate(op); err != nil {
  206. return fmt.Errorf("%s: %w", op.Desc, err)
  207. }
  208. }
  209. return nil
  210. }