live.go 191 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734
  1. // live.go — Adapter live (port de src/adapters/index.js, SPEC §7.2-§7.8):
  2. // compone el snapshot por router con degradación elegante (router caído →
  3. // offline + alerta tras 2 fallos seguidos; el resto sigue), single-flight en
  4. // GetOverview (los SSH son lo caro), persistencia de atribución en
  5. // device_attrib (solo wireless) y alertas en memoria (máx 100).
  6. package adapters
  7. import (
  8. "context"
  9. "database/sql"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "log"
  14. "math"
  15. "runtime/debug"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/gnacho/netpulse/agent/probe"
  22. "github.com/gnacho/netpulse/server-go/internal/alerts"
  23. "github.com/gnacho/netpulse/server-go/internal/config"
  24. "github.com/gnacho/netpulse/server-go/internal/db"
  25. "github.com/gnacho/netpulse/server-go/internal/deviceevents"
  26. "github.com/gnacho/netpulse/server-go/internal/oui"
  27. "github.com/gnacho/netpulse/server-go/internal/portseries"
  28. )
  29. // fmtUptime: "<d>d <h>h" (index.js:32-36).
  30. func fmtUptime(sec float64) string {
  31. d := int(sec) / 86400
  32. h := (int(sec) % 86400) / 3600
  33. return fmt.Sprintf("%dd %dh", d, h)
  34. }
  35. // bptr: puntero a bool (el view-model usa *bool para distinguir "ausente" de
  36. // "false" explícito, p.ej. Router.LldpAvailable).
  37. func bptr(v bool) *bool { return &v }
  38. // mbps: bps → Mbps 1 decimal (null → 0).
  39. func mbps(bps *float64) float64 {
  40. if bps == nil {
  41. return 0
  42. }
  43. return math.Round(*bps/1e6*10) / 10
  44. }
  45. // pickGateway: is_gateway → glinet → primero.
  46. func pickGateway(routers []RouterConfig) *RouterConfig {
  47. for i := range routers {
  48. if routers[i].IsGateway {
  49. return &routers[i]
  50. }
  51. }
  52. for i := range routers {
  53. if routers[i].Type == "glinet" {
  54. return &routers[i]
  55. }
  56. }
  57. if len(routers) > 0 {
  58. return &routers[0]
  59. }
  60. return nil
  61. }
  62. // pickGatewayCfg: same logic as pickGateway but from polled router configs.
  63. func pickGatewayCfg(polled map[string]*routerPolled) *RouterConfig {
  64. ids := make([]string, 0, len(polled))
  65. for id := range polled {
  66. ids = append(ids, id)
  67. }
  68. sort.Strings(ids)
  69. for _, id := range ids {
  70. if polled[id].cfg.IsGateway {
  71. return &polled[id].cfg
  72. }
  73. }
  74. for _, id := range ids {
  75. if polled[id].cfg.Type == "glinet" {
  76. return &polled[id].cfg
  77. }
  78. }
  79. if len(ids) > 0 {
  80. return &polled[ids[0]].cfg
  81. }
  82. return nil
  83. }
  84. // routerPolled es el sondeo de un tick de un router.
  85. type routerPolled struct {
  86. cfg RouterConfig
  87. client *OpenWrtClient
  88. sysInfo *SysInfo
  89. board *BoardInfo
  90. cpu int
  91. ram int
  92. temp int
  93. // #1256: SNMP rellena sysDescr (nombre/modelo completo del switch) y,
  94. // en MikroTik SwOS, la temperatura del chasis (hasTemp). hasTemp
  95. // distingue "no aplica" de "0 °C" para no pisar el null de #441.
  96. hasTemp bool
  97. // hasCpu: mismo contrato que hasTemp para la CPU de los switches SNMP
  98. // (tabla de procesos Netgear FastPath): sin bandera, el null de #441
  99. // pisaría la lectura real.
  100. hasCpu bool
  101. sysDescr string
  102. // sysName (#1256): hostname que el usuario define en el equipo; para
  103. // SNMP alimenta el Name visible de la unidad en flota.
  104. sysName string
  105. flash string
  106. firmwareAvailable string
  107. uptimeSec float64
  108. net *NetDevBps
  109. leases []DhcpLease
  110. // reservations: the `config host` entries of /etc/config/dhcp. They name
  111. // clients that never take a lease because their address is fixed on the
  112. // device itself.
  113. reservations []DhcpReservation
  114. // glClients (GL.iNet): base de clientes del firmware, superset de las
  115. // leases. Se usa SOLO para resolver IPs de dispositivos ya conocidos que
  116. // salen sin IP (dnsmasq sin lease), nunca para crear dispositivos nuevos.
  117. glClients []DhcpLease
  118. // arp: MAC→IP de /proc/net/arp (#377). Último recurso de resolución de
  119. // IP cuando ni el lease ni gl-clients la tienen (DHCP en otro equipo).
  120. arp map[string]string
  121. // arpDevs: MAC→interfaz de la tabla ARP (#1485). Permite distinguir el
  122. // ARP aprendido en el puerto WAN (primer salto del enlace) del de la LAN.
  123. arpDevs map[string]string
  124. // selfMacs: MACs de identidad del propio equipo aprendidas en sus puertos
  125. // internos/CPU (#1489). No son clientes y se absorben aunque las vea otro
  126. // miembro de la flota.
  127. selfMacs []string
  128. // arpStale: the subset of `arp` the kernel remembers without having
  129. // confirmed (STALE/FAILED/INCOMPLETE). Good enough to resolve an IP,
  130. // never enough to claim the host is connected -- an entry outlives the
  131. // device by minutes. Empty when the source could not report states.
  132. arpStale map[string]bool
  133. wireless map[string]WirelessClient
  134. ports []EthPort
  135. radios []Radio
  136. fdb map[string]string
  137. // wirelessSide: MACs que el bridge del router aprende en sus propios
  138. // puertos de radio (wl0.1, wlan0…) pero que la tabla de estaciones no
  139. // lista (MACs rotadas que siguen emitiendo, backhaul 4-address). El
  140. // agente las etiqueta con la banda de la radio; aquí mandan sobre el
  141. // fallback del FDB del gateway, que si no las dibuja como cableadas.
  142. wirelessSide map[string]string
  143. brMac string
  144. latencyMs *float64
  145. lossPct *float64
  146. // backhaul: "cable"|"wifi"|"" (desconocido → se omite en el contrato).
  147. backhaul string
  148. // lldp: vecinos LLDP del tier lento (nil = sin lldpd o sonda fallida).
  149. lldp []LldpNeighbor
  150. // lldpUnavailable: lldpd no está instalado en este router (issue #247) →
  151. // el view-model expone `lldpAvailable:false` para el hint de instalación.
  152. lldpUnavailable bool
  153. // lldpHint: aviso de config subóptima reportado por el agente (#1369,
  154. // p. ej. probe.HintLldpdBridgeOnly). Se recicla con la cache igual que
  155. // los vecinos; vacío = sin aviso.
  156. lldpHint string
  157. // clientBw (#551): contadores nlbwmon por MAC del último payload del
  158. // agente. nil = nlbwmon no instalado o sonda no disponible (→ la fuente
  159. // de tráfico por cliente cae a hostapd bytes de wireless).
  160. clientBw *probe.ClientBwData
  161. // luci: etiquetas de puertos/VLANs de LuCI (issue #258), si el router las
  162. // define en /etc/config/luci. Fuente de nombres para la topología.
  163. luci *probe.LuCILabels
  164. // wanInfo: estado de la conexión WAN (solo gateway, issue #276). Los APs
  165. // dejan el struct vacío (sin datos WAN).
  166. wanInfo probe.WanInfo
  167. // vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sin
  168. // datos (router sin bridge vlan filtering o sonda fallida).
  169. vlans []VlanPort
  170. // multiWan: the router's several internet connections and which one is
  171. // carrying traffic, as its own panel manages them. nil = never
  172. // reported (no such panel, or an older agent); an empty uplink list =
  173. // reported, and there is nothing to show.
  174. multiWan *MultiWanInfo
  175. // discovery: mDNS services + randomized MACs (#338). nil = sin datos
  176. // (umdns no instalado o sonda fallida).
  177. discovery *probe.DiscoveryData
  178. // dawnDetected: el agente reportó una sección DAWN en el payload. Se
  179. // usa para mostrar el aviso de deprecación (#426).
  180. dawnDetected bool
  181. // polledAt (issue #414): epoch ms en que se realizó el sondeo real. Se
  182. // usa para deduplicar filas de métricas cuando SNMP se cachea.
  183. polledAt int64
  184. // agentKind (#441): kind del agente cuyo payload construyó este sondeo
  185. // ("" = sondeo SSH/SNMP directo). "external" = pusher beacon/scraper sin
  186. // sección system → sin vitals.
  187. agentKind string
  188. // selfExpose (#832): el equipo se expone él mismo a Home Assistant por
  189. // MQTT (NetGrip con su MQTT activado) → el publisher de flota no publica
  190. // sus entidades por router.
  191. selfExpose bool
  192. }
  193. // extrasSnapshot es la caché anti-parpadeo por router.
  194. type extrasSnapshot struct {
  195. ports []EthPort
  196. radios []Radio
  197. wireless map[string]WirelessClient
  198. fdb map[string]string
  199. // wirelessSide: último hint bueno de MACs detrás de radios propias
  200. // (ver routerPolled.wirelessSide). Mismo anti-parpadeo que fdb.
  201. wirelessSide map[string]string
  202. luci *probe.LuCILabels
  203. vlans []VlanPort
  204. // multiWan: last good multi-WAN section. The event-driven pushes carry
  205. // no such section, and without keeping it the panel would blink out of
  206. // the page every time a device associates. Unlike wanInfo, which is a
  207. // live address and must never be recycled, this is structural.
  208. multiWan *MultiWanInfo
  209. // system (#441): última sección system BUENA del payload del agente.
  210. // Los pushes event-driven (wireless-only) van sin ella; sin este cache
  211. // las vitales del router parpadeaban a 0 entre pushes completos.
  212. system *probe.SystemData
  213. // lldp (#489): última sección lldp del payload. Mismo anti-parpadeo:
  214. // los pushes event-driven van sin ella y la topología no debe perder
  215. // los switches managed entre pushes completos.
  216. lldp *probe.LldpData
  217. // clientBw (#551): última sección clientbw del payload del agente.
  218. // Los pushes event-driven van sin ella; conservar la última buena evita
  219. // que la fuente nlbwmon parpadee entre pushes completos.
  220. clientBw *probe.ClientBwData
  221. }
  222. // backhaulCacheTTL: el medio del uplink cambia muy raro; no se sondea cada 5 s.
  223. const backhaulCacheTTL = 5 * time.Minute
  224. // backhaulCacheEntry: resultado cacheado de la detección de uplink wifi
  225. // (value "" = desconocido/sonda fallida → el campo se omite).
  226. type backhaulCacheEntry struct {
  227. value string
  228. at time.Time
  229. }
  230. // lldpCacheTTL: tier lento LLDP (45 s, como los extras cacheados).
  231. const lldpCacheTTL = 45 * time.Second
  232. // lldpCacheEntry: vecinos LLDP cacheados por router (nil = sin datos).
  233. // unavailable=true cuando lldpd NO está instalado en el router (ErrLldpUnavailable);
  234. // la UI lo usa para el hint "instala lldpd" (issue #247).
  235. type lldpCacheEntry struct {
  236. neighbors []LldpNeighbor
  237. unavailable bool
  238. at time.Time
  239. }
  240. // wanInfoCacheTTL: tier lento del estado WAN del gateway. La conexión WAN no
  241. // cambia cada tick; un sondeo cada 60 s sobra y evita martillear ubus.
  242. const wanInfoCacheTTL = 60 * time.Second
  243. // wanInfoCacheEntry: WanInfo cacheado del gateway (issue #276).
  244. type wanInfoCacheEntry struct {
  245. info probe.WanInfo
  246. at time.Time
  247. }
  248. // Live es el Snapshotter del modo live.
  249. type Live struct {
  250. cfg *config.Config
  251. db *db.DB
  252. pool *SSHPool
  253. mu sync.Mutex
  254. surveyMu sync.Mutex
  255. surveyRaw map[string]surveyEntry
  256. routers []RouterConfig
  257. gatewayCfg *RouterConfig
  258. clients map[string]*OpenWrtClient
  259. lastGood map[string]*Router
  260. lastStatus map[string]string
  261. boardCache map[string]*BoardInfo
  262. layoutCache map[string][]PortLayout
  263. extrasCache map[string]*extrasSnapshot
  264. // lastAgentIf: /proc/net/dev por iface del ÚLTIMO payload del agente
  265. // (contadores absolutos + ts) para calcular los rates por boca con el
  266. // delta entre payloads (issue #305). Protegido por mu.
  267. lastAgentIf map[string]*agentIfSample
  268. // lastClientBw (#551): contadores absolutos por (router, mac) de la
  269. // última muestra observada, para calcular el delta por cliente entre
  270. // polls. Mapa: routerID → mac → estado. Protegido por mu.
  271. lastClientBw map[string]map[string]*clientBwCounter
  272. // lastObsTs: ts del último payload del agente que alimentó las series
  273. // por puerto y el PortMonitor (issue #365). Protegido por mu.
  274. lastObsTs map[string]int64
  275. // snmpPorts (issue #309): contadores del último poll SNMP por router y
  276. // puerto. Se usa para calcular rxBps/txBps entre polls sucesivos.
  277. snmpPorts map[string]map[string]snmpPortSample
  278. // snmpLastPoll (issue #414): timestamp del último poll SNMP real por router.
  279. snmpLastPoll map[string]time.Time
  280. // fwAlert (#1411): estado de la alerta de firmware por unidad con target
  281. // configurado: qué relación se alertó y contra qué versiones. Con eso la
  282. // alerta es un episodio por unidad (se abre una vez, se actualiza solo si
  283. // cambia la versión o el target, y se resuelve al coincidir). Protegido
  284. // por mu.
  285. fwAlert map[string]fwAlertState
  286. // #1444: lista cacheada de releases publicados de OpenWrt (la publica el
  287. // ReleasesRefresher tras cada chequeo periódico) y episodios abiertos del
  288. // aviso "target no disponible upstream" (routerID → target alertado).
  289. fwReleases []string
  290. fwReleasesTs int64
  291. fwUnknownTarget map[string]string
  292. // snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
  293. // para loguear solo cuando el resultado cambia.
  294. snmpFdbCount map[string]int
  295. // snmpBrMac (#1036): última MAC base del bridge leída por SNMP por
  296. // router. Cache para no perderla cuando el equipo no contesta el OID
  297. // en un poll (la MAC alimenta el matching por MAC de la topología).
  298. snmpBrMac map[string]string
  299. // snmpPollStats (#930): contadores de éxito/fallo del poll SNMP por
  300. // router (ok, fail, consecFail, timestamps, último error). Protegido
  301. // por mu; en memoria (no persiste entre reinicios).
  302. snmpPollStats map[string]*snmpPollStat
  303. // ping (issue #930): probe ICMP inyectable para el ping de respaldo del
  304. // sondeo SNMP. nil/nulo en tests sin mock; el default real es pingHost.
  305. ping func(host string) bool
  306. // snmpLastMetricsTick (issue #414): polledAt del último tick que se persistió
  307. // en la tabla metrics, para evitar filas duplicadas cuando se reutiliza el
  308. // snapshot cacheado de un router SNMP.
  309. snmpLastMetricsTick map[string]int64
  310. lastPolled map[string]*routerPolled
  311. failCount map[string]int
  312. lastErr map[string]error // último error del sondeo (issue #257: distinguir sin-acceso de caído)
  313. // offlineOpen (issue #846): routers con un incidente de offline ABIERTO
  314. // (alerta emitida y aún no recuperados). Mientras esté abierto no se
  315. // re-emite la alerta aunque el estado flapee: un incidente = una alerta.
  316. // recoverStreak: éxitos seguidos del router con el incidente abierto; la
  317. // recuperación hay que estabilizarla (offlineRecoverTicks) para que un
  318. // flap breve no cierre el incidente.
  319. offlineOpen map[string]bool
  320. recoverStreak map[string]int
  321. engine *alerts.Engine
  322. wgActive map[string]bool
  323. wgActiveSince map[string]time.Time // when each active peer became active (disconnect duration)
  324. // wgPrimed (#1443): la primera pasada tras el arranque NO emite connects
  325. // (warmup: los peers activos al boot no son "conexiones"). Antes el
  326. // warmup se deducía de len(wgActive)>0, que además tragaba la primera
  327. // conexión real cuando el ciclo previo no tenía ningún peer activo
  328. // (túnel iniciado por la unidad local tras estar caído).
  329. wgPrimed bool
  330. // wgUrgent (#1441): claves de peer (WGPeer.Key) marcadas como urgentes:
  331. // sus caídas avisan (Urgent=true en la alerta), las del resto solo van al
  332. // log. Persistido en kv (wgUrgentKey).
  333. wgUrgent map[string]bool
  334. // wgUrgentMiss (#1445): ausencias consecutivas del peer en el dump por
  335. // clave urgente; a wgUrgentPruneMisses seguidas se recoge el flag.
  336. wgUrgentMiss map[string]int
  337. // weakStates (#1452): estado del ciclo de vida de la alerta de señal
  338. // débil por MAC (antes sólo se guardaba el último disparo). La máquina
  339. // pura vive en alerts.WeakSignalStep.
  340. weakStates map[string]alerts.WeakSignalState
  341. onlineMacs map[string]bool
  342. // unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
  343. // MAC. unknownAlerted: MACs que ya dispararon la alerta de desconocido
  344. // (issue #248, persistido en kv: cada MAC alerta UNA sola vez).
  345. unknownGrace map[string]int
  346. unknownAlerted map[string]bool
  347. unknownGraceNum int // ticks antes de declarar desconocido (default 3, #234)
  348. // rdns: reverse DNS fallback for devices nothing else named (rdns.go).
  349. rdns *rdnsCache
  350. // impostorActive (#1358): BSSID impostor → alertID emitida. Solo en
  351. // memoria a propósito: si el server reinicia y el impostor sigue
  352. // visible, la alerta se re-emite (seguridad prima sobre re-aviso).
  353. impostorActive map[string]string
  354. // impostorAllow (#1400): BSSIDs aprobados a mano como propios (APs
  355. // conocidos fuera de la flota: UniFi, Omada...). Persistido en kv
  356. // (impostorAllowKey) para sobrevivir reinicios.
  357. impostorAllow map[string]bool
  358. // impostorEnabled (#1400): interruptor global de la regla de impostores
  359. // (default true; persistido en kv impostorEnabledKey).
  360. impostorEnabled bool
  361. // Presencia wireless (issue #184): devicePresence = MAC → online del
  362. // último ciclo evaluado; presenceMisses = ticks seguidos sin verse.
  363. // presenceSeen evita la avalancha del primer ciclo (anti-arranque).
  364. presenceSeen bool
  365. devicePresence map[string]bool
  366. presenceMisses map[string]int
  367. presenceOfflineAfter int // ticks sin verse antes de declarar offline (default 3)
  368. // presencePruneAfter: ticks sin verse que eliminan la MAC de los mapas
  369. // (dispositivo que se fue para siempre; ~2h a 5s/tick, issue #206).
  370. presencePruneAfter int
  371. // offlineAlert (#1354): seguimiento opt-in de desconexión de dispositivos
  372. // marcados (notify_offline). offlineOnline marca qué MACs se vieron online
  373. // alguna vez (línea base del arranque); offlineMisses cuenta ticks offline
  374. // seguidos antes de confirmar; offlineAlerted evita re-emitir mientras el
  375. // incidente sigue abierto.
  376. offlineOnline map[string]bool
  377. offlineMisses map[string]int
  378. offlineAlerted map[string]bool
  379. offlineAlertNum int // ticks offline seguidos antes de emitir (default 3)
  380. // usteerAvailable: cache de "¿hay usteer en algún router?" para el flag del
  381. // overview (entrada /roaming). Refrescado asíncronamente (TTL 30s, 1 SSH
  382. // al gateway) por usteerAvailableCached para no bloquear buildOverview.
  383. usteerAvailable bool
  384. usteerCheckedAt time.Time
  385. usteerChecking bool
  386. seenOnlineMacs bool
  387. wanDown map[string]int
  388. // uplinkWatch: which internet connection each router was last seen
  389. // using, per router id, plus a candidate not yet believed. Memory
  390. // only: after a restart the first poll records in silence rather than
  391. // announcing a change that happened while nobody was looking.
  392. uplinkWatch map[string]*uplinkWatch
  393. backhaulCache map[string]backhaulCacheEntry
  394. lldpCache map[string]lldpCacheEntry
  395. wanInfoCache map[string]wanInfoCacheEntry
  396. // Agentes nativos (Tier 2): último payload por slug + flag de caída
  397. // (degradado a SSH tras emitir la alerta, SPEC-AGENTE-PILOTO §1).
  398. agents *AgentRegistry
  399. agentDown map[string]bool
  400. agentDownConfirm time.Duration // Dead Man's Switch: confirmar caída tras este periodo sin alertar
  401. // agentLatest (issue #400): fuente de la versión de referencia por kind
  402. // del agente ("" = check desactivado); agentOutdatedAlerted evita
  403. // re-emitir la recuperación ok más de una vez.
  404. agentLatest func(kind string) string
  405. agentOutdatedAlerted map[string]bool
  406. // #910: último "version|ref" reportado por router para la alerta de
  407. // desactualizado. EmitOrUpdate notifica en CADA actualización en sitio,
  408. // así que sin este guard cada push (30 s) reenviaba el push y refrescaba
  409. // el timestamp: solo se emite cuando el dato realmente cambia.
  410. agentOutdatedKey map[string]string
  411. // routerMacs: id → bridge MAC persistida en DB. Permite emparejar un agente
  412. // con su router aunque el slug elegido por el usuario no coincida con el id
  413. // autogenerado del router (#282).
  414. routerMacs map[string]string
  415. // sshAuthFailAlerted evita repetir la alerta de "SSH sin clave pero agente
  416. // vivo" (#281). Se limpia cuando el acceso SSH se recupera.
  417. sshAuthFailAlerted map[string]bool
  418. // portMon (issue #303/#307/#308): monitor de estado de puertos para
  419. // detección de flapping, ghost port y link degradado.
  420. portMon *PortMonitor
  421. // suppression (issue #332): grafo de dependencias topológicas para
  422. // suprimir alertas hijas cuando un router padre está offline.
  423. suppression *alerts.SuppressionGraph
  424. // now: reloj inyectable para tests deterministas (nil → time.Now).
  425. // Mismo patrón que AgentRegistry.SetClock.
  426. now func() time.Time
  427. agStd *AdGuardClient
  428. agGL *AdGuardGlinetClient
  429. agKey string
  430. // PVE (#561/#764): clientes por instancia Proxmox + caché del
  431. // inventario. Los clientes se reconstruyen si cambia la lista de
  432. // instancias (pveKey); el inventario se refresca con TTL.
  433. pveClients []pveInstClient
  434. pveKey string
  435. pveInv *pveInventory
  436. pveInvAt time.Time
  437. // fdbMemo (#656): última boca REAL donde el FDB vio cada MAC (epoch ms).
  438. // Los dispositivos callados (AV: TV, receptor, shield…) caducan su entrada
  439. // FDB a los ~5 min sin hablar y "saltaban" del switch inferido al anchor
  440. // del gateway entre ticks. La memo se usa SOLO como overlay de inferTopology
  441. // (nunca para crear presencia/online) mientras la entrada sea fresca.
  442. fdbMemo map[string]fdbPortMemo
  443. // uplinkPorts (#694): clasificación PERSISTENTE de puertos de subida por
  444. // router (routerID → puertos que ALGUNA VEZ aprendieron una brMac de otro
  445. // router). Sobrevive a los ticks donde la brMac del AP no está en el FDB
  446. // del gateway y a los sondeos fallidos, de modo que el puerto gateway→AP
  447. // siga tratándose como uplink y no como boca local (evita que el gateway
  448. // pise la memo de un satélite y que el cliente salte al principal).
  449. uplinkPorts map[string]map[string]bool
  450. sfMu sync.Mutex
  451. sfCall *sfCall
  452. }
  453. type sfCall struct {
  454. done chan struct{}
  455. ov *Overview
  456. err error
  457. }
  458. // NewLive crea el adapter live (db puede ser nil en tests).
  459. func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool) *Live {
  460. l := &Live{
  461. cfg: cfg,
  462. db: d,
  463. pool: pool,
  464. now: time.Now,
  465. lastGood: map[string]*Router{},
  466. lastStatus: map[string]string{},
  467. fwAlert: map[string]fwAlertState{},
  468. fwUnknownTarget: map[string]string{},
  469. boardCache: map[string]*BoardInfo{},
  470. layoutCache: map[string][]PortLayout{},
  471. extrasCache: map[string]*extrasSnapshot{},
  472. lastAgentIf: map[string]*agentIfSample{},
  473. lastClientBw: map[string]map[string]*clientBwCounter{},
  474. lastObsTs: map[string]int64{},
  475. snmpPorts: map[string]map[string]snmpPortSample{},
  476. snmpLastPoll: map[string]time.Time{},
  477. snmpFdbCount: map[string]int{},
  478. snmpBrMac: map[string]string{},
  479. snmpPollStats: map[string]*snmpPollStat{},
  480. ping: pingHost,
  481. snmpLastMetricsTick: map[string]int64{},
  482. lastPolled: map[string]*routerPolled{},
  483. failCount: map[string]int{},
  484. lastErr: map[string]error{},
  485. offlineOpen: map[string]bool{},
  486. recoverStreak: map[string]int{},
  487. engine: alerts.New(d, nil),
  488. wgActive: map[string]bool{},
  489. wgActiveSince: map[string]time.Time{},
  490. wgUrgent: map[string]bool{},
  491. wgUrgentMiss: map[string]int{},
  492. weakStates: map[string]alerts.WeakSignalState{},
  493. onlineMacs: map[string]bool{},
  494. unknownGrace: map[string]int{},
  495. unknownAlerted: map[string]bool{},
  496. unknownGraceNum: 3, // default de #234; el engine/demo puede afinarlo
  497. impostorActive: map[string]string{},
  498. impostorAllow: map[string]bool{},
  499. impostorEnabled: true,
  500. devicePresence: map[string]bool{},
  501. presenceMisses: map[string]int{},
  502. presenceOfflineAfter: 3,
  503. presencePruneAfter: 2000,
  504. offlineOnline: map[string]bool{},
  505. offlineMisses: map[string]int{},
  506. offlineAlerted: map[string]bool{},
  507. offlineAlertNum: 3,
  508. wanDown: map[string]int{},
  509. uplinkWatch: map[string]*uplinkWatch{},
  510. backhaulCache: map[string]backhaulCacheEntry{},
  511. lldpCache: map[string]lldpCacheEntry{},
  512. wanInfoCache: map[string]wanInfoCacheEntry{},
  513. agentDown: map[string]bool{},
  514. agentDownConfirm: 3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
  515. agentOutdatedAlerted: map[string]bool{},
  516. agentOutdatedKey: map[string]string{},
  517. routerMacs: map[string]string{},
  518. sshAuthFailAlerted: map[string]bool{},
  519. fdbMemo: map[string]fdbPortMemo{},
  520. uplinkPorts: map[string]map[string]bool{},
  521. portMon: NewPortMonitor(cfg != nil && cfg.GhostPortEnabled),
  522. suppression: alerts.NewSuppressionGraph(),
  523. }
  524. l.loadRouterMacs()
  525. l.engine.SetSuppression(l.suppression)
  526. // Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
  527. if d != nil {
  528. var flag string
  529. if err := d.QueryRow("SELECT value FROM kv WHERE key = 'attrib_v2'").Scan(&flag); err == sql.ErrNoRows {
  530. _, _ = d.Exec("DELETE FROM device_attrib")
  531. _, _ = d.Exec("INSERT INTO kv (key, value) VALUES ('attrib_v2', '1')")
  532. log.Printf("[netpulse] device_attrib limpiada (attrib_v2: solo wireless persiste)")
  533. }
  534. // issue #248: memoria per-MAC de "desconocido ya alertado", persistida
  535. // en kv para que un reinicio del servidor no vuelva a alertar las
  536. // MACs ya conocidas (clave `unknown_alerted:<mac>`).
  537. if rows, err := d.Query("SELECT key FROM kv WHERE key LIKE 'unknown_alerted:%'"); err == nil {
  538. for rows.Next() {
  539. var key string
  540. if rows.Scan(&key) == nil {
  541. l.unknownAlerted[strings.TrimPrefix(key, "unknown_alerted:")] = true
  542. }
  543. }
  544. rows.Close()
  545. }
  546. // #1400: BSSIDs de impostor aprobados a mano, persistidos en kv.
  547. var allowRaw string
  548. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "impostor_allowlist_v1").Scan(&allowRaw); err == nil {
  549. var list []string
  550. if json.Unmarshal([]byte(allowRaw), &list) == nil {
  551. for _, b := range list {
  552. l.impostorAllow[strings.ToUpper(strings.TrimSpace(b))] = true
  553. }
  554. }
  555. }
  556. // #1400: interruptor global de la regla (ausente = activada).
  557. var enRaw string
  558. if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "alerts.impostor_enabled").Scan(&enRaw); err == nil {
  559. l.impostorEnabled = enRaw != "0"
  560. }
  561. }
  562. // #1441: peers marcados como urgentes (persistidos en kv).
  563. l.loadWGUrgent()
  564. l.SetRouters(initial)
  565. // Only a real, non-demo server resolves names: NewLive(nil, ...) in tests
  566. // and the demo dataset stay off the network.
  567. if cfg != nil && !cfg.DemoMode {
  568. l.rdns = newRDNSCache()
  569. }
  570. return l
  571. }
  572. // loadRouterMacs carga las MACs persistidas de routers para poder emparejar
  573. // agentes con routers por bridge MAC (#282).
  574. func (l *Live) loadRouterMacs() {
  575. if l.db == nil {
  576. return
  577. }
  578. l.routerMacs = map[string]string{}
  579. rows, err := l.db.Query("SELECT id, mac FROM routers WHERE mac IS NOT NULL AND mac != ''")
  580. if err != nil {
  581. return
  582. }
  583. defer rows.Close()
  584. for rows.Next() {
  585. var id, mac string
  586. if rows.Scan(&id, &mac) == nil {
  587. l.routerMacs[id] = mac
  588. }
  589. }
  590. }
  591. // Mode: "live".
  592. func (l *Live) Mode() string { return "live" }
  593. // FleetFdbUplinks (rack canvas): enlaces derivados del FDB para el
  594. // auto-cableado. #1186: la unidad no-root cuyo FDB aprende más MACs bridge
  595. // de flota en puertos DISTINTOS es el switch gestionado (patrón de acceso:
  596. // una MAC por puerto); sus entradas FDB dan los cables exactos
  597. // switch(puerto) ↔ unidad(puerto) - incluido el propio gateway. Sin
  598. // candidato a switch (red plana) devuelve vacío: el auto-cableado no
  599. // inventa nada.
  600. func (l *Live) FleetFdbUplinks() map[string]FdbUplink {
  601. l.mu.Lock()
  602. gw := ""
  603. if l.gatewayCfg != nil {
  604. gw = l.gatewayCfg.ID
  605. }
  606. polled := cloneLastPolled(l.lastPolled)
  607. l.mu.Unlock()
  608. // Cobertura por unidad: MACs bridge de flota en su FDB y en cuántos
  609. // puertos distintos.
  610. type cover struct {
  611. macs map[string]bool
  612. ports map[string]bool
  613. }
  614. cov := map[string]*cover{}
  615. brMacOf := map[string]string{}
  616. for id, p := range polled {
  617. if p == nil {
  618. continue
  619. }
  620. if p.brMac != "" {
  621. brMacOf[id] = strings.ToUpper(p.brMac)
  622. }
  623. c := &cover{macs: map[string]bool{}, ports: map[string]bool{}}
  624. for mac := range p.fdb {
  625. upper := strings.ToUpper(mac)
  626. if owner, ok := brMacOf[upper]; ok && owner == id {
  627. continue // la propia MAC bridge no es "cobertura"
  628. }
  629. c.macs[upper] = true
  630. c.ports[p.fdb[mac]] = true
  631. }
  632. if len(c.macs) > 0 {
  633. cov[id] = c
  634. }
  635. }
  636. // Infraestructura: la unidad no-root con más MACs de flota aprendidas en
  637. // ≥ 2 puertos distintos (el patrón del switch: un vecino por puerto).
  638. infra, best := "", 0
  639. ids := make([]string, 0, len(cov))
  640. for id := range cov {
  641. ids = append(ids, id)
  642. }
  643. sort.Strings(ids)
  644. for _, id := range ids {
  645. if id == gw {
  646. continue
  647. }
  648. if n := len(cov[id].macs); n > best && len(cov[id].ports) >= 2 {
  649. infra, best = id, n
  650. }
  651. }
  652. if infra == "" {
  653. return map[string]FdbUplink{}
  654. }
  655. // Cables: cada MAC de flota aprendida por la infra en un puerto = un
  656. // cable infra(puerto) ↔ unidad(puerto hacia la infra). El root (gateway)
  657. // también sale: su enlace al switch es el uplink de toda la casa.
  658. infraBr := brMacOf[infra]
  659. out := map[string]FdbUplink{}
  660. for mac, port := range polled[infra].fdb {
  661. owner, ok := brMacOf[strings.ToUpper(mac)]
  662. if !ok || owner == infra {
  663. continue
  664. }
  665. childPort := ""
  666. if lm, ok := polled[owner]; ok && lm != nil {
  667. childPort = lm.fdb[infraBr]
  668. }
  669. out[owner] = FdbUplink{ChildID: owner, ParentID: infra, Port: port, ChildPort: childPort}
  670. }
  671. return out
  672. }
  673. // Tick: no-op (el sondeo real ocurre en GetOverview, como el JS).
  674. func cloneLastPolled(src map[string]*routerPolled) map[string]*routerPolled {
  675. if src == nil {
  676. return nil
  677. }
  678. dst := make(map[string]*routerPolled, len(src))
  679. for id, p := range src {
  680. dst[id] = p
  681. }
  682. return dst
  683. }
  684. func (l *Live) Tick(context.Context) error { return nil }
  685. // Close cierra el pool SSH.
  686. func (l *Live) Close() error {
  687. l.pool.Close()
  688. return nil
  689. }
  690. // SetRouters actualiza la lista en caliente y limpia cachés de bajas.
  691. func (l *Live) SetRouters(list []RouterConfig) {
  692. l.mu.Lock()
  693. defer l.mu.Unlock()
  694. l.routers = append([]RouterConfig(nil), list...)
  695. l.gatewayCfg = pickGateway(l.routers)
  696. l.clients = map[string]*OpenWrtClient{}
  697. for _, c := range l.routers {
  698. if !c.AgentOnly {
  699. l.clients[c.ID] = NewOpenWrtClient(c, l.pool, "root", "")
  700. }
  701. }
  702. ids := map[string]bool{}
  703. for _, r := range l.routers {
  704. ids[r.ID] = true
  705. }
  706. for id := range l.lastGood {
  707. if !ids[id] {
  708. delete(l.lastGood, id)
  709. }
  710. }
  711. for id := range l.lastStatus {
  712. if !ids[id] {
  713. delete(l.lastStatus, id)
  714. }
  715. }
  716. for id := range l.boardCache {
  717. if !ids[id] {
  718. delete(l.boardCache, id)
  719. }
  720. }
  721. for id := range l.layoutCache {
  722. if !ids[id] {
  723. delete(l.layoutCache, id)
  724. }
  725. }
  726. for id := range l.extrasCache {
  727. if !ids[id] {
  728. delete(l.extrasCache, id)
  729. }
  730. }
  731. for id := range l.lastAgentIf {
  732. if !ids[id] {
  733. delete(l.lastAgentIf, id)
  734. }
  735. }
  736. for id := range l.lastClientBw {
  737. if !ids[id] {
  738. delete(l.lastClientBw, id)
  739. }
  740. }
  741. for id := range l.snmpPorts {
  742. if !ids[id] {
  743. delete(l.snmpPorts, id)
  744. }
  745. }
  746. for id := range l.snmpLastPoll {
  747. if !ids[id] {
  748. delete(l.snmpLastPoll, id)
  749. }
  750. }
  751. for id := range l.snmpBrMac {
  752. if !ids[id] {
  753. delete(l.snmpBrMac, id)
  754. }
  755. }
  756. for id := range l.snmpLastMetricsTick {
  757. if !ids[id] {
  758. delete(l.snmpLastMetricsTick, id)
  759. }
  760. }
  761. for id := range l.snmpPollStats {
  762. if !ids[id] {
  763. delete(l.snmpPollStats, id)
  764. }
  765. }
  766. for id := range l.lastPolled {
  767. if !ids[id] {
  768. delete(l.lastPolled, id)
  769. }
  770. }
  771. for id := range l.failCount {
  772. if !ids[id] {
  773. delete(l.failCount, id)
  774. }
  775. }
  776. for id := range l.lastErr {
  777. if !ids[id] {
  778. delete(l.lastErr, id)
  779. }
  780. }
  781. // unknownGrace es per-MAC (no por router): se poda por ausencia en
  782. // trackUnknownDevices; aquí solo se limpia la lista completa si no queda
  783. // ningún router (config vacía tras un reset).
  784. if len(l.routers) == 0 {
  785. l.unknownGrace = map[string]int{}
  786. }
  787. for id := range l.backhaulCache {
  788. if !ids[id] {
  789. delete(l.backhaulCache, id)
  790. }
  791. }
  792. for id := range l.lldpCache {
  793. if !ids[id] {
  794. delete(l.lldpCache, id)
  795. }
  796. }
  797. for id := range l.wanInfoCache {
  798. if !ids[id] {
  799. delete(l.wanInfoCache, id)
  800. }
  801. }
  802. for id := range l.sshAuthFailAlerted {
  803. if !ids[id] {
  804. delete(l.sshAuthFailAlerted, id)
  805. }
  806. }
  807. l.loadRouterMacs()
  808. }
  809. // probeBackhaul detecta el medio del uplink (interfaz STA asociada → "wifi";
  810. // si no → "cable") con caché de 5 min: no se sondea cada tick. Error (router
  811. // sin wifi, ubus caído) → "" cacheado igualmente (el campo se omite y el
  812. // sondeo no se rompe).
  813. func (l *Live) probeBackhaul(routerID string, client *OpenWrtClient) string {
  814. l.mu.Lock()
  815. e, ok := l.backhaulCache[routerID]
  816. l.mu.Unlock()
  817. if ok && time.Since(e.at) < backhaulCacheTTL {
  818. return e.value
  819. }
  820. value := ""
  821. if wifi, err := client.GetWirelessUplink(); err == nil {
  822. value = "cable"
  823. if wifi {
  824. value = "wifi"
  825. }
  826. }
  827. l.mu.Lock()
  828. l.backhaulCache[routerID] = backhaulCacheEntry{value: value, at: time.Now()}
  829. l.mu.Unlock()
  830. return value
  831. }
  832. // probeWanInfo: estado de la conexión WAN del gateway (issue #276) con caché
  833. // de 60 s. En routers sin interfaz wan (APs) devuelve WanInfo vacío. Fallo de
  834. // ubus → vacío cacheado (el detalle sigue mostrando lo demás, sin romper).
  835. func (l *Live) probeWanInfo(routerID string, client *OpenWrtClient) probe.WanInfo {
  836. l.mu.Lock()
  837. e, ok := l.wanInfoCache[routerID]
  838. l.mu.Unlock()
  839. if ok && time.Since(e.at) < wanInfoCacheTTL {
  840. return e.info
  841. }
  842. info := client.GetWanInfo()
  843. l.mu.Lock()
  844. l.wanInfoCache[routerID] = wanInfoCacheEntry{info: info, at: time.Now()}
  845. l.mu.Unlock()
  846. return info
  847. }
  848. // probeLldp: vecinos LLDP del router con caché de 45 s (tier lento, como los
  849. // extras anti-parpadeo). Error o lldpd ausente → nil (sin datos; el FDB solo
  850. // sigue mandando, comportamiento actual intacto). Devuelve además si lldpd
  851. // NO está instalado (ErrLldpUnavailable) para que el view-model lo exponga
  852. // (issue #247): hint "instala lldpd" en la UI.
  853. func (l *Live) probeLldp(ctx context.Context, routerID string, client *OpenWrtClient) ([]LldpNeighbor, bool) {
  854. l.mu.Lock()
  855. e, ok := l.lldpCache[routerID]
  856. l.mu.Unlock()
  857. if ok && time.Since(e.at) < lldpCacheTTL {
  858. return e.neighbors, e.unavailable
  859. }
  860. neighbors, err := client.LldpNeighbors(ctx)
  861. unavailable := false
  862. if err != nil {
  863. if errors.Is(err, ErrLldpUnavailable) {
  864. unavailable = true
  865. } else {
  866. log.Printf("[netpulse] LLDP %s: %v", routerID, err)
  867. }
  868. neighbors = nil
  869. }
  870. l.mu.Lock()
  871. l.lldpCache[routerID] = lldpCacheEntry{neighbors: neighbors, unavailable: unavailable, at: time.Now()}
  872. l.mu.Unlock()
  873. return neighbors, unavailable
  874. }
  875. // getAdguardClient: kv (GL.iNet o estándar remoto) con fallback a .env (AGH estándar).
  876. func (l *Live) getAdguardClient() (std *AdGuardClient, gl *AdGuardGlinetClient) {
  877. l.mu.Lock()
  878. defer l.mu.Unlock()
  879. key := ""
  880. if l.db != nil {
  881. mode := "glinet"
  882. _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_mode'").Scan(&mode)
  883. var host string
  884. if err := l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_host'").Scan(&host); err == nil && host != "" {
  885. user := "root"
  886. _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_user'").Scan(&user)
  887. pass := ""
  888. _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_pass'").Scan(&pass)
  889. if pass != "" {
  890. if mode == "standard" {
  891. port := 3000
  892. var portStr string
  893. _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_port'").Scan(&portStr)
  894. if p, err := strconv.Atoi(portStr); err == nil && p > 0 {
  895. port = p
  896. }
  897. url := fmt.Sprintf("http://%s:%d", host, port)
  898. key = "std|" + url + "|" + user
  899. if l.agKey != key {
  900. l.agStd = NewAdGuardClient(url, user, pass)
  901. l.agGL = nil
  902. }
  903. } else {
  904. key = "gl|" + host + "|" + user
  905. if l.agKey != key {
  906. l.agGL = NewAdGuardGlinetClient(host, user, pass, l.pool)
  907. l.agStd = nil
  908. }
  909. }
  910. }
  911. }
  912. }
  913. if key == "" && l.cfg.Adguard != nil && l.cfg.Adguard.Pass != "" {
  914. key = "std|" + l.cfg.Adguard.URL
  915. if l.agKey != key {
  916. l.agStd = NewAdGuardClient(l.cfg.Adguard.URL, l.cfg.Adguard.User, l.cfg.Adguard.Pass)
  917. l.agGL = nil
  918. }
  919. }
  920. if key == "" {
  921. l.agStd = nil
  922. l.agGL = nil
  923. l.agKey = ""
  924. return nil, nil
  925. }
  926. if l.agKey != key {
  927. l.agKey = key
  928. if strings.HasPrefix(key, "gl|") {
  929. l.agStd = nil
  930. } else {
  931. l.agGL = nil
  932. }
  933. }
  934. return l.agStd, l.agGL
  935. }
  936. // histPoint es un punto de metricsHistory {t, down, up, cpu, ram, temp}.
  937. type histPoint struct {
  938. t string
  939. down, up float64
  940. cpu, ram, temp int
  941. }
  942. var weekdayES = []string{"Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"}
  943. // metricsHistory consulta las métricas históricas (index.js:122-147).
  944. // metricsHistoryBuckets lee el histórico largo desde la escalera de retención
  945. // (metrics_buckets, 5 min → 1 año). Usado para el rango 30d, cuyo raw ya se
  946. // purgó (7 días). Agrega los buckets de 5 min a ventanas de `bucket` ms para
  947. // limitar los puntos devueltos (~120 en 30d con ventanas de 6 h).
  948. func (l *Live) metricsHistoryBuckets(routerID string, span, bucket int64, fmtLabel func(time.Time) string) []histPoint {
  949. if l.db == nil || routerID == "" {
  950. return []histPoint{}
  951. }
  952. now := time.Now().UnixMilli()
  953. rows, err := l.db.Query(
  954. `SELECT (bucket_ts / ?) AS win, AVG(rx_avg) AS rx, AVG(tx_avg) AS tx,
  955. AVG(cpu_avg) AS cpu, AVG(ram_avg) AS ram, AVG(temp_avg) AS temp,
  956. MIN(bucket_ts) AS t0
  957. FROM metrics_buckets WHERE router_id = ? AND bucket_ts >= ?
  958. GROUP BY win ORDER BY win`,
  959. bucket, routerID, now-span)
  960. if err != nil {
  961. return []histPoint{}
  962. }
  963. defer rows.Close()
  964. out := []histPoint{}
  965. for rows.Next() {
  966. var b, t0 int64
  967. var rx, tx, cpu, ram, temp sql.NullFloat64
  968. if err := rows.Scan(&b, &rx, &tx, &cpu, &ram, &temp, &t0); err != nil {
  969. continue
  970. }
  971. hp := histPoint{t: fmtLabel(time.UnixMilli(t0).Local())}
  972. if rx.Valid {
  973. hp.down = math.Round(rx.Float64/1e6*10) / 10
  974. }
  975. if tx.Valid {
  976. hp.up = math.Round(tx.Float64/1e6*10) / 10
  977. }
  978. if cpu.Valid {
  979. hp.cpu = int(math.Round(cpu.Float64))
  980. }
  981. if ram.Valid {
  982. hp.ram = int(math.Round(ram.Float64))
  983. }
  984. if temp.Valid {
  985. hp.temp = int(math.Round(temp.Float64))
  986. }
  987. out = append(out, hp)
  988. }
  989. return out
  990. }
  991. func (l *Live) metricsHistory(routerID, rang string) []histPoint {
  992. if l.db == nil || routerID == "" {
  993. return []histPoint{}
  994. }
  995. now := time.Now().UnixMilli()
  996. var span, bucket int64
  997. var fmtLabel func(time.Time) string
  998. switch rang {
  999. case "1h":
  1000. span, bucket = 3600e3, 180e3
  1001. fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d:%02d", d.Hour(), d.Minute()) }
  1002. case "24h":
  1003. span, bucket = 86400e3, 3600e3
  1004. fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d", d.Hour()) }
  1005. case "7d":
  1006. span, bucket = 7*86400e3, 86400e3
  1007. fmtLabel = func(d time.Time) string { return weekdayES[d.Weekday()] }
  1008. case "30d":
  1009. span, bucket = 30*86400e3, 6*3600e3
  1010. fmtLabel = func(d time.Time) string { return fmt.Sprintf("%d", d.Day()) }
  1011. default:
  1012. return []histPoint{}
  1013. }
  1014. // Rango 30d: los raw se purgan a los 7 días, así que se lee de la escalera
  1015. // de retención (metrics_buckets). El resto de rangos usa la tabla raw
  1016. // (suficiente y más fino).
  1017. if rang == "30d" {
  1018. return l.metricsHistoryBuckets(routerID, span, bucket, fmtLabel)
  1019. }
  1020. rows, err := l.db.Query(
  1021. `SELECT (ts / ?) AS bucket, AVG(rx_bps) AS rx, AVG(tx_bps) AS tx, AVG(cpu) AS cpu, AVG(ram) AS ram, AVG(temp) AS temp, MIN(ts) AS t0
  1022. FROM metrics WHERE router_id = ? AND ts >= ? GROUP BY bucket ORDER BY bucket`,
  1023. bucket, routerID, now-span)
  1024. if err != nil {
  1025. return []histPoint{}
  1026. }
  1027. defer rows.Close()
  1028. out := []histPoint{}
  1029. for rows.Next() {
  1030. var b, t0 int64
  1031. var rx, tx, cpu, ram, temp sql.NullFloat64
  1032. if err := rows.Scan(&b, &rx, &tx, &cpu, &ram, &temp, &t0); err != nil {
  1033. continue
  1034. }
  1035. hp := histPoint{t: fmtLabel(time.UnixMilli(t0).Local())}
  1036. if rx.Valid {
  1037. hp.down = math.Round(rx.Float64/1e6*10) / 10
  1038. }
  1039. if tx.Valid {
  1040. hp.up = math.Round(tx.Float64/1e6*10) / 10
  1041. }
  1042. if cpu.Valid {
  1043. hp.cpu = int(math.Round(cpu.Float64))
  1044. }
  1045. if ram.Valid {
  1046. hp.ram = int(math.Round(ram.Float64))
  1047. }
  1048. if temp.Valid {
  1049. hp.temp = int(math.Round(temp.Float64))
  1050. }
  1051. out = append(out, hp)
  1052. }
  1053. return out
  1054. }
  1055. // wanDayStats rellena los campos del resumen WAN que solo el modo demo
  1056. // calculaba (issue #169): pico de hoy (Mbps + hora), media de bajada y total
  1057. // de 24 h, todo desde la tabla raw de métricas del gateway. La hora del pico
  1058. // usa el ts de la fila del máximo; el total estima bytes como
  1059. // SUM(rx_bps) × Δt (Δt = 86400/N s entre muestras, luego /8 bits→bytes).
  1060. // Sin BD, sin gateway o sin datos devuelve los valores cero/"—" de partida.
  1061. type wanDayStatsResult struct {
  1062. peakMbps float64
  1063. peakTime string
  1064. avgMbps float64
  1065. totalBytes float64
  1066. }
  1067. func (l *Live) wanDayStats(gwID string) wanDayStatsResult {
  1068. out := wanDayStatsResult{peakTime: "—"}
  1069. if l.db == nil || gwID == "" {
  1070. return out
  1071. }
  1072. now := time.Now()
  1073. if l.now != nil {
  1074. now = l.now()
  1075. }
  1076. startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).UnixMilli()
  1077. start24h := now.Add(-24 * time.Hour).UnixMilli()
  1078. // Pico de hoy: fila con MAX(rx_bps) y su ts (la hora del pico).
  1079. row := l.db.QueryRow(
  1080. `SELECT rx_bps, ts FROM metrics WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL
  1081. ORDER BY rx_bps DESC LIMIT 1`, gwID, startOfDay)
  1082. var peakBps float64
  1083. var peakTs int64
  1084. if err := row.Scan(&peakBps, &peakTs); err == nil {
  1085. out.peakMbps = math.Round(peakBps/1e6*10) / 10
  1086. out.peakTime = time.UnixMilli(peakTs).Local().Format("15:04")
  1087. }
  1088. // Media 24h + total: AVG(rx_bps) y bytes estimados con el Δt medio.
  1089. row = l.db.QueryRow(
  1090. `SELECT AVG(rx_bps), SUM(rx_bps), COUNT(rx_bps) FROM metrics
  1091. WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL`, gwID, start24h)
  1092. var avg, sum sql.NullFloat64
  1093. var n sql.NullInt64
  1094. if err := row.Scan(&avg, &sum, &n); err == nil && avg.Valid && sum.Valid && n.Valid && n.Int64 > 0 {
  1095. out.avgMbps = math.Round(avg.Float64/1e6*10) / 10
  1096. dt := float64(86400) / float64(n.Int64) // s entre muestras
  1097. out.totalBytes = sum.Float64 * dt / 8
  1098. }
  1099. return out
  1100. }
  1101. // pollRouter sondea un router; error si está inalcanzable. Si el router tiene
  1102. // agente nativo con payload fresco (Tier 2), el sondeo viene del último push
  1103. // y NO se toca SSH; si el agente expiró, se degrada a Tier 0 (SSH) con aviso.
  1104. func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled, error) {
  1105. if fresh, p := l.pollRouterAgent(cfg); fresh {
  1106. // Estado WAN del gateway (issue #276). Los agentes nuevos lo traen en
  1107. // el payload; para los viejos queda la sonda SSH (cache de 60 s), que
  1108. // no existe si el router es agent_only.
  1109. l.mu.Lock()
  1110. gw := l.gatewayCfg
  1111. client := l.clients[cfg.ID]
  1112. l.mu.Unlock()
  1113. hasWan := p.wanInfo.Proto != "" || p.wanInfo.IP != "" || p.wanInfo.Gateway != ""
  1114. if gw != nil && cfg.ID == gw.ID && client != nil && !hasWan {
  1115. p.wanInfo = l.probeWanInfo(cfg.ID, client)
  1116. }
  1117. return p, nil
  1118. }
  1119. if cfg.SnmpEnabled {
  1120. return l.pollRouterSNMP(cfg)
  1121. }
  1122. l.mu.Lock()
  1123. client := l.clients[cfg.ID]
  1124. gw := l.gatewayCfg
  1125. layout, hasLayout := l.layoutCache[cfg.ID]
  1126. board, hasBoard := l.boardCache[cfg.ID]
  1127. cached := l.extrasCache[cfg.ID]
  1128. l.mu.Unlock()
  1129. if client == nil {
  1130. return nil, fmt.Errorf("router %s sin cliente", cfg.ID)
  1131. }
  1132. // Calienta la conexión SSH en serie (equivalente al `ssh true` del JS:
  1133. // las llamadas de abajo multiplexan sobre la conexión ya establecida).
  1134. if _, err := l.pool.Run(cfg.SSHAddr(), "true", 0); err != nil {
  1135. return nil, err
  1136. }
  1137. // Layout de puertos (board.json): se lee una vez y se cachea
  1138. if !hasLayout {
  1139. if lay, err := client.GetPortLayout(); err == nil && len(lay) > 0 {
  1140. layout = lay
  1141. l.mu.Lock()
  1142. l.layoutCache[cfg.ID] = lay
  1143. l.mu.Unlock()
  1144. }
  1145. }
  1146. // sysInfo es la única sonda obligatoria (sin catch en el JS)
  1147. sysInfo, err := client.GetSysInfo()
  1148. if err != nil {
  1149. return nil, err
  1150. }
  1151. cpu, _ := client.GetCPUPercent()
  1152. temp, _ := client.GetTempC()
  1153. // NetDev: total agregado + rates POR IFACE (#305) en una sola lectura.
  1154. net, ifRates := client.GetNetDev()
  1155. if net == nil {
  1156. net = &NetDevBps{}
  1157. }
  1158. leases := client.GetDhcpLeases()
  1159. reservations := client.GetDhcpReservations()
  1160. arp, arpStale, arpDevs := client.GetArp()
  1161. // gl-clients (GL.iNet): complementa la resolución de IP donde dnsmasq no
  1162. // tiene lease (issue #5 bug 1). En routers sin el objeto ubus sale vacío
  1163. // — coste: una llamada ubus local por poll.
  1164. glClients := client.GetGlClients()
  1165. wireless := client.GetWirelessClients()
  1166. ports := client.GetEthPorts(layout, ifRates, l.probeWanInfo(cfg.ID, client).Port)
  1167. radios := client.GetRadios()
  1168. fdb := client.GetBridgeFdb()
  1169. brMac := client.GetBridgeMac()
  1170. // Tier lento: backhaul (5 min) y vecinos LLDP (45 s), ambos cacheados y
  1171. // tolerantes a error (router sin wifi/lldpd → campo ausente, sin romper).
  1172. backhaul := l.probeBackhaul(cfg.ID, client)
  1173. lldp, lldpUnavailable := l.probeLldp(ctx, cfg.ID, client)
  1174. if !hasBoard {
  1175. if b, err := client.GetBoard(); err == nil {
  1176. board = b
  1177. l.mu.Lock()
  1178. l.boardCache[cfg.ID] = b
  1179. l.mu.Unlock()
  1180. }
  1181. }
  1182. // Anti-parpadeo: conserva la última lista buena en sondas puntuales
  1183. // (null = sonda fallida; colección vacía = resultado real).
  1184. if cached == nil {
  1185. cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
  1186. wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
  1187. }
  1188. portsGood := cached.ports
  1189. if len(ports) > 0 {
  1190. portsGood = ports
  1191. }
  1192. radiosGood := cached.radios
  1193. if len(radios) > 0 {
  1194. radiosGood = radios
  1195. }
  1196. wirelessGood := cached.wireless
  1197. if wireless != nil {
  1198. wirelessGood = wireless
  1199. }
  1200. fdbGood := cached.fdb
  1201. if fdb != nil {
  1202. fdbGood = fdb
  1203. }
  1204. // wirelessSide solo nace del payload del agente: en la vía SSH una sonda
  1205. // FDB exitosa lo LIMPIA (nadie lo refresca por este camino y un hint
  1206. // huérfano seguiría atribuyendo MACs rotadas como wireless para siempre);
  1207. // una sonda fallida conserva el cache, mismo anti-parpadeo que fdbGood.
  1208. wsGood := cached.wirelessSide
  1209. if fdb != nil {
  1210. wsGood = nil
  1211. }
  1212. luciGood := cached.luci
  1213. if luci := client.GetLuCILabels(); luci != nil {
  1214. luciGood = luci
  1215. }
  1216. vlansGood := cached.vlans
  1217. if vlans := client.GetBridgeVlans(); vlans != nil {
  1218. vlansGood = vlans
  1219. }
  1220. l.mu.Lock()
  1221. l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, luci: luciGood, vlans: vlansGood}
  1222. l.mu.Unlock()
  1223. // Uso de RAM: #513. Si el agente reporta memory.used (procesos) lo
  1224. // usamos (lo que el usuario percibe como uso real); si no, la fórmula
  1225. // clásica sin caché reclamable (Cached) o MemAvailable. Ver memUsagePct.
  1226. mem := sysInfo.Memory
  1227. ramPct := 0
  1228. if mem.Total > 0 {
  1229. ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
  1230. }
  1231. isGw := gw != nil && cfg.ID == gw.ID
  1232. var latencyMs, lossPct *float64
  1233. if isGw {
  1234. latencyMs, lossPct, _ = client.GetWanLatency("")
  1235. } else if gw != nil {
  1236. latencyMs, _ = client.GetGatewayLatency(gw.Host)
  1237. }
  1238. // Estado WAN solo en el gateway (issue #276), tier lento cacheado.
  1239. var wanInfo probe.WanInfo
  1240. if isGw {
  1241. wanInfo = l.probeWanInfo(cfg.ID, client)
  1242. }
  1243. cpuV := 0
  1244. if cpu != nil {
  1245. cpuV = *cpu
  1246. }
  1247. tempV := 0
  1248. if temp != nil {
  1249. tempV = *temp
  1250. }
  1251. l.recordPortSamples(cfg.ID, portsGood)
  1252. // #551: tráfico por cliente. La vía SSH no sondea nlbwmon (el router
  1253. // gestionado por SSH raramente lo corre); la fuente resuelta es hostapd
  1254. // bytes por estación cuando el driver los expone. Gate de frescura:
  1255. // solo con la sonda wireless de ESTE poll (wireless != nil); si falló y
  1256. // se recicla la cache, los contadores repetidos darían deltas 0.
  1257. if wireless != nil {
  1258. if samples, source, ok := resolveClientBwSources(wireless, nil); ok {
  1259. l.recordClientBwSamples(cfg.ID, time.Now(), samples, source)
  1260. }
  1261. }
  1262. l.portMon.Observe(cfg.ID, portsGood, l.engine)
  1263. return &routerPolled{
  1264. cfg: cfg, client: client, sysInfo: sysInfo, board: board,
  1265. cpu: cpuV, ram: ramPct, temp: tempV,
  1266. uptimeSec: sysInfo.Uptime, net: net, leases: leases, reservations: reservations, arp: arp, arpStale: arpStale, arpDevs: arpDevs, glClients: glClients,
  1267. wireless: wirelessGood, ports: portsGood, radios: radiosGood,
  1268. fdb: fdbGood, wirelessSide: wsGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
  1269. backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
  1270. luci: luciGood, wanInfo: wanInfo, vlans: vlansGood,
  1271. polledAt: l.now().UnixMilli(),
  1272. }, nil
  1273. }
  1274. // fwAlertState (#1411): episodio de alerta de firmware abierto para una
  1275. // unidad. cmp es el resultado de firmwareCompare que se alertó; installed y
  1276. // target recuerdan contra qué se abrió para detectar el cambio de episodio.
  1277. type fwAlertState struct {
  1278. cmp int
  1279. installed string
  1280. target string
  1281. }
  1282. // evalFirmwareAlert (#1411/#1412) abre, refresca o resuelve la alerta de
  1283. // firmware de una unidad con target configurado. Un episodio por unidad: se
  1284. // emite al detectarse el mismatch (ID estable alert-firmware-<id>), se
  1285. // actualiza en sitio (EmitOrUpdate = episodio nuevo notificado) si cambia la
  1286. // versión instalada o el target, y se resuelve (modelo #1349) al volver a
  1287. // coincidir. Mientras el episodio sigue igual NO se re-emite: el feed no se
  1288. // re-firea cada ciclo. El downgrade (target más viejo) alerta con wording
  1289. // propio (#1412).
  1290. func (l *Live) evalFirmwareAlert(routerID, name, installed, target string, cmp int) {
  1291. id := "alert-firmware-" + routerID
  1292. l.mu.Lock()
  1293. if l.fwAlert == nil {
  1294. l.fwAlert = map[string]fwAlertState{}
  1295. }
  1296. st, active := l.fwAlert[routerID]
  1297. if cmp == fwMatch {
  1298. delete(l.fwAlert, routerID)
  1299. l.mu.Unlock()
  1300. if active {
  1301. l.engine.Resolve(id)
  1302. }
  1303. return
  1304. }
  1305. if active && st.cmp == cmp && st.installed == installed && st.target == target {
  1306. // Episodio en curso sin cambios: nada que hacer (#1411).
  1307. l.mu.Unlock()
  1308. return
  1309. }
  1310. l.fwAlert[routerID] = fwAlertState{cmp: cmp, installed: installed, target: target}
  1311. l.mu.Unlock()
  1312. ev := AlertEvent{
  1313. ID: id, Category: alerts.CatSystem, Urgent: false,
  1314. Severity: "warn", RouterID: routerID,
  1315. Vars: map[string]string{"router": name, "firmware": installed, "target": target},
  1316. Time: "just now",
  1317. }
  1318. if cmp == fwOlder {
  1319. ev.Title = "Firmware downgrade target"
  1320. ev.Description = fmt.Sprintf("%s: configured target %q is older than the installed firmware %q", name, target, installed)
  1321. ev.Type = alerts.HintFirmwareDowngrade
  1322. ev.Hint = alerts.HintFor(alerts.HintFirmwareDowngrade)
  1323. } else {
  1324. ev.Title = "Firmware outdated"
  1325. ev.Description = fmt.Sprintf("%s: firmware %q does not match the target %q", name, installed, target)
  1326. ev.Type = alerts.HintFirmware
  1327. ev.Hint = alerts.HintFor(alerts.HintFirmware)
  1328. }
  1329. l.engine.EmitOrUpdate(ev)
  1330. }
  1331. // SetFirmwareReleases (#1444) publica la lista cacheada de releases
  1332. // publicados (la alimenta el ReleasesRefresher tras cada chequeo periódico).
  1333. func (l *Live) SetFirmwareReleases(v []string, ts int64) {
  1334. l.mu.Lock()
  1335. defer l.mu.Unlock()
  1336. l.fwReleases = append([]string(nil), v...)
  1337. l.fwReleasesTs = ts
  1338. }
  1339. // firmwareTargetKnown (#1444): ¿figura el target entre los releases
  1340. // publicados? Con la lista vacía (chequeo aún sin éxito) NO se gatea: se
  1341. // conserva el comportamiento previo en flotas sin salida a
  1342. // downloads.openwrt.org.
  1343. func (l *Live) firmwareTargetKnown(target string) bool {
  1344. l.mu.Lock()
  1345. defer l.mu.Unlock()
  1346. if len(l.fwReleases) == 0 {
  1347. return true
  1348. }
  1349. for _, v := range l.fwReleases {
  1350. if v == target {
  1351. return true
  1352. }
  1353. }
  1354. return false
  1355. }
  1356. // evalFirmwareUnknownTarget (#1444): episodio del aviso "el target no existe
  1357. // upstream" (configuración, no firmware desactualizado). target == "" resuelve
  1358. // el episodio (target corregido, retirado o vuelto conocido).
  1359. func (l *Live) evalFirmwareUnknownTarget(routerID, name, target string) {
  1360. id := "alert-fw-target-unknown-" + routerID
  1361. l.mu.Lock()
  1362. if l.fwUnknownTarget == nil {
  1363. l.fwUnknownTarget = map[string]string{}
  1364. }
  1365. if target == "" {
  1366. _, active := l.fwUnknownTarget[routerID]
  1367. delete(l.fwUnknownTarget, routerID)
  1368. l.mu.Unlock()
  1369. if active {
  1370. l.engine.Resolve(id)
  1371. }
  1372. return
  1373. }
  1374. if prev, active := l.fwUnknownTarget[routerID]; active && prev == target {
  1375. l.mu.Unlock()
  1376. return
  1377. }
  1378. l.fwUnknownTarget[routerID] = target
  1379. l.mu.Unlock()
  1380. l.engine.EmitOrUpdate(AlertEvent{
  1381. ID: id, Category: alerts.CatSystem, Urgent: false,
  1382. Severity: "warn", RouterID: routerID,
  1383. Title: "Firmware target not available",
  1384. Description: fmt.Sprintf("%s: configured target %q is not among the published OpenWrt releases", name, target),
  1385. Type: alerts.HintFirmwareUnknownTarget,
  1386. Vars: map[string]string{"router": name, "target": target},
  1387. Time: "just now",
  1388. })
  1389. }
  1390. // buildRouter construye el Router del contrato (index.js:221-249).
  1391. // countBand acumula un cliente en la banda del desglose (issue #645). La
  1392. // banda "—" (desconocida) no cae en ninguna: suma ≤ total de clientes.
  1393. func countBand(split *demoBandSplit, band string) {
  1394. switch {
  1395. case strings.HasPrefix(band, "2.4"):
  1396. split.Band24++
  1397. case strings.HasPrefix(band, "5"):
  1398. split.Band5++
  1399. case strings.HasPrefix(band, "6"):
  1400. split.Band6++
  1401. case band == "cable":
  1402. split.Cable++
  1403. }
  1404. }
  1405. // allZeroF: ¿todos los valores del slice son 0 (o vacío)?
  1406. func allZeroF(v []float64) bool {
  1407. for _, x := range v {
  1408. if x != 0 {
  1409. return false
  1410. }
  1411. }
  1412. return true
  1413. }
  1414. func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
  1415. l.mu.Lock()
  1416. gw := l.gatewayCfg
  1417. l.mu.Unlock()
  1418. // issue #716: umbral de temperatura alta del router (default 65 °C).
  1419. thr := p.cfg.TempThresholdValue()
  1420. model := p.cfg.Name
  1421. if model == "" {
  1422. model = p.cfg.Host
  1423. }
  1424. if p.board != nil && p.board.Model != "" {
  1425. model = p.board.Model
  1426. }
  1427. // #1256: los switches SNMP no tienen board (sondeo sin SSH); el
  1428. // sysDescr declara el nombre/modelo completo del equipo.
  1429. if p.cfg.SnmpEnabled && p.sysDescr != "" {
  1430. model = p.sysDescr
  1431. }
  1432. name := p.cfg.Name
  1433. if name == "" {
  1434. name = p.cfg.Host
  1435. }
  1436. if p.board != nil && p.board.Hostname != "" {
  1437. name = p.board.Hostname
  1438. }
  1439. // #1256: los switches SNMP no tienen board; el sysName (hostname que el
  1440. // usuario define en el equipo, p. ej. la página de sistema de SwOS) es
  1441. // el nombre natural de la unidad.
  1442. if p.cfg.SnmpEnabled && p.sysName != "" {
  1443. name = p.sysName
  1444. }
  1445. health := 100
  1446. if p.cpu > 85 {
  1447. health -= 20
  1448. } else if p.cpu > 70 {
  1449. health -= 10
  1450. }
  1451. if p.temp > 75 {
  1452. health -= 25
  1453. } else if p.temp > thr {
  1454. health -= 12
  1455. }
  1456. if p.ram > 90 {
  1457. health -= 15
  1458. }
  1459. // issue #241: firmware fuera del target configurado penaliza la salud.
  1460. // #1412: la comparación es por versión de release parseada; un target más
  1461. // viejo que lo instalado (downgrade) no se penaliza como "desactualizado".
  1462. fwCmp := fwMatch
  1463. if p.cfg.FirmwareTarget != "" && p.board != nil {
  1464. fwCmp = firmwareCompare(p.board.Release.Description, p.cfg.FirmwareTarget)
  1465. if fwCmp == fwNewer || fwCmp == fwAmbiguous {
  1466. health -= 5
  1467. }
  1468. }
  1469. if health < 0 {
  1470. health = 0
  1471. }
  1472. isGw := gw != nil && p.cfg.ID == gw.ID
  1473. status := "online"
  1474. if p.temp > thr || p.cpu > 85 {
  1475. status = "warn"
  1476. }
  1477. sparkline := make([]float64, 0, len(history))
  1478. for _, h := range history {
  1479. sparkline = append(sparkline, h.down)
  1480. }
  1481. // #441: SNMP y pushers externos no pueden reportar CPU/RAM/temp. Se marca
  1482. // el router y las vitals van a null (la UI no pinta ceros falsos).
  1483. noVitals := p.cfg.SnmpEnabled || p.agentKind == "external"
  1484. r := Router{
  1485. ID: p.cfg.ID, Name: name, Model: model, ModelShort: model,
  1486. IP: p.cfg.Host, Status: status, Health: health,
  1487. CPU: iptr(p.cpu), RAM: iptr(p.ram), Temp: iptr(p.temp),
  1488. Uptime: fmtUptime(p.uptimeSec), Clients: len(p.leases),
  1489. Sparkline: sparkline, TempThreshold: thr,
  1490. LatencyMs: p.latencyMs,
  1491. }
  1492. if noVitals {
  1493. r.CPU, r.RAM, r.Temp = nil, nil, nil
  1494. v := resolvePartialVitals(p)
  1495. r.CPU, r.Temp = v.cpu, v.temp
  1496. r.VitalsAvailable = bptr(v.available)
  1497. }
  1498. r.SnmpEnabled = p.cfg.SnmpEnabled
  1499. if p.selfExpose {
  1500. r.SelfExpose = bptr(true)
  1501. }
  1502. if isGw {
  1503. r.Role, r.RoleBadge = "Gateway principal", "Principal"
  1504. } else if cfgIsSwitch(p.cfg) {
  1505. // external sondeado por SNMP = switch en la práctica (#661); evita el
  1506. // fallback AP para los switches SNMP de crowedavid (#1137).
  1507. r.Role, r.RoleBadge = "Switch", "SW"
  1508. } else if p.cfg.Type == "external" {
  1509. // #1137: un external genérico NO es un AP; el fallback anterior le
  1510. // colgaba el chip AP cian en la tarjeta del detalle.
  1511. r.Role, r.RoleBadge = "External", "EXT"
  1512. } else {
  1513. r.Role, r.RoleBadge = "Punto de acceso", "AP"
  1514. }
  1515. if p.brMac != "" {
  1516. r.MAC = p.brMac
  1517. }
  1518. if p.backhaul != "" {
  1519. r.Backhaul = p.backhaul
  1520. }
  1521. if uplink := l.uplinkLldp(p); uplink != nil {
  1522. r.Lldp = uplink
  1523. }
  1524. if p.lldpUnavailable {
  1525. r.LldpAvailable = bptr(false)
  1526. }
  1527. if p.lldpHint != "" {
  1528. r.LldpHint = p.lldpHint
  1529. }
  1530. if p.board != nil {
  1531. r.Firmware = p.board.Release.Description
  1532. }
  1533. if p.cfg.FirmwareTarget != "" {
  1534. r.FirmwareTarget = p.cfg.FirmwareTarget
  1535. }
  1536. if p.cfg.AgentOnly {
  1537. r.AgentOnly = true
  1538. }
  1539. if p.cfg.Type != "" {
  1540. r.Type = p.cfg.Type
  1541. }
  1542. if p.firmwareAvailable != "" && r.FirmwareTarget == "" {
  1543. r.FirmwareTarget = p.firmwareAvailable
  1544. }
  1545. // #1411/#1412: con target configurado la alerta es UN episodio por unidad
  1546. // (ID estable), no un re-fire por ciclo: se abre al detectar el mismatch,
  1547. // se actualiza si cambia la versión o el target, y se resuelve al
  1548. // coincidir. El downgrade (target más viejo) alerta con wording propio.
  1549. if p.firmwareAvailable != "" {
  1550. r.FirmwareOutdated = true
  1551. l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
  1552. // External pushers keep the per-cycle warning as before #1411; the
  1553. // five-minute dedup bounds it.
  1554. l.engine.Emit(AlertEvent{
  1555. ID: fmt.Sprintf("alert-firmware-%s-%d", p.cfg.ID, time.Now().UnixMilli()),
  1556. Category: alerts.CatSystem, Urgent: false,
  1557. Severity: "warn",
  1558. Title: "Firmware outdated",
  1559. Description: fmt.Sprintf("%s: firmware %q does not match the target %q", name, r.Firmware, p.cfg.FirmwareTarget),
  1560. Hint: alerts.HintFor(alerts.HintFirmware),
  1561. Type: alerts.HintFirmware,
  1562. Vars: map[string]string{"router": name, "firmware": r.Firmware, "target": p.cfg.FirmwareTarget},
  1563. Time: "just now", RouterID: p.cfg.ID,
  1564. })
  1565. } else if p.cfg.FirmwareTarget != "" {
  1566. // #1444: el target existe upstream → alerta normal de mismatch.
  1567. // Target desconocido upstream → aviso de configuración y SIN marca
  1568. // de desactualizado (un target inventado no es firmware viejo).
  1569. // Lista vacía (chequeo sin éxito aún) → comportamiento previo.
  1570. l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
  1571. if l.firmwareTargetKnown(p.cfg.FirmwareTarget) {
  1572. if fwCmp == fwNewer || fwCmp == fwAmbiguous {
  1573. r.FirmwareOutdated = true
  1574. }
  1575. if p.board != nil {
  1576. l.evalFirmwareAlert(p.cfg.ID, name, r.Firmware, p.cfg.FirmwareTarget, fwCmp)
  1577. }
  1578. } else {
  1579. l.evalFirmwareUnknownTarget(p.cfg.ID, name, p.cfg.FirmwareTarget)
  1580. }
  1581. } else {
  1582. // Sin target configurado: el aviso de target desconocido queda resuelto.
  1583. l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
  1584. }
  1585. if p.temp > thr {
  1586. r.HotMetric = "temp"
  1587. }
  1588. return r
  1589. }
  1590. // uplinkLldp: vecino LLDP del router que es OTRO router conocido → el uplink
  1591. // está identificado por LLDP y la app muestra el sufijo "· LLDP". El vecino se
  1592. // casa por chassis-MAC = bridge MAC de otro router (matching original) o, si
  1593. // el chassis-ID que anuncia lldpd difiere de la br-lan (habitual en OpenWrt,
  1594. // issue #252), por su mgmt-IP o nombre del chasis. Si el FDB dice dónde se
  1595. // aprendió esa MAC, el anuncio debe llegar por ese puerto (uplink); sin FDB,
  1596. // la MAC ya es evidencia suficiente. nil si no hay dato.
  1597. func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
  1598. if len(p.lldp) == 0 {
  1599. return nil
  1600. }
  1601. l.mu.Lock()
  1602. polled := cloneLastPolled(l.lastPolled)
  1603. l.mu.Unlock()
  1604. routers := routerIdentities(polled)
  1605. for i := range p.lldp {
  1606. nb := &p.lldp[i]
  1607. if neighborIsRouter(nb, routers, p.cfg.ID) == nil {
  1608. continue
  1609. }
  1610. if port, ok := p.fdb[nb.ChassisMac]; ok && port != nb.Port {
  1611. continue
  1612. }
  1613. return nb.info()
  1614. }
  1615. return nil
  1616. }
  1617. // offlineRouter: último bueno marcado offline o placeholder (index.js:251-272).
  1618. // pausedRouter (#1085): una unidad pausada no se sondea ni alerta. Se
  1619. // muestra con la última snapshot conocida (o el esqueleto básico) y el
  1620. // estado "paused", que la UI distingue con la insignia de pausada. Reutiliza
  1621. // offlineRouter para el esqueleto y le pisa el estado: pausar no es estar
  1622. // caído, y los flags de acceso/host key no aplican mientras no se sondea.
  1623. func (l *Live) pausedRouter(cfg RouterConfig) Router {
  1624. r := l.offlineRouter(cfg)
  1625. r.Status = "paused"
  1626. r.AccessMissing = false
  1627. r.HostKeyChanged = false
  1628. r.Disabled = true
  1629. return r
  1630. }
  1631. // issue #257: si el último fallo fue de ACCESO (el router responde pero la
  1632. // clave SSH no está autorizada), el estado es "unreachable" + accessMissing,
  1633. // no un "offline" de apagado/inalcanzable (config issue, no power issue).
  1634. func (l *Live) offlineRouter(cfg RouterConfig) Router {
  1635. l.mu.Lock()
  1636. prev := l.lastGood[cfg.ID]
  1637. gw := l.gatewayCfg
  1638. l.mu.Unlock()
  1639. var r Router
  1640. if prev != nil {
  1641. r = *prev
  1642. } else {
  1643. model := "OpenWrt"
  1644. switch cfg.Type {
  1645. case "glinet":
  1646. model = "GL.iNet"
  1647. case "managed-switch":
  1648. model = "Managed Switch"
  1649. }
  1650. name := cfg.Name
  1651. if name == "" {
  1652. name = cfg.Host
  1653. }
  1654. r = Router{
  1655. ID: cfg.ID, Name: name, Model: model, ModelShort: model,
  1656. IP: cfg.Host, Health: 0,
  1657. CPU: iptr(0), RAM: iptr(0), Temp: iptr(0),
  1658. Uptime: "—", Clients: 0, Sparkline: []float64{},
  1659. Type: cfg.Type,
  1660. }
  1661. if gw != nil && cfg.ID == gw.ID {
  1662. r.Role, r.RoleBadge = "Gateway principal", "Principal"
  1663. } else if cfg.Type == "managed-switch" || (cfg.Type == "external" && cfg.SnmpEnabled) {
  1664. r.Role, r.RoleBadge = "Switch", "SW"
  1665. } else if cfg.Type == "external" {
  1666. r.Role, r.RoleBadge = "External", "EXT"
  1667. } else {
  1668. r.Role, r.RoleBadge = "Punto de acceso", "AP"
  1669. }
  1670. }
  1671. r.Type = cfg.Type
  1672. r.Status = "offline"
  1673. if l.accessMissing(cfg.ID) {
  1674. r.Status = "unreachable"
  1675. r.AccessMissing = true
  1676. }
  1677. if l.hostKeyChanged(cfg.ID) {
  1678. r.Status = "unreachable"
  1679. r.HostKeyChanged = true
  1680. }
  1681. return r
  1682. }
  1683. // accessMissing: el último fallo de sondeo de este router fue de ACCESO
  1684. // (SSH responde pero la clave no está autorizada / ubus rechaza), es decir
  1685. // el router está vivo pero el servidor no puede entrar (issue #257).
  1686. func (l *Live) accessMissing(routerID string) bool {
  1687. l.mu.Lock()
  1688. defer l.mu.Unlock()
  1689. return isAccessError(l.lastErr[routerID])
  1690. }
  1691. // hostKeyChanged: el último fallo de sondeo fue una clave SSH distinta a la
  1692. // registrada (issue #603). El router está vivo; la conexión se rechaza hasta
  1693. // que el admin confirme el re-onboard.
  1694. func (l *Live) hostKeyChanged(routerID string) bool {
  1695. l.mu.Lock()
  1696. defer l.mu.Unlock()
  1697. return isHostKeyError(l.lastErr[routerID])
  1698. }
  1699. // AcceptHostKey confirma el re-onboard de un router tras una host key cambiada
  1700. // (#603): borra su entrada known_hosts (siguiente sondeo = TOFU) y resetea el
  1701. // error para que el router deje de mostrarse como "host key changed".
  1702. func (l *Live) AcceptHostKey(routerID string) error {
  1703. if l.pool == nil {
  1704. return errors.New("ssh pool no configurado")
  1705. }
  1706. l.mu.Lock()
  1707. var cfg *RouterConfig
  1708. for i := range l.routers {
  1709. if l.routers[i].ID == routerID {
  1710. cfg = &l.routers[i]
  1711. break
  1712. }
  1713. }
  1714. l.mu.Unlock()
  1715. if cfg == nil {
  1716. return fmt.Errorf("router %q no configurado", routerID)
  1717. }
  1718. // #1524: la entrada known_hosts se escribe con la forma de la dirección
  1719. // que diala el pool ([host]:puerto en puertos no estándar, host pelado en
  1720. // el 22). Se pasan ambas formas: la SSHAddr efectiva y el host pelado, por
  1721. // si queda una entrada vieja de cuando el router no tenía puerto custom.
  1722. if err := l.pool.RemoveHostKey(cfg.SSHAddr(), cfg.Host); err != nil {
  1723. return err
  1724. }
  1725. l.mu.Lock()
  1726. delete(l.lastErr, routerID)
  1727. l.failCount[routerID] = 0
  1728. l.mu.Unlock()
  1729. return nil
  1730. }
  1731. // isAccessError: ¿el error indica que el router RESPONDE pero el acceso
  1732. // SSH/ubus no está configurado? (handshake SSH que rechaza la clave del
  1733. // servidor). Un fallo de conexión (refused/timeout/red) NO es un fallo de
  1734. // acceso: ahí el router puede estar apagado o inalcanzable (issue #257).
  1735. func isAccessError(err error) bool {
  1736. if err == nil {
  1737. return false
  1738. }
  1739. msg := strings.ToLower(err.Error())
  1740. for _, hint := range []string{
  1741. "unable to authenticate",
  1742. "no supported methods",
  1743. "permission denied",
  1744. "authentication failed",
  1745. "not authorized",
  1746. } {
  1747. if strings.Contains(msg, hint) {
  1748. return true
  1749. }
  1750. }
  1751. return false
  1752. }
  1753. // isHostKeyError: el router responde pero su host key no casa con la
  1754. // registrada (issue #603). No es un fallo de acceso ni una caída: requiere
  1755. // confirmación explícita de re-onboard.
  1756. func isHostKeyError(err error) bool {
  1757. if err == nil {
  1758. return false
  1759. }
  1760. var hk *HostKeyChangedError
  1761. return errors.As(err, &hk) || strings.Contains(strings.ToLower(err.Error()), "re-onboard required")
  1762. }
  1763. // pollAll sondea todos los routers en paralelo (Promise.allSettled).
  1764. // issue #1085: las unidades pausadas (disabled) NO se sondean; se limpian
  1765. // sus contadores de fallo y sus alertas de offline abiertas, y quedan con
  1766. // estado "paused" en el overview (ver pausedRouter).
  1767. func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
  1768. l.mu.Lock()
  1769. routers := append([]RouterConfig(nil), l.routers...)
  1770. l.mu.Unlock()
  1771. active := make([]RouterConfig, 0, len(routers))
  1772. for _, cfg := range routers {
  1773. if cfg.Disabled {
  1774. continue
  1775. }
  1776. active = append(active, cfg)
  1777. }
  1778. type result struct {
  1779. cfg RouterConfig
  1780. p *routerPolled
  1781. err error
  1782. }
  1783. results := make([]result, len(active))
  1784. var wg sync.WaitGroup
  1785. for i, cfg := range active {
  1786. wg.Add(1)
  1787. go func(i int, cfg RouterConfig) {
  1788. defer wg.Done()
  1789. p, err := l.pollRouter(ctx, cfg)
  1790. results[i] = result{cfg, p, err}
  1791. }(i, cfg)
  1792. }
  1793. wg.Wait()
  1794. polled := map[string]*routerPolled{}
  1795. l.mu.Lock()
  1796. defer l.mu.Unlock()
  1797. // #1085: una unidad pausada no se sondea: sus fallos en curso se anulan
  1798. // (al reanudar, el sondeo arranca limpio) y sus alertas de offline se
  1799. // resuelven: pausar no es estar caído.
  1800. for _, cfg := range routers {
  1801. if !cfg.Disabled {
  1802. continue
  1803. }
  1804. l.failCount[cfg.ID] = 0
  1805. delete(l.lastErr, cfg.ID)
  1806. delete(l.lastStatus, cfg.ID)
  1807. l.resolveOfflineAlerts(cfg.ID)
  1808. }
  1809. for _, res := range results {
  1810. if res.err == nil {
  1811. polled[res.cfg.ID] = res.p
  1812. l.failCount[res.cfg.ID] = 0
  1813. delete(l.lastErr, res.cfg.ID)
  1814. // Persiste la bridgeMAC del router (issue #196): la exclusión de
  1815. // "dispositivo desconocido" no debe depender de que este router se
  1816. // sondee bien en el tick actual.
  1817. if l.db != nil && res.p.brMac != "" {
  1818. _, _ = l.db.Exec("UPDATE routers SET mac = ? WHERE id = ?", res.p.brMac, res.cfg.ID)
  1819. if res.p.brMac != "" {
  1820. // #1334: la identidad MAC también se actualiza EN PROCESO;
  1821. // el write a BD solo era útil tras un reinicio, y el
  1822. // matching de agentes (MatchRouter) la consulta en vivo.
  1823. l.routerMacs[res.cfg.ID] = res.p.brMac
  1824. }
  1825. }
  1826. // Router recuperado (offline→online, SPEC-ALERTAS §1). issue #846:
  1827. // con incidente abierto la recuperación debe estabilizarse antes
  1828. // de cerrarlo (un flap breve no rearma ni cierra la alerta).
  1829. if l.offlineOpen[res.cfg.ID] || l.lastStatus[res.cfg.ID] == "offline" {
  1830. l.trackRouterRecovered(&res.cfg)
  1831. }
  1832. l.lastStatus[res.cfg.ID] = "online"
  1833. // WAN/Internet caído: gateway OK pero ping a internet con 100 %
  1834. // de pérdida en 2 sondeos seguidos (mismo debounce que offline).
  1835. if l.gatewayCfg != nil && res.cfg.ID == l.gatewayCfg.ID {
  1836. l.trackWanDown(&res.cfg, res.p)
  1837. }
  1838. // Any router can have two lines; this is not a gateway-only
  1839. // arrangement.
  1840. l.trackUplinkChange(res.cfg, res.p, time.Now())
  1841. continue
  1842. }
  1843. fails := l.failCount[res.cfg.ID] + 1
  1844. l.failCount[res.cfg.ID] = fails
  1845. l.lastErr[res.cfg.ID] = res.err
  1846. log.Printf("[netpulse] router %s inalcanzable (%d): %v", res.cfg.LogLabel(), fails, res.err)
  1847. l.trackRouterOffline(&res.cfg, res.err, fails)
  1848. if fails >= 2 {
  1849. l.lastStatus[res.cfg.ID] = "offline"
  1850. }
  1851. }
  1852. // Reconciliación de huérfanas (issue #846): cada ciclo, los routers que
  1853. // responden SIN incidente abierto se limpian de alertas de offline de
  1854. // procesos anteriores (offlineOpen vive en memoria y no sobrevive a un
  1855. // reinicio; si el router responde, el que estuvo caído fue el servidor).
  1856. // Corre en cada ciclo (no solo en el arranque) para ser auto-sanante
  1857. // aunque el router falle justo en el primer ciclo tras arrancar. Los
  1858. // routers caídos conservan la suya hasta que trackRouterOffline la
  1859. // sustituye por la del incidente nuevo.
  1860. l.reconcileOfflineOrphans(polled)
  1861. l.lastPolled = polled
  1862. return polled
  1863. }
  1864. // reconcileOfflineOrphans retira las alertas de offline huérfanas de los
  1865. // routers que responden sin incidente abierto (issue #846). Debe llamarse
  1866. // con l.mu tomado.
  1867. func (l *Live) reconcileOfflineOrphans(polled map[string]*routerPolled) {
  1868. for id := range polled {
  1869. if !l.offlineOpen[id] {
  1870. l.resolveOfflineAlerts(id)
  1871. }
  1872. }
  1873. }
  1874. // emitRouterRecovered: evento "router recuperado" (offline→online;
  1875. // category router, urgent false, severity ok — SPEC-ALERTAS §1).
  1876. // Debe llamarse con l.mu tomado (mismo contexto que el resto de emisiones).
  1877. func (l *Live) emitRouterRecovered(routerID, name string) {
  1878. if l.suppression != nil {
  1879. l.suppression.MarkUp(routerID)
  1880. }
  1881. l.engine.Emit(AlertEvent{
  1882. ID: fmt.Sprintf("alert-recovered-%s-%d", routerID, time.Now().UnixMilli()),
  1883. Category: alerts.CatRouter, Urgent: false,
  1884. Severity: "ok",
  1885. Title: name + " recovered",
  1886. Description: fmt.Sprintf("%s is responding again", name),
  1887. Type: alerts.TypeRouterRecovered,
  1888. Vars: map[string]string{"router": name},
  1889. Time: "just now", RouterID: routerID,
  1890. })
  1891. }
  1892. // offlineRecoverTicks: sondeos seguidos con éxito necesarios para cerrar un
  1893. // incidente de offline (issue #846). Un flap breve (online transitorio entre
  1894. // fallos) no cierra el incidente: la alerta de caída sigue abierta y no se
  1895. // emite "recuperado" hasta que el router responde de forma estable.
  1896. const offlineRecoverTicks = 3
  1897. // trackRouterOffline (issue #846): alerta crítica de offline tras 2 fallos
  1898. // seguidos. Un fallo de ACCESO (SSH responde pero la clave no está
  1899. // autorizada, #257) o una host key cambiada (#603) no es una caída — el
  1900. // router está vivo; la UI lo marca "sin acceso" y no merece alerta crítica.
  1901. // Mientras el incidente esté abierto NO se re-emite (aunque el estado flapee
  1902. // entre offline y online): un incidente = una alerta = una notificación.
  1903. // Debe llamarse con l.mu tomado.
  1904. func (l *Live) trackRouterOffline(cfg *RouterConfig, err error, fails int) {
  1905. quietErr := isAccessError(err) || isHostKeyError(err)
  1906. if fails < 2 || quietErr || l.offlineOpen[cfg.ID] {
  1907. return
  1908. }
  1909. if l.offlineOpen == nil {
  1910. l.offlineOpen = map[string]bool{}
  1911. l.recoverStreak = map[string]int{}
  1912. }
  1913. name := cfg.Name
  1914. if name == "" {
  1915. name = cfg.Host
  1916. }
  1917. if l.suppression != nil {
  1918. l.suppression.MarkDown(cfg.ID)
  1919. }
  1920. ev := AlertEvent{
  1921. ID: fmt.Sprintf("alert-offline-%s-%d", cfg.ID, time.Now().UnixMilli()),
  1922. Category: alerts.CatRouter, Urgent: true,
  1923. Severity: "critical",
  1924. Title: name + " offline",
  1925. Description: fmt.Sprintf("No response from %s: %v", cfg.Host, err),
  1926. Hint: alerts.HintFor(alerts.HintDeviceOffline),
  1927. Type: alerts.TypeRouterOffline,
  1928. Vars: map[string]string{"router": name, "host": cfg.Host, "error": fmt.Sprint(err)},
  1929. Time: "just now", RouterID: cfg.ID,
  1930. }
  1931. // Sin dedup de 5 min: al cerrarse, el incidente anterior retiró su alerta
  1932. // del feed (resolveOfflineAlerts) y la ventana bloquearía ésta — el "una
  1933. // alerta por outage" lo garantiza offlineOpen, no el dedup.
  1934. l.engine.EmitNoDedup(ev)
  1935. // Huérfanas de un proceso anterior (reinicio del servidor durante una
  1936. // caída): la alerta del incidente nuevo las sustituye, nunca se acumulan.
  1937. l.removeStaleOfflineAlerts(cfg.ID, ev.ID)
  1938. l.offlineOpen[cfg.ID] = true
  1939. l.recoverStreak[cfg.ID] = 0
  1940. }
  1941. // removeStaleOfflineAlerts elimina las alertas de offline del router salvo
  1942. // keepID (issue #846): al abrir un incidente sustituye las huérfanas que un
  1943. // proceso anterior dejó en alert_log (offlineOpen vive en memoria y no
  1944. // sobrevive a un reinicio). Debe llamarse con l.mu tomado.
  1945. func (l *Live) removeStaleOfflineAlerts(routerID, keepID string) {
  1946. ids := []string{}
  1947. for _, ev := range l.engine.List() {
  1948. if ev.RouterID == routerID && strings.HasPrefix(ev.ID, "alert-offline-") && ev.ID != keepID {
  1949. ids = append(ids, ev.ID)
  1950. }
  1951. }
  1952. if len(ids) > 0 {
  1953. l.engine.Remove(ids...)
  1954. }
  1955. }
  1956. // trackRouterRecovered (issue #846): cierra el incidente de offline cuando la
  1957. // recuperación es estable (offlineRecoverTicks éxitos seguidos): elimina las
  1958. // alertas de caída del router y emite el evento "recuperado" como relevo
  1959. // positivo en el feed. Con incidente abierto, un éxito aislado NO cierra nada
  1960. // (la caída sigue viva y no se insiste). Sin incidente abierto —caída sin
  1961. // alerta por error de acceso (#257/#603)— se resuelve en el primer éxito,
  1962. // como antes. Debe llamarse con l.mu tomado.
  1963. func (l *Live) trackRouterRecovered(cfg *RouterConfig) {
  1964. if l.offlineOpen[cfg.ID] {
  1965. if l.recoverStreak == nil {
  1966. l.recoverStreak = map[string]int{}
  1967. }
  1968. l.recoverStreak[cfg.ID]++
  1969. if l.recoverStreak[cfg.ID] < offlineRecoverTicks {
  1970. return
  1971. }
  1972. delete(l.offlineOpen, cfg.ID)
  1973. delete(l.recoverStreak, cfg.ID)
  1974. }
  1975. name := cfg.Name
  1976. if name == "" {
  1977. name = cfg.Host
  1978. }
  1979. l.resolveOfflineAlerts(cfg.ID)
  1980. l.emitRouterRecovered(cfg.ID, name)
  1981. }
  1982. // resolveOfflineAlerts elimina las alertas de offline pendientes del router
  1983. // (issue #846; antes #256 las marcaba leídas): al volver online la caída se
  1984. // retira del feed en vez de quedar ahí para siempre. El evento "recuperado"
  1985. // (emitRouterRecovered) es el relevo positivo que sustituye la caída. Debe
  1986. // llamarse con l.mu tomado.
  1987. func (l *Live) resolveOfflineAlerts(routerID string) {
  1988. ids := []string{}
  1989. for _, ev := range l.engine.List() {
  1990. if ev.RouterID == routerID && strings.HasPrefix(ev.ID, "alert-offline-") {
  1991. ids = append(ids, ev.ID)
  1992. }
  1993. }
  1994. if len(ids) > 0 {
  1995. l.engine.Remove(ids...)
  1996. }
  1997. }
  1998. // trackWanDown detecta "WAN/Internet caído" (category internet, urgent true,
  1999. // critical — SPEC-ALERTAS §1): el gateway responde por SSH pero su ping a
  2000. // internet da 100 % de pérdida en 2 sondeos seguidos (debounce como offline).
  2001. // Al recuperarse la WAN se resetea el estado (la próxima caída vuelve a
  2002. // alertar). Debe llamarse con l.mu tomado.
  2003. func (l *Live) trackWanDown(cfg *RouterConfig, p *routerPolled) {
  2004. key := cfg.ID + ":wan"
  2005. if p == nil || p.lossPct == nil || *p.lossPct < 100 {
  2006. l.wanDown[cfg.ID] = 0
  2007. l.lastStatus[key] = "up"
  2008. return
  2009. }
  2010. l.wanDown[cfg.ID]++
  2011. if l.wanDown[cfg.ID] >= 2 && l.lastStatus[key] != "down" {
  2012. l.lastStatus[key] = "down"
  2013. name := cfg.Name
  2014. if name == "" {
  2015. name = cfg.Host
  2016. }
  2017. l.engine.Emit(AlertEvent{
  2018. ID: fmt.Sprintf("alert-wan-%s-%d", cfg.ID, time.Now().UnixMilli()),
  2019. Category: alerts.CatInternet, Urgent: true,
  2020. Severity: "critical",
  2021. Title: "Internet down",
  2022. Description: fmt.Sprintf("%s responds but cannot reach the internet (100%% packet loss)", name),
  2023. Hint: alerts.HintFor(alerts.HintWanDown),
  2024. Type: alerts.HintWanDown,
  2025. Vars: map[string]string{"router": name},
  2026. Time: "just now", RouterID: cfg.ID,
  2027. })
  2028. }
  2029. }
  2030. // normalizeMultiWan makes a reported section safe to serve.
  2031. //
  2032. // Anything holding an agent token can push whatever it likes, and a section
  2033. // without its list of connections would go out as a null the page then
  2034. // reads a length from. A nil slice becomes an empty one, which already
  2035. // means "nothing to show" everywhere downstream.
  2036. func normalizeMultiWan(m *MultiWanInfo) *MultiWanInfo {
  2037. if m == nil {
  2038. return nil
  2039. }
  2040. if m.Uplinks == nil {
  2041. m.Uplinks = []WanUplink{}
  2042. }
  2043. return m
  2044. }
  2045. // uplinkWatch is one router's multi-WAN history, as much of it as an alert
  2046. // needs.
  2047. type uplinkWatch struct {
  2048. active string // the connection last CONFIRMED as carrying traffic
  2049. primary string // the preferred one at that moment, for "moved back"
  2050. candidate string // a different one seen, not yet believed
  2051. since time.Time // when the candidate was first seen
  2052. }
  2053. // uplinkSettle is how long a new connection must hold the traffic before it
  2054. // counts as a change. A failover that bounces straight back — a link
  2055. // renegotiating, a tracker blip while rules reload — then produces no alert
  2056. // at all, which is the point: the interesting event is the one that lasts.
  2057. const uplinkSettle = 45 * time.Second
  2058. // trackUplinkChange alerts when the internet starts going out through a
  2059. // different connection, and again when it comes back to the main one.
  2060. //
  2061. // The first observation of a router is recorded in silence. Otherwise every
  2062. // restart of this server would announce a failover that happened days ago,
  2063. // and the feed would fill with history on each deploy. Must be called with
  2064. // l.mu held.
  2065. func (l *Live) trackUplinkChange(cfg RouterConfig, p *routerPolled, now time.Time) {
  2066. if p == nil || p.multiWan == nil {
  2067. return
  2068. }
  2069. // Fewer than two connections is nothing to fail over between: forget
  2070. // the router, so a second line added later starts from silence.
  2071. if len(p.multiWan.Uplinks) < 2 {
  2072. delete(l.uplinkWatch, cfg.ID)
  2073. return
  2074. }
  2075. active := p.multiWan.Active
  2076. if active == "" {
  2077. // Nothing is steering. Not a move, and not something to guess at.
  2078. return
  2079. }
  2080. w := l.uplinkWatch[cfg.ID]
  2081. if w == nil {
  2082. l.uplinkWatch[cfg.ID] = &uplinkWatch{active: active, primary: p.multiWan.Primary}
  2083. return
  2084. }
  2085. w.primary = p.multiWan.Primary
  2086. if active == w.active {
  2087. w.candidate, w.since = "", time.Time{}
  2088. return
  2089. }
  2090. if active != w.candidate {
  2091. w.candidate, w.since = active, now
  2092. return
  2093. }
  2094. if now.Sub(w.since) < uplinkSettle {
  2095. return
  2096. }
  2097. from := w.active
  2098. w.active, w.candidate, w.since = active, "", time.Time{}
  2099. l.emitUplinkChange(cfg, p.multiWan, from, active)
  2100. }
  2101. // emitUplinkChange reports the move. Coming back to the preferred
  2102. // connection is its own event: after a failover, "it is over" is the part
  2103. // somebody is waiting for. Must be called with l.mu held.
  2104. func (l *Live) emitUplinkChange(cfg RouterConfig, mw *MultiWanInfo, from, to string) {
  2105. name := cfg.Name
  2106. if name == "" {
  2107. name = cfg.Host
  2108. }
  2109. vars := map[string]string{"router": name, "from": from, "to": to}
  2110. restored := to == mw.Primary && mw.Primary != ""
  2111. for _, u := range mw.Uplinks {
  2112. if u.Name == to && u.Metered {
  2113. // Moving onto a pay-per-use line is different news: it starts
  2114. // costing money.
  2115. vars["metered"] = "1"
  2116. }
  2117. }
  2118. ev := AlertEvent{
  2119. ID: fmt.Sprintf("alert-uplink-%s-%d", cfg.ID, time.Now().UnixMilli()),
  2120. Category: alerts.CatInternet,
  2121. // The internet category only lets urgent events through by
  2122. // default, so a quiet one here would simply never be seen.
  2123. Urgent: true,
  2124. Severity: "warn",
  2125. // The destination is part of the title on purpose: the engine
  2126. // deduplicates on category+title+router, and a failover and its
  2127. // recovery inside that window would otherwise collapse into one.
  2128. Title: "Internet is going out through " + to,
  2129. Description: fmt.Sprintf("%s moved the traffic from %s to %s", name, from, to),
  2130. Hint: alerts.HintFor(alerts.HintUplinkSwitch),
  2131. Type: alerts.HintUplinkSwitch,
  2132. Vars: vars,
  2133. Time: "just now", RouterID: cfg.ID,
  2134. }
  2135. if restored {
  2136. ev.Severity = "ok"
  2137. ev.Title = "Internet is back on " + to
  2138. ev.Description = fmt.Sprintf("%s moved the traffic back to %s", name, to)
  2139. ev.Hint = ""
  2140. ev.Type = alerts.TypeUplinkRestored
  2141. }
  2142. l.engine.Emit(ev)
  2143. }
  2144. // trackUnknownDevices emite "dispositivo desconocido se conecta" cuando un
  2145. // cliente SIN nombre (Name == MAC, sin hostname DHCP ni alias — device_attrib
  2146. // no guarda alias) pasa de no-online a online y PERMANECE nameless durante
  2147. // `unknownGraceNum` ticks seguidos (issue #234): un dispositivo conocido que
  2148. // reconecta resuelve su lease DHCP en 1-2 ticks y nunca alcanza el umbral.
  2149. // La memoria per-MAC persistida (issue #248) garantiza que cada MAC desconocida
  2150. // alerta UNA sola vez en la vida del servidor, hasta que se confíe en
  2151. // Settings (known_macs) o se resete. El primer ciclo de sondeo del proceso
  2152. // NO alerta (evita la avalancha de arranque: todo lo ya conectado sería
  2153. // "nuevo"). Las MAC de la allowlist known_macs (issue #196) nunca alertan,
  2154. // haya alias o no. Toma l.mu internamente.
  2155. func (l *Live) trackUnknownDevices(devices []Device, dists []DistributionNode) {
  2156. l.mu.Lock()
  2157. defer l.mu.Unlock()
  2158. // issue #196: MACs de la allowlist (confiables) → nunca "desconocido".
  2159. trusted := map[string]bool{}
  2160. if l.db != nil {
  2161. if rows, err := l.db.Query("SELECT mac FROM known_macs"); err == nil {
  2162. for rows.Next() {
  2163. var mac string
  2164. if rows.Scan(&mac) == nil {
  2165. trusted[mac] = true
  2166. }
  2167. }
  2168. rows.Close()
  2169. }
  2170. }
  2171. nowOnline := map[string]bool{}
  2172. for _, d := range devices {
  2173. if !d.Online {
  2174. continue
  2175. }
  2176. nowOnline[d.MAC] = true
  2177. if trusted[d.MAC] {
  2178. delete(l.unknownGrace, d.MAC)
  2179. continue
  2180. }
  2181. // issue #234: con hostname (lease resuelto) el dispositivo es
  2182. // conocido; se resetea su gracia y nunca alerta.
  2183. if d.Name != d.MAC {
  2184. delete(l.unknownGrace, d.MAC)
  2185. continue
  2186. }
  2187. // issue #248: esta MAC ya alertó alguna vez → no vuelve a hacerlo.
  2188. if l.unknownAlerted[d.MAC] {
  2189. delete(l.unknownGrace, d.MAC)
  2190. continue
  2191. }
  2192. // Solo los dispositivos que ACABAN de conectarse (o que ya estaban en
  2193. // gracia) acumulan ticks; los conectados antes del arranque no entran.
  2194. _, counting := l.unknownGrace[d.MAC]
  2195. if l.seenOnlineMacs && (counting || !l.onlineMacs[d.MAC]) {
  2196. l.unknownGrace[d.MAC]++
  2197. if l.unknownGrace[d.MAC] >= l.unknownGraceNum {
  2198. l.emitUnknownDevice(d, devices, dists)
  2199. l.unknownAlerted[d.MAC] = true
  2200. l.persistUnknownAlerted(d.MAC)
  2201. delete(l.unknownGrace, d.MAC)
  2202. }
  2203. }
  2204. }
  2205. // La gracia solo acumula en estado "online + sin nombre": cualquier otra
  2206. // transición la resetea (una reconexión futura parte de cero).
  2207. for mac := range l.unknownGrace {
  2208. if !nowOnline[mac] {
  2209. delete(l.unknownGrace, mac)
  2210. }
  2211. }
  2212. l.onlineMacs = nowOnline
  2213. l.seenOnlineMacs = true
  2214. }
  2215. // persistUnknownAlerted guarda en kv la memoria per-MAC (issue #248) para que
  2216. // sobreviva a reinicios del servidor. Con db nil (demo/tests) es no-op.
  2217. // Debe llamarse con l.mu tomado.
  2218. func (l *Live) persistUnknownAlerted(mac string) {
  2219. if l.db == nil {
  2220. return
  2221. }
  2222. _, _ = l.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "unknown_alerted:"+mac)
  2223. }
  2224. // routerDisplayName: nombre visible de un router por id ("" si no está en la
  2225. // flota). Usado por las alertas para interpolar la clave i18n {{router}}.
  2226. // Debe llamarse con l.mu tomado.
  2227. func (l *Live) routerDisplayName(id string) string {
  2228. for _, r := range l.routers {
  2229. if r.ID == id {
  2230. return r.Name
  2231. }
  2232. }
  2233. return id
  2234. }
  2235. // emitUnknownDevice: evento "dispositivo desconocido se conecta" (category
  2236. // clients, warn, NO urgente — issue #196). "Desconocido" = sin nombre/alias:
  2237. // device_attrib no guarda alias, así que la señal práctica es un cliente sin
  2238. // hostname DHCP (Name == MAC). Debe llamarse con l.mu tomado.
  2239. //
  2240. // The alert has to be actionable: a MAC on its own tells nobody which box to
  2241. // walk up to, so it also carries the IP, what the client hangs off and the
  2242. // port there, when those are known. They are: this runs after the topology
  2243. // pass and the Proxmox/UniFi seals, so AttachTo is already resolved.
  2244. func (l *Live) emitUnknownDevice(d Device, devices []Device, dists []DistributionNode) {
  2245. where, port := l.deviceLocation(d, devices, dists)
  2246. vars := map[string]string{
  2247. "mac": d.MAC,
  2248. "router": l.routerDisplayName(d.RouterID),
  2249. "where": where,
  2250. }
  2251. // Only the facts we actually have: the app renders one row per var and an
  2252. // empty one would read as "we know this and it is blank".
  2253. if d.IP != "" {
  2254. vars["ip"] = d.IP
  2255. }
  2256. if port != "" {
  2257. vars["port"] = port
  2258. }
  2259. if d.Band != "" && d.Band != "—" {
  2260. vars["band"] = d.Band
  2261. }
  2262. if d.SignalDbm != nil {
  2263. vars["signal"] = fmt.Sprintf("%d", *d.SignalDbm)
  2264. }
  2265. desc := fmt.Sprintf("%s connected to %s", d.MAC, where)
  2266. if d.IP != "" {
  2267. desc = fmt.Sprintf("%s · %s connected to %s", d.MAC, d.IP, where)
  2268. }
  2269. if d.Band != "" && d.Band != "cable" {
  2270. desc += " · " + d.Band
  2271. }
  2272. if d.SignalDbm != nil {
  2273. desc += fmt.Sprintf(" · %d dBm", *d.SignalDbm)
  2274. }
  2275. l.engine.Emit(AlertEvent{
  2276. ID: fmt.Sprintf("alert-unknown-%s-%d", d.MAC, time.Now().UnixMilli()),
  2277. Category: alerts.CatClients, Urgent: true,
  2278. Severity: "warn",
  2279. Title: "Unknown device",
  2280. Description: desc,
  2281. Hint: alerts.HintFor(alerts.HintUnknownDevice),
  2282. Type: alerts.HintUnknownDevice,
  2283. Vars: vars,
  2284. Time: "just now", RouterID: d.RouterID,
  2285. })
  2286. }
  2287. // DismissUnknownDevice implementa Snapshotter (#772): marca la MAC como ya
  2288. // avisada para que trackUnknownDevices no vuelva a alertar ("dejar como
  2289. // anónimo"). Persiste en kv (issue #248) para sobrevivir a reinicios.
  2290. func (l *Live) DismissUnknownDevice(mac string) {
  2291. mac = strings.ToUpper(strings.TrimSpace(mac))
  2292. if len(mac) != 17 {
  2293. return
  2294. }
  2295. l.mu.Lock()
  2296. defer l.mu.Unlock()
  2297. l.unknownAlerted[mac] = true
  2298. l.persistUnknownAlerted(mac)
  2299. delete(l.unknownGrace, mac)
  2300. }
  2301. // deviceLocation: where a client is plugged in, as the two strings the alert
  2302. // interpolates. `where` is the box it hangs off — the AP, switch or
  2303. // hypervisor named by AttachTo, which may be a distribution node or another
  2304. // device acting as a hub — falling back to its router, which is always known.
  2305. // `port` is the physical port when the bridge FDB or the controller reports
  2306. // one (empty for wireless clients). Must be called with l.mu held.
  2307. func (l *Live) deviceLocation(d Device, devices []Device, dists []DistributionNode) (where, port string) {
  2308. port = d.PortLabel
  2309. if port == "" {
  2310. port = d.Port
  2311. }
  2312. if d.AttachTo != "" {
  2313. for _, n := range dists {
  2314. if n.ID != d.AttachTo {
  2315. continue
  2316. }
  2317. where = firstNonEmpty(n.Name, n.Ip)
  2318. // A client behind a switch is learnt on the router port that the
  2319. // switch itself hangs off, so that port describes the uplink, not
  2320. // the client: naming it next to the switch would send someone to
  2321. // the wrong socket.
  2322. if n.Port == d.Port {
  2323. port = ""
  2324. }
  2325. break
  2326. }
  2327. if where == "" {
  2328. for _, o := range devices {
  2329. if o.ID == d.AttachTo {
  2330. where = firstNonEmpty(o.Name, o.IP)
  2331. break
  2332. }
  2333. }
  2334. }
  2335. }
  2336. if where == "" {
  2337. where = l.routerDisplayName(d.RouterID)
  2338. }
  2339. return where, port
  2340. }
  2341. func firstNonEmpty(vals ...string) string {
  2342. for _, v := range vals {
  2343. if v != "" {
  2344. return v
  2345. }
  2346. }
  2347. return ""
  2348. }
  2349. // trackDevicePresence emite device_offline/device_online cuando una MAC
  2350. // wireless pasa de vista a no-vista (N ticks) o viceversa (issue #184).
  2351. // Solo se rastrean MACs wireless (Band != "cable"): el FDB de cableados es
  2352. // volátil y daría falsos offline. Anti-falsos positivos: un tick perdido no
  2353. // dispara — hace falta `presenceOfflineAfter` ticks seguidos sin verse.
  2354. // Anti-arranque: el primer ciclo solo puebla el estado (todo lo ya conectado
  2355. // en boot no genera online). Poda: una MAC offline desde hace muchos ticks
  2356. // (dispositivo que se fue para siempre) se elimina de los mapas para que no
  2357. // crezcan sin límite (issue #206). Toma l.mu.
  2358. func (l *Live) trackDevicePresence(devices []Device, nowMs int64) {
  2359. l.mu.Lock()
  2360. defer l.mu.Unlock()
  2361. seen := map[string]bool{}
  2362. for _, d := range devices {
  2363. if !d.Online || d.Band == "cable" {
  2364. continue
  2365. }
  2366. seen[d.MAC] = true
  2367. if l.presenceSeen && !l.devicePresence[d.MAC] {
  2368. l.insertDeviceEvent(d.MAC, d.RouterID, deviceevents.StateOnline, d.SignalDbm, nowMs)
  2369. }
  2370. l.devicePresence[d.MAC] = true
  2371. l.presenceMisses[d.MAC] = 0
  2372. }
  2373. for mac, wasOnline := range l.devicePresence {
  2374. if !wasOnline {
  2375. // Ya offline: la MAC no re-emite, pero el contador sigue
  2376. // creciendo para que la poda pueda eliminarla (issue #206).
  2377. l.presenceMisses[mac]++
  2378. continue
  2379. }
  2380. if seen[mac] {
  2381. continue
  2382. }
  2383. l.presenceMisses[mac]++
  2384. if l.presenceMisses[mac] >= l.presenceOfflineAfter {
  2385. l.insertDeviceEvent(mac, l.lastRouterFor(mac), deviceevents.StateOffline, nil, nowMs)
  2386. l.devicePresence[mac] = false
  2387. }
  2388. }
  2389. // Poda: MACs offline desde hace muchos ticks (se fueron para siempre) se
  2390. // eliminan para que los mapas no crezcan sin límite (issue #206).
  2391. // Zero-value (pruneAfter==0) = poda desactivada.
  2392. if l.presencePruneAfter > 0 {
  2393. for mac, misses := range l.presenceMisses {
  2394. if misses >= l.presencePruneAfter {
  2395. delete(l.presenceMisses, mac)
  2396. delete(l.devicePresence, mac)
  2397. }
  2398. }
  2399. }
  2400. l.presenceSeen = true
  2401. }
  2402. // trackOfflineDevices (#1354): alerta volátil opt-in cuando un dispositivo
  2403. // marcado (override notify_offline) cae de la red. La transición
  2404. // online->offline se CONFIRMA tras offlineAlertNum (default 3) ticks offline
  2405. // seguidos, espejo de trackDevicePresence; un flap corto dentro de la gracia
  2406. // no emite nada. Anti-arranque: solo alerta para MACs vistas online alguna vez
  2407. // (una MAC ya offline al arrancar nunca "se desconecta"). Al volver online se
  2408. // retira la entrada volátil (engine.Remove), de modo que el feed se
  2409. // auto-resuelve. Toma l.mu internamente.
  2410. func (l *Live) trackOfflineDevices(devices []Device) {
  2411. l.mu.Lock()
  2412. defer l.mu.Unlock()
  2413. for _, d := range devices {
  2414. if !d.NotifyOffline {
  2415. continue
  2416. }
  2417. if d.Online {
  2418. l.offlineOnline[d.MAC] = true
  2419. if l.offlineAlerted[d.MAC] {
  2420. l.offlineAlerted[d.MAC] = false
  2421. l.engine.Remove("alert-device-offline-" + d.MAC)
  2422. }
  2423. l.offlineMisses[d.MAC] = 0
  2424. continue
  2425. }
  2426. // Solo transiciones reales: MACs que ya vimos online en un ciclo previo.
  2427. if !l.offlineOnline[d.MAC] {
  2428. continue
  2429. }
  2430. l.offlineMisses[d.MAC]++
  2431. if l.offlineMisses[d.MAC] >= l.offlineAlertNum && !l.offlineAlerted[d.MAC] {
  2432. l.offlineAlerted[d.MAC] = true
  2433. l.emitDeviceOffline(d)
  2434. }
  2435. }
  2436. }
  2437. // emitDeviceOffline emite la alerta volátil de desconexión (category clients,
  2438. // warn, urgente). ID estable por MAC: un incidente = una entrada del feed.
  2439. // Debe llamarse con l.mu tomado.
  2440. func (l *Live) emitDeviceOffline(d Device) {
  2441. name := d.Name
  2442. if name == "" {
  2443. name = d.MAC
  2444. }
  2445. router := l.routerDisplayName(d.RouterID)
  2446. l.engine.EmitVolatile(AlertEvent{
  2447. ID: "alert-device-offline-" + d.MAC,
  2448. Category: alerts.CatClients, Urgent: true,
  2449. Severity: "warn",
  2450. Title: fmt.Sprintf("Device offline: %s", name),
  2451. Description: fmt.Sprintf("%s went offline on %s", name, router),
  2452. Hint: alerts.HintFor(alerts.HintDeviceOffline),
  2453. Type: alerts.TypeDeviceOffline,
  2454. Vars: map[string]string{"device": name, "router": router},
  2455. Time: "just now", RouterID: d.RouterID,
  2456. })
  2457. }
  2458. // insertDeviceEvent persiste una transición de presencia. Con db nil
  2459. // (demo/tests sin BD) es no-op. Debe llamarse con l.mu tomado.
  2460. func (l *Live) insertDeviceEvent(mac, routerID, state string, signalDbm *int, nowMs int64) {
  2461. if l.db == nil {
  2462. return
  2463. }
  2464. _ = deviceevents.Insert(l.db.DB, deviceevents.Event{
  2465. TsMs: nowMs, MAC: mac, RouterID: routerID, State: state,
  2466. SignalDbm: signalDbm,
  2467. })
  2468. }
  2469. // lastRouterFor devuelve el último router conocido de una MAC desde
  2470. // device_attrib (o vacío si no hay registro). Debe llamarse con l.mu tomado.
  2471. func (l *Live) lastRouterFor(mac string) string {
  2472. if l.db == nil {
  2473. return ""
  2474. }
  2475. var routerID string
  2476. _ = l.db.QueryRow("SELECT router_id FROM device_attrib WHERE mac = ?", mac).Scan(&routerID)
  2477. return routerID
  2478. }
  2479. // parseSpeedMbps converts a human speed string ("1 Gbps", "100 Mbps", "2.5G")
  2480. // to Mbps. Returns 0 on unknown formats.
  2481. func parseSpeedMbps(s string) int {
  2482. s = strings.TrimSpace(s)
  2483. if s == "" {
  2484. return 0
  2485. }
  2486. s = strings.ReplaceAll(s, "bps", "")
  2487. s = strings.ReplaceAll(s, "Bps", "")
  2488. s = strings.TrimSpace(s)
  2489. if strings.HasSuffix(s, "G") {
  2490. numStr := strings.TrimSpace(strings.TrimSuffix(s, "G"))
  2491. if v, err := strconv.ParseFloat(numStr, 64); err == nil {
  2492. return int(v * 1000)
  2493. }
  2494. }
  2495. if strings.HasSuffix(s, "M") {
  2496. numStr := strings.TrimSpace(strings.TrimSuffix(s, "M"))
  2497. if v, err := strconv.ParseFloat(numStr, 64); err == nil {
  2498. return int(v)
  2499. }
  2500. }
  2501. return 0
  2502. }
  2503. // recordPortSamples persists per-port time series samples (issue #302).
  2504. // Called after port stats are collected (SSH or agent path).
  2505. func (l *Live) recordPortSamples(routerID string, ports []EthPort) {
  2506. if l.db == nil || l.db.PortSeries == nil || len(ports) == 0 {
  2507. return
  2508. }
  2509. now := time.Now()
  2510. for _, p := range ports {
  2511. if p.ID == "" {
  2512. continue
  2513. }
  2514. _ = l.db.PortSeries.RecordSample(portseries.PortSample{
  2515. RouterID: routerID, PortID: p.ID, TS: now,
  2516. RxBytes: p.RxBytes, TxBytes: p.TxBytes,
  2517. RxErrors: p.RxErrs, TxErrors: p.TxErrs,
  2518. RxBps: p.RxBps, TxBps: p.TxBps,
  2519. SpeedMbps: parseSpeedMbps(p.Speed),
  2520. })
  2521. }
  2522. }
  2523. // pollAdGuard: stats del cliente configurado; fallback inactivo si falla.
  2524. func (l *Live) pollAdGuard(ctx context.Context) *AdGuardStats {
  2525. // Servicio desactivado en Ajustes > Servicios (#813): ni sondeo ni
  2526. // penalización. Clave ausente = activo (compat).
  2527. if l.db != nil {
  2528. var v string
  2529. if err := l.db.QueryRow("SELECT value FROM kv WHERE key = 'settings.services.adguard'").Scan(&v); err == nil && (v == "0" || v == "false") {
  2530. return nil
  2531. }
  2532. }
  2533. std, gl := l.getAdguardClient()
  2534. if std == nil && gl == nil {
  2535. return nil
  2536. }
  2537. var stats *AdGuardStats
  2538. var err error
  2539. host := ""
  2540. if std != nil {
  2541. u := std.url
  2542. if i := strings.Index(u, "://"); i >= 0 {
  2543. u = u[i+3:]
  2544. }
  2545. host = strings.SplitN(u, ":", 2)[0]
  2546. stats, err = std.GetStats(ctx)
  2547. if err != nil {
  2548. port := 3000
  2549. if len(u) > len(host)+1 {
  2550. if p, err := strconv.Atoi(u[len(host)+1:]); err == nil && p > 0 {
  2551. port = p
  2552. }
  2553. }
  2554. return &AdGuardStats{
  2555. Host: host, Port: port, Status: "inactive",
  2556. TopBlocked: []TopBlocked{},
  2557. }
  2558. }
  2559. return stats
  2560. } else {
  2561. host = gl.Host
  2562. stats, err = gl.GetStats(ctx)
  2563. }
  2564. if err != nil {
  2565. log.Printf("[netpulse] AdGuard inalcanzable: %v", err)
  2566. return &AdGuardStats{
  2567. Host: host, Port: 3000, Status: "inactive",
  2568. TopBlocked: []TopBlocked{},
  2569. }
  2570. }
  2571. return stats
  2572. }
  2573. // pollWireGuard: gateway WireGuard stats plus connect/disconnect alerts.
  2574. func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
  2575. l.mu.Lock()
  2576. gw := l.gatewayCfg
  2577. l.mu.Unlock()
  2578. if gw == nil {
  2579. return nil
  2580. }
  2581. peerNames := map[string]WGPeerName{}
  2582. for _, d := range devices {
  2583. if d.IP != "" {
  2584. peerNames[d.IP] = WGPeerName{ID: d.ID, Name: d.Name, Type: d.Type}
  2585. }
  2586. }
  2587. // #1441: copia del conjunto de urgentes para estamparlo en cada peer sin
  2588. // tener el mutex tomado durante el sondeo SSH.
  2589. l.mu.Lock()
  2590. urgent := l.wgUrgentCopyLocked()
  2591. l.mu.Unlock()
  2592. stats, err := GetWireGuardStats(l.pool, gw.SSHAddr(), l.cfg.WGInterface, "", peerNames, urgent)
  2593. if err != nil {
  2594. log.Printf("[netpulse] WireGuard no disponible: %v", err)
  2595. return &WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
  2596. }
  2597. // Transitions run only on a successful poll: a failed poll would mark every
  2598. // previously active peer as spuriously disconnected.
  2599. l.applyWireGuardTransitions(stats, gw.ID)
  2600. // #1445: recoge los flags urgentes de peers que dejaron de existir.
  2601. l.pruneWGUrgent(stats.Peers)
  2602. return stats
  2603. }
  2604. // wgUrgentPruneMisses (#1445): ausencias consecutivas en el dump antes de
  2605. // recoger un flag urgente. Un dump parcial (una interfaz no respondió, #714)
  2606. // no borra flags de peers vivos; sólo desaparece del router de verdad quien
  2607. // lleva varios sondeos seguidos sin aparecer.
  2608. const wgUrgentPruneMisses = 3
  2609. // pruneWGUrgent recoge las claves urgentes que llevan wgUrgentPruneMisses
  2610. // sondeos seguidos sin casar con ningún peer configurado. Con dumps vacíos no
  2611. // cuenta ausencias (no borra nada): sin peers no hay evidencia de nada.
  2612. func (l *Live) pruneWGUrgent(peers []WGPeer) {
  2613. if len(peers) == 0 {
  2614. return
  2615. }
  2616. present := map[string]bool{}
  2617. for _, p := range peers {
  2618. k := p.Key
  2619. if k == "" {
  2620. k = p.ID
  2621. }
  2622. present[k] = true
  2623. }
  2624. l.mu.Lock()
  2625. defer l.mu.Unlock()
  2626. changed := false
  2627. for k := range l.wgUrgent {
  2628. if present[k] {
  2629. if l.wgUrgentMiss[k] != 0 {
  2630. delete(l.wgUrgentMiss, k)
  2631. changed = true
  2632. }
  2633. continue
  2634. }
  2635. l.wgUrgentMiss[k]++
  2636. if l.wgUrgentMiss[k] >= wgUrgentPruneMisses {
  2637. delete(l.wgUrgent, k)
  2638. delete(l.wgUrgentMiss, k)
  2639. changed = true
  2640. }
  2641. }
  2642. if changed {
  2643. l.saveWGUrgentLocked()
  2644. }
  2645. }
  2646. // applyWireGuardTransitions emits connect (handshake) and disconnect alerts for
  2647. // peers whose active state changed since the last successful poll, and keeps
  2648. // wgActive/wgActiveSince in sync. A peer that was never active cannot emit a
  2649. // disconnect; the first post-boot cycle never emits a connect (warmup).
  2650. //
  2651. // #1443: el tracker se indexa por Key (pubkey base64url estable, #1441) con
  2652. // fallback a ID: WGPeer.ID puede cambiar entre sondeos ("peer-<idx>" según
  2653. // la posición en el dump) y un cambio de identificador simulaba un
  2654. // disconnect+connect fantasma. Los eventos de transición salen por
  2655. // EmitNoDedup: cada uno es un incidente real (un connect y un disconnect
  2656. // del mismo peer llevan el mismo título y el dedup de 5 min se comía los
  2657. // flaps). El warmup es un flag propio (wgPrimed), no len(wgActive)>0: con
  2658. // el guarda viejo, la primera conexión de un túnel iniciado por la unidad
  2659. // local (ciclo previo con 0 peers activos) se perdía para siempre.
  2660. //
  2661. // #1441: la alerta de un peer URGENTE sale con Urgent=true (aviso push); la de
  2662. // un peer normal con Urgent=false (solo queda en el log). La categoría y los
  2663. // IDs no cambian: lo único que distingue a un site-to-site de un portátil es
  2664. // el flag que puso el admin.
  2665. func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
  2666. // wgTrackKey: identidad estable del peer para el tracker (#1443).
  2667. wgTrackKey := func(p WGPeer) string {
  2668. if p.Key != "" {
  2669. return p.Key
  2670. }
  2671. return p.ID
  2672. }
  2673. activeNow := map[string]bool{}
  2674. peerByKey := map[string]WGPeer{}
  2675. for _, p := range stats.Peers {
  2676. k := wgTrackKey(p)
  2677. peerByKey[k] = p
  2678. if p.Active {
  2679. activeNow[k] = true
  2680. }
  2681. }
  2682. l.mu.Lock()
  2683. defer l.mu.Unlock()
  2684. // Urgencia por peer: el flag viene estampado del sondeo (Urgent) y, por si
  2685. // el llamador construyó los WGPeer a mano, se cruza con el conjunto
  2686. // persistido por Key o por ID.
  2687. urgentNow := map[string]bool{}
  2688. for k, p := range peerByKey {
  2689. urgentNow[k] = p.Urgent || l.wgUrgent[p.Key] || l.wgUrgent[p.ID]
  2690. }
  2691. // Disconnects: previously active peers no longer present in activeNow.
  2692. // #1445: si el peer desapareció del dump en el mismo ciclo de su caída,
  2693. // urgentNow no lo ve: se respalda con el conjunto persistido (la clave
  2694. // trackeada ES la Key, así que l.wgUrgent[id] devuelve su flag aunque el
  2695. // peer no esté en la muestra).
  2696. for id := range l.wgActive {
  2697. if activeNow[id] {
  2698. continue
  2699. }
  2700. name := id
  2701. if p, ok := peerByKey[id]; ok {
  2702. name = p.Name
  2703. }
  2704. dur := wgDuration(time.Since(l.wgActiveSince[id]))
  2705. l.engine.EmitNoDedup(AlertEvent{
  2706. ID: fmt.Sprintf("alert-wg-down-%s-%d", id, time.Now().UnixMilli()),
  2707. Category: alerts.CatVPN,
  2708. Urgent: urgentNow[id] || l.wgUrgent[id],
  2709. Severity: "info",
  2710. Title: "WireGuard disconnect",
  2711. Description: fmt.Sprintf("%s disconnected after %s", name, dur),
  2712. Type: alerts.TypeWireguardDisconnect,
  2713. Vars: map[string]string{"peer": name, "duration": dur},
  2714. Time: "just now",
  2715. RouterID: gwID,
  2716. })
  2717. delete(l.wgActiveSince, id)
  2718. }
  2719. // Connects: newly active peers, skipping the first post-boot cycle
  2720. // (warmup, wgPrimed) y sin dedup de 5 min: cada reconexión es un
  2721. // incidente propio que el operador espera ver (#1443).
  2722. for id := range activeNow {
  2723. if l.wgActive[id] {
  2724. continue
  2725. }
  2726. if l.wgPrimed {
  2727. name := id
  2728. if p, ok := peerByKey[id]; ok {
  2729. name = p.Name
  2730. }
  2731. l.engine.EmitNoDedup(AlertEvent{
  2732. ID: fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
  2733. Category: alerts.CatVPN,
  2734. Urgent: urgentNow[id],
  2735. Severity: "info",
  2736. Title: "WireGuard handshake",
  2737. Description: name + " connected",
  2738. Type: alerts.TypeWireguardHandshake,
  2739. Vars: map[string]string{"peer": name},
  2740. Time: "just now",
  2741. RouterID: gwID,
  2742. })
  2743. }
  2744. l.wgActiveSince[id] = time.Now()
  2745. }
  2746. l.wgActive = activeNow
  2747. l.wgPrimed = true
  2748. }
  2749. // wgDuration humanizes a WireGuard session duration as "Xh Ym" (hours and
  2750. // minutes). Negative values collapse to "0h 0m".
  2751. func wgDuration(d time.Duration) string {
  2752. if d < 0 {
  2753. d = 0
  2754. }
  2755. h := int(d.Hours())
  2756. m := int(d.Minutes()) % 60
  2757. return fmt.Sprintf("%dh %dm", h, m)
  2758. }
  2759. // buildDevices: unión de leases + MACs vistas (wireless > FDB satélites >
  2760. // FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
  2761. func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []Device {
  2762. leasesByMac := map[string]DhcpLease{}
  2763. leaseRouter := map[string]string{}
  2764. arpByMac := map[string]string{}
  2765. glByMac := map[string]DhcpLease{}
  2766. resByMac := map[string]DhcpReservation{}
  2767. for rID, p := range polled {
  2768. for mac, ip := range p.arp {
  2769. arpByMac[mac] = ip
  2770. }
  2771. for _, le := range p.leases {
  2772. if le.MAC != "" {
  2773. leasesByMac[le.MAC] = le
  2774. leaseRouter[le.MAC] = rID
  2775. }
  2776. }
  2777. // Static reservations: the name and address pinned in
  2778. // /etc/config/dhcp, and the only ones a client with a fixed address
  2779. // of its own ever gets, since it never takes a lease.
  2780. for _, r := range p.reservations {
  2781. if r.MAC != "" {
  2782. resByMac[r.MAC] = r
  2783. }
  2784. }
  2785. // gl-clients: fallback de IP para MACs sin lease (dnsmasq sin ese
  2786. // cliente). No crea dispositivos: solo enriquece los ya resueltos
  2787. // por wireless/FDB (issue #5 bug 1).
  2788. for _, le := range p.glClients {
  2789. if le.MAC != "" && le.IP != "" {
  2790. glByMac[le.MAC] = le
  2791. }
  2792. }
  2793. }
  2794. // Discovery (#338): aggregate mDNS host-by-IP and random MAC sets from
  2795. // all polled routers. Used to enrich devices below.
  2796. mdnsHostByIP := map[string]string{}
  2797. randomMACs := map[string]bool{}
  2798. mdnsSvcByHost := map[string][]string{}
  2799. for _, p := range polled {
  2800. if p.discovery == nil {
  2801. continue
  2802. }
  2803. for ip, host := range p.discovery.HostByIP {
  2804. mdnsHostByIP[ip] = host
  2805. }
  2806. for _, mac := range p.discovery.RandomMACs {
  2807. randomMACs[mac] = true
  2808. }
  2809. for host, svcs := range p.discovery.Services {
  2810. mdnsSvcByHost[host] = svcs
  2811. }
  2812. }
  2813. type knownInfo struct {
  2814. routerID string
  2815. band string
  2816. signal *int
  2817. }
  2818. known := map[string]knownInfo{}
  2819. if l.db != nil {
  2820. rows, err := l.db.Query("SELECT mac, router_id, band, signal_dbm FROM device_attrib")
  2821. if err == nil {
  2822. defer rows.Close()
  2823. for rows.Next() {
  2824. var mac, routerID, band string
  2825. var signal sql.NullInt64
  2826. if rows.Scan(&mac, &routerID, &band, &signal) == nil {
  2827. k := knownInfo{routerID: routerID, band: band}
  2828. if signal.Valid {
  2829. v := int(signal.Int64)
  2830. k.signal = &v
  2831. }
  2832. known[mac] = k
  2833. }
  2834. }
  2835. }
  2836. }
  2837. now := time.Now().UnixMilli()
  2838. type seenInfo struct {
  2839. routerID string
  2840. band string
  2841. signal *int
  2842. }
  2843. seen := map[string]seenInfo{}
  2844. // (1) wireless de cualquier router: la ÚNICA que se persiste
  2845. for routerID, p := range polled {
  2846. for mac, w := range p.wireless {
  2847. sig := w.SignalDbm
  2848. seen[mac] = seenInfo{routerID, w.Band, &sig}
  2849. if l.db != nil {
  2850. _, _ = l.db.Exec(
  2851. `INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?, ?, ?, ?, ?)
  2852. ON CONFLICT(mac) DO UPDATE SET router_id=excluded.router_id, band=excluded.band, signal_dbm=excluded.signal_dbm, last_seen=excluded.last_seen`,
  2853. mac, routerID, w.Band, w.SignalDbm, now)
  2854. }
  2855. }
  2856. }
  2857. // (1b) hint wireless-side del FDB (#rotMAC): MACs que el bridge de un
  2858. // router aprende en sus propios puertos de radio pero que la tabla de
  2859. // estaciones no lista (MACs rotadas/aleatorias que siguen emitiendo,
  2860. // clientes en backhaul 4-address). Sin esto la única evidencia que queda
  2861. // es el FDB de tránsito del gateway y su fallback las dibuja como
  2862. // cableadas colgadas del switch. Mandan sobre (2)/(3) pero NO sobre (1):
  2863. // una asociación real de iw es siempre mejor evidencia que un FDB.
  2864. // Orden determinista para MACs vistas por varios routers: ids ordenados y
  2865. // first-wins (cada mapa wirelessSide clavea MACs distintas dentro de un
  2866. // mismo router, así que el único empate posible es entre routers).
  2867. {
  2868. ids := make([]string, 0, len(polled))
  2869. for routerID := range polled {
  2870. ids = append(ids, routerID)
  2871. }
  2872. sort.Strings(ids)
  2873. for _, routerID := range ids {
  2874. p := polled[routerID]
  2875. if p == nil {
  2876. continue
  2877. }
  2878. for mac, band := range p.wirelessSide {
  2879. if _, ok := seen[mac]; ok {
  2880. continue
  2881. }
  2882. seen[mac] = seenInfo{routerID, band, nil}
  2883. if l.db != nil {
  2884. // Sin signal_dbm en el DO UPDATE: el hint no trae RSSI y
  2885. // pisar con NULL el último bueno de una asociación real
  2886. // rompería la serie de señal del dispositivo.
  2887. _, _ = l.db.Exec(
  2888. `INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?, ?, ?, ?, ?)
  2889. ON CONFLICT(mac) DO UPDATE SET router_id=excluded.router_id, band=excluded.band, last_seen=excluded.last_seen`,
  2890. mac, routerID, band, nil, now)
  2891. }
  2892. }
  2893. }
  2894. }
  2895. l.mu.Lock()
  2896. gw := l.gatewayCfg
  2897. registered := make(map[string]bool, len(l.routers))
  2898. for _, rc := range l.routers {
  2899. registered[rc.ID] = true
  2900. }
  2901. l.mu.Unlock()
  2902. gwID := ""
  2903. if gw != nil {
  2904. gwID = gw.ID
  2905. }
  2906. // A stored attribution outlives the router it names. Deleting a router --
  2907. // or an integration that registered some, as the UniFi scraper did for
  2908. // each AP -- leaves its clients in device_attrib pointing at an id that
  2909. // no longer exists, and every per-router count then attributes them to
  2910. // nothing: the gateway's card showed 18 of the 45 clients it serves.
  2911. // Hand them to the gateway, which is the router actually serving them
  2912. // once the one they remember is gone.
  2913. if gwID != "" {
  2914. for mac, k := range known {
  2915. if k.routerID != "" && !registered[k.routerID] {
  2916. k.routerID = gwID
  2917. known[mac] = k
  2918. }
  2919. }
  2920. }
  2921. // (2) FDB de satélites: pista solo de ESTE tick (no se guarda).
  2922. // REGLA DE RECONCILIACIÓN (issue #656): una MAC aprendida por un satélite
  2923. // en una boca que NO es su uplink (boca no-infra) es un cliente cableado
  2924. // directo de ESE satélite — el FDB la aprendió en un puerto físico suyo.
  2925. // Aunque el gateway también la vea en su FDB (porque el satélite está
  2926. // bridged al mismo segmento L2, como un dumb AP/bridge), la boca local
  2927. // del satélite es la evidencia más específica de dónde va el cable, así
  2928. // que se atribuye al satélite.
  2929. // El uplink queda excluido por infraPorts (boca donde se aprende una MAC
  2930. // de bridge de otro router = tránsito); aquí NO se cuenta.
  2931. // (3) FDB del gateway: solo las MACs que ningún satélite haya reclamado
  2932. // en una boca local, para no quedarse fuera si el gateway las ve en su
  2933. // propio FDB (misma LAN bridged).
  2934. // EXCEPCIÓN preservada: los routers agent-only (switches con agente
  2935. // propio) son la fuente más específica — sus dispositivos se conservan
  2936. // con RouterID del switch (esta ruta ya los trataba por separado).
  2937. // MACs de bridge de todos los routers sondeados: una boca de satélite
  2938. // que aprende una de ellas es un UPLINK (enlaza con otro equipo de red),
  2939. // y lo que aprende por ahí es el resto de la LAN en tránsito, no clientes
  2940. // locales. Sin esto, un switch agent-only (excepción de abajo) se
  2941. // atribuía toda la red vista por su uplink (#291).
  2942. brMacByRouter := map[string]bool{}
  2943. for _, pr := range polled {
  2944. if pr.brMac != "" {
  2945. brMacByRouter[pr.brMac] = true
  2946. }
  2947. }
  2948. for routerID, p := range polled {
  2949. if routerID == gwID {
  2950. continue
  2951. }
  2952. infraPorts := l.uplinkPortsFor(routerID, p.fdb, brMacByRouter)
  2953. for mac, port := range p.fdb {
  2954. if infraPorts[port] {
  2955. continue // uplink: MACs en tránsito, no clientes de este equipo
  2956. }
  2957. if _, ok := seen[mac]; !ok {
  2958. seen[mac] = seenInfo{routerID, "cable", nil}
  2959. }
  2960. }
  2961. }
  2962. // (3) FDB del gateway: solo si no hay memoria (mala pista; no se guarda)
  2963. if gwID != "" {
  2964. if gwPolled := polled[gwID]; gwPolled != nil {
  2965. for mac := range gwPolled.fdb {
  2966. if _, ok := seen[mac]; !ok {
  2967. if _, ok := known[mac]; !ok {
  2968. seen[mac] = seenInfo{gwID, "cable", nil}
  2969. }
  2970. }
  2971. }
  2972. }
  2973. }
  2974. // (4) ARP (#507): hosts cableados con IP estática visibles SOLO en la
  2975. // tabla ARP del router (ni wireless, ni FDB, ni lease, ni device_attrib).
  2976. // Se itera en orden de router ID para atribuir deterministamente el
  2977. // RouterID correcto cuando varios routers ven la misma MAC (misma LAN).
  2978. // La exclusión de MACs de router/bridge se aplica en el bucle de
  2979. // dispositivos (routerMacs), igual que para leases/known: aquí no se
  2980. // duplica ese filtro.
  2981. //
  2982. // Presence needs a CONFIRMED neighbour, not merely an entry in the
  2983. // table: the kernel keeps a stale neighbour for minutes after the host
  2984. // has gone, and this branch is the last resort -- the host has no lease,
  2985. // no FDB entry and no wireless association, so nothing else would
  2986. // contradict it. The map then drew a device that is not there, and, with
  2987. // no port either, hung it off the gateway bubble. A host that really is
  2988. // connected answers, so the kernel reconfirms it and it stays; a host
  2989. // that is only remembered drops out on the next tick instead of waiting
  2990. // for the entry to age out. A source that cannot report states (old
  2991. // agent, /proc/net/arp fallback) marks nothing stale and keeps the old
  2992. // behaviour.
  2993. // #1485: el ARP aprendido en el puerto WAN del gateway identifica al
  2994. // primer salto del enlace (ONT/módem en bridge tras PPPoE). Va antes del
  2995. // paso ARP general para que ese MAC no se atribuya como cliente LAN: se
  2996. // marca WanSide y lo dibuja el mapa como peer WAN bajo Internet. Solo si
  2997. // no tiene ya evidencia LAN (la LAN manda) y solo en la boca WAN del
  2998. // gateway, nunca en sus bocas LAN.
  2999. wanSide := map[string]bool{}
  3000. if gwID != "" && wanPort != "" {
  3001. if gwP := polled[gwID]; gwP != nil {
  3002. for mac, dev := range gwP.arpDevs {
  3003. if dev != wanPort {
  3004. continue
  3005. }
  3006. if _, ok := seen[mac]; ok {
  3007. continue
  3008. }
  3009. seen[mac] = seenInfo{gwID, "cable", nil}
  3010. wanSide[mac] = true
  3011. }
  3012. }
  3013. }
  3014. arpConfirmed := map[string]bool{}
  3015. for _, p := range polled {
  3016. for mac := range p.arp {
  3017. if !p.arpStale[mac] {
  3018. arpConfirmed[mac] = true
  3019. }
  3020. }
  3021. }
  3022. arpRouterIDs := make([]string, 0, len(polled))
  3023. for routerID := range polled {
  3024. arpRouterIDs = append(arpRouterIDs, routerID)
  3025. }
  3026. sort.Strings(arpRouterIDs)
  3027. for _, routerID := range arpRouterIDs {
  3028. for mac := range polled[routerID].arp {
  3029. if _, ok := seen[mac]; ok {
  3030. continue
  3031. }
  3032. if _, ok := known[mac]; ok {
  3033. continue
  3034. }
  3035. if !arpConfirmed[mac] {
  3036. continue
  3037. }
  3038. seen[mac] = seenInfo{routerID, "cable", nil}
  3039. }
  3040. }
  3041. // (5) Atribución sticky (#678): un cableado que este tick solo aparece en el
  3042. // FDB del gateway por su UPLINK (tránsito) o en la tabla ARP —donde gana el
  3043. // gateway por orden alfabético— recupera el router real donde la memo lo vio
  3044. // por última vez en una boca local. Solo corrige ATRIBUCIÓN: no crea
  3045. // presencia (el dispositivo ya estaba en `seen`). Si el gateway lo ve en una
  3046. // boca NO-uplink, esa evidencia fresca manda y no se toca.
  3047. if gwID != "" && len(l.fdbMemo) > 0 {
  3048. gwPolled := polled[gwID]
  3049. gwInfraPorts := map[string]bool{}
  3050. if gwPolled != nil {
  3051. gwInfraPorts = l.uplinkPortsFor(gwID, gwPolled.fdb, brMacByRouter)
  3052. }
  3053. l.mu.Lock()
  3054. memo := l.fdbMemo
  3055. l.mu.Unlock()
  3056. nowMs := time.Now().UnixMilli()
  3057. ttlMs := fdbStickyTTL.Milliseconds()
  3058. for mac, s := range seen {
  3059. if s.band != "cable" || s.routerID != gwID {
  3060. continue
  3061. }
  3062. m, ok := memo[mac]
  3063. if !ok || nowMs-m.ts > ttlMs || m.routerID == "" || m.routerID == gwID {
  3064. continue
  3065. }
  3066. // El gateway solo lo ve por el uplink (o no lo ve en su FDB): el
  3067. // cable está en el satélite según la última observación local.
  3068. if gwPolled != nil {
  3069. if port, inFdb := gwPolled.fdb[mac]; inFdb && !gwInfraPorts[port] {
  3070. continue // boca local del gateway: evidencia fresca, no tocar
  3071. }
  3072. }
  3073. seen[mac] = seenInfo{m.routerID, "cable", nil}
  3074. }
  3075. }
  3076. allMacs := map[string]bool{}
  3077. for mac := range leasesByMac {
  3078. allMacs[mac] = true
  3079. }
  3080. for mac := range seen {
  3081. allMacs[mac] = true
  3082. }
  3083. for mac := range known {
  3084. allMacs[mac] = true
  3085. }
  3086. routerMacs := map[string]bool{}
  3087. // issue #196: MACs de bridge de los routers REGISTRADOS (persistidas),
  3088. // no solo las de los routers que sondeó bien en este tick. Un router que
  3089. // falló el sondeo sigue sin ser "cliente desconocido".
  3090. if l.db != nil {
  3091. if rows, err := l.db.Query("SELECT mac FROM routers WHERE mac IS NOT NULL AND mac != ''"); err == nil {
  3092. for rows.Next() {
  3093. var mac string
  3094. if rows.Scan(&mac) == nil {
  3095. routerMacs[mac] = true
  3096. }
  3097. }
  3098. rows.Close()
  3099. }
  3100. }
  3101. // #1206: los BSSID propios de la flota (reportados por los agentes,
  3102. // #1087) son infraestructura, no clientes: sin esto aparecían en la
  3103. // tabla de clientes al dejar de filtrarse por la retención de #1145.
  3104. if l.agents != nil {
  3105. for _, b := range l.agents.LocalBssids() {
  3106. routerMacs[b] = true
  3107. }
  3108. }
  3109. for _, p := range polled {
  3110. if p.brMac != "" {
  3111. routerMacs[p.brMac] = true
  3112. }
  3113. // #1489: identidades del propio switch (MACs de su puerto interno/CPU).
  3114. // Un vecino las aprende al gestionarlo y sin esto salen como clientes.
  3115. for _, mac := range p.selfMacs {
  3116. routerMacs[strings.ToUpper(mac)] = true
  3117. }
  3118. }
  3119. // #1489: la MAC que responde por la IP de gestion de una unidad de flota es
  3120. // la propia unidad (pila de mgmt del switch), no un cliente: su FDB la ve en
  3121. // el puerto interno y las FDB vecinas la aprenden al gestionarla. Se absorbe
  3122. // junto a las MACs de bridge. Si el Host es un nombre, no casa con ninguna IP
  3123. // de ARP y no absorbe nada.
  3124. mgmtHosts := map[string]bool{}
  3125. for _, p := range polled {
  3126. if p.cfg.Host != "" {
  3127. mgmtHosts[p.cfg.Host] = true
  3128. }
  3129. }
  3130. l.mu.Lock()
  3131. for _, rc := range l.routers {
  3132. if rc.Host != "" {
  3133. mgmtHosts[rc.Host] = true
  3134. }
  3135. }
  3136. l.mu.Unlock()
  3137. if len(mgmtHosts) > 0 {
  3138. for _, p := range polled {
  3139. for mac, ip := range p.arp {
  3140. if mgmtHosts[ip] {
  3141. routerMacs[strings.ToUpper(mac)] = true
  3142. }
  3143. }
  3144. }
  3145. }
  3146. // issue #196: allowlist de dispositivos confiables (mac → alias).
  3147. knownMacs := map[string]string{}
  3148. if l.db != nil {
  3149. if rows, err := l.db.Query("SELECT mac, name FROM known_macs"); err == nil {
  3150. for rows.Next() {
  3151. var mac, name string
  3152. if rows.Scan(&mac, &name) == nil {
  3153. knownMacs[mac] = name
  3154. }
  3155. }
  3156. rows.Close()
  3157. }
  3158. }
  3159. // issue #437/#797: overrides manuales de dispositivo (icono, nombre
  3160. // visible y tipo) sobre el dispositivo auto-descubierto.
  3161. type overrideInfo struct {
  3162. Icon string
  3163. Name string
  3164. DeviceType string
  3165. BannedBands string
  3166. NotifyOffline bool
  3167. }
  3168. deviceOverrides := map[string]overrideInfo{}
  3169. if l.db != nil {
  3170. if rows, err := l.db.Query("SELECT mac, icon, name, device_type, banned_bands, notify_offline FROM device_overrides"); err == nil {
  3171. for rows.Next() {
  3172. var mac, name, deviceType, bannedBands string
  3173. var icon sql.NullString
  3174. var notifyOffline bool
  3175. if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands, &notifyOffline); err == nil {
  3176. // Clave en minúsculas: las MACs de los sondeos pueden
  3177. // llegar en cualquier caso y el lookup debe ser robusto
  3178. // (#797: icon overrides que "desaparecían" por caso).
  3179. deviceOverrides[strings.ToLower(mac)] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline}
  3180. }
  3181. }
  3182. rows.Close()
  3183. }
  3184. }
  3185. lldpCapsByMac := map[string]string{}
  3186. for _, p := range polled {
  3187. for _, nb := range p.lldp {
  3188. if nb.ChassisMac != "" && len(nb.Caps) > 0 {
  3189. lldpCapsByMac[nb.ChassisMac] = strings.Join(nb.Caps, ",")
  3190. }
  3191. }
  3192. }
  3193. devices := []Device{}
  3194. for mac := range allMacs {
  3195. if routerMacs[mac] {
  3196. continue // los routers no son clientes
  3197. }
  3198. lease, hasLease := leasesByMac[mac]
  3199. s, isSeen := seen[mac]
  3200. // Fabricante desconocido = campo VACÍO, no un literal. El server no
  3201. // tiene idioma: "Desconocido" viajaba tal cual hasta la UI y salía en
  3202. // español en una interfaz en inglés. Quien pinta, traduce.
  3203. manufacturer := oui.Lookup(mac)
  3204. defaultRouterID := gwID
  3205. if defaultRouterID == "" {
  3206. if rID, ok := leaseRouter[mac]; ok {
  3207. defaultRouterID = rID
  3208. }
  3209. }
  3210. d := Device{
  3211. ID: strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
  3212. MAC: mac, Manufacturer: manufacturer,
  3213. TrafficMbps: 0, Sparkline: []float64{},
  3214. RouterID: defaultRouterID, Band: "—",
  3215. Online: isSeen, WanSide: wanSide[mac],
  3216. }
  3217. res, hasRes := resByMac[mac]
  3218. if hasLease {
  3219. switch {
  3220. case lease.Hostname != "":
  3221. d.Name = lease.Hostname
  3222. case hasRes && res.Name != "":
  3223. d.Name = res.Name
  3224. default:
  3225. d.Name = mac
  3226. }
  3227. d.IP = lease.IP
  3228. if lease.LeaseExpiresAt != nil {
  3229. remaining := int(*lease.LeaseExpiresAt - now/1000)
  3230. if remaining < 0 {
  3231. remaining = 0
  3232. }
  3233. d.LeaseRemaining = &remaining
  3234. }
  3235. } else {
  3236. d.Name = mac
  3237. // The name pinned in /etc/config/dhcp: a client with a fixed
  3238. // address of its own never takes a lease, so this is the only
  3239. // name the router has for it.
  3240. if hasRes {
  3241. if res.Name != "" {
  3242. d.Name = res.Name
  3243. }
  3244. d.IP = res.IP
  3245. }
  3246. // Fallback gl-clients (GL.iNet): el cliente no tiene lease pero el
  3247. // firmware sí conoce su IP (y a veces nombre). (issue #5 bug 1)
  3248. if gl, ok := glByMac[mac]; ok {
  3249. d.IP = gl.IP
  3250. if gl.Hostname != "" {
  3251. d.Name = gl.Hostname
  3252. }
  3253. }
  3254. }
  3255. // Fallback ARP (#377): el DHCP vive en otro equipo, pero cualquier
  3256. // router de la flota que enrute la LAN conoce la MAC→IP.
  3257. if d.IP == "" {
  3258. if ip, ok := arpByMac[mac]; ok {
  3259. d.IP = ip
  3260. }
  3261. }
  3262. // issue #196: la allowlist manda sobre el nombre por defecto. Con
  3263. // alias (Name != MAC) el dispositivo deja de ser "desconocido".
  3264. if alias, ok := knownMacs[mac]; ok && alias != "" {
  3265. d.Name = alias
  3266. }
  3267. // issue #437/#797: overrides manuales (icono, nombre) se aplican sobre
  3268. // el dispositivo auto-descubierto; el nombre manual manda incluso
  3269. // sobre el alias de la allowlist.
  3270. if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
  3271. if ov.Icon != "" {
  3272. d.IconOverride = ov.Icon
  3273. }
  3274. if ov.Name != "" {
  3275. d.Name = ov.Name
  3276. d.NameOverride = ov.Name
  3277. }
  3278. }
  3279. vendorClass := ""
  3280. clientID := ""
  3281. if hasLease {
  3282. vendorClass = lease.VendorClass
  3283. clientID = lease.ClientID
  3284. }
  3285. // Tipo estimado con reglas deterministas (hostname, huella DHCP y
  3286. // capacidades LLDP). Con nombre-MAC (sin hostname) queda "desconocido".
  3287. d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
  3288. // mDNS enrichment (#338): resolve hostname from IP → lookup services.
  3289. if d.IP != "" {
  3290. if host, ok := mdnsHostByIP[d.IP]; ok {
  3291. if svcs, ok := mdnsSvcByHost[host]; ok {
  3292. d.MdnsServices = svcs
  3293. }
  3294. // If the device has no name (just MAC), use the mDNS hostname.
  3295. if d.Name == mac {
  3296. d.Name = host
  3297. }
  3298. }
  3299. }
  3300. // Static-IP hosts never take a lease: fall back to their PTR record.
  3301. if d.Name == mac && d.IP != "" {
  3302. if host := l.rdns.Name(d.IP); host != "" {
  3303. d.Name = host
  3304. // The type above was guessed from the MAC, which says
  3305. // nothing. Guess it again now that there is a hostname.
  3306. d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
  3307. }
  3308. }
  3309. if randomMACs[mac] {
  3310. d.RandomMAC = true
  3311. }
  3312. // mDNS-based type refinement (#338): if the hostname/DHCP classification
  3313. // yielded "desconocido" but mDNS services are available, try to classify.
  3314. if d.Type == "desconocido" && len(d.MdnsServices) > 0 {
  3315. d.Type = guessFromMdns(d.MdnsServices)
  3316. }
  3317. // issue #797: el tipo manual manda sobre la clasificación (reglas,
  3318. // huella DHCP y refinación mDNS).
  3319. if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok && ov.DeviceType != "" {
  3320. d.Type = ov.DeviceType
  3321. d.TypeOverride = ov.DeviceType
  3322. }
  3323. // #1354: flag opt-in de alerta por desconexión (override persistido).
  3324. if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
  3325. d.NotifyOffline = ov.NotifyOffline
  3326. }
  3327. if isSeen {
  3328. d.RouterID = s.routerID
  3329. d.Band = s.band
  3330. d.SignalDbm = s.signal
  3331. } else if k, ok := known[mac]; ok {
  3332. d.RouterID = k.routerID
  3333. d.Band = k.band
  3334. d.SignalDbm = k.signal
  3335. } else if rID, ok := leaseRouter[mac]; ok && d.RouterID == "" {
  3336. d.RouterID = rID
  3337. }
  3338. // #551: TrafficMbps del cliente desde el rate en memoria (nlbwmon u
  3339. // hostapd) sin consultar la store en cada rebuild. Solo online; los
  3340. // offline no tienen rate (la UI pinta "—").
  3341. if isSeen {
  3342. if rxBps, txBps := l.clientBwRateFor(mac); rxBps+txBps > 0 {
  3343. d.TrafficMbps = (rxBps + txBps) / 1e6
  3344. }
  3345. }
  3346. devices = append(devices, d)
  3347. }
  3348. // Give clients learned only in an SNMP switch's FDB a traffic figure from
  3349. // that port's counters (see switchporttraffic.go).
  3350. l.applySnmpSwitchPortTraffic(polled, devices)
  3351. // Orden estable por MAC (issue #656): buildDevices itera un mapa de Go
  3352. // (allMacs), cuyo orden es aleatorio entre ticks. Ese orden llega al
  3353. // frontend y alimenta la asignación de ranuras de los anillos de la
  3354. // topología → los chips saltaban de posición al refrescar. Ordenar por
  3355. // MAC hace el contrato determinista para el mismo set de dispositivos.
  3356. sort.Slice(devices, func(i, j int) bool { return devices[i].MAC < devices[j].MAC })
  3357. // #1151: canónicas + fusión de enlazadas (orden: normalizar -> fusionar).
  3358. return normalizeDevices(mergeLinkedDevices(devices, l.deviceLinks()))
  3359. }
  3360. // normalizeDevices: MACs a formato canónico (mayúsculas, ':') y dedup por
  3361. // MAC. La caché gl-clients de GL.iNet emite MACs con guiones y entradas
  3362. // caducadas: sin normalizar el mismo cliente puede aparecer duplicado
  3363. // (#1145). Gana la entrada online; hostname/IP/fabricante de la descartada
  3364. // enriquecen a la conservada.
  3365. func normalizeDevices(devices []Device) []Device {
  3366. byMac := make(map[string]int, len(devices))
  3367. out := make([]Device, 0, len(devices))
  3368. for _, d := range devices {
  3369. mac := strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(d.MAC), "-", ":"))
  3370. d.MAC = mac
  3371. if i, ok := byMac[mac]; ok {
  3372. a, b := out[i], d
  3373. if b.Online && !a.Online {
  3374. a, b = b, a
  3375. }
  3376. if a.Hostname == "" {
  3377. a.Hostname = b.Hostname
  3378. }
  3379. if a.IP == "" {
  3380. a.IP = b.IP
  3381. }
  3382. if a.Manufacturer == "" {
  3383. a.Manufacturer = b.Manufacturer
  3384. }
  3385. if a.Name == "" {
  3386. a.Name = b.Name
  3387. }
  3388. out[i] = a
  3389. continue
  3390. }
  3391. byMac[mac] = len(out)
  3392. out = append(out, d)
  3393. }
  3394. return out
  3395. }
  3396. // emitTempAlert emite la alerta de temperatura alta UNA vez por proceso
  3397. // (flag, como el JS), usando el umbral del router (issue #716; default 65).
  3398. // Debe llamarse con l.mu tomado.
  3399. func (l *Live) emitTempAlert(cfg RouterConfig, router Router) {
  3400. thr := cfg.TempThresholdValue()
  3401. if router.Temp == nil || *router.Temp <= thr || l.lastStatus[cfg.ID+":temp"] == "warn" {
  3402. return
  3403. }
  3404. l.lastStatus[cfg.ID+":temp"] = "warn"
  3405. l.engine.Emit(AlertEvent{
  3406. ID: fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
  3407. Category: alerts.CatRouter, Urgent: true,
  3408. Severity: "warn",
  3409. Title: "High temperature on " + router.Name,
  3410. Description: fmt.Sprintf("%d °C, above the threshold (%d °C)", *router.Temp, thr),
  3411. Hint: alerts.HintFor(alerts.HintHighTemp),
  3412. Type: alerts.HintHighTemp,
  3413. Vars: map[string]string{"router": router.Name, "temp": strconv.Itoa(*router.Temp), "threshold": strconv.Itoa(thr)},
  3414. Time: "just now", RouterID: cfg.ID,
  3415. })
  3416. }
  3417. // computeHealth (index.js:462-486).
  3418. func computeHealth(routers []Router, adguard *AdGuardStats, wg *WireGuardStats) HealthScore {
  3419. score := 100
  3420. breakdown := []HealthDelta{}
  3421. wanScore := 100
  3422. wifiScore := 100
  3423. infraScore := 100
  3424. svcScore := 100
  3425. for _, r := range routers {
  3426. if r.Status == "offline" {
  3427. score -= 30
  3428. infraScore -= 40
  3429. breakdown = append(breakdown, HealthDelta{Label: r.Name + " offline", Delta: -30})
  3430. } else if r.Temp != nil {
  3431. thr := r.TempThreshold
  3432. if thr <= 0 {
  3433. thr = DefaultTempThreshold
  3434. }
  3435. if *r.Temp > thr {
  3436. score -= 8
  3437. infraScore -= 10
  3438. breakdown = append(breakdown, HealthDelta{Label: "temp. " + r.Name, Delta: -8})
  3439. }
  3440. }
  3441. }
  3442. if adguard != nil && adguard.Status != "active" {
  3443. score -= 5
  3444. svcScore -= 20
  3445. breakdown = append(breakdown, HealthDelta{Label: "AdGuard inactivo", Delta: -5})
  3446. }
  3447. // #1442: VPN en la nota de salud. "inactive" con interfaces descubiertas
  3448. // = túnel caído (quirk #714: sin interfaces WireGuard en el router el
  3449. // estado también es "inactive", pero Interface queda vacío y NO se
  3450. // penaliza: no hay nada que vigilar). Con la interfaz caída no se
  3451. // cuentan peers: están caídos por ella, no por sí mismos (no doble
  3452. // penalización). Cada peer importante (urgente, #1441) caído resta
  3453. // acotado para que uno solo no domine la nota.
  3454. if wg != nil && wg.Status != "active" && wg.Interface != "" {
  3455. score -= 10
  3456. svcScore -= 15
  3457. breakdown = append(breakdown, HealthDelta{Label: "WireGuard caído", Delta: -10})
  3458. } else if wg != nil {
  3459. urgentDown := []string{}
  3460. for _, p := range wg.Peers {
  3461. if p.Urgent && !p.Active {
  3462. urgentDown = append(urgentDown, p.Name)
  3463. }
  3464. }
  3465. if len(urgentDown) > 0 {
  3466. delta := 6 * len(urgentDown)
  3467. if delta > 12 {
  3468. delta = 12
  3469. }
  3470. score -= delta
  3471. svcScore -= delta + 3
  3472. if len(urgentDown) == 1 {
  3473. breakdown = append(breakdown, HealthDelta{Label: "peer WireGuard " + urgentDown[0] + " caído", Delta: -delta})
  3474. } else {
  3475. breakdown = append(breakdown, HealthDelta{Label: fmt.Sprintf("%d peers WireGuard importantes caídos", len(urgentDown)), Delta: -delta})
  3476. }
  3477. }
  3478. }
  3479. if score < 0 {
  3480. score = 0
  3481. }
  3482. if wanScore < 0 {
  3483. wanScore = 0
  3484. }
  3485. if wifiScore < 0 {
  3486. wifiScore = 0
  3487. }
  3488. if infraScore < 0 {
  3489. infraScore = 0
  3490. }
  3491. if svcScore < 0 {
  3492. svcScore = 0
  3493. }
  3494. label := "Atención"
  3495. if score >= 85 {
  3496. label = "Excelente"
  3497. } else if score >= 65 {
  3498. label = "Bueno"
  3499. }
  3500. note := "Sin penalizaciones."
  3501. if len(breakdown) > 0 {
  3502. labels := make([]string, len(breakdown))
  3503. for i, b := range breakdown {
  3504. labels[i] = b.Label
  3505. }
  3506. note = "Penalizado por: " + strings.Join(labels, ", ") + "."
  3507. }
  3508. return HealthScore{
  3509. Score: score, Label: label, Caption: "Puntuación de salud de la red",
  3510. Note: note, Breakdown: breakdown,
  3511. Subscores: []Subscore{
  3512. {Key: "wan", Label: "WAN", Score: wanScore},
  3513. {Key: "wifi", Label: "WiFi", Score: wifiScore},
  3514. {Key: "infra", Label: "Infra", Score: infraScore},
  3515. {Key: "services", Label: "Servicios", Score: svcScore},
  3516. },
  3517. }
  3518. }
  3519. // defaultWan (index.js:488-503).
  3520. func (l *Live) defaultWan(gw *RouterConfig) WAN {
  3521. l.mu.Lock()
  3522. var p *routerPolled
  3523. if gw != nil {
  3524. p = l.lastPolled[gw.ID]
  3525. }
  3526. l.mu.Unlock()
  3527. wan := WAN{
  3528. Plan: "—", PublicIP: "—", Isp: "—", PeakTodayTime: "—", Total24h: 0,
  3529. }
  3530. if p != nil {
  3531. if p.net != nil {
  3532. wan.DownMbps = mbps(p.net.RxBps)
  3533. wan.UpMbps = mbps(p.net.TxBps)
  3534. }
  3535. if p.latencyMs != nil {
  3536. wan.LatencyMs = *p.latencyMs
  3537. }
  3538. if p.lossPct != nil {
  3539. wan.LossPct = *p.lossPct
  3540. }
  3541. // Conexión WAN real (issue #276): proto/IP/gateway/DNS desde ubus.
  3542. if wi := p.wanInfo; wi.IP != "" || wi.Proto != "" {
  3543. wan.Proto = wi.Proto
  3544. if wi.IP != "" {
  3545. wan.PublicIP = wi.IP
  3546. }
  3547. wan.Gateway = wi.Gateway
  3548. wan.DNS = wi.DNS
  3549. }
  3550. }
  3551. // Resumen del día desde la BD (issue #169): pico de hoy, media y total
  3552. // 24h solo los poblaba el modo demo; aquí se calculan con la tabla raw.
  3553. if gw != nil {
  3554. ds := l.wanDayStats(gw.ID)
  3555. wan.PeakTodayMbps = ds.peakMbps
  3556. wan.PeakTodayTime = ds.peakTime
  3557. wan.AvgDownMbps = ds.avgMbps
  3558. wan.Total24h = ds.totalBytes
  3559. }
  3560. return wan
  3561. }
  3562. // GetOverview: single-flight (los llamantes concurrentes comparten sondeo).
  3563. // Si buildOverview paniquea, el líder lo transforma en error y todos los
  3564. // seguidores reciben ese error en vez de bloquear para siempre.
  3565. func (l *Live) GetOverview(ctx context.Context) (ov *Overview, err error) {
  3566. l.sfMu.Lock()
  3567. if c := l.sfCall; c != nil {
  3568. l.sfMu.Unlock()
  3569. <-c.done
  3570. return c.ov, c.err
  3571. }
  3572. c := &sfCall{done: make(chan struct{})}
  3573. l.sfCall = c
  3574. l.sfMu.Unlock()
  3575. defer func() {
  3576. if r := recover(); r != nil {
  3577. err = fmt.Errorf("panic en buildOverview: %v\n%s", r, debug.Stack())
  3578. ov = nil
  3579. }
  3580. c.ov, c.err = ov, err
  3581. close(c.done)
  3582. l.sfMu.Lock()
  3583. l.sfCall = nil
  3584. l.sfMu.Unlock()
  3585. }()
  3586. return l.buildOverview(ctx)
  3587. }
  3588. func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
  3589. polled := l.pollAll(ctx)
  3590. l.mu.Lock()
  3591. routers := append([]RouterConfig(nil), l.routers...)
  3592. gw := l.gatewayCfg
  3593. l.mu.Unlock()
  3594. routerList := make([]Router, 0, len(routers))
  3595. for _, cfg := range routers {
  3596. p := polled[cfg.ID]
  3597. if cfg.Disabled {
  3598. // #1085: unidad pausada: última snapshot conocida (o el
  3599. // esqueleto) con estado "paused"; nunca offline ni alerta.
  3600. routerList = append(routerList, l.pausedRouter(cfg))
  3601. continue
  3602. }
  3603. if p == nil {
  3604. l.mu.Lock()
  3605. prev := l.lastGood[cfg.ID]
  3606. fails := l.failCount[cfg.ID]
  3607. l.mu.Unlock()
  3608. if prev != nil && fails < 2 {
  3609. routerList = append(routerList, *prev)
  3610. } else {
  3611. routerList = append(routerList, l.offlineRouter(cfg))
  3612. }
  3613. continue
  3614. }
  3615. router := l.buildRouter(p, l.metricsHistory(cfg.ID, "24h"))
  3616. l.mu.Lock()
  3617. l.lastGood[cfg.ID] = &router
  3618. l.emitTempAlert(cfg, router)
  3619. l.mu.Unlock()
  3620. routerList = append(routerList, router)
  3621. }
  3622. // #656/#678: refrescar la memo sticky ANTES de buildDevices (su paso 5 la
  3623. // usa para atribuir al satélite los dispositivos callados) y usarla también
  3624. // como overlay de inferTopology (puerto/attachTo).
  3625. nowMs := time.Now().UnixMilli()
  3626. memo := l.updateFdbMemo(polled, nowMs)
  3627. // #1485: buildDevices necesita la boca WAN (ARP del primer salto del
  3628. // enlace); sale del estado WAN del propio sondeo del gateway.
  3629. wanPort := ""
  3630. if gw != nil {
  3631. if gp := polled[gw.ID]; gp != nil {
  3632. wanPort = gp.wanInfo.Port
  3633. }
  3634. }
  3635. devices := l.buildDevices(polled, wanPort)
  3636. stickyPolled := overlayStickyFdb(polled, memo, nowMs)
  3637. devices, distNodes := inferTopology(stickyPolled, devices)
  3638. // Capa 2 manual (issue #142): overrides de topología tras el autodiscover.
  3639. // Sin BD (tests/demo) → no-op.
  3640. var overrides []TopologyOverride
  3641. if l.db != nil {
  3642. overrides = loadTopologyOverrides(l.db)
  3643. devices, distNodes = applyTopologyOverrides(routerList, devices, distNodes, overrides)
  3644. }
  3645. // Capa 3 PVE (#561): si hay cluster Proxmox configurado, el inventario
  3646. // read-only sella hypervisor/ct con attachTo correcto (la relación
  3647. // CT→host no es deducible del L2) y crea los distnodes kind=hypervisor
  3648. // para que el frontend anide los CTs bajo el host. Va DESPUÉS de los
  3649. // overrides manuales: un override explícito del usuario tiene prioridad
  3650. // sobre el sello.
  3651. distNodes = l.sealProxmoxInfra(devices, distNodes)
  3652. // Supresión topológica (#332): actualizar grafo parent→child.
  3653. // Todos los no-gateway cuelgan del gateway.
  3654. l.mu.Lock()
  3655. if gw != nil && l.suppression != nil {
  3656. parents := map[string]string{}
  3657. for _, r := range routers {
  3658. if r.ID != gw.ID {
  3659. parents[r.ID] = gw.ID
  3660. }
  3661. }
  3662. l.suppression.SetTopology(parents)
  3663. }
  3664. l.mu.Unlock()
  3665. // Aviso de señal débil con ciclo de vida completo (#1452): un episodio
  3666. // abierto por MAC, disparo con guarda de 24 h entre episodios y cierre
  3667. // automático cuando la señal se mantiene por encima del umbral + margen
  3668. // de histéresis durante N muestras consecutivas. Un cliente sin datos
  3669. // (offline o sin señal reportada) no cuenta como recuperado. La
  3670. // itinerancia no abre ni cierra nada: se juzga la señal del cliente.
  3671. var weakSignalDB *sql.DB
  3672. if l.db != nil {
  3673. weakSignalDB = l.db.DB
  3674. }
  3675. weakDbm := alerts.WeakSignalDbm(weakSignalDB)
  3676. weakHyst := alerts.WeakSignalHysteresisDbm(weakSignalDB)
  3677. weakSamples := alerts.WeakSignalResolveSamples(weakSignalDB)
  3678. weakNow := time.Now().UnixMilli()
  3679. for i := range devices {
  3680. d := &devices[i]
  3681. l.mu.Lock()
  3682. st := l.weakStates[d.MAC]
  3683. fireID, resolveID, episodeStart := alerts.WeakSignalStep(&st, d.MAC, d.SignalDbm, d.Online, weakDbm, weakHyst, weakSamples, weakNow)
  3684. l.weakStates[d.MAC] = st
  3685. if fireID != "" || resolveID != "" {
  3686. routerName := l.routerDisplayName(d.RouterID)
  3687. if routerName == "" {
  3688. routerName = d.RouterID
  3689. }
  3690. if fireID != "" {
  3691. l.engine.Emit(AlertEvent{
  3692. ID: fireID,
  3693. Category: alerts.CatSignal, Urgent: false,
  3694. Severity: "warn", Title: "Weak signal on " + d.Name,
  3695. Description: fmt.Sprintf("%d dBm on %s - check coverage or move closer to an AP", *d.SignalDbm, routerName),
  3696. Hint: alerts.HintFor(alerts.HintWifiWeak),
  3697. Type: alerts.HintWifiWeak,
  3698. Vars: map[string]string{"device": d.Name, "signal": strconv.Itoa(*d.SignalDbm), "router": routerName},
  3699. Time: "just now", RouterID: d.RouterID,
  3700. })
  3701. }
  3702. if resolveID != "" {
  3703. // El episodio cerrado se conserva en el log con su ts de
  3704. // cierre (#1349); el evento ok referencia qué cierra y lleva
  3705. // el valor de recuperación y la duración del episodio. Si el
  3706. // usuario desestimó la alerta a mano antes, no se emite el
  3707. // cierre (su ID ya no está en el feed).
  3708. wasOpen := l.engine.Has(resolveID)
  3709. l.engine.Resolve(resolveID)
  3710. if wasOpen {
  3711. l.emitWeakRecovered(d, routerName, resolveID, episodeStart, weakNow)
  3712. }
  3713. }
  3714. }
  3715. l.mu.Unlock()
  3716. }
  3717. // #1292: lápidas filtradas de la lista final (una estación stale del AP
  3718. // re-emite la MAC en cada ciclo sin pasar por device_seen).
  3719. devices = l.filterTombstoned(devices)
  3720. l.trackUnknownDevices(devices, distNodes)
  3721. l.trackOfflineDevices(devices)
  3722. l.trackDevicePresence(devices, time.Now().UnixMilli())
  3723. // #954: first/last seen persistente de TODOS los clientes online.
  3724. // #1323: los que entran al registro por primera vez CON nombre alertan
  3725. // ("new client"); los sin nombre los cubre unknown-device (#234).
  3726. firstTimers := l.noteDevicesSeen(devices, time.Now().UnixMilli())
  3727. l.trackNewClients(firstTimers, devices, distNodes)
  3728. // #1095: el overview (snapshot SSE del que vive la tabla de clientes)
  3729. // escribía las marcas pero NUNCA las aplicaba: la UI en vivo mostraba
  3730. // "—" aunque la API REST las tuviera (sólo los detalles las aplicaban).
  3731. l.applyDeviceSeen(devices)
  3732. // #1145: retención indefinida - clientes del registro que ya no se ven
  3733. // en ninguna fuente viva salen como offline (con último nombre y seen).
  3734. // El overview es el snapshot SSE del que vive la tabla de clientes.
  3735. devices = append(devices, l.ghostDevices(devices)...)
  3736. // Clientes reales por router (atribución wireless/FDB, no leases)
  3737. countClientsPerRouter(routerList, devices)
  3738. // Sparkline de la tarjeta para fuentes sin throughput bps (switch beacon/
  3739. // SNMP sin métricas agregadas): su línea de tráfico 24h sale de los fps de
  3740. // sus puertos (port_series), no de la tabla metrics (siempre 0 ahí).
  3741. for i := range routerList {
  3742. r := &routerList[i]
  3743. if r.VitalsAvailable != nil && !*r.VitalsAvailable && allZeroF(r.Sparkline) && l.db != nil && l.db.PortSeries != nil {
  3744. if sp, err := l.db.PortSeries.HourlyFpsTotal(r.ID, len(r.Sparkline)); err == nil && len(sp) > 0 && !allZeroF(sp) {
  3745. r.Sparkline = sp
  3746. }
  3747. }
  3748. }
  3749. adguard := l.pollAdGuard(ctx)
  3750. wireguard := l.pollWireGuard(devices)
  3751. gwID := ""
  3752. if gw != nil {
  3753. gwID = gw.ID
  3754. }
  3755. // MACs registradas (routers.mac): permiten a fleetFdbEvidence anclar
  3756. // unidades sin bridge MAC utilizable (DSM: docker0 en bridgeDetect, sin
  3757. // lldpd) desde el FDB del switch que aprende su NIC (p. ej. NAS en xg4).
  3758. registeredMacs := make(map[string]string, len(routerList))
  3759. for _, r := range routerList {
  3760. if r.MAC != "" {
  3761. registeredMacs[r.ID] = r.MAC
  3762. }
  3763. }
  3764. // #1279: uplinks resueltos por LLDP (regla de puerto raíz); mandan sobre
  3765. // la evidencia FDB/device en BuildTopoSemantics. Se calcula ANTES que la
  3766. // FDB para sembrar profundidades: un switch core cuya MAC de chasis nadie
  3767. // aprende no tiene candidato padre por FDB y, sin semilla, su profundidad
  3768. // queda desconocida y las unidades cableadas en él caen al gateway.
  3769. lldpEvidence := fleetLldpEvidence(polled, gwID)
  3770. seedDepth := map[string]int{}
  3771. {
  3772. seedDepth[gwID] = 0
  3773. for pass := 0; pass <= len(lldpEvidence); pass++ {
  3774. changed := false
  3775. for child, ev := range lldpEvidence {
  3776. if d, ok := seedDepth[ev.parent]; ok {
  3777. if _, has := seedDepth[child]; !has || seedDepth[child] > d+1 {
  3778. seedDepth[child] = d + 1
  3779. changed = true
  3780. }
  3781. }
  3782. }
  3783. if !changed {
  3784. break
  3785. }
  3786. }
  3787. }
  3788. fdbEvidence := fleetFdbEvidence(polled, gwID, registeredMacs, seedDepth)
  3789. // #1321: los attaches manuales (#142) cuya MAC es la bridge de una unidad
  3790. // de flota fijan su uplink por encima de toda inferencia.
  3791. overrideUplinks := fleetOverrideEvidence(overrides, routerList)
  3792. wan := l.defaultWan(gw)
  3793. for _, r := range routerList {
  3794. if r.ID == gwID && r.Status == "offline" {
  3795. wan.PublicIP = "—"
  3796. }
  3797. }
  3798. trafficOf := func(rang string) []TrafficPoint {
  3799. h := l.metricsHistory(gwID, rang)
  3800. out := make([]TrafficPoint, 0, len(h))
  3801. for _, p := range h {
  3802. out = append(out, TrafficPoint{T: p.t, Down: p.down, Up: p.up})
  3803. }
  3804. return out
  3805. }
  3806. ag := AdGuardStats{Status: "inactive", TopBlocked: []TopBlocked{}}
  3807. if adguard != nil {
  3808. ag = *adguard
  3809. }
  3810. wgStats := WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
  3811. if wireguard != nil {
  3812. wgStats = *wireguard
  3813. }
  3814. online := 0
  3815. for _, d := range devices {
  3816. if d.Online {
  3817. online++
  3818. }
  3819. }
  3820. top := append([]Device(nil), devices...)
  3821. sort.SliceStable(top, func(i, j int) bool { return top[i].TrafficMbps > top[j].TrafficMbps })
  3822. if len(top) > 5 {
  3823. top = top[:5]
  3824. }
  3825. // #1051: evidencia FDB directa para anclar uplinks de flota sin depender
  3826. // de que la unidad aparezca como device (la MAC bridge de cada router
  3827. // aprendida en el FDB de otro miembro dice dónde cuelga).
  3828. // El motor de alertas es el dueño de la lista y del read-state
  3829. // (SPEC-ALERTAS §3-4): UnreadAlerts = no leídas que pasaron config.
  3830. alertsCopy := l.engine.List()
  3831. unread := l.engine.UnreadCount()
  3832. usteerAvailable := l.usteerAvailableCached()
  3833. dawnDetected := dawnDeprecatedFromPolled(polled)
  3834. // #1417: los clientes cableados que la FDB de un switch de flota aprendió
  3835. // en un puerto no-raíz cuelgan físicamente de él (switches SNMP externos
  3836. // de #1137 incluidos). Antes de la semántica: los blobs del gateway que
  3837. // queden vacíos los absorbe después #1374 sin dejar huérfanos.
  3838. claimSwitchFdbClients(polled, devices, distNodes, gwID, fdbEvidence, lldpEvidence, overrideUplinks)
  3839. topo := BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway, fdbEvidence, lldpEvidence, overrideUplinks) // SPEC-65 D65-3 + #1042/#1051/#1279/#1321
  3840. // #1374: retirar de la lista que ve el frontend los distnodes absorbidos
  3841. // como sombra de un switch gestionado. Slice NUEVO: filtrar in situ
  3842. // reescribe el backing array compartido y duplica el último (#1378).
  3843. if len(topo.AbsorbedDists) > 0 {
  3844. absorbed := map[string]bool{}
  3845. for _, id := range topo.AbsorbedDists {
  3846. absorbed[id] = true
  3847. }
  3848. filtered := make([]DistributionNode, 0, len(distNodes))
  3849. for _, dn := range distNodes {
  3850. if !absorbed[dn.ID] {
  3851. filtered = append(filtered, dn)
  3852. }
  3853. }
  3854. distNodes = filtered
  3855. }
  3856. fillUplinkSpeeds(polled, distNodes, topo.Links)
  3857. fillWiredSpeeds(polled, distNodes, topo.Links) // #1384
  3858. // #1429/#1471: la boca del hijo sale de la evidencia que resolvió el
  3859. // enlace, sea FDB o LLDP (el vecino LLDP guarda el puerto local). Misma
  3860. // precedencia que BuildTopoSemantics al construir el enlace: LLDP manda y
  3861. // la FDB rellena los huecos.
  3862. childEvidence := make(map[string]topoParent, len(fdbEvidence)+len(lldpEvidence))
  3863. for id, ev := range fdbEvidence {
  3864. childEvidence[id] = ev
  3865. }
  3866. for id, ev := range lldpEvidence {
  3867. childEvidence[id] = ev
  3868. }
  3869. fillUplinkSpeedsFromChild(polled, childEvidence, topo.Links)
  3870. return &Overview{
  3871. Health: computeHealth(routerList, adguard, wireguard),
  3872. WAN: wan,
  3873. Traffic: TrafficByRange{H1: trafficOf("1h"), H24: trafficOf("24h"), D7: trafficOf("7d"), D30: trafficOf("30d")},
  3874. Adguard: ag, Wireguard: wgStats, Routers: routerList,
  3875. DeviceTotals: DeviceTotals{
  3876. Total: len(devices), Online: online, KnownOffline: len(devices) - online,
  3877. NewToday: countNewToday(devices),
  3878. },
  3879. TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
  3880. DistributionNodes: distNodes,
  3881. Topology: topo,
  3882. Devices: devices,
  3883. Usteer: &UsteerOverview{Available: usteerAvailable},
  3884. DawnDeprecated: dawnDetected,
  3885. RoamingDaemon: classifyRoamingDaemon(usteerAvailable, dawnDetected),
  3886. VM: ViewModelVersion, // SPEC-65 D65-4
  3887. Ts: time.Now().Unix(),
  3888. }, nil
  3889. }
  3890. // emitWeakRecovered emite el cierre del episodio de señal débil (#1452).
  3891. // El cierre lleva ID ESTABLE por MAC (alert-weak-<mac>-ok) y va con
  3892. // EmitOrUpdate (#1518): un episodio nuevo del mismo dispositivo REEMPLAZA la
  3893. // entrada anterior en el log en vez de apilar otra "resuelta" idéntica (un
  3894. // cliente que oscila de cobertura dejaba dos cierres iguales a los 27 min).
  3895. // El histórico de episodios no se pierde: queda en los avisos originales
  3896. // (warn), marcados como resueltos por #1349. Se llama con l.mu tomado, igual
  3897. // que el resto de emisiones del bucle de dispositivos.
  3898. func (l *Live) emitWeakRecovered(d *Device, routerName, resolveID string, episodeStart, weakNow int64) {
  3899. recSignal := ""
  3900. if d.SignalDbm != nil {
  3901. recSignal = strconv.Itoa(*d.SignalDbm)
  3902. }
  3903. durMin := int((weakNow - episodeStart) / 60000)
  3904. dur := "<1 min"
  3905. if durMin >= 1 {
  3906. dur = fmt.Sprintf("%d min", durMin)
  3907. }
  3908. l.engine.EmitOrUpdate(AlertEvent{
  3909. ID: fmt.Sprintf("alert-weak-%s-ok", d.MAC),
  3910. Category: alerts.CatSignal, Urgent: false,
  3911. Severity: "ok", Title: "Weak signal resolved on " + d.Name,
  3912. Description: fmt.Sprintf("back to %s dBm on %s after %s", recSignal, routerName, dur),
  3913. Type: alerts.TypeWifiWeakRecovered,
  3914. Vars: map[string]string{"device": d.Name, "signal": recSignal, "router": routerName, "duration": dur},
  3915. Resolves: []string{resolveID},
  3916. Time: "just now", RouterID: d.RouterID,
  3917. })
  3918. }
  3919. // classifyRoamingDaemon decide que daemon de roaming esta activo en la red a
  3920. // partir de los flags recogidos del sondeo (#428).
  3921. func classifyRoamingDaemon(usteerAvailable, dawnDetected bool) RoamingDaemon {
  3922. switch {
  3923. case usteerAvailable && dawnDetected:
  3924. return RoamingDaemonBoth
  3925. case usteerAvailable:
  3926. return RoamingDaemonUsteer
  3927. case dawnDetected:
  3928. return RoamingDaemonDawn
  3929. default:
  3930. return RoamingDaemonNone
  3931. }
  3932. }
  3933. // dawnDeprecatedFromPolled devuelve true si algún router reporta DAWN en
  3934. // el payload del agente. Extraído para poder testearlo sin levantar SSH.
  3935. func dawnDeprecatedFromPolled(polled map[string]*routerPolled) bool {
  3936. for _, p := range polled {
  3937. if p.dawnDetected {
  3938. return true
  3939. }
  3940. }
  3941. return false
  3942. }
  3943. // usteerAvailableCached devuelve si hay usteer en la red (cacheado). Lanza un
  3944. // refresco asíncrono (1 SSH al gateway, TTL 30s) cuando el cache está stale,
  3945. // sin bloquear el overview: la primera llamada devuelve false y el flag llega
  3946. // en el overview siguiente una vez refrescado.
  3947. func (l *Live) usteerAvailableCached() bool {
  3948. l.mu.Lock()
  3949. avail := l.usteerAvailable
  3950. checked := l.usteerCheckedAt
  3951. checking := l.usteerChecking
  3952. gw := l.gatewayCfg
  3953. l.mu.Unlock()
  3954. if gw == nil {
  3955. return false
  3956. }
  3957. if checking || time.Since(checked) < 30*time.Second {
  3958. return avail
  3959. }
  3960. l.mu.Lock()
  3961. l.usteerChecking = true
  3962. host := gw.SSHAddr()
  3963. l.mu.Unlock()
  3964. go func() {
  3965. out, err := l.pool.Run(host, "ubus call usteer local_info", 4*time.Second)
  3966. l.mu.Lock()
  3967. l.usteerChecking = false
  3968. l.usteerCheckedAt = time.Now()
  3969. l.usteerAvailable = err == nil && strings.TrimSpace(out) != ""
  3970. l.mu.Unlock()
  3971. }()
  3972. return avail
  3973. }
  3974. // BoardInfoFor (#477): último ubus system board cacheado del router, ya sea
  3975. // por push del agente (polledFromAgent) o por sondeo SSH. Solo lectura.
  3976. func (l *Live) BoardInfoFor(id string) *BoardInfo {
  3977. l.mu.Lock()
  3978. defer l.mu.Unlock()
  3979. return l.boardCache[id]
  3980. }
  3981. // GetRouters: tarjetas desde la caché del último tick (index.js:600-610).
  3982. func (l *Live) GetRouters(context.Context) []Router {
  3983. l.mu.Lock()
  3984. routers := append([]RouterConfig(nil), l.routers...)
  3985. polled := cloneLastPolled(l.lastPolled)
  3986. l.mu.Unlock()
  3987. out := make([]Router, 0, len(routers))
  3988. for _, cfg := range routers {
  3989. p := polled[cfg.ID]
  3990. if cfg.Disabled {
  3991. out = append(out, l.pausedRouter(cfg))
  3992. continue
  3993. }
  3994. if p == nil {
  3995. l.mu.Lock()
  3996. prev := l.lastGood[cfg.ID]
  3997. fails := l.failCount[cfg.ID]
  3998. l.mu.Unlock()
  3999. if prev != nil && fails < 2 {
  4000. out = append(out, *prev)
  4001. } else {
  4002. out = append(out, l.offlineRouter(cfg))
  4003. }
  4004. continue
  4005. }
  4006. out = append(out, l.buildRouter(p, l.metricsHistory(cfg.ID, "24h")))
  4007. }
  4008. // buildRouter leaves Clients as the DHCP lease count, which is not the
  4009. // number the card means: it counts devices that are offline and misses
  4010. // every device without a lease. The overview has always corrected it;
  4011. // this endpoint did not, so the routers page and the map disagreed --
  4012. // 34 against 45 on the same router.
  4013. countClientsPerRouter(out, l.attributedDevices())
  4014. return out
  4015. }
  4016. // countClientsPerRouter sets each router's client count and band split to
  4017. // the online devices attributed to it. Attribution is per router, not per
  4018. // subtree: in a mesh each node counts its own stations, and clients of gear
  4019. // that is not a NetPulse router (a UniFi AP, say) belong to the router that
  4020. // serves them.
  4021. func countClientsPerRouter(routers []Router, devices []Device) {
  4022. counts := make(map[string]int, len(routers))
  4023. splits := make(map[string]*demoBandSplit, len(routers))
  4024. for i := range routers {
  4025. splits[routers[i].ID] = &demoBandSplit{}
  4026. }
  4027. for _, d := range devices {
  4028. if !d.Online {
  4029. continue
  4030. }
  4031. if split, ok := splits[d.RouterID]; ok {
  4032. counts[d.RouterID]++
  4033. countBand(split, d.Band)
  4034. }
  4035. }
  4036. for i := range routers {
  4037. routers[i].Clients = counts[routers[i].ID]
  4038. routers[i].BandSplit = splits[routers[i].ID]
  4039. }
  4040. }
  4041. // liveExtras es el objeto extras del detalle live (index.js:677-700).
  4042. type liveExtras struct {
  4043. MAC string `json:"mac"`
  4044. Firmware string `json:"firmware"`
  4045. FirmwareUpdated bool `json:"firmwareUpdated"`
  4046. FirmwareAvailable string `json:"firmwareAvailable,omitempty"`
  4047. LastReboot string `json:"lastReboot"`
  4048. Soc string `json:"soc"`
  4049. Flash string `json:"flash"`
  4050. RamMb int `json:"ramMb"`
  4051. // Timezone (#1500): nombre IANA del equipo; lo aporta el agente desde
  4052. // /etc/localtime (ubus nunca lo dio y ningún sondeo SSH/SNMP tampoco).
  4053. Timezone string `json:"timezone,omitempty"`
  4054. // UsedMb (#1501): RAM en uso en MiB con la misma fórmula del porcentaje
  4055. // (memUsedBytes); el front la pinta directamente en vez de derivarla de
  4056. // pct × total, que acumulaba el error de redondeo.
  4057. UsedMb int `json:"usedMb,omitempty"`
  4058. BandSplit demoBandSplit `json:"bandSplit"`
  4059. TrafficNow float64 `json:"trafficNow"`
  4060. GatewayLatencySpark []float64 `json:"gatewayLatencySpark"`
  4061. BackhaulSignal []float64 `json:"backhaulSignal"`
  4062. Radios []Radio `json:"radios"`
  4063. Ports []EthPort `json:"ports"`
  4064. EthPorts []EthPort `json:"ethPorts"`
  4065. }
  4066. // GetRouterDetail (index.js:612-715). Id desconocido → (nil, nil).
  4067. func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, error) {
  4068. l.mu.Lock()
  4069. var cfg *RouterConfig
  4070. for i := range l.routers {
  4071. if l.routers[i].ID == id {
  4072. cfg = &l.routers[i]
  4073. break
  4074. }
  4075. }
  4076. p := l.lastPolled[id]
  4077. gw := l.gatewayCfg
  4078. polledAll := cloneLastPolled(l.lastPolled)
  4079. l.mu.Unlock()
  4080. if cfg == nil {
  4081. return nil, nil
  4082. }
  4083. var router Router
  4084. if p != nil {
  4085. router = l.buildRouter(p, l.metricsHistory(id, "24h"))
  4086. } else {
  4087. router = l.offlineRouter(*cfg)
  4088. }
  4089. // Mapa global MAC → lease + MAC de bridge → nombre de router
  4090. leaseMap := map[string]DhcpLease{}
  4091. routerByMac := map[string]string{}
  4092. // Clientes WiFi por MAC → AP que los sirve (#291): si la única MAC de
  4093. // una boca del switch es un cliente WiFi, el equipo ENCHUFADO es el AP,
  4094. // no el cliente. La atribución correcta de la boca es el AP.
  4095. wifiByMac := map[string]string{}
  4096. for _, polled := range polledAll {
  4097. apName := polled.cfg.Name
  4098. if apName == "" {
  4099. apName = polled.cfg.Host
  4100. }
  4101. for mac := range polled.wireless {
  4102. wifiByMac[mac] = apName
  4103. }
  4104. }
  4105. // Alias manuales (Settings > known_macs): fallback de nombre para MACs
  4106. // sin lease (estáticas, equipos sin DHCP), mismo criterio que la lista
  4107. // de dispositivos (#291: match MAC→nombre también en bocas de switch).
  4108. aliasByMac := map[string]string{}
  4109. if l.db != nil {
  4110. if rows, err := l.db.Query("SELECT mac, name FROM known_macs"); err == nil {
  4111. for rows.Next() {
  4112. var mac, name string
  4113. if rows.Scan(&mac, &name) == nil && name != "" {
  4114. aliasByMac[mac] = name
  4115. }
  4116. }
  4117. rows.Close()
  4118. }
  4119. }
  4120. for _, polled := range polledAll {
  4121. for _, le := range polled.leases {
  4122. if le.MAC != "" {
  4123. leaseMap[le.MAC] = le
  4124. }
  4125. }
  4126. if polled.brMac != "" {
  4127. name := polled.cfg.Name
  4128. if name == "" {
  4129. name = polled.cfg.Host
  4130. }
  4131. routerByMac[polled.brMac] = name
  4132. }
  4133. }
  4134. // Boca → MACs aprendidas (vecino inmediato). Indexado por INTERFAZ: el
  4135. // FDB y los vecinos LLDP vienen con el nombre de la interfaz, y el id de
  4136. // la boca no siempre lo es (una boca WAN se llama "wan" aunque su
  4137. // interfaz sea "eth1", o "lan1" cuando el uplink es un PPPoE sobre esa
  4138. // boca). Sin esto, esa boca sale sin el dispositivo que tiene enfrente.
  4139. portMacs := map[string][]string{}
  4140. if p != nil {
  4141. for mac, portName := range p.fdb {
  4142. portMacs[portName] = append(portMacs[portName], mac)
  4143. }
  4144. }
  4145. ports := []EthPort{}
  4146. if p != nil {
  4147. ports = p.ports
  4148. }
  4149. var depsLldp []LldpNeighbor
  4150. if p != nil {
  4151. depsLldp = p.lldp
  4152. }
  4153. deps := portEnrichDeps{
  4154. routerByMac: routerByMac,
  4155. leaseMap: leaseMap,
  4156. aliasByMac: aliasByMac,
  4157. wifiByMac: wifiByMac,
  4158. portMacs: portMacs,
  4159. lldp: depsLldp,
  4160. }
  4161. enriched := make([]EthPort, 0, len(ports))
  4162. for _, port := range ports {
  4163. if !port.Up {
  4164. enriched = append(enriched, port)
  4165. continue
  4166. }
  4167. enriched = append(enriched, enrichEthPort(port, portNetdev(port), deps))
  4168. }
  4169. // Per-port health score (issue #299): compute from recent series + flapping.
  4170. l.enrichPortHealth(id, enriched)
  4171. radios := []Radio{}
  4172. if p != nil && p.radios != nil {
  4173. radios = p.radios
  4174. }
  4175. seriesOf := func(rang string) []PerfPoint {
  4176. h := l.metricsHistory(id, rang)
  4177. out := make([]PerfPoint, 0, len(h))
  4178. for _, hp := range h {
  4179. out = append(out, PerfPoint{T: hp.t, CPU: float64(hp.cpu), RAM: float64(hp.ram), Temp: float64(hp.temp)})
  4180. }
  4181. return out
  4182. }
  4183. clients := []Device{}
  4184. detDevices, _ := inferTopology(polledAll, l.buildDevices(polledAll, ""))
  4185. // #954: first/last seen también en los clientes del detalle del router.
  4186. l.applyDeviceSeen(detDevices)
  4187. for _, d := range detDevices {
  4188. if d.RouterID == id {
  4189. clients = append(clients, d)
  4190. }
  4191. }
  4192. // Desglose por banda de los clientes online (issue #645): mismo criterio
  4193. // que la tarjeta de la flota (solo online; "—" no cae en ninguna banda).
  4194. var bandSplit demoBandSplit
  4195. for _, d := range clients {
  4196. if d.Online {
  4197. countBand(&bandSplit, d.Band)
  4198. }
  4199. }
  4200. extras := liveExtras{
  4201. MAC: "—", Firmware: "—", FirmwareUpdated: true, LastReboot: "—",
  4202. Soc: "—", Flash: "—", RamMb: 0,
  4203. BandSplit: bandSplit,
  4204. GatewayLatencySpark: l.latencySpark24h(id),
  4205. BackhaulSignal: []float64{},
  4206. Radios: radios,
  4207. Ports: enriched,
  4208. EthPorts: enriched,
  4209. }
  4210. if p != nil {
  4211. if p.brMac != "" {
  4212. extras.MAC = p.brMac
  4213. }
  4214. if p.board != nil {
  4215. extras.Firmware = p.board.Release.Description
  4216. extras.Soc = p.board.System
  4217. if extras.Soc == "" {
  4218. extras.Soc = "—"
  4219. }
  4220. }
  4221. if p.firmwareAvailable != "" {
  4222. extras.FirmwareAvailable = p.firmwareAvailable
  4223. extras.FirmwareUpdated = false
  4224. }
  4225. if p.flash != "" {
  4226. extras.Flash = p.flash
  4227. }
  4228. if p.uptimeSec > 0 {
  4229. rb := time.Now().Add(-time.Duration(p.uptimeSec) * time.Second)
  4230. extras.LastReboot = fmt.Sprintf("%02d/%02d/%d, %02d:%02d", rb.Day(), int(rb.Month()), rb.Year(), rb.Hour(), rb.Minute())
  4231. }
  4232. if p.sysInfo != nil && p.sysInfo.Memory.Total > 0 {
  4233. // MiB, no MB SI: un módulo de 2 GiB debe leerse "2048 MB" en el
  4234. // panel, que es como el usuario lee el tamaño del chip (#1501;
  4235. // antes /1e6 daba 2097).
  4236. extras.RamMb = int(math.Round(p.sysInfo.Memory.Total / (1024 * 1024)))
  4237. m := p.sysInfo.Memory
  4238. extras.UsedMb = int(math.Round(memUsedBytes(m.Total, m.Free, m.Buffered, m.Cached, m.Available, m.Used) / (1024 * 1024)))
  4239. }
  4240. if p.sysInfo != nil && p.sysInfo.Timezone != "" {
  4241. extras.Timezone = p.sysInfo.Timezone
  4242. }
  4243. if p.net != nil {
  4244. extras.TrafficNow = mbps(p.net.RxBps)
  4245. }
  4246. }
  4247. var vlans []VlanPort
  4248. if p != nil && len(p.vlans) > 0 {
  4249. vlans = p.vlans
  4250. }
  4251. var multiWan *MultiWanInfo
  4252. if p != nil {
  4253. multiWan = p.multiWan
  4254. }
  4255. detail := &RouterDetail{
  4256. Router: router, Ports: enriched, Radios: radios, Backhaul: nil,
  4257. Series: PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
  4258. Clients: clients, Extras: extras, Vlans: vlans, MultiWan: multiWan,
  4259. }
  4260. // #930: contadores de salud SNMP del router (solo si se sondea por SNMP).
  4261. if cfg.SnmpEnabled {
  4262. l.mu.Lock()
  4263. if st := l.snmpPollStats[id]; st != nil {
  4264. detail.SnmpOk = st.Ok
  4265. detail.SnmpFail = st.Fail
  4266. detail.SnmpConsecFail = st.ConsecFail
  4267. detail.LastSnmpErr = st.LastErr
  4268. }
  4269. l.mu.Unlock()
  4270. }
  4271. if gw != nil && id == gw.ID {
  4272. detail.Adguard = l.pollAdGuard(ctx)
  4273. detail.Wireguard = l.pollWireGuard(clients)
  4274. } else {
  4275. // Backhaul real del AP: boca que enlaza con otro router + latencia
  4276. // (la elección de boca vive en backhaul.go).
  4277. uplink := pickBackhaulUplink(enriched)
  4278. speed := "—"
  4279. if uplink != nil && uplink.Speed != "" {
  4280. speed = uplink.Speed
  4281. }
  4282. latency := 0.0
  4283. if p != nil && p.latencyMs != nil {
  4284. latency = *p.latencyMs
  4285. }
  4286. detail.Backhaul = demoBackhaul{
  4287. Kind: "cable", Headline: "Cable · " + speed + " · full duplex", LatencyMs: latency,
  4288. }
  4289. }
  4290. return detail, nil
  4291. }
  4292. // GetDevices: buildDevices sobre el último sondeo (+ inferencia FDB de
  4293. // topología: Port/AttachTo, como en buildOverview).
  4294. func (l *Live) GetDevices(context.Context) []Device {
  4295. return l.attributedDevices()
  4296. }
  4297. // latencySpark24h: serie 24h de latencia de la unidad en buckets horarios
  4298. // (AVG de latency_ms en la tabla metrics, solo muestras con sonda). #1148:
  4299. // alimenta el spark real del detalle; vacía si no hay historial (sin sonda
  4300. // o unidad recién añadida) para que el front pinte "sin datos" y no ceros.
  4301. func (l *Live) latencySpark24h(routerID string) []float64 {
  4302. if l.db == nil || routerID == "" {
  4303. return []float64{}
  4304. }
  4305. rows, err := l.db.Query(
  4306. `SELECT (ts / 3600000) AS bucket, AVG(latency_ms) AS lat
  4307. FROM metrics WHERE router_id = ? AND ts >= ? AND latency_ms IS NOT NULL
  4308. GROUP BY bucket ORDER BY bucket`,
  4309. routerID, l.now().UnixMilli()-86400e3)
  4310. if err != nil {
  4311. return []float64{}
  4312. }
  4313. defer rows.Close()
  4314. out := []float64{}
  4315. for rows.Next() {
  4316. var bucket int64
  4317. var lat float64
  4318. if err := rows.Scan(&bucket, &lat); err != nil {
  4319. continue
  4320. }
  4321. out = append(out, lat)
  4322. }
  4323. return out
  4324. }
  4325. // attributedDevices builds the device list with everything that decides who
  4326. // a device belongs to and whether it is online: inference over the sticky
  4327. // FDB overlay, then the Proxmox and UniFi seals. The seals are not optional
  4328. // for a count -- the UniFi one is what marks a station on a controller AP as
  4329. // online, and without it a router's clients come out short.
  4330. func (l *Live) attributedDevices() []Device {
  4331. l.mu.Lock()
  4332. polled := cloneLastPolled(l.lastPolled)
  4333. l.mu.Unlock()
  4334. // #656/#678: memo sticky fresca ANTES de buildDevices (atribución) y como
  4335. // overlay de inferTopology (paridad con el overview), ANTES del sellado PVE
  4336. // (que sobreescribe attachTo con ground truth del cluster).
  4337. detailNowMs := time.Now().UnixMilli()
  4338. detailMemo := l.updateFdbMemo(polled, detailNowMs)
  4339. // #1485 también en el detalle: sin la boca WAN, el bloque de ARP WAN-side
  4340. // no sella WanSide y /api/devices discrepa del overview (la ONT bridged
  4341. // vuelve como cliente cableado del gateway y el mapa pierde el chip del
  4342. // peer WAN). Misma resolución que en buildOverview.
  4343. detailWanPort := ""
  4344. l.mu.Lock()
  4345. gwCfg := l.gatewayCfg
  4346. l.mu.Unlock()
  4347. if gwCfg != nil {
  4348. if gp := polled[gwCfg.ID]; gp != nil {
  4349. detailWanPort = gp.wanInfo.Port
  4350. }
  4351. }
  4352. devices, _ := inferTopology(
  4353. overlayStickyFdb(polled, detailMemo, detailNowMs),
  4354. l.buildDevices(polled, detailWanPort),
  4355. )
  4356. // #1292: lápidas fuera de la lista del detalle (la fuente viva puede
  4357. // seguir emitiendo la MAC borrada).
  4358. devices = l.filterTombstoned(devices)
  4359. // #561: sellado de infraestructura con el inventario PVE (si configurado).
  4360. // El detalle no consume distnodes, pero el sellado de devices sí corre.
  4361. l.sealProxmoxInfra(devices, nil)
  4362. // #954 + #1095: first/last seen persistente (device_seen) en el payload
  4363. // final. La escritura vivía SOLO en buildOverview: si por lo que fuera
  4364. // esa lista no contenía un cliente (p. ej. flota agent-only), el visto
  4365. // nunca se persistía y aquí se mostraba "—" para siempre. Escribir también
  4366. // desde la lista que la UI realmente consume hace el write-through
  4367. // inevitable; el upsert es idempotente y barato.
  4368. l.noteDevicesSeen(devices, time.Now().UnixMilli())
  4369. l.applyDeviceSeen(devices)
  4370. // #1145: retención indefinida - clientes del registro que ya no se ven
  4371. // en ninguna fuente viva salen como offline con su último nombre y seen.
  4372. devices = append(devices, l.ghostDevices(devices)...)
  4373. return devices
  4374. }
  4375. // RouterServingDHCP devuelve el id del router cuyo último sondeo reportó la
  4376. // MAC en su tabla de leases DHCP (issue #537). Ese router es el que sirve
  4377. // DHCP al dispositivo (no necesariamente el gateway global: una LAN separada
  4378. // tras un router/AP con su propio dnsmasq, p. ej. rt-lab en 192.168.2.x, es
  4379. // quien concede el lease). Vacío si ningún router la reportó (IP estática o
  4380. // sin lease en el último snapshot).
  4381. func (l *Live) RouterServingDHCP(mac string) string {
  4382. mac = strings.ToUpper(strings.TrimSpace(mac))
  4383. if mac == "" {
  4384. return ""
  4385. }
  4386. l.mu.Lock()
  4387. polled := cloneLastPolled(l.lastPolled)
  4388. l.mu.Unlock()
  4389. for id, p := range polled {
  4390. if p == nil || p.cfg.AgentOnly {
  4391. continue // agent-only no tiene vía SSH para escribir la reserva
  4392. }
  4393. for _, le := range p.leases {
  4394. if strings.ToUpper(le.MAC) == mac {
  4395. return id
  4396. }
  4397. }
  4398. }
  4399. return ""
  4400. }
  4401. // GetAlerts: copia de las alertas en memoria.
  4402. func (l *Live) GetAlerts(context.Context) []AlertEvent {
  4403. return l.engine.List()
  4404. }
  4405. // AlertsEngine: motor de alertas del adapter (SPEC-ALERTAS §3).
  4406. func (l *Live) AlertsEngine() *alerts.Engine { return l.engine }
  4407. // GetMetricsRows: filas para el poller (index.js:725-739).
  4408. func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
  4409. l.mu.Lock()
  4410. polled := l.lastPolled
  4411. rows := []MetricsRow{}
  4412. for id, p := range polled {
  4413. // issue #414: los routers SNMP cacheados repiten el mismo snapshot
  4414. // entre polls reales; no se vuelve a persistir la misma fila.
  4415. if p.cfg.SnmpEnabled && p.polledAt != 0 && p.polledAt <= l.snmpLastMetricsTick[id] {
  4416. continue
  4417. }
  4418. row := MetricsRow{
  4419. RouterID: id,
  4420. CPU: fptr(float64(p.cpu)),
  4421. RAM: fptr(float64(p.ram)),
  4422. Temp: fptr(float64(p.temp)),
  4423. LatencyMs: p.latencyMs,
  4424. }
  4425. // #441/#1568: sin lecturas no se persisten ceros falsos, pero una
  4426. // fuente SNMP/external con CPU o temperatura confirmada sí las conserva.
  4427. if p.cfg.SnmpEnabled || p.agentKind == "external" {
  4428. v := resolvePartialVitals(p)
  4429. row.CPU, row.RAM, row.Temp = nil, nil, nil
  4430. if v.cpu != nil {
  4431. row.CPU = fptr(float64(*v.cpu))
  4432. }
  4433. if v.temp != nil {
  4434. row.Temp = fptr(float64(*v.temp))
  4435. }
  4436. }
  4437. if p.net != nil {
  4438. row.RxBps = p.net.RxBps
  4439. row.TxBps = p.net.TxBps
  4440. }
  4441. rows = append(rows, row)
  4442. if p.cfg.SnmpEnabled {
  4443. l.snmpLastMetricsTick[id] = p.polledAt
  4444. }
  4445. }
  4446. l.mu.Unlock()
  4447. return rows
  4448. }
  4449. // GetAdguardClients: solo GL tiene /control/clients (nil si no configurado).
  4450. func (l *Live) GetAdguardClients(ctx context.Context) ([]AdguardClient, error) {
  4451. _, gl := l.getAdguardClient()
  4452. if gl == nil {
  4453. return nil, nil
  4454. }
  4455. return gl.QueryClients(ctx)
  4456. }
  4457. // usteerAPRaw es la forma cruda de una entrada de `ubus call usteer
  4458. // local_info` / `remote_info` (por iface o ip#iface).
  4459. type usteerAPRaw struct {
  4460. BSSID string `json:"bssid"`
  4461. SSID string `json:"ssid"`
  4462. Freq int `json:"freq"`
  4463. NAssoc int `json:"n_assoc"`
  4464. Load int `json:"load"`
  4465. }
  4466. // usteerClientRaw es la forma cruda de una entrada de `ubus call usteer
  4467. // connected_clients` (por MAC).
  4468. type usteerClientRaw struct {
  4469. Signal int `json:"signal"`
  4470. }
  4471. // GetUsteer: red usteer (roaming/steering). nil si ningún router responde.
  4472. //
  4473. // A diferencia de DAWN (que distribuía el hearing map en get_network), usteer
  4474. // expone `local_info` por router (los APs propios) y `connected_clients` por
  4475. // iface. Se sondea cada router con SSH (local_info + connected_clients) y se
  4476. // agregan sus APs locales; el mesh marca por router si usteer está activo y
  4477. // cuántos APs ve. Los clientes se asocian a cada AP por nombre de iface.
  4478. func (l *Live) GetUsteer(context.Context) (*Usteer, error) {
  4479. l.mu.Lock()
  4480. routers := append([]RouterConfig(nil), l.routers...)
  4481. reg := l.agents
  4482. macs := make(map[string]string, len(l.routerMacs))
  4483. for k, v := range l.routerMacs {
  4484. macs[k] = v
  4485. }
  4486. l.mu.Unlock()
  4487. aps := []UsteerAP{}
  4488. mesh := []UsteerMesh{}
  4489. for _, cfg := range routers {
  4490. name := cfg.Name
  4491. if name == "" {
  4492. name = cfg.ID
  4493. }
  4494. if cfg.SnmpEnabled {
  4495. mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
  4496. continue
  4497. }
  4498. if cfg.AgentOnly {
  4499. // #1431: en flotas agent-only no hay sondeo SSH; la vista se
  4500. // alimenta del payload que el agente empuja (usteer + wireless).
  4501. apsR, seen := []UsteerAP{}, 0
  4502. if reg != nil {
  4503. if _, p, fresh := reg.MatchRouter(cfg, macs); fresh && p != nil {
  4504. apsR, seen = usteerAPsFromPayload(name, p)
  4505. }
  4506. }
  4507. mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: seen > 0, ApsSeen: seen})
  4508. aps = append(aps, apsR...)
  4509. continue
  4510. }
  4511. localOut, err := l.pool.Run(cfg.SSHAddr(), "ubus call usteer local_info", 0)
  4512. if err != nil {
  4513. mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
  4514. continue
  4515. }
  4516. var local map[string]usteerAPRaw
  4517. if json.Unmarshal([]byte(localOut), &local) != nil {
  4518. mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
  4519. continue
  4520. }
  4521. clientsOut, _ := l.pool.Run(cfg.SSHAddr(), "ubus call usteer connected_clients", 0)
  4522. clientsByIface := map[string]map[string]usteerClientRaw{}
  4523. _ = json.Unmarshal([]byte(clientsOut), &clientsByIface)
  4524. seen := 0
  4525. for iface, raw := range local {
  4526. if raw.SSID == "" || raw.BSSID == "" {
  4527. continue
  4528. }
  4529. aps = append(aps, buildUsteerAPWithClients(iface, raw, clientsByIface[iface], name, true))
  4530. seen++
  4531. }
  4532. mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: true, ApsSeen: seen})
  4533. }
  4534. if len(aps) == 0 {
  4535. return nil, nil
  4536. }
  4537. return &Usteer{APs: aps, Mesh: mesh}, nil
  4538. }
  4539. // sshRunner es el subconjunto de *SSHPool que usan las funciones live que
  4540. // ejecutan comandos remotos. Permite inyectar runners falsos en tests.
  4541. type sshRunner interface {
  4542. Run(host, cmd string, timeout time.Duration) (string, error)
  4543. }
  4544. // KickUsteerClient busca la MAC en los connected_clients de cada router y la
  4545. // expulsa del AP hostapd donde esté conectada. El motivo 5 (DISASSOC_DUE_TO_BSS_TRANSITION_PROHIBITED)
  4546. // con deauth=true fuerza al cliente a reasociarse; ban_time corto (120 ms) evita
  4547. // que vuelva inmediatamente al mismo AP sin impedir la reconexión normal.
  4548. //
  4549. // Si el cliente aparece en varios routers (transición de roaming) o un
  4550. // del_client falla por un estado transitorio del AP, intenta expulsarlo de
  4551. // cada uno hasta que un intento tenga éxito. Solo devuelve error cuando el
  4552. // cliente no está en ningún router o cuando todos los intentos fallan.
  4553. func (l *Live) KickUsteerClient(ctx context.Context, mac string) error {
  4554. target := strings.ToUpper(strings.TrimSpace(mac))
  4555. if target == "" || !validMAC(target) {
  4556. return fmt.Errorf("invalid MAC")
  4557. }
  4558. l.mu.Lock()
  4559. routers := append([]RouterConfig(nil), l.routers...)
  4560. l.mu.Unlock()
  4561. return kickUsteerClient(target, routers, l.pool)
  4562. }
  4563. func kickUsteerClient(target string, routers []RouterConfig, runner sshRunner) error {
  4564. var failures []string
  4565. for _, cfg := range routers {
  4566. if cfg.AgentOnly {
  4567. continue
  4568. }
  4569. out, err := runner.Run(cfg.Host, "ubus call usteer connected_clients", 0)
  4570. if err != nil {
  4571. continue
  4572. }
  4573. var clients map[string]map[string]usteerClientRaw
  4574. if err := json.Unmarshal([]byte(out), &clients); err != nil {
  4575. continue
  4576. }
  4577. for iface, macs := range clients {
  4578. var found bool
  4579. for m := range macs {
  4580. if strings.ToUpper(m) == target {
  4581. found = true
  4582. break
  4583. }
  4584. }
  4585. if !found {
  4586. continue
  4587. }
  4588. cmd := fmt.Sprintf("ubus call %s del_client '{\"addr\":\"%s\",\"reason\":5,\"deauth\":true,\"ban_time\":120000}'", iface, target)
  4589. if _, err := runner.Run(cfg.Host, cmd, 0); err != nil {
  4590. name := cfg.Name
  4591. if name == "" {
  4592. name = cfg.Host
  4593. }
  4594. failures = append(failures, name)
  4595. continue
  4596. }
  4597. return nil
  4598. }
  4599. }
  4600. if len(failures) > 0 {
  4601. return fmt.Errorf("could not disconnect from %s", strings.Join(failures, "; "))
  4602. }
  4603. return fmt.Errorf("client not found")
  4604. }
  4605. // validMAC acepta MAC con separadores ':' o '-'.
  4606. func validMAC(s string) bool {
  4607. parts := strings.Split(s, ":")
  4608. if len(parts) != 6 {
  4609. parts = strings.Split(s, "-")
  4610. }
  4611. if len(parts) != 6 {
  4612. return false
  4613. }
  4614. for _, p := range parts {
  4615. if len(p) != 2 {
  4616. return false
  4617. }
  4618. for i := 0; i < len(p); i++ {
  4619. c := p[i]
  4620. if !((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {
  4621. return false
  4622. }
  4623. }
  4624. }
  4625. return true
  4626. }
  4627. // buildUsteerAP construye un UsteerAP desde una entrada cruda de local_info.
  4628. // Band se deriva de freq (>= 5000 MHz → 5 GHz). Función pura para testear.
  4629. func buildUsteerAP(iface string, raw usteerAPRaw, hostname string, local bool) UsteerAP {
  4630. band := "2.4 GHz"
  4631. if raw.Freq >= 5000 {
  4632. band = "5 GHz"
  4633. }
  4634. return UsteerAP{
  4635. SSID: raw.SSID,
  4636. BSSID: strings.ToUpper(raw.BSSID),
  4637. Hostname: hostname,
  4638. Band: band,
  4639. Freq: raw.Freq,
  4640. UtilizationPct: raw.Load,
  4641. ClientCount: raw.NAssoc,
  4642. Clients: []UsteerClient{},
  4643. Local: local,
  4644. Iface: iface,
  4645. }
  4646. }
  4647. // buildUsteerAPWithClients enriquece un AP con los clientes de
  4648. // connected_clients para ese mismo iface. Los clientes se ordenan por MAC
  4649. // para respuestas deterministas.
  4650. func buildUsteerAPWithClients(iface string, raw usteerAPRaw, clients map[string]usteerClientRaw, hostname string, local bool) UsteerAP {
  4651. ap := buildUsteerAP(iface, raw, hostname, local)
  4652. for mac, c := range clients {
  4653. if c.Signal >= 0 {
  4654. continue // señal 0/positiva = sin datos
  4655. }
  4656. ap.Clients = append(ap.Clients, UsteerClient{
  4657. MAC: strings.ToUpper(mac),
  4658. Signal: c.Signal,
  4659. })
  4660. }
  4661. sort.Slice(ap.Clients, func(i, j int) bool { return ap.Clients[i].MAC < ap.Clients[j].MAC })
  4662. return ap
  4663. }
  4664. // ---------------------------------------------------------------------------
  4665. // 802.11r (Fast BSS Transition) — Fase 14.3
  4666. // ---------------------------------------------------------------------------
  4667. // parseUciWireless parsea la salida de `uci show wireless` (líneas
  4668. // `wireless.SECTION.FIELD='VALUE'` y `wireless.SECTION=TYPE`) y devuelve los
  4669. // wifi-iface con sus campos relevantes para 802.11r. Ignora wifi-device y
  4670. // cualquier otra sección que no sea wifi-iface (pero usa wifi-device para
  4671. // mapear device → {channel, band}). Función pura — fácil de testear.
  4672. //
  4673. // Formato uci: las comillas simples envuelven los valores; los campos lista
  4674. // (como rrm_nr_list) se emiten como varias líneas con el mismo nombre — aquí
  4675. // nos quedamos con el último valor escalar (no nos interesan las listas).
  4676. func parseUciWireless(out string) []Dot11rIface {
  4677. type sec struct {
  4678. typ string
  4679. fields map[string]string
  4680. }
  4681. sections := map[string]*sec{}
  4682. order := []string{}
  4683. for _, line := range strings.Split(out, "\n") {
  4684. line = strings.TrimRight(line, "\r")
  4685. if !strings.HasPrefix(line, "wireless.") {
  4686. continue
  4687. }
  4688. rest := line[len("wireless."):]
  4689. // Caso 1: wireless.SECTION=TYPE (declaración de sección, sin punto en SECTION).
  4690. if eq := strings.IndexByte(rest, '='); eq > 0 {
  4691. head := rest[:eq]
  4692. if !strings.Contains(head, ".") {
  4693. if _, ok := sections[head]; !ok {
  4694. sections[head] = &sec{fields: map[string]string{}}
  4695. order = append(order, head)
  4696. }
  4697. sections[head].typ = unquoteUci(rest[eq+1:])
  4698. continue
  4699. }
  4700. }
  4701. // Caso 2: wireless.SECTION.FIELD='VALUE'
  4702. parts := strings.SplitN(rest, ".", 2)
  4703. if len(parts) != 2 {
  4704. continue
  4705. }
  4706. section, field := parts[0], parts[1]
  4707. if _, ok := sections[section]; !ok {
  4708. sections[section] = &sec{fields: map[string]string{}}
  4709. order = append(order, section)
  4710. }
  4711. if eq := strings.IndexByte(field, '='); eq > 0 {
  4712. fname := field[:eq]
  4713. fval := field[eq+1:]
  4714. sections[section].fields[fname] = unquoteUci(fval)
  4715. }
  4716. }
  4717. // device → {channel, band} desde las secciones wifi-device.
  4718. type devInfo struct {
  4719. channel int
  4720. band string
  4721. }
  4722. devMap := map[string]devInfo{}
  4723. for _, name := range order {
  4724. s := sections[name]
  4725. if s.typ != "wifi-device" {
  4726. continue
  4727. }
  4728. ch, _ := strconv.Atoi(s.fields["channel"])
  4729. band := ""
  4730. switch s.fields["band"] {
  4731. case "2g":
  4732. band = "2.4 GHz"
  4733. case "5g":
  4734. band = "5 GHz"
  4735. case "6g":
  4736. band = "6 GHz"
  4737. case "60g":
  4738. band = "60 GHz"
  4739. }
  4740. devMap[name] = devInfo{channel: ch, band: band}
  4741. }
  4742. ifaces := []Dot11rIface{}
  4743. for _, name := range order {
  4744. s := sections[name]
  4745. if s.typ != "wifi-iface" {
  4746. continue
  4747. }
  4748. f := s.fields
  4749. dev := f["device"]
  4750. di := devMap[dev]
  4751. ifaces = append(ifaces, Dot11rIface{
  4752. Section: name,
  4753. Device: dev,
  4754. Ifname: f["ifname"],
  4755. SSID: f["ssid"],
  4756. MAC: f["macaddr"],
  4757. Channel: di.channel,
  4758. Band: di.band,
  4759. Network: f["network"],
  4760. Disabled: f["disabled"] == "1",
  4761. Encryption: f["encryption"],
  4762. Dot11REnabled: f["ieee80211r"] == "1",
  4763. MobilityDomain: f["mobility_domain"],
  4764. FTOverDS: f["ft_over_ds"] == "1",
  4765. FTPSKGenerateLocal: f["ft_psk_generate_local"] == "1",
  4766. PMKR1Push: f["pmk_r1_push"] == "1",
  4767. NASID: f["nasid"],
  4768. Dot11KEnabled: f["ieee80211k"] == "1",
  4769. Dot11VEnabled: f["ieee80211v"] == "1",
  4770. BSSTransition: f["bss_transition"] == "1",
  4771. MFP: f["ieee80211w"] == "1",
  4772. })
  4773. }
  4774. return ifaces
  4775. }
  4776. // dot11rSkip (#541): una iface no debe contar para usteer si pertenece a una
  4777. // red invitada/aislada (guest/iot/wan) o está deshabilitada. La red principal
  4778. // de roaming es "lan" (o la red no aislada). Si no puede determinarse, se deja
  4779. // pasar (mejor mostrar de más que ocultar la principal por un nombre raro).
  4780. func dot11rSkip(ifc Dot11rIface) bool {
  4781. if ifc.Disabled {
  4782. return true
  4783. }
  4784. switch ifc.Network {
  4785. case "guest", "iot", "wan":
  4786. return true
  4787. }
  4788. return false
  4789. }
  4790. // unquoteUci quita las comillas simples que uci envuelve a los valores y
  4791. // desescapa \' → '. `uci show` SIEMPRE envuelve en comillas simples.
  4792. func unquoteUci(s string) string {
  4793. if len(s) >= 2 && s[0] == '\'' && s[len(s)-1] == '\'' {
  4794. return strings.ReplaceAll(s[1:len(s)-1], `\'`, `'`)
  4795. }
  4796. return s
  4797. }
  4798. type dot11rIfaceRef struct {
  4799. routerID string
  4800. iface Dot11rIface
  4801. }
  4802. // GetDot11r: estado 802.11r (Fast BSS Transition) por router y SSID. Recorre
  4803. // los routers (saltando agent-only, que son switches sin wifi) y hace SSH
  4804. // `uci show wireless` a cada uno. Devuelve (nil, nil) si ningún router con
  4805. // wifi tiene 802.11r habilitado -> el handler responde 503.
  4806. func (l *Live) GetDot11r(ctx context.Context) (*Dot11rOverview, error) {
  4807. l.mu.Lock()
  4808. routers := append([]RouterConfig(nil), l.routers...)
  4809. reg := l.agents
  4810. macs := make(map[string]string, len(l.routerMacs))
  4811. for k, v := range l.routerMacs {
  4812. macs[k] = v
  4813. }
  4814. l.mu.Unlock()
  4815. out := Dot11rOverview{Routers: []Dot11rRouter{}, SSIDs: []Dot11rSSID{}}
  4816. ssidIfaces := map[string][]dot11rIfaceRef{}
  4817. for _, cfg := range routers {
  4818. name := cfg.Name
  4819. if name == "" {
  4820. name = cfg.ID
  4821. }
  4822. r := Dot11rRouter{RouterID: cfg.ID, Name: name, Ifaces: []Dot11rIface{}}
  4823. // #1450: en flotas agent-only no hay llave SSH. La config sale del
  4824. // último payload del agente (uciWirelessRaw), parseado con la MISMA
  4825. // parseUciWireless del camino SSH. Solo payload fresco (mismo
  4826. // criterio que la vista usteer, #1431): un router que dejó de
  4827. // empujar no debe seguir pintando su config como actual.
  4828. // SNMP (sin SSH en absoluto, #1026) y agentes antiguos sin el campo
  4829. // se listan con Available=false, como antes.
  4830. var ifaces []Dot11rIface
  4831. switch {
  4832. case cfg.AgentOnly:
  4833. if reg != nil {
  4834. if _, p, fresh := reg.MatchRouter(cfg, macs); fresh && p != nil {
  4835. ifaces = dot11rIfacesFromPayload(p)
  4836. }
  4837. }
  4838. if len(ifaces) == 0 {
  4839. out.Routers = append(out.Routers, r)
  4840. continue
  4841. }
  4842. case cfg.SnmpEnabled:
  4843. out.Routers = append(out.Routers, r)
  4844. continue
  4845. default:
  4846. uciOut, err := l.pool.Run(cfg.SSHAddr(), "uci show wireless", 0)
  4847. if err != nil {
  4848. out.Routers = append(out.Routers, r)
  4849. continue
  4850. }
  4851. ifaces = parseUciWireless(uciOut)
  4852. }
  4853. r.Available = true
  4854. r.Ifaces = ifaces
  4855. out.Routers = append(out.Routers, r)
  4856. for _, ifc := range ifaces {
  4857. if ifc.SSID == "" || dot11rSkip(ifc) {
  4858. continue
  4859. }
  4860. ssidIfaces[ifc.SSID] = append(ssidIfaces[ifc.SSID], dot11rIfaceRef{routerID: cfg.ID, iface: ifc})
  4861. }
  4862. }
  4863. // Agregar por SSID.
  4864. ssids := make([]Dot11rSSID, 0, len(ssidIfaces))
  4865. for ssid, refs := range ssidIfaces {
  4866. enabled := 0
  4867. mobilityDomain := ""
  4868. ftOverDS := false
  4869. ftPSK := false
  4870. routerSet := map[string]bool{}
  4871. for _, ref := range refs {
  4872. if ref.iface.Dot11REnabled {
  4873. enabled++
  4874. if mobilityDomain == "" {
  4875. mobilityDomain = ref.iface.MobilityDomain
  4876. ftOverDS = ref.iface.FTOverDS
  4877. ftPSK = ref.iface.FTPSKGenerateLocal
  4878. }
  4879. }
  4880. routerSet[ref.routerID] = true
  4881. }
  4882. routerIDs := make([]string, 0, len(routerSet))
  4883. for id := range routerSet {
  4884. routerIDs = append(routerIDs, id)
  4885. }
  4886. sort.Strings(routerIDs)
  4887. ssids = append(ssids, Dot11rSSID{
  4888. SSID: ssid,
  4889. EnabledEverywhere: enabled > 0 && enabled == len(refs),
  4890. EnabledCount: enabled,
  4891. TotalCount: len(refs),
  4892. MobilityDomain: mobilityDomain,
  4893. FTOverDS: ftOverDS,
  4894. FTPSKGenerateLocal: ftPSK,
  4895. IfaceCount: len(refs),
  4896. RouterIDs: routerIDs,
  4897. })
  4898. }
  4899. sort.Slice(ssids, func(i, j int) bool { return ssids[i].SSID < ssids[j].SSID })
  4900. out.SSIDs = ssids
  4901. for _, s := range ssids {
  4902. if s.EnabledCount > 0 {
  4903. out.Available = true
  4904. break
  4905. }
  4906. }
  4907. // #1450: si la configuración wifi SÍ se pudo leer pero ningún SSID tiene
  4908. // 802.11r, la vista está disponible (el panel pinta el estado "inactivo"
  4909. // en vez de un error de lectura). Antes este caso devolvía (nil, nil) y el
  4910. // handler respondía 503, que la UI mostraba como "no se pudo leer".
  4911. if !out.Available {
  4912. for _, r := range out.Routers {
  4913. if r.Available {
  4914. out.Available = true
  4915. break
  4916. }
  4917. }
  4918. }
  4919. if !out.Available {
  4920. return nil, nil
  4921. }
  4922. out.Anomalies = buildRoamingAnomalies(ssidIfaces)
  4923. return &out, nil
  4924. }
  4925. // buildRoamingAnomalies detecta problemas de configuración de roaming a partir
  4926. // de las interfaces wifi-iface agrupadas por SSID (#428).
  4927. func buildRoamingAnomalies(ssidIfaces map[string][]dot11rIfaceRef) []RoamingAnomaly {
  4928. var anomalies []RoamingAnomaly
  4929. for ssid, refs := range ssidIfaces {
  4930. // Solo consideramos interfaces con 802.11r habilitado para las
  4931. // comprobaciones de consistencia.
  4932. enabled := make([]dot11rIfaceRef, 0, len(refs))
  4933. for _, ref := range refs {
  4934. if ref.iface.Dot11REnabled {
  4935. enabled = append(enabled, ref)
  4936. }
  4937. }
  4938. if len(enabled) == 0 {
  4939. continue
  4940. }
  4941. // 802.11r parcial: algunas interfaces del SSID lo tienen y otras no.
  4942. if len(enabled) < len(refs) {
  4943. anomalies = append(anomalies, RoamingAnomaly{
  4944. Kind: "partial_11r",
  4945. SSID: ssid,
  4946. Message: fmt.Sprintf("802.11r habilitado solo en %d de %d interfaces del SSID %q", len(enabled), len(refs), ssid),
  4947. })
  4948. }
  4949. // Mobility domain inconsistente.
  4950. md := ""
  4951. mdOk := true
  4952. for _, ref := range enabled {
  4953. if md == "" {
  4954. md = ref.iface.MobilityDomain
  4955. } else if ref.iface.MobilityDomain != "" && ref.iface.MobilityDomain != md {
  4956. mdOk = false
  4957. break
  4958. }
  4959. }
  4960. if !mdOk {
  4961. anomalies = append(anomalies, RoamingAnomaly{
  4962. Kind: "mobility_domain_mismatch",
  4963. SSID: ssid,
  4964. Message: fmt.Sprintf("Mobility domain distinto entre routers para el SSID %q", ssid),
  4965. })
  4966. }
  4967. // FT mode inconsistente.
  4968. ftOverDS := enabled[0].iface.FTOverDS
  4969. ftMixed := false
  4970. for _, ref := range enabled[1:] {
  4971. if ref.iface.FTOverDS != ftOverDS {
  4972. ftMixed = true
  4973. break
  4974. }
  4975. }
  4976. if ftMixed {
  4977. anomalies = append(anomalies, RoamingAnomaly{
  4978. Kind: "ft_mode_mismatch",
  4979. SSID: ssid,
  4980. Message: fmt.Sprintf("Modo FT mixto (over-the-DS / over-the-air) para el SSID %q", ssid),
  4981. })
  4982. }
  4983. }
  4984. return anomalies
  4985. }
  4986. // ---------------------------------------------------------------------------
  4987. // WiFi Survey (canal utilization) — Fase 14.4
  4988. // ---------------------------------------------------------------------------
  4989. // freqToChannel mapea frecuencia MHz → número de canal IEEE 802.11.
  4990. // 2.4 GHz: 2412-2472 → 1-13; 2484 → 14. 5 GHz: 5000+5*N → N (5180=36, ...).
  4991. // 60 GHz: 56160+2160*N → N+1.
  4992. func freqToChannel(freq int) int {
  4993. switch {
  4994. case freq >= 2412 && freq <= 2472:
  4995. return (freq-2412)/5 + 1
  4996. case freq == 2484:
  4997. return 14
  4998. case freq >= 5160 && freq <= 5885:
  4999. // Canales UNII: 5160=ch32 ... 5885=ch177. Fórmula general (freq-5000)/5.
  5000. return (freq - 5000) / 5
  5001. case freq >= 5940 && freq <= 7115:
  5002. // 6 GHz (Wi-Fi 6E): 5950=ch1 ... 7115=ch233. Mismo (freq-5000)/5, con offset.
  5003. return (freq-5950)/5 + 1
  5004. case freq == 56160:
  5005. return 1
  5006. case freq >= 56160:
  5007. return (freq-56160)/2160 + 1
  5008. }
  5009. return 0
  5010. }
  5011. // freqToBand devuelve "2.4 GHz"|"5 GHz"|"6 GHz"|"60 GHz"|"" según la frecuencia.
  5012. func freqToBand(freq int) string {
  5013. switch {
  5014. case freq >= 2412 && freq <= 2484:
  5015. return "2.4 GHz"
  5016. case freq >= 5160 && freq <= 5885:
  5017. return "5 GHz"
  5018. case freq >= 5945 && freq <= 7115:
  5019. return "6 GHz"
  5020. case freq >= 56160:
  5021. return "60 GHz"
  5022. }
  5023. return ""
  5024. }
  5025. // parseIwSurvey parsea la salida de `iw dev wlanX survey dump` y devuelve
  5026. // un map device → lista de SurveyChannel (uno por frecuencia). Función pura
  5027. // para testear con fixtures reales sin SSH.
  5028. //
  5029. // Formato (ejemplo Flint2):
  5030. //
  5031. // Survey data from wlan0
  5032. // frequency: 2412 MHz [in use]
  5033. // noise: -90 dBm
  5034. // channel active time: 3632796925 ms
  5035. // channel busy time: 878259766 ms
  5036. // channel receive time: 440957725 ms
  5037. // channel transmit time: 340995043 ms
  5038. // Survey data from wlan0
  5039. // frequency: 2417 MHz
  5040. // noise: -92 dBm
  5041. // channel active time: 72 ms
  5042. // channel busy time: 20 ms
  5043. // ...
  5044. //
  5045. // Cada bloque empieza con "Survey data from <dev>". Los valores están
  5046. // tabulados y separados por ":". El "[in use]" marca el canal operativo.
  5047. // ParseIwSurvey parsea la salida de `iw dev wlanX survey dump` (#1214):
  5048. // exportada para que el httpapi pueda parsear el survey crudo que empuja el
  5049. // agente en unidades agent-only.
  5050. func ParseIwSurvey(out string) map[string][]SurveyChannel {
  5051. type rawChannel struct {
  5052. freq int
  5053. inUse bool
  5054. noise int
  5055. activeMs float64
  5056. busyMs float64
  5057. rxMs float64
  5058. txMs float64
  5059. }
  5060. result := map[string][]SurveyChannel{}
  5061. var currentDev string
  5062. var current *rawChannel
  5063. flush := func() {
  5064. if currentDev == "" || current == nil {
  5065. return
  5066. }
  5067. ch := SurveyChannel{
  5068. Freq: current.freq,
  5069. Channel: freqToChannel(current.freq),
  5070. InUse: current.inUse,
  5071. NoiseDbm: current.noise,
  5072. }
  5073. if current.activeMs > 0 {
  5074. ch.BusyPct = current.busyMs / current.activeMs * 100
  5075. ch.RxPct = current.rxMs / current.activeMs * 100
  5076. ch.TxPct = current.txMs / current.activeMs * 100
  5077. }
  5078. result[currentDev] = append(result[currentDev], ch)
  5079. current = nil
  5080. }
  5081. for _, line := range strings.Split(out, "\n") {
  5082. line = strings.TrimRight(line, "\r")
  5083. trimmed := strings.TrimSpace(line)
  5084. if strings.HasPrefix(trimmed, "Survey data from ") {
  5085. flush()
  5086. currentDev = strings.TrimPrefix(trimmed, "Survey data from ")
  5087. continue
  5088. }
  5089. if currentDev == "" {
  5090. continue
  5091. }
  5092. parts := strings.SplitN(trimmed, ":", 2)
  5093. if len(parts) != 2 {
  5094. continue
  5095. }
  5096. // Solo inicializamos el canal si la línea tiene un campo válido.
  5097. // Evita crear un canal vacío al final de cada bloque (línea "" final).
  5098. if current == nil {
  5099. current = &rawChannel{}
  5100. }
  5101. key := strings.TrimSpace(parts[0])
  5102. val := strings.TrimSpace(parts[1])
  5103. switch key {
  5104. case "frequency":
  5105. fmt.Sscanf(val, "%d MHz", &current.freq)
  5106. if strings.Contains(val, "[in use]") {
  5107. current.inUse = true
  5108. }
  5109. case "noise":
  5110. fmt.Sscanf(val, "%d dBm", &current.noise)
  5111. case "channel active time":
  5112. fmt.Sscanf(val, "%f ms", &current.activeMs)
  5113. case "channel busy time":
  5114. fmt.Sscanf(val, "%f ms", &current.busyMs)
  5115. case "channel receive time":
  5116. fmt.Sscanf(val, "%f ms", &current.rxMs)
  5117. case "channel transmit time":
  5118. fmt.Sscanf(val, "%f ms", &current.txMs)
  5119. }
  5120. }
  5121. flush()
  5122. return result
  5123. }
  5124. // surveyEntry: survey crudo del agente con su marca de tiempo (#1214).
  5125. type surveyEntry struct {
  5126. raw string
  5127. at time.Time
  5128. }
  5129. const agentSurveyTTL = 15 * time.Minute
  5130. // StoreAgentSurvey guarda el texto crudo de `iw survey dump` que empuja un
  5131. // agente (#1214): fuente de la lente "Ahora" en unidades agent-only sin SSH.
  5132. // El httpapi lo llama en cada push que traiga surveyRaw.
  5133. func (l *Live) StoreAgentSurvey(routerID, raw string) {
  5134. if raw == "" {
  5135. return
  5136. }
  5137. l.surveyMu.Lock()
  5138. if l.surveyRaw == nil {
  5139. l.surveyRaw = map[string]surveyEntry{}
  5140. }
  5141. l.surveyRaw[routerID] = surveyEntry{raw: raw, at: time.Now()}
  5142. l.surveyMu.Unlock()
  5143. }
  5144. // agentSurveyRadios parsea el survey crudo del agente si está fresco
  5145. // (agentSurveyTTL); nil si no hay datos o caducaron.
  5146. func (l *Live) agentSurveyRadios(routerID string) []SurveyRadio {
  5147. l.surveyMu.Lock()
  5148. e, ok := l.surveyRaw[routerID]
  5149. l.surveyMu.Unlock()
  5150. if !ok || time.Since(e.at) > agentSurveyTTL {
  5151. return nil
  5152. }
  5153. per := ParseIwSurvey(e.raw)
  5154. radios := []SurveyRadio{}
  5155. for dev, channels := range per {
  5156. if len(channels) == 0 {
  5157. continue
  5158. }
  5159. band := ""
  5160. for _, c := range channels {
  5161. if c.InUse {
  5162. band = freqToBand(c.Freq)
  5163. break
  5164. }
  5165. }
  5166. if band == "" {
  5167. band = freqToBand(channels[0].Freq)
  5168. }
  5169. radios = append(radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
  5170. }
  5171. return radios
  5172. }
  5173. // GetSurvey: utilización por canal wifi (iw survey dump) por router y radio.
  5174. // Recorre los routers (saltando agent-only, que no tienen wifi) y hace SSH
  5175. // `iw dev` para listar interfaces, luego `iw dev wlanX survey dump` por cada
  5176. // una. Devuelve (nil, nil) si ningún router responde → el handler 503.
  5177. func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
  5178. l.mu.Lock()
  5179. routers := append([]RouterConfig(nil), l.routers...)
  5180. l.mu.Unlock()
  5181. out := SurveyOverview{Routers: []SurveyRouter{}}
  5182. any := false
  5183. // #1308: el gateway YA NO se excluye. La exclusión venía de #1214, cuando
  5184. // el survey vivía en la pestaña de roaming (los clientes no reanclan al
  5185. // gateway en flotas con APs). Desde #1229 la lente es de CANALES, donde el
  5186. // gateway es un AP más: su agente empuja iw survey dump igual que los
  5187. // demás (#1270) y su espectro importa para el análisis.
  5188. for _, cfg := range routers {
  5189. name := cfg.Name
  5190. if name == "" {
  5191. name = cfg.ID
  5192. }
  5193. r := SurveyRouter{RouterID: cfg.ID, Name: name, Radios: []SurveyRadio{}}
  5194. // Agent-only y SNMP (#1026): unidades sin SSH. Las agent-only pueden
  5195. // traer survey vía push del agente (#1214); SNMP se lista sin radios.
  5196. if cfg.AgentOnly {
  5197. if radios := l.agentSurveyRadios(cfg.ID); len(radios) > 0 {
  5198. r.Available = true
  5199. r.Radios = radios
  5200. any = true
  5201. }
  5202. out.Routers = append(out.Routers, r)
  5203. continue
  5204. }
  5205. if cfg.SnmpEnabled {
  5206. out.Routers = append(out.Routers, r)
  5207. continue
  5208. }
  5209. // Lista de interfaces wifi (wlanX).
  5210. devsOut, err := l.pool.Run(cfg.SSHAddr(), "iw dev 2>/dev/null | awk '/Interface/ {print $2}'", 0)
  5211. if err != nil {
  5212. out.Routers = append(out.Routers, r)
  5213. continue
  5214. }
  5215. devs := []string{}
  5216. for _, line := range strings.Split(devsOut, "\n") {
  5217. d := strings.TrimSpace(line)
  5218. // iw dev solo lista interfaces wifi, pero el nombre puede ser
  5219. // wlan0/wlan1 (driver estándar) o phy0-ap0/phy1-ap0 (mt76,
  5220. // Xiaomi AX6). Aceptamos cualquier token no vacío que awk haya
  5221. // extraído de la línea "Interface <name>".
  5222. if d != "" {
  5223. devs = append(devs, d)
  5224. }
  5225. }
  5226. if len(devs) == 0 {
  5227. out.Routers = append(out.Routers, r)
  5228. continue
  5229. }
  5230. r.Available = true
  5231. any = true
  5232. for _, dev := range devs {
  5233. surveyOut, err := l.pool.Run(cfg.SSHAddr(), "iw dev "+dev+" survey dump 2>/dev/null", 0)
  5234. if err != nil {
  5235. continue
  5236. }
  5237. channels := ParseIwSurvey(surveyOut)[dev]
  5238. if len(channels) == 0 {
  5239. continue
  5240. }
  5241. band := ""
  5242. // El canal in use define la banda del radio.
  5243. for _, c := range channels {
  5244. if c.InUse {
  5245. band = freqToBand(c.Freq)
  5246. break
  5247. }
  5248. }
  5249. if band == "" {
  5250. band = freqToBand(channels[0].Freq)
  5251. }
  5252. r.Radios = append(r.Radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
  5253. }
  5254. out.Routers = append(out.Routers, r)
  5255. }
  5256. if !any {
  5257. return nil, nil
  5258. }
  5259. out.Available = true
  5260. return &out, nil
  5261. }
  5262. // allWifiOfOneAP: ¿todas las MACs de la boca son clientes WiFi del mismo AP?
  5263. func allWifiOfOneAP(macs []string, wifiByMac map[string]string) bool {
  5264. if len(macs) == 0 {
  5265. return false
  5266. }
  5267. ap := wifiByMac[macs[0]]
  5268. if ap == "" {
  5269. return false
  5270. }
  5271. for _, m := range macs[1:] {
  5272. if wifiByMac[m] != ap {
  5273. return false
  5274. }
  5275. }
  5276. return true
  5277. }
  5278. // prefijos OUI de virtualización: la MAC aprendida es una NIC virtual.
  5279. var virtualMACPrefixes = []string{
  5280. "52:54:00", // QEMU/KVM (Proxmox VMs por defecto)
  5281. "BC:24:11", // Proxmox Server Solutions
  5282. "00:15:5D", // Microsoft Hyper-V
  5283. "00:50:56", // VMware ESX
  5284. "00:1C:14", // VMware
  5285. "08:00:27", // VirtualBox
  5286. }
  5287. func isVirtualMAC(mac string) bool {
  5288. m := strings.ToUpper(mac)
  5289. for _, p := range virtualMACPrefixes {
  5290. if strings.HasPrefix(m, p) {
  5291. return true
  5292. }
  5293. }
  5294. return false
  5295. }
  5296. // virtualDetail: nombre legible de la VM/CT detrás del hypervisor.
  5297. func virtualDetail(mac string, leases map[string]DhcpLease, aliases map[string]string) string {
  5298. if n := deviceDisplayName(mac, leases, aliases); n != mac {
  5299. return n + " (VM/CT detrás)"
  5300. }
  5301. return "VM/CT detrás"
  5302. }
  5303. // isCuratedLabel: label renombrada a mano (no el "Port N" por defecto).
  5304. func isCuratedLabel(port EthPort) bool {
  5305. if port.Label == "" {
  5306. return false
  5307. }
  5308. n := strings.TrimPrefix(port.Label, "Port ")
  5309. if n == port.Label {
  5310. return true // no sigue el patrón por defecto
  5311. }
  5312. _, err := strconv.Atoi(n)
  5313. return err != nil // "Port <número>" = default; cualquier otra cosa, curada
  5314. }
  5315. // labelMatchesDevice: ¿la label curada nombra al propio dispositivo
  5316. // aprendido (p. ej. "hikvision") y no a la infraestructura que hay delante?
  5317. func labelMatchesDevice(label, mac string, leases map[string]DhcpLease, aliases map[string]string) bool {
  5318. name := strings.ToLower(deviceDisplayName(mac, leases, aliases))
  5319. l := strings.ToLower(label)
  5320. if name == "" || l == "" {
  5321. return false
  5322. }
  5323. return strings.Contains(name, l) || strings.Contains(l, name)
  5324. }
  5325. // deviceDisplayName: hostname de lease > alias > MAC.
  5326. func deviceDisplayName(mac string, leases map[string]DhcpLease, aliases map[string]string) string {
  5327. if le, ok := leases[mac]; ok && le.Hostname != "" {
  5328. return le.Hostname
  5329. }
  5330. if a := aliases[mac]; a != "" {
  5331. return a
  5332. }
  5333. return mac
  5334. }
  5335. // portEnrichDeps: mapas compartidos del enriquecimiento de bocas del
  5336. // detalle (extraído de GetRouterDetail, #1150, para poder testearlo).
  5337. type portEnrichDeps struct {
  5338. routerByMac map[string]string
  5339. leaseMap map[string]DhcpLease
  5340. aliasByMac map[string]string
  5341. wifiByMac map[string]string
  5342. portMacs map[string][]string
  5343. lldp []LldpNeighbor
  5344. }
  5345. // enrichEthPort: enriquece UNA boca encendida con el par que tiene enfrente
  5346. // (router-link, cliente WiFi detrás del AP, dispositivo único, agregación).
  5347. // Mismo comportamiento que el bucle inline que sustituye (#1150).
  5348. func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
  5349. all := d.portMacs[netdev]
  5350. // #1036: d.portMacs se construye iterando el FDB (mapa), así que el
  5351. // ORDEN de las MACs por boca cambia en cada tick. Con 2-3 MACs la
  5352. // heurística de "primera con hostname DHCP" elegía un dispositivo
  5353. // distinto por ciclo y la etiqueta del puerto flappeaba. Orden
  5354. // estable: la selección queda determinista entre polls.
  5355. sort.Strings(all)
  5356. // 1) ¿Otro router al otro lado? (uplink router↔router)
  5357. neighbor := ""
  5358. for _, mac := range all {
  5359. if _, ok := d.routerByMac[mac]; ok {
  5360. neighbor = mac
  5361. break
  5362. }
  5363. }
  5364. if neighbor != "" {
  5365. port.ConnectedTo = d.routerByMac[neighbor]
  5366. // El cliente traduce la plantilla según PeerKind (#1039).
  5367. port.PeerKind = PeerKindRouterLink
  5368. // #1150: con switches encadenados la boca aprende las MACs de bridge
  5369. // de VARIAS unidades (el tráfico de sw2 atraviesa sw1) y la primera
  5370. // MAC ordenada puede nombrar al switch LEJANO. El LLDP anuncia al
  5371. // vecino DIRECTO de la boca: su chassis MAC (si es unidad conocida)
  5372. // o su sysName manda sobre la MAC ordenada, y la mgmt-ip va al
  5373. // detalle del hover.
  5374. if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
  5375. port.PeerKind = PeerKindRouterLinkLLDP
  5376. if nb.ChassisMac != "" {
  5377. // La MAC del vecino (su bridge) va al hover como en las bocas
  5378. // de dispositivo único (#1150).
  5379. port.DeviceMac = strings.ToUpper(nb.ChassisMac)
  5380. if name, ok := d.routerByMac[strings.ToUpper(nb.ChassisMac)]; ok {
  5381. port.ConnectedTo = name
  5382. } else if dn := nb.displayName(); dn != "" {
  5383. port.ConnectedTo = dn
  5384. }
  5385. } else if dn := nb.displayName(); dn != "" {
  5386. port.ConnectedTo = dn
  5387. }
  5388. if nb.Mgmt != "" {
  5389. port.Detail = nb.Mgmt + " · LLDP"
  5390. }
  5391. }
  5392. return port
  5393. }
  5394. // 1.5) Cliente WiFi detrás de un AP: la boca del switch lleva al AP
  5395. // (el cliente viaja por su radio). Atribuir la boca al AP y señalar
  5396. // el cliente como "detrás" (#291). Guard de longitud PRIMERO: una
  5397. // boca up sin MACs aprendidas llega con all vacío.
  5398. if len(all) > 0 {
  5399. if ap, isWifi := d.wifiByMac[all[0]]; isWifi && allWifiOfOneAP(all, d.wifiByMac) {
  5400. port.ConnectedTo = ap
  5401. port.DeviceMac = all[0]
  5402. // La pista "cliente WiFi detrás" la traduce el cliente
  5403. // según PeerKind (#1039); el nombre del AP viaja en ConnectedTo.
  5404. port.PeerKind = PeerKindAPWiFi
  5405. return port
  5406. }
  5407. }
  5408. // 2) Un solo dispositivo final
  5409. if len(all) == 1 {
  5410. mac := all[0]
  5411. lease, ok := d.leaseMap[mac]
  5412. // #931: un vecino LLDP en esta boca es el propio equipo
  5413. // anunciándose; su sysName/mgmt-ip son mejor identificación que
  5414. // la MAC pelada cuando no hay hostname DHCP ni alias.
  5415. lldpName, lldpMgmt := "", ""
  5416. if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
  5417. lldpName = nb.displayName()
  5418. lldpMgmt = nb.Mgmt
  5419. }
  5420. // MAC de virtualización (QEMU/KVM, Proxmox, VMware, Hyper-V):
  5421. // el equipo enchufado es el hypervisor; lo aprendido es una
  5422. // NIC virtual de una VM/CT (#291).
  5423. if isVirtualMAC(mac) {
  5424. port.ConnectedTo = "Hypervisor"
  5425. port.DeviceMac = mac
  5426. port.Detail = virtualDetail(mac, d.leaseMap, d.aliasByMac)
  5427. return port
  5428. }
  5429. // Label curada que no coincide con el dispositivo resuelto:
  5430. // - si el dispositivo tiene nombre real (lease/alias), la label
  5431. // nombra la infraestructura física y lo aprendido está DETRÁS
  5432. // (p. ej. ngxpm detrás de citadel-02);
  5433. // - si el dispositivo no tiene nombre mejor que su MAC, la label
  5434. // ES su nombre (bautizada a mano: "hikvision"), y la MAC queda
  5435. // como detalle.
  5436. if isCuratedLabel(port) && !labelMatchesDevice(port.Label, mac, d.leaseMap, d.aliasByMac) {
  5437. name := deviceDisplayName(mac, d.leaseMap, d.aliasByMac)
  5438. port.DeviceMac = mac
  5439. if name != mac {
  5440. // El cliente compone "nombre · detrás de <label>" con
  5441. // su i18n (#1039); aquí viaja el nombre a pelo.
  5442. port.ConnectedTo = name
  5443. port.PeerKind = PeerKindCurated
  5444. } else if lldpName != "" {
  5445. // #931: sin nombre mejor, el equipo se anuncia por LLDP.
  5446. port.ConnectedTo = lldpName
  5447. port.PeerKind = PeerKindMAC
  5448. } else {
  5449. port.ConnectedTo = port.Label
  5450. port.PeerKind = PeerKindMAC
  5451. }
  5452. if lease, ok := d.leaseMap[mac]; ok && lease.IP != "" {
  5453. port.Detail = lease.IP
  5454. } else if lldpMgmt != "" && lldpName != "" {
  5455. port.Detail = lldpMgmt + " · LLDP"
  5456. }
  5457. return port
  5458. }
  5459. switch {
  5460. case ok && lease.Hostname != "":
  5461. port.ConnectedTo = lease.Hostname
  5462. case ok && lease.IP != "":
  5463. port.ConnectedTo = lease.IP
  5464. case d.aliasByMac[mac] != "":
  5465. port.ConnectedTo = d.aliasByMac[mac]
  5466. case lldpName != "":
  5467. // #931: sin lease ni alias, el nombre anunciado por el
  5468. // propio equipo (LLDP sysName) es la mejor etiqueta.
  5469. port.ConnectedTo = lldpName
  5470. if lldpMgmt != "" {
  5471. port.Detail = lldpMgmt + " · LLDP"
  5472. }
  5473. default:
  5474. port.ConnectedTo = mac
  5475. }
  5476. port.DeviceMac = mac
  5477. if ok && lease.IP != "" {
  5478. port.Detail = lease.IP + " · full duplex"
  5479. }
  5480. return port
  5481. }
  5482. // 3) Varios: el vecino es un switch/hub/hipervisor
  5483. if len(all) > 1 {
  5484. // Muchas MACs detrás de una boca = agregación (hipervisor Proxmox
  5485. // con CTs, switch tonto): nombrar UN CT al azar engaña (la MAC es
  5486. // virtual, no el equipo enchufado). La label curada del puerto ya
  5487. // identifica el físico; aquí se cuenta lo que hay detrás (#291).
  5488. if len(all) > 3 {
  5489. // deviceCount lo traduce la app; aquí NO se formatea texto (#1036).
  5490. port.DeviceCount = len(all)
  5491. return port
  5492. }
  5493. // Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
  5494. // es mejor pista que el hostname DHCP.
  5495. if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil && nb.displayName() != "" {
  5496. port.ConnectedTo = nb.displayName()
  5497. if nb.Mgmt != "" {
  5498. port.Detail = nb.Mgmt + " · LLDP"
  5499. } else {
  5500. port.Detail = "LLDP"
  5501. }
  5502. return port
  5503. }
  5504. infraMac := ""
  5505. for _, mac := range all {
  5506. if le, ok := d.leaseMap[mac]; ok && le.Hostname != "" {
  5507. infraMac = mac
  5508. break
  5509. }
  5510. }
  5511. if infraMac == "" {
  5512. // Sin hostname DHCP: primer alias manual como pista (#291).
  5513. for _, mac := range all {
  5514. if d.aliasByMac[mac] != "" {
  5515. infraMac = mac
  5516. break
  5517. }
  5518. }
  5519. }
  5520. if infraMac != "" {
  5521. if lease, ok := d.leaseMap[infraMac]; ok && lease.Hostname != "" {
  5522. port.ConnectedTo = lease.Hostname
  5523. port.DeviceMac = infraMac
  5524. if lease.IP != "" {
  5525. port.Detail = lease.IP
  5526. }
  5527. } else if alias := d.aliasByMac[infraMac]; alias != "" {
  5528. port.ConnectedTo = alias
  5529. port.DeviceMac = infraMac
  5530. }
  5531. } else {
  5532. // Switch/bridge tonto inferido: sin lease ni alias que lo
  5533. // nombre. El cliente traduce la etiqueta (#1039/#1040).
  5534. port.PeerKind = PeerKindInferredSwitch
  5535. }
  5536. return port
  5537. }
  5538. return port
  5539. }