usteer.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. // usteer.go - modulo de orquestacion "usteer".
  2. //
  3. // Instala/configura usteer (daemon oficial de OpenWrt para roaming/steering)
  4. // y alinea los parametros de roaming 802.11k/v/r en los APs. El modulo es
  5. // declarativo: compara el estado detectado contra un baseline deseado y
  6. // genera las Ops allowlistedas necesarias.
  7. //
  8. // Baseline por defecto (verificado en red Mandor):
  9. // - aggressiveness=3 (BSS-transition-request con disassociation imminent y timer)
  10. // - band_steering_threshold=5
  11. // - load_balancing_threshold=0
  12. // - debug_level=2, syslog=1, network=lan, enabled=1
  13. // - 802.11k=1, 802.11v=1, 802.11r=1, bss_transition=1, ft_over_ds=0,
  14. // ft_psk_generate_local=1, mobility_domain comun
  15. // - random_bssid=0 en todas las radios
  16. package orchestr
  17. import (
  18. "fmt"
  19. "regexp"
  20. "strconv"
  21. "strings"
  22. "time"
  23. "github.com/gnacho/netpulse/agent/executor"
  24. )
  25. // UsteerDesired es el estado deseado del modulo usteer.
  26. type UsteerDesired struct {
  27. Enabled bool `json:"enabled"`
  28. SSID string `json:"ssid,omitempty"` // SSID a gestionar; vacio = todas las de modo AP
  29. MobilityDomain string `json:"mobilityDomain,omitempty"` // p. ej. "2025"
  30. Aggressiveness string `json:"aggressiveness,omitempty"` // default "3"
  31. BandSteeringThreshold string `json:"bandSteeringThreshold,omitempty"` // default "5"
  32. LoadBalancingThreshold string `json:"loadBalancingThreshold,omitempty"` // default "0"
  33. DebugLevel string `json:"debugLevel,omitempty"` // default "2"
  34. IEEE80211K bool `json:"ieee80211k,omitempty"`
  35. IEEE80211R bool `json:"ieee80211r,omitempty"`
  36. IEEE80211V bool `json:"ieee80211v,omitempty"`
  37. BSSTransition bool `json:"bssTransition,omitempty"`
  38. FTOverDS bool `json:"ftOverDs,omitempty"`
  39. FTPskGenerateLocal bool `json:"ftPskGenerateLocal,omitempty"`
  40. }
  41. // UsteerSSID describe una seccion wifi-iface.
  42. type UsteerSSID struct {
  43. Section string
  44. SSID string
  45. Mode string
  46. Device string
  47. IEEE80211K string
  48. IEEE80211R string
  49. IEEE80211V string
  50. BSSTransition string
  51. FTOverDS string
  52. FTPskGenerateLocal string
  53. MobilityDomain string
  54. }
  55. // UsteerRadio describe una seccion wifi-device.
  56. type UsteerRadio struct {
  57. Section string
  58. RandomBSSID string
  59. }
  60. // UsteerScenario describe el estado detectado de usteer en un router.
  61. type UsteerScenario struct {
  62. Manager string // apk | opkg | ""
  63. UsteerInstalled bool
  64. UsteerRunning bool
  65. WpadVariant string // basic | mbedtls | wolfssl | openssl | other | ""
  66. HostapdDirOK bool
  67. Config map[string]string // usteer.@usteer[-1] options
  68. SSIDs []UsteerSSID
  69. Radios []UsteerRadio
  70. }
  71. const probeUsteerCmd = `echo '===PKG_MGR==='
  72. [ -x /usr/bin/apk ] && echo apk || echo opkg
  73. echo '===USTEER_INST==='
  74. [ -x /etc/init.d/usteer ] && echo yes || echo no
  75. echo '===USTEER_RUN==='
  76. /etc/init.d/usteer running >/dev/null 2>&1 && echo yes || echo no
  77. echo '===WPAD==='
  78. opkg list-installed 2>/dev/null | grep -E '^wpad-' || true
  79. apk list --installed 2>/dev/null | grep -E '^wpad-' || true
  80. echo '===HOSTAPD_DIR==='
  81. [ -d /var/run/hostapd ] && echo yes || echo no
  82. echo '===USTEER_UCI==='
  83. uci show usteer 2>/dev/null
  84. echo '===WIRELESS_UCI==='
  85. uci show wireless 2>/dev/null
  86. echo '===END==='`
  87. // DetectUsteer ejecuta el probe combinado via SSH y devuelve el escenario.
  88. func DetectUsteer(run CommandRunner, host string) (UsteerScenario, error) {
  89. out, err := run.Run(host, probeUsteerCmd, 10*time.Second)
  90. if err != nil {
  91. return UsteerScenario{}, err
  92. }
  93. return parseUsteer(out), nil
  94. }
  95. func parseUsteer(out string) UsteerScenario {
  96. sc := UsteerScenario{Config: map[string]string{}}
  97. sections := splitSections(out)
  98. sc.Manager = strings.TrimSpace(firstNonEmpty(sections["PKG_MGR"]))
  99. if sc.Manager == "" {
  100. sc.Manager = "opkg"
  101. }
  102. sc.UsteerInstalled = strings.TrimSpace(firstNonEmpty(sections["USTEER_INST"])) == "yes"
  103. sc.UsteerRunning = strings.TrimSpace(firstNonEmpty(sections["USTEER_RUN"])) == "yes"
  104. sc.HostapdDirOK = strings.TrimSpace(firstNonEmpty(sections["HOSTAPD_DIR"])) == "yes"
  105. sc.WpadVariant = parseWpadVariant(sections["WPAD"])
  106. for _, line := range sections["USTEER_UCI"] {
  107. line = strings.TrimSpace(line)
  108. // usteer.@usteer[N].option='value'
  109. m := reUsteerOption.FindStringSubmatch(line)
  110. if m == nil {
  111. continue
  112. }
  113. sc.Config[m[1]] = strings.Trim(m[2], "'")
  114. }
  115. sc.SSIDs, sc.Radios = parseWirelessUsteer(sections["WIRELESS_UCI"])
  116. return sc
  117. }
  118. // reUsteerOption captura `usteer.@usteer[N].option='value'`. `uci show usteer`
  119. // imprime la sección anónima con su índice real (`@usteer[0]`), no con la
  120. // referencia `[-1]` que solo vale para `uci set`. Se aceptan ambas formas.
  121. var reUsteerOption = regexp.MustCompile(`^usteer\.@usteer\[-?\d+\]\.([a-z0-9_]+)=(.+)$`)
  122. func parseWirelessUsteer(lines []string) (ssids []UsteerSSID, radios []UsteerRadio) {
  123. uci := strings.Join(lines, "\n")
  124. for _, line := range lines {
  125. line = strings.TrimSpace(line)
  126. if !strings.HasPrefix(line, "wireless.") {
  127. continue
  128. }
  129. rest := strings.TrimPrefix(line, "wireless.")
  130. parts := strings.SplitN(rest, "=", 2)
  131. if len(parts) != 2 {
  132. continue
  133. }
  134. secFull := parts[0]
  135. typ := strings.Trim(parts[1], "'")
  136. if typ == "wifi-iface" {
  137. ssids = append(ssids, UsteerSSID{
  138. Section: secFull,
  139. SSID: wirelessOpt(uci, secFull, "ssid"),
  140. Mode: wirelessOpt(uci, secFull, "mode"),
  141. Device: wirelessOpt(uci, secFull, "device"),
  142. IEEE80211K: wirelessOpt(uci, secFull, "ieee80211k"),
  143. IEEE80211R: wirelessOpt(uci, secFull, "ieee80211r"),
  144. IEEE80211V: wirelessOpt(uci, secFull, "ieee80211v"),
  145. BSSTransition: wirelessOpt(uci, secFull, "bss_transition"),
  146. FTOverDS: wirelessOpt(uci, secFull, "ft_over_ds"),
  147. FTPskGenerateLocal: wirelessOpt(uci, secFull, "ft_psk_generate_local"),
  148. MobilityDomain: wirelessOpt(uci, secFull, "mobility_domain"),
  149. })
  150. } else if typ == "wifi-device" {
  151. radios = append(radios, UsteerRadio{
  152. Section: secFull,
  153. RandomBSSID: wirelessOpt(uci, secFull, "random_bssid"),
  154. })
  155. }
  156. }
  157. return
  158. }
  159. // UsteerOps genera las Ops para reconciliar el estado deseado de usteer.
  160. func UsteerOps(desired UsteerDesired, sc UsteerScenario) []executor.Op {
  161. if !desired.Enabled {
  162. return usteerDisableOps(sc)
  163. }
  164. d := normalizeUsteerDesired(desired)
  165. var ops []executor.Op
  166. // 1. Instalar usteer si falta.
  167. if !sc.UsteerInstalled {
  168. if sc.Manager == "apk" {
  169. ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "usteer"}, Desc: "Install usteer (apk)"})
  170. ops = append(ops, executor.Op{Kind: "apk_install", Args: map[string]string{"package": "luci-app-usteer"}, Desc: "Install LuCI usteer (apk)"})
  171. } else {
  172. ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "usteer"}, Desc: "Install usteer (opkg)"})
  173. ops = append(ops, executor.Op{Kind: "install", Args: map[string]string{"package": "luci-app-usteer"}, Desc: "Install LuCI usteer (opkg)"})
  174. }
  175. }
  176. // 2. Asegurar wpad completo si solo hay wpad-basic/mini.
  177. if sc.WpadVariant == "basic" || sc.WpadVariant == "mini" || sc.WpadVariant == "" {
  178. pkg := "wpad-wolfssl"
  179. if sc.Manager == "apk" {
  180. pkg = "wpad-mbedtls"
  181. }
  182. ops = append(ops, executor.Op{Kind: installKind(sc.Manager), Args: map[string]string{"package": pkg}, Desc: "Install full wpad for usteer"})
  183. }
  184. // 3. Asegurar la seccion usteer y options.
  185. if len(sc.Config) == 0 {
  186. ops = append(ops, executor.Op{Kind: "uci_set_named", Args: map[string]string{"config": "usteer", "section": "usteer", "type": "usteer"}, Desc: "Ensure usteer section"})
  187. }
  188. setUsteerOptionIfDiffers(&ops, sc, "enabled", "1")
  189. setUsteerOptionIfDiffers(&ops, sc, "network", "lan")
  190. setUsteerOptionIfDiffers(&ops, sc, "syslog", "1")
  191. setUsteerOptionIfDiffers(&ops, sc, "debug_level", d.DebugLevel)
  192. setUsteerOptionIfDiffers(&ops, sc, "aggressiveness", d.Aggressiveness)
  193. setUsteerOptionIfDiffers(&ops, sc, "band_steering_threshold", d.BandSteeringThreshold)
  194. setUsteerOptionIfDiffers(&ops, sc, "load_balancing_threshold", d.LoadBalancingThreshold)
  195. setUsteerOptionIfDiffers(&ops, sc, "min_connect_snr", "0")
  196. setUsteerOptionIfDiffers(&ops, sc, "min_snr", "0")
  197. setUsteerOptionIfDiffers(&ops, sc, "roam_trigger_snr", "0")
  198. setUsteerOptionIfDiffers(&ops, sc, "roam_scan_snr", "0")
  199. // 4. Wireless: aplicar baseline a cada SSID de modo AP.
  200. for _, s := range sc.SSIDs {
  201. if s.Mode != "ap" {
  202. continue
  203. }
  204. if d.SSID != "" && s.SSID != d.SSID {
  205. continue
  206. }
  207. sec := s.Section
  208. setWirelessBoolIfDiffers(&ops, s.IEEE80211K, sec, "ieee80211k", d.IEEE80211K, true)
  209. setWirelessBoolIfDiffers(&ops, s.IEEE80211R, sec, "ieee80211r", d.IEEE80211R, true)
  210. setWirelessBoolIfDiffers(&ops, s.IEEE80211V, sec, "ieee80211v", d.IEEE80211V, true)
  211. setWirelessBoolIfDiffers(&ops, s.BSSTransition, sec, "bss_transition", d.BSSTransition, true)
  212. setWirelessBoolIfDiffers(&ops, s.FTOverDS, sec, "ft_over_ds", d.FTOverDS, false)
  213. setWirelessBoolIfDiffers(&ops, s.FTPskGenerateLocal, sec, "ft_psk_generate_local", d.FTPskGenerateLocal, true)
  214. if d.MobilityDomain != "" && s.MobilityDomain != d.MobilityDomain {
  215. ops = append(ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": sec, "option": "mobility_domain", "value": d.MobilityDomain}, Desc: "Set mobility domain on " + sec})
  216. }
  217. }
  218. // 5. Radios: random_bssid=0.
  219. for _, r := range sc.Radios {
  220. if r.RandomBSSID != "0" {
  221. ops = append(ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "wireless", "section": r.Section, "option": "random_bssid", "value": "0"}, Desc: "Disable random BSSID on " + r.Section})
  222. }
  223. }
  224. if len(ops) == 0 {
  225. return nil
  226. }
  227. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "usteer"}, Desc: "Commit usteer config"})
  228. ops = append(ops, executor.Op{Kind: "uci_commit", Args: map[string]string{"config": "wireless"}, Desc: "Commit wireless config"})
  229. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "usteer", "action": "enable"}, Desc: "Enable usteer on boot"})
  230. ops = append(ops, executor.Op{Kind: "service", Args: map[string]string{"name": "usteer", "action": "start"}, Desc: "Start usteer"})
  231. return ops
  232. }
  233. func setUsteerOptionIfDiffers(ops *[]executor.Op, sc UsteerScenario, option, want string) {
  234. if want == "" {
  235. return
  236. }
  237. if sc.Config[option] == want {
  238. return
  239. }
  240. *ops = append(*ops, executor.Op{Kind: "uci_set", Args: map[string]string{"config": "usteer", "section": "@usteer[-1]", "option": option, "value": want}, Desc: "Set usteer " + option})
  241. }
  242. func usteerDisableOps(sc UsteerScenario) []executor.Op {
  243. if !sc.UsteerInstalled && len(sc.Config) == 0 {
  244. return nil
  245. }
  246. return []executor.Op{
  247. {Kind: "uci_set", Args: map[string]string{"config": "usteer", "section": "@usteer[-1]", "option": "enabled", "value": "0"}, Desc: "Disable usteer"},
  248. {Kind: "uci_commit", Args: map[string]string{"config": "usteer"}, Desc: "Commit usteer config"},
  249. {Kind: "service", Args: map[string]string{"name": "usteer", "action": "stop"}, Desc: "Stop usteer"},
  250. {Kind: "service", Args: map[string]string{"name": "usteer", "action": "disable"}, Desc: "Disable usteer on boot"},
  251. }
  252. }
  253. func normalizeUsteerDesired(d UsteerDesired) UsteerDesired {
  254. if d.Aggressiveness == "" {
  255. d.Aggressiveness = "3"
  256. }
  257. if d.BandSteeringThreshold == "" {
  258. d.BandSteeringThreshold = "5"
  259. }
  260. if d.LoadBalancingThreshold == "" {
  261. d.LoadBalancingThreshold = "0"
  262. }
  263. if d.DebugLevel == "" {
  264. d.DebugLevel = "2"
  265. }
  266. return d
  267. }
  268. // UsteerHealthcheck verifica que usteer responde y ve vecinos tras el apply.
  269. func UsteerHealthcheck(run CommandRunner, host string) error {
  270. out, err := run.Run(host, "ubus call usteer remote_hosts", 5*time.Second)
  271. if err != nil {
  272. return fmt.Errorf("usteer remote_hosts failed: %w", err)
  273. }
  274. out = strings.TrimSpace(out)
  275. if out == "" || out == "{}" {
  276. return fmt.Errorf("usteer remote_hosts returned empty mesh")
  277. }
  278. return nil
  279. }
  280. // UsteerDriftWarnings devuelve advertencias de inconsistencia legibles para la UI.
  281. func UsteerDriftWarnings(d UsteerDesired, sc UsteerScenario) []string {
  282. d = normalizeUsteerDesired(d)
  283. var warns []string
  284. if !sc.UsteerInstalled {
  285. warns = append(warns, "usteer no esta instalado")
  286. }
  287. if !sc.HostapdDirOK {
  288. warns = append(warns, "El directorio /var/run/hostapd no existe")
  289. }
  290. mdom := d.MobilityDomain
  291. for _, s := range sc.SSIDs {
  292. if s.Mode != "ap" {
  293. continue
  294. }
  295. if d.SSID != "" && s.SSID != d.SSID {
  296. continue
  297. }
  298. if mdom != "" && s.MobilityDomain != mdom {
  299. warns = append(warns, "Dominio de movilidad inconsistente en "+s.Section)
  300. }
  301. if s.IEEE80211K != "1" {
  302. warns = append(warns, "802.11k desactivado en "+s.Section)
  303. }
  304. if s.IEEE80211R != "1" {
  305. warns = append(warns, "802.11r desactivado en "+s.Section)
  306. }
  307. if s.IEEE80211V != "1" {
  308. warns = append(warns, "802.11v desactivado en "+s.Section)
  309. }
  310. }
  311. for _, r := range sc.Radios {
  312. if r.RandomBSSID != "0" {
  313. warns = append(warns, "random_bssid activo en "+r.Section)
  314. }
  315. }
  316. return warns
  317. }
  318. // UsteerMethod devuelve active/inactive para la UI.
  319. func UsteerMethod(sc UsteerScenario) string {
  320. if sc.UsteerRunning {
  321. return "active"
  322. }
  323. return "inactive"
  324. }
  325. // Int helpers para comparar valores numericos si fuese necesario.
  326. func usteerInt(s string) int {
  327. v, _ := strconv.Atoi(strings.TrimSpace(s))
  328. return v
  329. }
  330. func validateUsteerOps(ops []executor.Op) error {
  331. for _, op := range ops {
  332. if err := executor.Validate(op); err != nil {
  333. return fmt.Errorf("%s: %w", op.Desc, err)
  334. }
  335. }
  336. return nil
  337. }