live.go 218 KB

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