live.go 226 KB

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