| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628 |
- // live.go — Adapter live (port de src/adapters/index.js, SPEC §7.2-§7.8):
- // compone el snapshot por router con degradación elegante (router caído →
- // offline + alerta tras 2 fallos seguidos; el resto sigue), single-flight en
- // GetOverview (los SSH son lo caro), persistencia de atribución en
- // device_attrib (solo wireless) y alertas en memoria (máx 100).
- package adapters
- import (
- "context"
- "database/sql"
- "encoding/json"
- "errors"
- "fmt"
- "log"
- "maps"
- "math"
- "runtime/debug"
- "sort"
- "strconv"
- "strings"
- "sync"
- "time"
- "github.com/gnacho/netpulse/agent/macaddr"
- "github.com/gnacho/netpulse/agent/probe"
- "github.com/gnacho/netpulse/server-go/internal/alerts"
- "github.com/gnacho/netpulse/server-go/internal/config"
- "github.com/gnacho/netpulse/server-go/internal/db"
- "github.com/gnacho/netpulse/server-go/internal/deviceevents"
- "github.com/gnacho/netpulse/server-go/internal/oui"
- "github.com/gnacho/netpulse/server-go/internal/portseries"
- "github.com/gnacho/netpulse/server-go/internal/roamevents"
- )
- // uptimeLabel: "—" cuando ninguna fuente declaró uptime (#55). Un pusher que
- // no recoge la sección system.sysinfo dejaba uptimeSec en 0 y la tarjeta
- // pintaba "0d 0h", que se lee como un uptime real de cero.
- func uptimeLabel(p *routerPolled) string {
- if p == nil || !p.hasUptime {
- return "—"
- }
- return fmtUptime(p.uptimeSec)
- }
- // fmtUptime: "<d>d <h>h" (index.js:32-36).
- func fmtUptime(sec float64) string {
- d := int(sec) / 86400
- h := (int(sec) % 86400) / 3600
- return fmt.Sprintf("%dd %dh", d, h)
- }
- // bptr: puntero a bool (el view-model usa *bool para distinguir "ausente" de
- // "false" explícito, p.ej. Router.LldpAvailable).
- func bptr(v bool) *bool { return &v }
- // mbps: bps → Mbps 1 decimal (null → 0).
- func mbps(bps *float64) float64 {
- if bps == nil {
- return 0
- }
- return math.Round(*bps/1e6*10) / 10
- }
- // pickGateway: is_gateway → glinet → primero.
- func pickGateway(routers []RouterConfig) *RouterConfig {
- for i := range routers {
- if routers[i].IsGateway {
- return &routers[i]
- }
- }
- for i := range routers {
- if routers[i].Type == "glinet" {
- return &routers[i]
- }
- }
- if len(routers) > 0 {
- return &routers[0]
- }
- return nil
- }
- // pickGatewayCfg: same logic as pickGateway but from polled router configs.
- func pickGatewayCfg(polled map[string]*routerPolled) *RouterConfig {
- ids := make([]string, 0, len(polled))
- for id := range polled {
- ids = append(ids, id)
- }
- sort.Strings(ids)
- for _, id := range ids {
- if polled[id].cfg.IsGateway {
- return &polled[id].cfg
- }
- }
- for _, id := range ids {
- if polled[id].cfg.Type == "glinet" {
- return &polled[id].cfg
- }
- }
- if len(ids) > 0 {
- return &polled[ids[0]].cfg
- }
- return nil
- }
- // routerPolled es el sondeo de un tick de un router.
- type routerPolled struct {
- cfg RouterConfig
- client *OpenWrtClient
- sysInfo *SysInfo
- board *BoardInfo
- cpu int
- ram int
- temp int
- // #1256: SNMP rellena sysDescr (nombre/modelo completo del switch) y,
- // en MikroTik SwOS, la temperatura del chasis (hasTemp). hasTemp
- // distingue "no aplica" de "0 °C" para no pisar el null de #441.
- hasTemp bool
- // hasCpu: mismo contrato que hasTemp para la CPU de los switches SNMP
- // (tabla de procesos Netgear FastPath): sin bandera, el null de #441
- // pisaría la lectura real.
- hasCpu bool
- // hasRam: mismo contrato para la RAM. Solo una fuente que declara memoria
- // (Mem.Total>0 en el payload del agente/pusher) la pone; un SNMP sin
- // lectura de memoria sigue sirviendo nil.
- hasRam bool
- sysDescr string
- // sysName (#1256): hostname que el usuario define en el equipo; para
- // SNMP alimenta el Name visible de la unidad en flota.
- sysName string
- // snmpFirmware/snmpModelShort (#1767): identity read from ENTITY-MIB.
- // Empty when the unit has no table, so the sysDescr fallback stays.
- snmpFirmware string
- snmpModelShort string
- // snmpSoC: chip declarado por la MIB privada del fabricante (#1802). No
- // tiene equivalente genérico en SNMP; nil board = sin chip hasta ahora.
- snmpSoC string
- flash string
- firmwareAvailable string
- uptimeSec float64
- // hasUptime: alguna fuente declaró el uptime. Sin este flag, un payload sin
- // system.sysinfo (un pusher que no lo recoge) deja uptimeSec en 0 y la
- // tarjeta pinta "0d 0h", que es un dato falso, no "sin dato" (#55).
- hasUptime bool
- net *NetDevBps
- leases []DhcpLease
- // reservations: the `config host` entries of /etc/config/dhcp. They name
- // clients that never take a lease because their address is fixed on the
- // device itself.
- reservations []DhcpReservation
- // glClients (GL.iNet): base de clientes del firmware, superset de las
- // leases. Se usa SOLO para resolver IPs de dispositivos ya conocidos que
- // salen sin IP (dnsmasq sin lease), nunca para crear dispositivos nuevos.
- glClients []DhcpLease
- // arp: MAC→IP de /proc/net/arp (#377). Último recurso de resolución de
- // IP cuando ni el lease ni gl-clients la tienen (DHCP en otro equipo).
- arp map[string]string
- // arpDevs: MAC→interfaz de la tabla ARP (#1485). Permite distinguir el
- // ARP aprendido en el puerto WAN (primer salto del enlace) del de la LAN.
- arpDevs map[string]string
- // selfMacs: MACs de identidad del propio equipo aprendidas en sus puertos
- // internos/CPU (#1489). No son clientes y se absorben aunque las vea otro
- // miembro de la flota.
- selfMacs []string
- // arpStale: the subset of `arp` the kernel remembers without having
- // confirmed (STALE/FAILED/INCOMPLETE). Good enough to resolve an IP,
- // never enough to claim the host is connected -- an entry outlives the
- // device by minutes. Empty when the source could not report states.
- arpStale map[string]bool
- wireless map[string]WirelessClient
- ports []EthPort
- radios []Radio
- fdb map[string]string
- // fdbVlans: MAC → VLAN con la que el bridge aprendió esa MAC (#1757). El
- // PVID de un puerto dice por dónde entra una trama sin etiquetar, no en
- // qué VLAN vive el cliente: solo este dato lo dice. Vacío = sin dato (el
- // bridge no tiene VLAN filtering, o la sonda es por SSH y no lo reporta).
- fdbVlans map[string]int
- // networks: redes logicas declaradas en UCI (#1889).
- networks []probe.UciNetwork
- // wifiNet: ifname inalambrico -> red UCI (#1942). Mismo anti-parpadeo
- // que networks: se conserva la ultima lectura buena.
- wifiNet map[string]string
- // wirelessSide: MACs que el bridge del router aprende en sus propios
- // puertos de radio (wl0.1, wlan0…) pero que la tabla de estaciones no
- // lista (MACs rotadas que siguen emitiendo, backhaul 4-address). El
- // agente las etiqueta con la banda de la radio; aquí mandan sobre el
- // fallback del FDB del gateway, que si no las dibuja como cableadas.
- wirelessSide map[string]string
- brMac string
- latencyMs *float64
- lossPct *float64
- // backhaul: "cable"|"wifi"|"" (desconocido → se omite en el contrato).
- backhaul string
- // lldp: vecinos LLDP del tier lento (nil = sin lldpd o sonda fallida).
- lldp []LldpNeighbor
- // lldpUnavailable: lldpd no está instalado en este router (issue #247) →
- // el view-model expone `lldpAvailable:false` para el hint de instalación.
- lldpUnavailable bool
- // lldpHint: aviso de config subóptima reportado por el agente (#1369,
- // p. ej. probe.HintLldpdBridgeOnly). Se recicla con la cache igual que
- // los vecinos; vacío = sin aviso.
- lldpHint string
- // clientBw (#551): contadores nlbwmon por MAC del último payload del
- // agente. nil = nlbwmon no instalado o sonda no disponible (→ la fuente
- // de tráfico por cliente cae a hostapd bytes de wireless).
- clientBw *probe.ClientBwData
- // luci: etiquetas de puertos/VLANs de LuCI (issue #258), si el router las
- // define en /etc/config/luci. Fuente de nombres para la topología.
- luci *probe.LuCILabels
- // wanInfo: estado de la conexión WAN (solo gateway, issue #276). Los APs
- // dejan el struct vacío (sin datos WAN).
- wanInfo probe.WanInfo
- // vlans: VLANs del bridge (issue #315, bridge vlan show). nil = sin
- // datos (router sin bridge vlan filtering o sonda fallida).
- vlans []VlanPort
- // multiWan: the router's several internet connections and which one is
- // carrying traffic, as its own panel manages them. nil = never
- // reported (no such panel, or an older agent); an empty uplink list =
- // reported, and there is nothing to show.
- multiWan *MultiWanInfo
- // discovery: mDNS services + randomized MACs (#338). nil = sin datos
- // (umdns no instalado o sonda fallida).
- discovery *probe.DiscoveryData
- // dawnDetected: el agente reportó una sección DAWN en el payload. Se
- // usa para mostrar el aviso de deprecación (#426).
- dawnDetected bool
- // polledAt (issue #414): epoch ms en que se realizó el sondeo real. Se
- // usa para deduplicar filas de métricas cuando SNMP se cachea.
- polledAt int64
- // agentKind (#441): kind del agente cuyo payload construyó este sondeo
- // ("" = sondeo SSH/SNMP directo). "external" = pusher beacon/scraper sin
- // sección system → sin vitals.
- agentKind string
- // agentStale: agent-only unit whose pusher is past the down-confirm
- // window. The cached payload is still served (#850) but the card reads
- // offline, not online, so it agrees with the probe table.
- agentStale bool
- // selfExpose (#832): el equipo se expone él mismo a Home Assistant por
- // MQTT (NetGrip con su MQTT activado) → el publisher de flota no publica
- // sus entidades por router.
- selfExpose bool
- }
- // extrasSnapshot es la caché anti-parpadeo por router.
- type extrasSnapshot struct {
- ports []EthPort
- radios []Radio
- wireless map[string]WirelessClient
- fdb map[string]string
- // fdbVlans: MAC → VLAN del FDB (#1757). Mismo anti-parpadeo que fdb: solo
- // nace del payload del agente y una sonda SSH exitosa lo limpia.
- fdbVlans map[string]int
- // networks: última lista buena de redes UCI (#1889).
- networks []probe.UciNetwork
- // wifiNet: último mapa ifname -> red UCI bueno (#1942).
- wifiNet map[string]string
- // wirelessSide: último hint bueno de MACs detrás de radios propias
- // (ver routerPolled.wirelessSide). Mismo anti-parpadeo que fdb.
- wirelessSide map[string]string
- luci *probe.LuCILabels
- vlans []VlanPort
- // multiWan: last good multi-WAN section. The event-driven pushes carry
- // no such section, and without keeping it the panel would blink out of
- // the page every time a device associates. Unlike wanInfo, which is a
- // live address and must never be recycled, this is structural.
- multiWan *MultiWanInfo
- // system (#441): última sección system BUENA del payload del agente.
- // Los pushes event-driven (wireless-only) van sin ella; sin este cache
- // las vitales del router parpadeaban a 0 entre pushes completos.
- system *probe.SystemData
- // systemKind: el agent kind (probe.Payload.Kind) que escribió system. El
- // cache se clave solo por ID, y una fuente sin sección system no debe
- // heredar las vitales que confirmó otra fuente del mismo router.
- systemKind string
- // lldp (#489): última sección lldp del payload. Mismo anti-parpadeo:
- // los pushes event-driven van sin ella y la topología no debe perder
- // los switches managed entre pushes completos.
- lldp *probe.LldpData
- // clientBw (#551): última sección clientbw del payload del agente.
- // Los pushes event-driven van sin ella; conservar la última buena evita
- // que la fuente nlbwmon parpadee entre pushes completos.
- clientBw *probe.ClientBwData
- }
- // backhaulCacheTTL: el medio del uplink cambia muy raro; no se sondea cada 5 s.
- const backhaulCacheTTL = 5 * time.Minute
- // backhaulCacheEntry: resultado cacheado de la detección de uplink wifi
- // (value "" = desconocido/sonda fallida → el campo se omite).
- type backhaulCacheEntry struct {
- value string
- at time.Time
- }
- // lldpCacheTTL: tier lento LLDP (45 s, como los extras cacheados).
- const lldpCacheTTL = 45 * time.Second
- // lldpCacheEntry: vecinos LLDP cacheados por router (nil = sin datos).
- // unavailable=true cuando lldpd NO está instalado en el router (ErrLldpUnavailable);
- // la UI lo usa para el hint "instala lldpd" (issue #247).
- type lldpCacheEntry struct {
- neighbors []LldpNeighbor
- unavailable bool
- at time.Time
- }
- // wanInfoCacheTTL: tier lento del estado WAN del gateway. La conexión WAN no
- // cambia cada tick; un sondeo cada 60 s sobra y evita martillear ubus.
- const wanInfoCacheTTL = 60 * time.Second
- // wanInfoCacheEntry: WanInfo cacheado del gateway (issue #276).
- type wanInfoCacheEntry struct {
- info probe.WanInfo
- at time.Time
- }
- // Live es el Snapshotter del modo live.
- type Live struct {
- cfg *config.Config
- db *db.DB
- pool *SSHPool
- mu sync.Mutex
- surveyMu sync.Mutex
- surveyRaw map[string]surveyEntry
- routers []RouterConfig
- gatewayCfg *RouterConfig
- clients map[string]*OpenWrtClient
- // #1818: MAC nuevas que aun no han demostrado permanencia (60 s).
- transientMu sync.Mutex
- transient map[string]transientSeen
- lastGood map[string]*Router
- lastStatus map[string]string
- boardCache map[string]*BoardInfo
- layoutCache map[string][]PortLayout
- extrasCache map[string]*extrasSnapshot
- // lastAgentIf: /proc/net/dev por iface del ÚLTIMO payload del agente
- // (contadores absolutos + ts) para calcular los rates por boca con el
- // delta entre payloads (issue #305). Protegido por mu.
- lastAgentIf map[string]*agentIfSample
- // lastClientBw (#551): contadores absolutos por (router, mac) de la
- // última muestra observada, para calcular el delta por cliente entre
- // polls. Mapa: routerID → mac → estado. Protegido por mu.
- lastClientBw map[string]map[string]*clientBwCounter
- // lastObsTs: ts del último payload del agente que alimentó las series
- // por puerto y el PortMonitor (issue #365). Protegido por mu.
- lastObsTs map[string]int64
- // snmpPorts (issue #309): contadores del último poll SNMP por router y
- // puerto. Se usa para calcular rxBps/txBps entre polls sucesivos.
- snmpPorts map[string]map[string]snmpPortSample
- // snmpLastPoll (issue #414): timestamp del último poll SNMP real por router.
- snmpLastPoll map[string]time.Time
- // snmpSurface (#1726): última superficie leída por SNMP (velocidad de
- // boca, errores y LLDP) de las unidades que además van por pusher, para
- // no sondear SNMP en cada push. Protegido por mu.
- snmpSurface map[string]snmpSurfaceEntry
- // fwAlert (#1411): estado de la alerta de firmware por unidad con target
- // configurado: qué relación se alertó y contra qué versiones. Con eso la
- // alerta es un episodio por unidad (se abre una vez, se actualiza solo si
- // cambia la versión o el target, y se resuelve al coincidir). Protegido
- // por mu.
- fwAlert map[string]fwAlertState
- // #1444: lista cacheada de releases publicados de OpenWrt (la publica el
- // ReleasesRefresher tras cada chequeo periódico) y episodios abiertos del
- // aviso "target no disponible upstream" (routerID → target alertado).
- fwReleases []string
- fwReleasesTs int64
- fwUnknownTarget map[string]string
- // snmpFdbCount (#928): último conteo de entradas FDB por router SNMP,
- // para loguear solo cuando el resultado cambia.
- snmpFdbCount map[string]int
- // snmpHr (#1725): si el agente de cada router publica HOST-RESOURCES y
- // cuándo se preguntó. Se cachea porque hay agentes que descartan el árbol
- // sin responder, y eso cuesta 10 s por operación.
- snmpHr map[string]snmpHrEntry
- // snmpBrMac (#1036): última MAC base del bridge leída por SNMP por
- // router. Cache para no perderla cuando el equipo no contesta el OID
- // en un poll (la MAC alimenta el matching por MAC de la topología).
- snmpBrMac map[string]string
- // snmpPollStats (#930): contadores de éxito/fallo del poll SNMP por
- // router (ok, fail, consecFail, timestamps, último error). Protegido
- // por mu; en memoria (no persiste entre reinicios).
- snmpPollStats map[string]*snmpPollStat
- // ping (issue #930): probe ICMP inyectable para el ping de respaldo del
- // sondeo SNMP. nil/nulo en tests sin mock; el default real es pingHost.
- ping func(host string) bool
- // snmpLastMetricsTick (issue #414): polledAt del último tick que se persistió
- // en la tabla metrics, para evitar filas duplicadas cuando se reutiliza el
- // snapshot cacheado de un router SNMP.
- snmpLastMetricsTick map[string]int64
- lastPolled map[string]*routerPolled
- failCount map[string]int
- lastErr map[string]error // último error del sondeo (issue #257: distinguir sin-acceso de caído)
- // offlineOpen (issue #846): routers con un incidente de offline ABIERTO
- // (alerta emitida y aún no recuperados). Mientras esté abierto no se
- // re-emite la alerta aunque el estado flapee: un incidente = una alerta.
- // recoverStreak: éxitos seguidos del router con el incidente abierto; la
- // recuperación hay que estabilizarla (offlineRecoverTicks) para que un
- // flap breve no cierre el incidente.
- offlineOpen map[string]bool
- recoverStreak map[string]int
- engine *alerts.Engine
- wgActive map[string]bool
- wgActiveSince map[string]time.Time // when each active peer became active (disconnect duration)
- // wgPrimed (#1443): la primera pasada tras el arranque NO emite connects
- // (warmup: los peers activos al boot no son "conexiones"). Antes el
- // warmup se deducía de len(wgActive)>0, que además tragaba la primera
- // conexión real cuando el ciclo previo no tenía ningún peer activo
- // (túnel iniciado por la unidad local tras estar caído).
- wgPrimed bool
- // wgUrgent (#1441): claves de peer (WGPeer.Key) marcadas como urgentes:
- // sus caídas avisan (Urgent=true en la alerta), las del resto solo van al
- // log. Persistido en kv (wgUrgentKey).
- wgUrgent map[string]bool
- // wgUrgentMiss (#1445): ausencias consecutivas del peer en el dump por
- // clave urgente; a wgUrgentPruneMisses seguidas se recoge el flag.
- wgUrgentMiss map[string]int
- // weakStates (#1452): estado del ciclo de vida de la alerta de señal
- // débil por MAC (antes sólo se guardaba el último disparo). La máquina
- // pura vive en alerts.WeakSignalStep.
- weakStates map[string]alerts.WeakSignalState
- onlineMacs map[string]bool
- // unknownGrace: ticks consecutivos online+sin nombre (Name == MAC) por
- // MAC. unknownAlerted: MACs que ya dispararon la alerta de desconocido
- // (issue #248, persistido en kv: cada MAC alerta UNA sola vez).
- unknownGrace map[string]int
- unknownAlerted map[string]bool
- unknownGraceNum int // ticks antes de declarar desconocido (default 3, #234)
- // unverifiedSince: primera vez (unix ms) que una MAC sin ninguna prueba
- // de host se ve en una tabla de reenvío. unverifiedNoted: MACs que ya
- // dejaron su nota informativa (#1873, persistida en kv). unverifiedAfterMs
- // es el umbral en tiempo real (0 = default), no en ticks: la cadencia de
- // sondeo cambia con el kind de la unidad y con la configuración.
- unverifiedSince map[string]int64
- unverifiedNoted map[string]bool
- unverifiedAfterMs int64
- // #2111: un cliente asociado por WiFi que no tiene IP es un cliente real
- // (la asociación lo prueba) pero sin dirección. wifiNoIPSince/Noted
- // acumulan su persistencia y dejan UNA nota informativa por MAC, sin
- // contador urgente. wifiNoIPAfterMs es el umbral en tiempo real (0 =
- // default), igual que el de #1873.
- wifiNoIPSince map[string]int64
- wifiNoIPNoted map[string]bool
- wifiNoIPAfterMs int64
- // rdns: reverse DNS fallback for devices nothing else named (rdns.go).
- rdns *rdnsCache
- // impostorActive (#1358): BSSID impostor → alertID emitida. Solo en
- // memoria a propósito: si el server reinicia y el impostor sigue
- // visible, la alerta se re-emite (seguridad prima sobre re-aviso).
- impostorActive map[string]string
- // impostorAllow (#1400): BSSIDs aprobados a mano como propios (APs
- // conocidos fuera de la flota: UniFi, Omada...). Persistido en kv
- // (impostorAllowKey) para sobrevivir reinicios.
- impostorAllow map[string]bool
- // impostorEnabled (#1400): interruptor global de la regla de impostores
- // (default true; persistido en kv impostorEnabledKey).
- impostorEnabled bool
- // Presencia wireless (issue #184): devicePresence = MAC → online del
- // último ciclo evaluado; presenceMisses = ticks seguidos sin verse.
- // presenceSeen evita la avalancha del primer ciclo (anti-arranque).
- presenceSeen bool
- devicePresence map[string]bool
- presenceMisses map[string]int
- presenceOfflineAfter int // ticks sin verse antes de declarar offline (default 3)
- // presencePruneAfter: ticks sin verse que eliminan la MAC de los mapas
- // (dispositivo que se fue para siempre; ~2h a 5s/tick, issue #206).
- presencePruneAfter int
- // offlineAlert (#1354): seguimiento opt-in de desconexión de dispositivos
- // marcados (notify_offline). offlineOnline marca qué MACs se vieron online
- // alguna vez (línea base del arranque); offlineMisses cuenta ticks offline
- // seguidos antes de confirmar; offlineAlerted evita re-emitir mientras el
- // incidente sigue abierto.
- offlineOnline map[string]bool
- offlineMisses map[string]int
- offlineAlerted map[string]bool
- offlineAlertNum int // ticks offline seguidos antes de emitir (default 3)
- // usteerAvailable: cache de "¿hay usteer en algún router?" para el flag del
- // overview (entrada /roaming). Refrescado asíncronamente (TTL 30s, 1 SSH
- // al gateway) por usteerAvailableCached para no bloquear buildOverview.
- usteerAvailable bool
- usteerCheckedAt time.Time
- usteerChecking bool
- seenOnlineMacs bool
- wanDown map[string]int
- // uplinkWatch: which internet connection each router was last seen
- // using, per router id, plus a candidate not yet believed. Memory
- // only: after a restart the first poll records in silence rather than
- // announcing a change that happened while nobody was looking.
- uplinkWatch map[string]*uplinkWatch
- backhaulCache map[string]backhaulCacheEntry
- lldpCache map[string]lldpCacheEntry
- wanInfoCache map[string]wanInfoCacheEntry
- // roams derivados (#1740): último salto emitido por MAC, para no rebotar
- // A→B→A cuando buildDevices corre con una foto cacheada del poll
- // (attributedDevices) y la atribución guardada es más nueva. Mutex
- // propio: la derivación ocurre fuera de mu.
- roamMu sync.Mutex
- lastRoam map[string]roamMark
- // Agentes nativos (Tier 2): último payload por slug + flag de caída
- // (degradado a SSH tras emitir la alerta, SPEC-AGENTE-PILOTO §1).
- agents *AgentRegistry
- agentDown map[string]bool
- agentDownConfirm time.Duration // Dead Man's Switch: confirmar caída tras este periodo sin alertar
- // agentLatest (issue #400): fuente de la versión de referencia por kind
- // del agente ("" = check desactivado); agentOutdatedAlerted evita
- // re-emitir la recuperación ok más de una vez.
- agentLatest func(kind string) string
- agentOutdatedAlerted map[string]bool
- // #910: último "version|ref" reportado por router para la alerta de
- // desactualizado. EmitOrUpdate notifica en CADA actualización en sitio,
- // así que sin este guard cada push (30 s) reenviaba el push y refrescaba
- // el timestamp: solo se emite cuando el dato realmente cambia.
- agentOutdatedKey map[string]string
- // routerMacs: id → bridge MAC persistida en DB. Permite emparejar un agente
- // con su router aunque el slug elegido por el usuario no coincida con el id
- // autogenerado del router (#282).
- routerMacs map[string]string
- // sshAuthFailAlerted evita repetir la alerta de "SSH sin clave pero agente
- // vivo" (#281). Se limpia cuando el acceso SSH se recupera.
- sshAuthFailAlerted map[string]bool
- // portMon (issue #303/#307/#308): monitor de estado de puertos para
- // detección de flapping, ghost port y link degradado.
- portMon *PortMonitor
- // suppression (issue #332): grafo de dependencias topológicas para
- // suprimir alertas hijas cuando un router padre está offline.
- suppression *alerts.SuppressionGraph
- // now: reloj inyectable para tests deterministas (nil → time.Now).
- // Mismo patrón que AgentRegistry.SetClock.
- now func() time.Time
- agStd *AdGuardClient
- agGL *AdGuardGlinetClient
- agKey string
- // PVE (#561/#764): clientes por instancia Proxmox + caché del
- // inventario. Los clientes se reconstruyen si cambia la lista de
- // instancias (pveKey); el inventario se refresca con TTL.
- pveClients []pveInstClient
- pveKey string
- pveInv *pveInventory
- pveInvAt time.Time
- // fdbMemo (#656): última boca REAL donde el FDB vio cada MAC (epoch ms).
- // Los dispositivos callados (AV: TV, receptor, shield…) caducan su entrada
- // FDB a los ~5 min sin hablar y "saltaban" del switch inferido al anchor
- // del gateway entre ticks. La memo se usa SOLO como overlay de inferTopology
- // (nunca para crear presencia/online) mientras la entrada sea fresca.
- fdbMemo map[string]fdbPortMemo
- // uplinkPorts (#694): clasificación PERSISTENTE de puertos de subida por
- // router (routerID → puertos que ALGUNA VEZ aprendieron una brMac de otro
- // router). Sobrevive a los ticks donde la brMac del AP no está en el FDB
- // del gateway y a los sondeos fallidos, de modo que el puerto gateway→AP
- // siga tratándose como uplink y no como boca local (evita que el gateway
- // pise la memo de un satélite y que el cliente salte al principal).
- uplinkPorts map[string]map[string]bool
- sfMu sync.Mutex
- sfCall *sfCall
- }
- type sfCall struct {
- done chan struct{}
- ov *Overview
- err error
- }
- // NewLive crea el adapter live (db puede ser nil en tests).
- func NewLive(cfg *config.Config, d *db.DB, initial []RouterConfig, pool *SSHPool) *Live {
- l := &Live{
- cfg: cfg,
- db: d,
- pool: pool,
- now: time.Now,
- lastGood: map[string]*Router{},
- lastStatus: map[string]string{},
- fwAlert: map[string]fwAlertState{},
- fwUnknownTarget: map[string]string{},
- boardCache: map[string]*BoardInfo{},
- layoutCache: map[string][]PortLayout{},
- extrasCache: map[string]*extrasSnapshot{},
- lastAgentIf: map[string]*agentIfSample{},
- lastClientBw: map[string]map[string]*clientBwCounter{},
- lastObsTs: map[string]int64{},
- snmpPorts: map[string]map[string]snmpPortSample{},
- snmpLastPoll: map[string]time.Time{},
- snmpSurface: map[string]snmpSurfaceEntry{},
- snmpFdbCount: map[string]int{},
- snmpBrMac: map[string]string{},
- snmpHr: map[string]snmpHrEntry{},
- snmpPollStats: map[string]*snmpPollStat{},
- ping: pingHost,
- snmpLastMetricsTick: map[string]int64{},
- lastPolled: map[string]*routerPolled{},
- failCount: map[string]int{},
- lastErr: map[string]error{},
- offlineOpen: map[string]bool{},
- recoverStreak: map[string]int{},
- engine: alerts.New(d, nil),
- wgActive: map[string]bool{},
- wgActiveSince: map[string]time.Time{},
- wgUrgent: map[string]bool{},
- wgUrgentMiss: map[string]int{},
- weakStates: map[string]alerts.WeakSignalState{},
- onlineMacs: map[string]bool{},
- unknownGrace: map[string]int{},
- unknownAlerted: map[string]bool{},
- unknownGraceNum: 3, // default de #234; el engine/demo puede afinarlo
- unverifiedSince: map[string]int64{},
- unverifiedNoted: map[string]bool{},
- wifiNoIPSince: map[string]int64{},
- wifiNoIPNoted: map[string]bool{},
- impostorActive: map[string]string{},
- impostorAllow: map[string]bool{},
- impostorEnabled: true,
- devicePresence: map[string]bool{},
- presenceMisses: map[string]int{},
- presenceOfflineAfter: 3,
- presencePruneAfter: 2000,
- offlineOnline: map[string]bool{},
- offlineMisses: map[string]int{},
- offlineAlerted: map[string]bool{},
- offlineAlertNum: 3,
- wanDown: map[string]int{},
- uplinkWatch: map[string]*uplinkWatch{},
- backhaulCache: map[string]backhaulCacheEntry{},
- lldpCache: map[string]lldpCacheEntry{},
- wanInfoCache: map[string]wanInfoCacheEntry{},
- agentDown: map[string]bool{},
- agentDownConfirm: 3 * time.Minute, // Dead Man's Switch (P6): 3 min por defecto
- agentOutdatedAlerted: map[string]bool{},
- agentOutdatedKey: map[string]string{},
- routerMacs: map[string]string{},
- sshAuthFailAlerted: map[string]bool{},
- fdbMemo: map[string]fdbPortMemo{},
- uplinkPorts: map[string]map[string]bool{},
- portMon: NewPortMonitor(cfg != nil && cfg.GhostPortEnabled),
- suppression: alerts.NewSuppressionGraph(),
- }
- l.loadRouterMacs()
- l.engine.SetSuppression(l.suppression)
- // Migración una vez (attrib_v2): tabla limpia (index.js:385-394)
- if d != nil {
- var flag string
- if err := d.QueryRow("SELECT value FROM kv WHERE key = 'attrib_v2'").Scan(&flag); err == sql.ErrNoRows {
- _, _ = d.Exec("DELETE FROM device_attrib")
- _, _ = d.Exec("INSERT INTO kv (key, value) VALUES ('attrib_v2', '1')")
- log.Printf("[netpulse] device_attrib cleared (attrib_v2: only wireless persists)")
- }
- // issue #248: memoria per-MAC de "desconocido ya alertado", persistida
- // en kv para que un reinicio del servidor no vuelva a alertar las
- // MACs ya conocidas (clave `unknown_alerted:<mac>`).
- if rows, err := d.Query("SELECT key FROM kv WHERE key LIKE 'unknown_alerted:%'"); err == nil {
- for rows.Next() {
- var key string
- if rows.Scan(&key) == nil {
- l.unknownAlerted[strings.TrimPrefix(key, "unknown_alerted:")] = true
- }
- }
- rows.Close()
- }
- // #1873: MACs que ya dejaron su nota de baja prioridad, para no
- // repetirla tras un reinicio (clave `unverified_mac_noted:<mac>`).
- if rows, err := d.Query("SELECT key FROM kv WHERE key LIKE 'wifi_noip_noted:%'"); err == nil {
- for rows.Next() {
- var key string
- if rows.Scan(&key) == nil {
- l.wifiNoIPNoted[strings.TrimPrefix(key, "wifi_noip_noted:")] = true
- }
- }
- rows.Close()
- }
- if rows, err := d.Query("SELECT key FROM kv WHERE key LIKE 'unverified_mac_noted:%'"); err == nil {
- for rows.Next() {
- var key string
- if rows.Scan(&key) == nil {
- l.unverifiedNoted[strings.TrimPrefix(key, "unverified_mac_noted:")] = true
- }
- }
- rows.Close()
- }
- // #1400: BSSIDs de impostor aprobados a mano, persistidos en kv.
- var allowRaw string
- if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "impostor_allowlist_v1").Scan(&allowRaw); err == nil {
- var list []string
- if json.Unmarshal([]byte(allowRaw), &list) == nil {
- for _, b := range list {
- l.impostorAllow[strings.ToUpper(strings.TrimSpace(b))] = true
- }
- }
- }
- // #1400: interruptor global de la regla (ausente = activada).
- var enRaw string
- if err := d.QueryRow("SELECT value FROM kv WHERE key = ?", "alerts.impostor_enabled").Scan(&enRaw); err == nil {
- l.impostorEnabled = enRaw != "0"
- }
- }
- // #1441: peers marcados como urgentes (persistidos en kv).
- l.loadWGUrgent()
- l.SetRouters(initial)
- // Only a real, non-demo server resolves names: NewLive(nil, ...) in tests
- // and the demo dataset stay off the network.
- if cfg != nil && !cfg.DemoMode {
- l.rdns = newRDNSCache()
- }
- return l
- }
- // loadRouterMacs carga las MACs persistidas de routers para poder emparejar
- // agentes con routers por bridge MAC (#282).
- func (l *Live) loadRouterMacs() {
- if l.db == nil {
- return
- }
- l.routerMacs = map[string]string{}
- rows, err := l.db.Query("SELECT id, mac FROM routers WHERE mac IS NOT NULL AND mac != ''")
- if err != nil {
- return
- }
- defer rows.Close()
- for rows.Next() {
- var id, mac string
- if rows.Scan(&id, &mac) == nil {
- l.routerMacs[id] = mac
- }
- }
- }
- // Mode: "live".
- func (l *Live) Mode() string { return "live" }
- // El rack comprueba FleetFdbProvider en tiempo de ejecución: si la firma
- // diverge, los hints de flota desaparecen sin error (pasó con #1190).
- var _ FleetFdbProvider = (*Live)(nil)
- // FleetFdbUplinks (rack canvas): enlaces derivados del FDB de la unidad
- // designada como central para el auto-cableado (#1186/#1190). Cada MAC bridge
- // de flota que la central aprende en un puerto es un cable central(puerto) ↔
- // unidad(puerto donde la unidad aprende a la central), incluido el propio
- // gateway. infraMAC sustituye a la MAC bridge de la central si el sondeo no
- // la tiene. Central vacía o sin sondeo → vacío: el auto-cableado no inventa
- // nada.
- func (l *Live) FleetFdbUplinks(infraID, infraMAC string) map[string]FdbUplink {
- l.mu.Lock()
- polled := cloneLastPolled(l.lastPolled)
- l.mu.Unlock()
- out := map[string]FdbUplink{}
- infra := polled[infraID]
- if infraID == "" || infra == nil {
- return out
- }
- ownerOf := map[string]string{} // MAC bridge (mayúsculas) → unidad
- for id, p := range polled {
- if p != nil && p.brMac != "" {
- ownerOf[strings.ToUpper(p.brMac)] = id
- }
- }
- infraBr := infra.brMac
- if infraBr == "" {
- infraBr = infraMAC
- }
- for mac, port := range infra.fdb {
- owner, ok := ownerOf[strings.ToUpper(mac)]
- if !ok || owner == infraID {
- continue
- }
- childPort := ""
- if child := polled[owner]; child != nil && infraBr != "" {
- childPort, _ = fdbPortOf(child.fdb, infraBr)
- }
- out[owner] = FdbUplink{ChildID: owner, ParentID: infraID, Port: port, ChildPort: childPort}
- }
- return out
- }
- // Tick: no-op (el sondeo real ocurre en GetOverview, como el JS).
- func cloneLastPolled(src map[string]*routerPolled) map[string]*routerPolled {
- if src == nil {
- return nil
- }
- dst := make(map[string]*routerPolled, len(src))
- for id, p := range src {
- dst[id] = p
- }
- return dst
- }
- func (l *Live) Tick(context.Context) error { return nil }
- // Close cierra el pool SSH.
- func (l *Live) Close() error {
- l.pool.Close()
- return nil
- }
- // SetRouters actualiza la lista en caliente y limpia cachés de bajas.
- func (l *Live) SetRouters(list []RouterConfig) {
- l.mu.Lock()
- defer l.mu.Unlock()
- l.routers = append([]RouterConfig(nil), list...)
- l.gatewayCfg = pickGateway(l.routers)
- l.clients = map[string]*OpenWrtClient{}
- for _, c := range l.routers {
- if !c.AgentOnly {
- l.clients[c.ID] = NewOpenWrtClient(c, l.pool, "root", "")
- }
- }
- ids := map[string]bool{}
- for _, r := range l.routers {
- ids[r.ID] = true
- }
- for id := range l.lastGood {
- if !ids[id] {
- delete(l.lastGood, id)
- }
- }
- for id := range l.lastStatus {
- if !ids[id] {
- delete(l.lastStatus, id)
- }
- }
- for id := range l.boardCache {
- if !ids[id] {
- delete(l.boardCache, id)
- }
- }
- for id := range l.layoutCache {
- if !ids[id] {
- delete(l.layoutCache, id)
- }
- }
- for id := range l.extrasCache {
- if !ids[id] {
- delete(l.extrasCache, id)
- }
- }
- for id := range l.lastAgentIf {
- if !ids[id] {
- delete(l.lastAgentIf, id)
- }
- }
- for id := range l.lastClientBw {
- if !ids[id] {
- delete(l.lastClientBw, id)
- }
- }
- for id := range l.snmpPorts {
- if !ids[id] {
- delete(l.snmpPorts, id)
- }
- }
- for id := range l.snmpLastPoll {
- if !ids[id] {
- delete(l.snmpLastPoll, id)
- }
- }
- for id := range l.snmpBrMac {
- if !ids[id] {
- delete(l.snmpBrMac, id)
- }
- }
- for id := range l.snmpLastMetricsTick {
- if !ids[id] {
- delete(l.snmpLastMetricsTick, id)
- }
- }
- for id := range l.snmpPollStats {
- if !ids[id] {
- delete(l.snmpPollStats, id)
- }
- }
- for id := range l.lastPolled {
- if !ids[id] {
- delete(l.lastPolled, id)
- }
- }
- for id := range l.failCount {
- if !ids[id] {
- delete(l.failCount, id)
- }
- }
- for id := range l.lastErr {
- if !ids[id] {
- delete(l.lastErr, id)
- }
- }
- // unknownGrace es per-MAC (no por router): se poda por ausencia en
- // trackUnknownDevices; aquí solo se limpia la lista completa si no queda
- // ningún router (config vacía tras un reset).
- if len(l.routers) == 0 {
- l.unknownGrace = map[string]int{}
- }
- for id := range l.backhaulCache {
- if !ids[id] {
- delete(l.backhaulCache, id)
- }
- }
- for id := range l.lldpCache {
- if !ids[id] {
- delete(l.lldpCache, id)
- }
- }
- for id := range l.wanInfoCache {
- if !ids[id] {
- delete(l.wanInfoCache, id)
- }
- }
- for id := range l.sshAuthFailAlerted {
- if !ids[id] {
- delete(l.sshAuthFailAlerted, id)
- }
- }
- l.loadRouterMacs()
- }
- // probeBackhaul detecta el medio del uplink (interfaz STA asociada → "wifi";
- // si no → "cable") con caché de 5 min: no se sondea cada tick. Error (router
- // sin wifi, ubus caído) → "" cacheado igualmente (el campo se omite y el
- // sondeo no se rompe).
- func (l *Live) probeBackhaul(routerID string, client *OpenWrtClient) string {
- l.mu.Lock()
- e, ok := l.backhaulCache[routerID]
- l.mu.Unlock()
- if ok && time.Since(e.at) < backhaulCacheTTL {
- return e.value
- }
- value := ""
- if wifi, err := client.GetWirelessUplink(); err == nil {
- value = "cable"
- if wifi {
- value = "wifi"
- }
- }
- l.mu.Lock()
- l.backhaulCache[routerID] = backhaulCacheEntry{value: value, at: time.Now()}
- l.mu.Unlock()
- return value
- }
- // probeWanInfo: estado de la conexión WAN del gateway (issue #276) con caché
- // de 60 s. En routers sin interfaz wan (APs) devuelve WanInfo vacío. Fallo de
- // ubus → vacío cacheado (el detalle sigue mostrando lo demás, sin romper).
- func (l *Live) probeWanInfo(routerID string, client *OpenWrtClient) probe.WanInfo {
- l.mu.Lock()
- e, ok := l.wanInfoCache[routerID]
- l.mu.Unlock()
- if ok && time.Since(e.at) < wanInfoCacheTTL {
- return e.info
- }
- info := client.GetWanInfo()
- l.mu.Lock()
- l.wanInfoCache[routerID] = wanInfoCacheEntry{info: info, at: time.Now()}
- l.mu.Unlock()
- return info
- }
- // probeLldp: vecinos LLDP del router con caché de 45 s (tier lento, como los
- // extras anti-parpadeo). Error o lldpd ausente → nil (sin datos; el FDB solo
- // sigue mandando, comportamiento actual intacto). Devuelve además si lldpd
- // NO está instalado (ErrLldpUnavailable) para que el view-model lo exponga
- // (issue #247): hint "instala lldpd" en la UI.
- func (l *Live) probeLldp(ctx context.Context, routerID string, client *OpenWrtClient) ([]LldpNeighbor, bool) {
- l.mu.Lock()
- e, ok := l.lldpCache[routerID]
- l.mu.Unlock()
- if ok && time.Since(e.at) < lldpCacheTTL {
- return e.neighbors, e.unavailable
- }
- neighbors, err := client.LldpNeighbors(ctx)
- unavailable := false
- if err != nil {
- if errors.Is(err, ErrLldpUnavailable) {
- unavailable = true
- } else {
- log.Printf("[netpulse] LLDP %s: %v", routerID, err)
- }
- neighbors = nil
- }
- l.mu.Lock()
- l.lldpCache[routerID] = lldpCacheEntry{neighbors: neighbors, unavailable: unavailable, at: time.Now()}
- l.mu.Unlock()
- return neighbors, unavailable
- }
- // getAdguardClient: kv (GL.iNet o estándar remoto) con fallback a .env (AGH estándar).
- func (l *Live) getAdguardClient() (std *AdGuardClient, gl *AdGuardGlinetClient) {
- l.mu.Lock()
- defer l.mu.Unlock()
- key := ""
- if l.db != nil {
- mode := "glinet"
- _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_mode'").Scan(&mode)
- var host string
- if err := l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_host'").Scan(&host); err == nil && host != "" {
- user := "root"
- _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_user'").Scan(&user)
- pass := ""
- _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_pass'").Scan(&pass)
- if pass != "" {
- if mode == "standard" {
- port := 3000
- var portStr string
- _ = l.db.QueryRow("SELECT value FROM kv WHERE key='adguard_port'").Scan(&portStr)
- if p, err := strconv.Atoi(portStr); err == nil && p > 0 {
- port = p
- }
- url := fmt.Sprintf("http://%s:%d", host, port)
- key = "std|" + url + "|" + user
- if l.agKey != key {
- l.agStd = NewAdGuardClient(url, user, pass)
- l.agGL = nil
- }
- } else {
- key = "gl|" + host + "|" + user
- if l.agKey != key {
- l.agGL = NewAdGuardGlinetClient(host, user, pass, l.pool)
- l.agStd = nil
- }
- }
- }
- }
- }
- if key == "" && l.cfg.Adguard != nil && l.cfg.Adguard.Pass != "" {
- key = "std|" + l.cfg.Adguard.URL
- if l.agKey != key {
- l.agStd = NewAdGuardClient(l.cfg.Adguard.URL, l.cfg.Adguard.User, l.cfg.Adguard.Pass)
- l.agGL = nil
- }
- }
- if key == "" {
- l.agStd = nil
- l.agGL = nil
- l.agKey = ""
- return nil, nil
- }
- if l.agKey != key {
- l.agKey = key
- if strings.HasPrefix(key, "gl|") {
- l.agStd = nil
- } else {
- l.agGL = nil
- }
- }
- return l.agStd, l.agGL
- }
- // vitalInt descarta un CERO no confirmado (#1947): sin hasTemp/hasCpu/hasRam
- // el 0 es "sin sensor", no una lectura. Un valor distinto de cero se mantiene
- // para no romper fuentes que no marcan el flag.
- func vitalInt(ok bool, v int) *int {
- if !ok && v == 0 {
- return nil
- }
- return &v
- }
- // vitalFloat es la variante para metrics: el cero sin confirmar no se
- // persiste, que era lo que dejaba la grafica de temperatura plana en 0.
- func vitalFloat(ok bool, v int) *float64 {
- if !ok && v == 0 {
- return nil
- }
- f := float64(v)
- return &f
- }
- // histPoint es un punto de metricsHistory {t, down, up, cpu, ram, temp}.
- type histPoint struct {
- t string
- down, up float64
- cpu, ram, temp int
- }
- // metricsHistory consulta las métricas históricas (index.js:122-147).
- // metricsHistoryBuckets lee el histórico largo desde la escalera de retención
- // (metrics_buckets, 5 min → 1 año). Usado para el rango 30d, cuyo raw ya se
- // purgó (7 días). Agrega los buckets de 5 min a ventanas de `bucket` ms para
- // limitar los puntos devueltos (~120 en 30d con ventanas de 6 h).
- func (l *Live) metricsHistoryBuckets(routerID string, span, bucket int64, fmtLabel func(time.Time) string) []histPoint {
- if l.db == nil || routerID == "" {
- return []histPoint{}
- }
- now := time.Now().UnixMilli()
- rows, err := l.db.Query(
- `SELECT (bucket_ts / ?) AS win, MAX(rx_max) AS rx, MAX(tx_max) AS tx,
- AVG(cpu_avg) AS cpu, AVG(ram_avg) AS ram, AVG(temp_avg) AS temp,
- MIN(bucket_ts) AS t0
- FROM metrics_buckets WHERE router_id = ? AND bucket_ts >= ?
- GROUP BY win ORDER BY win`,
- bucket, routerID, now-span)
- if err != nil {
- return []histPoint{}
- }
- defer rows.Close()
- out := []histPoint{}
- for rows.Next() {
- var b, t0 int64
- var rx, tx, cpu, ram, temp sql.NullFloat64
- if err := rows.Scan(&b, &rx, &tx, &cpu, &ram, &temp, &t0); err != nil {
- continue
- }
- hp := histPoint{t: fmtLabel(time.UnixMilli(t0).Local())}
- if rx.Valid {
- hp.down = math.Round(rx.Float64/1e6*10) / 10
- }
- if tx.Valid {
- hp.up = math.Round(tx.Float64/1e6*10) / 10
- }
- if cpu.Valid {
- hp.cpu = int(math.Round(cpu.Float64))
- }
- if ram.Valid {
- hp.ram = int(math.Round(ram.Float64))
- }
- if temp.Valid {
- hp.temp = int(math.Round(temp.Float64))
- }
- out = append(out, hp)
- }
- return out
- }
- func (l *Live) metricsHistory(routerID, rang string) []histPoint {
- if l.db == nil || routerID == "" {
- return []histPoint{}
- }
- now := time.Now().UnixMilli()
- var span, bucket int64
- var fmtLabel func(time.Time) string
- switch rang {
- case "1h":
- span, bucket = 3600e3, 180e3
- fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d:%02d", d.Hour(), d.Minute()) }
- case "24h":
- // #2046: 15 min en vez de una hora. 96 puntos siguen siendo legibles
- // en el gráfico y dan la forma real del día (antes se perdían los
- // picos entre horas).
- span, bucket = 86400e3, 900e3
- fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d:%02d", d.Hour(), d.Minute()) }
- case "7d":
- // #2046: 6 h en vez de un día, 28 puntos. La etiqueta lleva el día y
- // la hora porque con cuatro puntos por día solo el día no distingue.
- // #2062: el día de la semana dependía del idioma (weekdayES lo
- // pintaba en español también en una UI en inglés). El día del mes es
- // neutro y coincide con el formato del rango 30d.
- span, bucket = 7*86400e3, 6*3600e3
- fmtLabel = func(d time.Time) string { return fmt.Sprintf("%02d %02dh", d.Day(), d.Hour()) }
- case "30d":
- span, bucket = 30*86400e3, 6*3600e3
- fmtLabel = func(d time.Time) string { return fmt.Sprintf("%d", d.Day()) }
- default:
- return []histPoint{}
- }
- // Rango 30d: los raw se purgan a los 7 días, así que se lee de la escalera
- // de retención (metrics_buckets). El resto de rangos usa la tabla raw
- // (suficiente y más fino).
- if rang == "30d" {
- return l.metricsHistoryBuckets(routerID, span, bucket, fmtLabel)
- }
- rows, err := l.db.Query(
- `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
- FROM metrics WHERE router_id = ? AND ts >= ? GROUP BY bucket ORDER BY bucket`,
- bucket, routerID, now-span)
- if err != nil {
- return []histPoint{}
- }
- defer rows.Close()
- out := []histPoint{}
- for rows.Next() {
- var b, t0 int64
- var rx, tx, cpu, ram, temp sql.NullFloat64
- if err := rows.Scan(&b, &rx, &tx, &cpu, &ram, &temp, &t0); err != nil {
- continue
- }
- hp := histPoint{t: fmtLabel(time.UnixMilli(t0).Local())}
- if rx.Valid {
- hp.down = math.Round(rx.Float64/1e6*10) / 10
- }
- if tx.Valid {
- hp.up = math.Round(tx.Float64/1e6*10) / 10
- }
- if cpu.Valid {
- hp.cpu = int(math.Round(cpu.Float64))
- }
- if ram.Valid {
- hp.ram = int(math.Round(ram.Float64))
- }
- if temp.Valid {
- hp.temp = int(math.Round(temp.Float64))
- }
- out = append(out, hp)
- }
- return out
- }
- // wanDayStats rellena los campos del resumen WAN que solo el modo demo
- // calculaba (issue #169): pico de hoy (Mbps + hora), media de bajada y total
- // de 24 h, todo desde la tabla raw de métricas del gateway. La hora del pico
- // usa el ts de la fila del máximo; el total estima bytes como
- // SUM(rx_bps) × Δt (Δt = 86400/N s entre muestras, luego /8 bits→bytes).
- // Sin BD, sin gateway o sin datos devuelve los valores cero/"—" de partida.
- type wanDayStatsResult struct {
- peakMbps float64
- peakTime string
- avgMbps float64
- totalBytes float64
- }
- func (l *Live) wanDayStats(gwID string) wanDayStatsResult {
- out := wanDayStatsResult{peakTime: "—"}
- if l.db == nil || gwID == "" {
- return out
- }
- now := time.Now()
- if l.now != nil {
- now = l.now()
- }
- startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).UnixMilli()
- start24h := now.Add(-24 * time.Hour).UnixMilli()
- // Pico de hoy: fila con MAX(rx_bps) y su ts (la hora del pico).
- row := l.db.QueryRow(
- `SELECT rx_bps, ts FROM metrics WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL
- ORDER BY rx_bps DESC LIMIT 1`, gwID, startOfDay)
- var peakBps float64
- var peakTs int64
- if err := row.Scan(&peakBps, &peakTs); err == nil {
- out.peakMbps = math.Round(peakBps/1e6*10) / 10
- out.peakTime = time.UnixMilli(peakTs).Local().Format("15:04")
- }
- // Media 24h + total: AVG(rx_bps) y bytes estimados con el Δt medio.
- row = l.db.QueryRow(
- `SELECT AVG(rx_bps), SUM(rx_bps), COUNT(rx_bps) FROM metrics
- WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL`, gwID, start24h)
- var avg, sum sql.NullFloat64
- var n sql.NullInt64
- if err := row.Scan(&avg, &sum, &n); err == nil && avg.Valid && sum.Valid && n.Valid && n.Int64 > 0 {
- out.avgMbps = math.Round(avg.Float64/1e6*10) / 10
- dt := float64(86400) / float64(n.Int64) // s entre muestras
- out.totalBytes = sum.Float64 * dt / 8
- }
- return out
- }
- // wanRangeSpans son los rangos que sirve la gráfica de tráfico. La clave es la
- // misma que usa el contrato de las series ("1h", "24h", "7d", "30d").
- var wanRangeSpans = []struct {
- key string
- span time.Duration
- }{
- {"1h", time.Hour},
- {"24h", 24 * time.Hour},
- {"7d", 7 * 24 * time.Hour},
- {"30d", 30 * 24 * time.Hour},
- }
- // wanRawRetention: los samples crudos de metrics se purgan a los 7 días, así
- // que por encima de eso el resumen sale de metrics_buckets.
- const wanRawRetention = 7 * 24 * time.Hour
- // wanRangeStats resume el tráfico de bajada del gateway en cada rango (#2047).
- // Sale de las muestras, no de los puntos del gráfico: los puntos ya vienen
- // agregados (MAX por bucket) y promediarlos daría la media de los picos.
- func (l *Live) wanRangeStats(gwID string) map[string]WANRangeStat {
- if l.db == nil || gwID == "" {
- return nil
- }
- now := time.Now()
- if l.now != nil {
- now = l.now()
- }
- out := make(map[string]WANRangeStat, len(wanRangeSpans))
- for _, r := range wanRangeSpans {
- if st, ok := l.wanRangeStat(gwID, now.Add(-r.span), r.span); ok {
- out[r.key] = st
- }
- }
- if len(out) == 0 {
- return nil
- }
- return out
- }
- func (l *Live) wanRangeStat(gwID string, from time.Time, span time.Duration) (WANRangeStat, bool) {
- if span > wanRawRetention {
- // Largo plazo: cada bucket de 5 min guarda la media del tramo, así que
- // el volumen es SUM(rx_avg) × 300 s entre 8 bits por byte.
- row := l.db.QueryRow(
- `SELECT MAX(rx_max), SUM(rx_avg), SUM(rx_avg * n), SUM(n)
- FROM metrics_buckets
- WHERE router_id = ? AND bucket_ts >= ? AND rx_avg IS NOT NULL`,
- gwID, from.UnixMilli())
- var peak, sumAvg, sumAvgN sql.NullFloat64
- var n sql.NullFloat64
- if err := row.Scan(&peak, &sumAvg, &sumAvgN, &n); err != nil || !n.Valid || n.Float64 <= 0 {
- return WANRangeStat{}, false
- }
- st := WANRangeStat{Samples: int64(n.Float64)}
- if peak.Valid {
- st.PeakMbps = math.Round(peak.Float64/1e6*10) / 10
- }
- if sumAvgN.Valid {
- st.AvgMbps = math.Round(sumAvgN.Float64/n.Float64/1e6*10) / 10
- }
- if sumAvg.Valid {
- st.TotalBytes = sumAvg.Float64 * (float64(db.BucketMS) / 1000) / 8
- }
- return st, true
- }
- // Corto plazo: muestras crudas. El intervalo real entre muestras sale de
- // los timestamps, no de suponer que cubren el rango entero (un router
- // instalado hace una hora no ha transferido 24 h de tráfico).
- row := l.db.QueryRow(
- `SELECT MAX(rx_bps), AVG(rx_bps), SUM(rx_bps), COUNT(rx_bps), MIN(ts), MAX(ts)
- FROM metrics
- WHERE router_id = ? AND ts >= ? AND rx_bps IS NOT NULL`,
- gwID, from.UnixMilli())
- var peak, avg, sum sql.NullFloat64
- var n, minTs, maxTs sql.NullInt64
- if err := row.Scan(&peak, &avg, &sum, &n, &minTs, &maxTs); err != nil || !n.Valid || n.Int64 == 0 {
- return WANRangeStat{}, false
- }
- st := WANRangeStat{Samples: n.Int64}
- if peak.Valid {
- st.PeakMbps = math.Round(peak.Float64/1e6*10) / 10
- }
- if avg.Valid {
- st.AvgMbps = math.Round(avg.Float64/1e6*10) / 10
- }
- if sum.Valid && minTs.Valid && maxTs.Valid && n.Int64 > 1 {
- dt := float64(maxTs.Int64-minTs.Int64) / 1000 / float64(n.Int64-1)
- if dt > 0 {
- st.TotalBytes = sum.Float64 * dt / 8
- }
- }
- return st, true
- }
- // pollRouter sondea un router; error si está inalcanzable. Si el router tiene
- // agente nativo con payload fresco (Tier 2), el sondeo viene del último push
- // y NO se toca SSH; si el agente expiró, se degrada a Tier 0 (SSH) con aviso.
- func (l *Live) pollRouter(ctx context.Context, cfg RouterConfig) (*routerPolled, error) {
- if fresh, p := l.pollRouterAgent(cfg); fresh {
- // Estado WAN del gateway (issue #276). Los agentes nuevos lo traen en
- // el payload; para los viejos queda la sonda SSH (cache de 60 s), que
- // no existe si el router es agent_only.
- l.mu.Lock()
- gw := l.gatewayCfg
- client := l.clients[cfg.ID]
- l.mu.Unlock()
- hasWan := p.wanInfo.Proto != "" || p.wanInfo.IP != "" || p.wanInfo.Gateway != ""
- if gw != nil && cfg.ID == gw.ID && client != nil && !hasWan {
- p.wanInfo = l.probeWanInfo(cfg.ID, client)
- }
- // #1726: si la unidad también tiene SNMP configurado, completar con
- // SNMP lo que el payload no puede dar (velocidad de boca, errores,
- // LLDP). Sin esto el ajuste era un no-op silencioso.
- l.mergeSNMPSurface(cfg, p)
- return p, nil
- }
- if cfg.SnmpEnabled {
- return l.pollRouterSNMP(cfg)
- }
- l.mu.Lock()
- client := l.clients[cfg.ID]
- gw := l.gatewayCfg
- layout, hasLayout := l.layoutCache[cfg.ID]
- board, hasBoard := l.boardCache[cfg.ID]
- cached := l.extrasCache[cfg.ID]
- l.mu.Unlock()
- if client == nil {
- return nil, fmt.Errorf("router %s has no client", cfg.ID)
- }
- // Calienta la conexión SSH en serie (equivalente al `ssh true` del JS:
- // las llamadas de abajo multiplexan sobre la conexión ya establecida).
- if _, err := l.pool.Run(cfg.SSHAddr(), "true", 0); err != nil {
- return nil, err
- }
- // Layout de puertos (board.json): se lee una vez y se cachea
- if !hasLayout {
- if lay, err := client.GetPortLayout(); err == nil && len(lay) > 0 {
- layout = lay
- l.mu.Lock()
- l.layoutCache[cfg.ID] = lay
- l.mu.Unlock()
- }
- }
- // sysInfo es la única sonda obligatoria (sin catch en el JS)
- sysInfo, err := client.GetSysInfo()
- if err != nil {
- return nil, err
- }
- cpu, _ := client.GetCPUPercent()
- temp, _ := client.GetTempC()
- // NetDev: total agregado + rates POR IFACE (#305) en una sola lectura.
- netAgg, ifRates := client.GetNetDev()
- wanIface := l.probeWanInfo(cfg.ID, client)
- // #2048: el tráfico del router es el de su WAN, no la suma de todas las
- // bocas (que cuenta la bajada dos veces: entra por la WAN y sale por la
- // LAN). Sin WAN identificable se mantiene el agregado.
- net := pickRouterNet(netAgg, wanIface.Port, ifRates)
- leases := client.GetDhcpLeases()
- reservations := client.GetDhcpReservations()
- arp, arpStale, arpDevs := client.GetArp()
- // gl-clients (GL.iNet): complementa la resolución de IP donde dnsmasq no
- // tiene lease (issue #5 bug 1). En routers sin el objeto ubus sale vacío
- // — coste: una llamada ubus local por poll.
- glClients := client.GetGlClients()
- wireless := client.GetWirelessClients()
- ports := client.GetEthPorts(layout, ifRates, wanIface.Port)
- radios := client.GetRadios()
- fdb := client.GetBridgeFdb()
- brMac := client.GetBridgeMac()
- // Tier lento: backhaul (5 min) y vecinos LLDP (45 s), ambos cacheados y
- // tolerantes a error (router sin wifi/lldpd → campo ausente, sin romper).
- backhaul := l.probeBackhaul(cfg.ID, client)
- lldp, lldpUnavailable := l.probeLldp(ctx, cfg.ID, client)
- if !hasBoard {
- if b, err := client.GetBoard(); err == nil {
- board = b
- l.mu.Lock()
- l.boardCache[cfg.ID] = b
- l.mu.Unlock()
- }
- }
- // Anti-parpadeo: conserva la última lista buena en sondas puntuales
- // (null = sonda fallida; colección vacía = resultado real).
- if cached == nil {
- cached = &extrasSnapshot{ports: []EthPort{}, radios: []Radio{},
- wireless: map[string]WirelessClient{}, fdb: map[string]string{}}
- }
- portsGood := cached.ports
- if len(ports) > 0 {
- portsGood = ports
- }
- radiosGood := cached.radios
- if len(radios) > 0 {
- radiosGood = radios
- }
- wirelessGood := cached.wireless
- if wireless != nil {
- wirelessGood = wireless
- }
- fdbGood := cached.fdb
- if fdb != nil {
- fdbGood = fdb
- }
- // wirelessSide solo nace del payload del agente: en la vía SSH una sonda
- // FDB exitosa lo LIMPIA (nadie lo refresca por este camino y un hint
- // huérfano seguiría atribuyendo MACs rotadas como wireless para siempre);
- // una sonda fallida conserva el cache, mismo anti-parpadeo que fdbGood.
- wsGood := cached.wirelessSide
- if fdb != nil {
- wsGood = nil
- }
- // La VLAN del FDB viaja solo en el payload del agente: la sonda SSH no la
- // lee y una lectura buena sin ella LIMPIA el cache (un valor viejo pintaría
- // al cliente en un segmento que ya dejó).
- fdbVlansGood := cached.fdbVlans
- if fdb != nil {
- fdbVlansGood = nil
- }
- luciGood := cached.luci
- if luci := client.GetLuCILabels(); luci != nil {
- luciGood = luci
- }
- vlansGood := cached.vlans
- if vlans := client.GetBridgeVlans(); vlans != nil {
- vlansGood = vlans
- }
- // #1889: la misma configuracion UCI dice las redes logicas de la unidad.
- networksGood := cached.networks
- if nets := client.GetNetworks(); nets != nil {
- networksGood = nets
- }
- // #1942: la config wireless dice a que red pertenece cada iface AP, la
- // unica fuente que atribuye clientes WiFi sin adivinar por el puerto.
- wifiNetGood := cached.wifiNet
- if raw, err := client.pool.Run(client.Host, "uci show wireless", 0); err == nil {
- wifiNetGood = wifiNetworkMap(parseUciWireless(raw))
- }
- l.mu.Lock()
- l.extrasCache[cfg.ID] = &extrasSnapshot{ports: portsGood, radios: radiosGood, wireless: wirelessGood, fdb: fdbGood, fdbVlans: fdbVlansGood, luci: luciGood, vlans: vlansGood, networks: networksGood, wifiNet: wifiNetGood}
- l.mu.Unlock()
- // Uso de RAM: #513. Si el agente reporta memory.used (procesos) lo
- // usamos (lo que el usuario percibe como uso real); si no, la fórmula
- // clásica sin caché reclamable (Cached) o MemAvailable. Ver memUsagePct.
- mem := sysInfo.Memory
- ramPct := 0
- if mem.Total > 0 {
- ramPct = memUsagePct(mem.Total, mem.Free, mem.Buffered, mem.Cached, mem.Available, mem.Used)
- }
- isGw := gw != nil && cfg.ID == gw.ID
- var latencyMs, lossPct *float64
- if isGw {
- latencyMs, lossPct, _ = client.GetWanLatency("")
- } else if gw != nil {
- latencyMs, _ = client.GetGatewayLatency(gw.Host)
- }
- // Estado WAN solo en el gateway (issue #276), tier lento cacheado.
- var wanInfo probe.WanInfo
- if isGw {
- wanInfo = l.probeWanInfo(cfg.ID, client)
- }
- cpuV := 0
- if cpu != nil {
- cpuV = *cpu
- }
- tempV := 0
- if temp != nil {
- tempV = *temp
- }
- l.recordPortSamples(cfg.ID, portsGood)
- // #551: tráfico por cliente. La vía SSH no sondea nlbwmon (el router
- // gestionado por SSH raramente lo corre); la fuente resuelta es hostapd
- // bytes por estación cuando el driver los expone. Gate de frescura:
- // solo con la sonda wireless de ESTE poll (wireless != nil); si falló y
- // se recicla la cache, los contadores repetidos darían deltas 0.
- if wireless != nil {
- if samples, source, ok := resolveClientBwSources(wireless, nil); ok {
- l.recordClientBwSamples(cfg.ID, time.Now(), samples, source)
- }
- }
- l.portMon.Observe(cfg.ID, portsGood, l.engine)
- return &routerPolled{
- cfg: cfg, client: client, sysInfo: sysInfo, board: board,
- cpu: cpuV, ram: ramPct, temp: tempV,
- hasCpu: cpu != nil, hasRam: mem.Total > 0, hasTemp: temp != nil,
- uptimeSec: sysInfo.Uptime, net: net, leases: leases, reservations: reservations, arp: arp, arpStale: arpStale, arpDevs: arpDevs, glClients: glClients,
- wireless: wirelessGood, ports: portsGood, radios: radiosGood,
- fdb: withoutBatadvBla(fdbGood), fdbVlans: fdbVlansGood, wirelessSide: wsGood, brMac: brMac, latencyMs: latencyMs, lossPct: lossPct,
- backhaul: backhaul, lldp: lldp, lldpUnavailable: lldpUnavailable,
- luci: luciGood, wanInfo: wanInfo, vlans: vlansGood, networks: networksGood, wifiNet: wifiNetGood,
- polledAt: l.now().UnixMilli(),
- }, nil
- }
- // fwAlertState (#1411): episodio de alerta de firmware abierto para una
- // unidad. cmp es el resultado de firmwareCompare que se alertó; installed y
- // target recuerdan contra qué se abrió para detectar el cambio de episodio.
- type fwAlertState struct {
- cmp int
- installed string
- target string
- }
- // evalFirmwareAlert (#1411/#1412) abre, refresca o resuelve la alerta de
- // firmware de una unidad con target configurado. Un episodio por unidad: se
- // emite al detectarse el mismatch (ID estable alert-firmware-<id>), se
- // actualiza en sitio (EmitOrUpdate = episodio nuevo notificado) si cambia la
- // versión instalada o el target, y se resuelve (modelo #1349) al volver a
- // coincidir. Mientras el episodio sigue igual NO se re-emite: el feed no se
- // re-firea cada ciclo. El downgrade (target más viejo) alerta con wording
- // propio (#1412).
- func (l *Live) evalFirmwareAlert(routerID, name, installed, target string, cmp int) {
- id := "alert-firmware-" + routerID
- l.mu.Lock()
- if l.fwAlert == nil {
- l.fwAlert = map[string]fwAlertState{}
- }
- st, active := l.fwAlert[routerID]
- if cmp == fwMatch {
- delete(l.fwAlert, routerID)
- l.mu.Unlock()
- if active {
- l.engine.Resolve(id)
- }
- return
- }
- if active && st.cmp == cmp && st.installed == installed && st.target == target {
- // Episodio en curso sin cambios: nada que hacer (#1411).
- l.mu.Unlock()
- return
- }
- l.fwAlert[routerID] = fwAlertState{cmp: cmp, installed: installed, target: target}
- l.mu.Unlock()
- ev := AlertEvent{
- ID: id, Category: alerts.CatSystem, Urgent: false,
- Severity: "warn", RouterID: routerID,
- Vars: map[string]string{"router": name, "firmware": installed, "target": target},
- Time: "just now",
- }
- if cmp == fwOlder {
- ev.Title = "Firmware downgrade target"
- ev.Description = fmt.Sprintf("%s: configured target %q is older than the installed firmware %q", name, target, installed)
- ev.Type = alerts.HintFirmwareDowngrade
- ev.Hint = alerts.HintFor(alerts.HintFirmwareDowngrade)
- } else {
- ev.Title = "Firmware outdated"
- ev.Description = fmt.Sprintf("%s: firmware %q does not match the target %q", name, installed, target)
- ev.Type = alerts.HintFirmware
- ev.Hint = alerts.HintFor(alerts.HintFirmware)
- }
- l.engine.EmitOrUpdate(ev)
- }
- // SetFirmwareReleases (#1444) publica la lista cacheada de releases
- // publicados (la alimenta el ReleasesRefresher tras cada chequeo periódico).
- func (l *Live) SetFirmwareReleases(v []string, ts int64) {
- l.mu.Lock()
- defer l.mu.Unlock()
- l.fwReleases = append([]string(nil), v...)
- l.fwReleasesTs = ts
- }
- // firmwareTargetKnown (#1444): ¿figura el target entre los releases
- // publicados? Con la lista vacía (chequeo aún sin éxito) NO se gatea: se
- // conserva el comportamiento previo en flotas sin salida a
- // downloads.openwrt.org.
- func (l *Live) firmwareTargetKnown(target string) bool {
- l.mu.Lock()
- defer l.mu.Unlock()
- if len(l.fwReleases) == 0 {
- return true
- }
- for _, v := range l.fwReleases {
- if v == target {
- return true
- }
- }
- return false
- }
- // evalFirmwareUnknownTarget (#1444): episodio del aviso "el target no existe
- // upstream" (configuración, no firmware desactualizado). target == "" resuelve
- // el episodio (target corregido, retirado o vuelto conocido).
- func (l *Live) evalFirmwareUnknownTarget(routerID, name, target string) {
- id := "alert-fw-target-unknown-" + routerID
- l.mu.Lock()
- if l.fwUnknownTarget == nil {
- l.fwUnknownTarget = map[string]string{}
- }
- if target == "" {
- _, active := l.fwUnknownTarget[routerID]
- delete(l.fwUnknownTarget, routerID)
- l.mu.Unlock()
- if active {
- l.engine.Resolve(id)
- }
- return
- }
- if prev, active := l.fwUnknownTarget[routerID]; active && prev == target {
- l.mu.Unlock()
- return
- }
- l.fwUnknownTarget[routerID] = target
- l.mu.Unlock()
- l.engine.EmitOrUpdate(AlertEvent{
- ID: id, Category: alerts.CatSystem, Urgent: false,
- Severity: "warn", RouterID: routerID,
- Title: "Firmware target not available",
- Description: fmt.Sprintf("%s: configured target %q is not among the published OpenWrt releases", name, target),
- Type: alerts.HintFirmwareUnknownTarget,
- Vars: map[string]string{"router": name, "target": target},
- Time: "just now",
- })
- }
- // buildRouter construye el Router del contrato (index.js:221-249).
- // countBand acumula un cliente en la banda del desglose (issue #645). La
- // banda "—" (desconocida) no cae en ninguna: suma ≤ total de clientes.
- func countBand(split *demoBandSplit, band string) {
- switch {
- case strings.HasPrefix(band, "2.4"):
- split.Band24++
- case strings.HasPrefix(band, "5"):
- split.Band5++
- case strings.HasPrefix(band, "6"):
- split.Band6++
- case band == "cable":
- split.Cable++
- }
- }
- // allZeroF: ¿todos los valores del slice son 0 (o vacío)?
- func allZeroF(v []float64) bool {
- for _, x := range v {
- if x != 0 {
- return false
- }
- }
- return true
- }
- // vlanPortsWithNames joins the VLAN numbers from `bridge vlan show` with the
- // names LuCI keeps for them (uci show network, #258). The bridge output only
- // carries numbers and both arrive in the same poll, so the join is by id and
- // only where a label exists (#1757).
- func vlanPortsWithNames(ports []VlanPort, luci *probe.LuCILabels) []VlanPort {
- if luci == nil || len(luci.VlanLabels) == 0 {
- return ports
- }
- out := make([]VlanPort, len(ports))
- for i, vp := range ports {
- out[i] = vp
- out[i].Vlans = make([]VlanEntry, len(vp.Vlans))
- copy(out[i].Vlans, vp.Vlans)
- for j := range out[i].Vlans {
- if name := luci.VlanLabels[strconv.Itoa(out[i].Vlans[j].ID)]; name != "" {
- out[i].Vlans[j].Name = name
- }
- }
- }
- return out
- }
- // inventorySource (#1917) nombra la vía que produjo este sondeo. El sondeo
- // del agente llega con su Kind ya resuelto; el resto sale del cliente SSH o
- // del recolector SNMP, que es lo que distingue "ssh" de "snmp".
- func (p *routerPolled) inventorySource() string {
- switch p.agentKind {
- case "native", "netgrip":
- return "agent"
- case "":
- if p.cfg.SnmpEnabled {
- return "snmp"
- }
- return "ssh"
- default:
- return p.agentKind
- }
- }
- // displayRole (#1892): rol visible de una unidad a partir de la evidencia de
- // su payload. Una unidad external con agent_only se pintaba como Switch aunque
- // fuese un AP o un NAS, porque el badge leia el mismo flag que autoriza a
- // reclamar clientes con la FDB (#1417). Aqui solo se decide el texto:
- // - clientes inalambricos y sin WAN -> AP (un AP puente no enruta).
- // - managed-switch o SNMP -> Switch (un switch de flota se anuncia asi).
- // - pusher agent-only con 4 o mas bocas fisicas, sin radios y sin
- // interfaces que solo expone un host (docker0, sit0, bridges, VLAN) ->
- // Switch (crs305). Un NAS con Docker anuncia diez interfaces y no es un
- // chasis: los puertos no fisicos lo delatan (#1892).
- // - external sin nada de lo anterior -> External (un NAS no es un switch).
- // - el resto -> AP, que es el papel de las unidades OpenWrt de la flota.
- //
- // p == nil es una unidad sin sondeo (offline): decide la configuracion.
- func displayRole(p *routerPolled, cfg RouterConfig, isGw bool) (string, string) {
- if isGw {
- return "Gateway principal", "Principal"
- }
- if p == nil {
- if cfg.Type == "managed-switch" || cfg.SnmpEnabled {
- return "Switch", "SW"
- }
- if cfg.Type == "external" {
- return "External", "EXT"
- }
- return "Punto de acceso", "AP"
- }
- wireless := len(p.wireless) > 0 || len(p.wirelessSide) > 0 || len(p.radios) > 0
- wan := p.wanInfo.Proto != "" || p.wanInfo.IP != "" || p.wanInfo.Gateway != "" ||
- p.wanInfo.Port != "" || p.multiWan != nil
- if wireless && !wan {
- return "Punto de acceso", "AP"
- }
- if cfg.Type == "managed-switch" || cfg.SnmpEnabled {
- return "Switch", "SW"
- }
- if cfg.AgentOnly && !wireless && len(p.ports) >= 4 && !hostLikePorts(p.ports) {
- return "Switch", "SW"
- }
- if cfg.Type == "external" {
- return "External", "EXT"
- }
- return "Punto de acceso", "AP"
- }
- // hostLikePorts dice si el payload anuncia interfaces que solo expone un host:
- // puentes de Docker, tuneles, VLAN, LAG o WiFi. Un chasis anuncia sus bocas
- // ethernet y nada mas, asi que ver una de estas significa que la unidad es una
- // maquina con varias NICs, no un switch (#1892). Familia vacia o "ethernet" es
- // boca fisica.
- func hostLikePorts(ports []EthPort) bool {
- for _, port := range ports {
- switch port.Family {
- case "", "ethernet":
- default:
- return true
- }
- }
- return false
- }
- // overrideInfo es el override manual persistido por MAC (#437/#797).
- type overrideInfo struct {
- Icon string
- Name string
- DeviceType string
- BannedBands string
- NotifyOffline bool
- }
- // loadDeviceOverrides lee los overrides manuales, con clave en minúsculas
- // para que el lookup sea robusto al caso de la MAC (#797). Lo usan tanto
- // buildDevices (clientes vivos) como ghostDevices (retenidos offline):
- // un override debe verse igual esté el cliente online u offline.
- func (l *Live) loadDeviceOverrides() map[string]overrideInfo {
- out := map[string]overrideInfo{}
- if l.db == nil {
- return out
- }
- rows, err := l.db.Query("SELECT mac, icon, name, device_type, banned_bands, notify_offline FROM device_overrides")
- if err != nil {
- return out
- }
- defer rows.Close()
- for rows.Next() {
- var mac, name, deviceType, bannedBands string
- var icon sql.NullString
- var notifyOffline bool
- if err := rows.Scan(&mac, &icon, &name, &deviceType, &bannedBands, ¬ifyOffline); err == nil {
- out[strings.ToLower(mac)] = overrideInfo{Icon: icon.String, Name: name, DeviceType: deviceType, BannedBands: bannedBands, NotifyOffline: notifyOffline}
- }
- }
- return out
- }
- func (l *Live) buildRouter(p *routerPolled, history []histPoint) Router {
- l.mu.Lock()
- gw := l.gatewayCfg
- l.mu.Unlock()
- // issue #716: umbral de temperatura alta del router (default 65 °C).
- thr := p.cfg.TempThresholdValue()
- model := p.cfg.Name
- if model == "" {
- model = p.cfg.Host
- }
- if p.board != nil && p.board.Model != "" {
- model = p.board.Model
- }
- // #1256: los switches SNMP no tienen board (sondeo sin SSH); el
- // sysDescr declara el nombre/modelo completo del equipo.
- if p.cfg.SnmpEnabled && p.sysDescr != "" {
- model = p.sysDescr
- }
- name := p.cfg.Name
- if name == "" {
- name = p.cfg.Host
- }
- if p.board != nil && p.board.Hostname != "" {
- name = p.board.Hostname
- }
- // #1256: los switches SNMP no tienen board; el sysName (hostname que el
- // usuario define en el equipo, p. ej. la página de sistema de SwOS) es
- // el nombre natural de la unidad.
- if p.cfg.SnmpEnabled && p.sysName != "" {
- name = p.sysName
- }
- health := 100
- if p.cpu > 85 {
- health -= 20
- } else if p.cpu > 70 {
- health -= 10
- }
- if p.temp > 75 {
- health -= 25
- } else if p.temp > thr {
- health -= 12
- }
- if p.ram > 90 {
- health -= 15
- }
- // issue #241: firmware fuera del target configurado penaliza la salud.
- // #1412: la comparación es por versión de release parseada; un target más
- // viejo que lo instalado (downgrade) no se penaliza como "desactualizado".
- fwCmp := fwMatch
- if p.cfg.FirmwareTarget != "" && p.board != nil {
- fwCmp = firmwareCompare(p.board.Release.Description, p.cfg.FirmwareTarget)
- if fwCmp == fwNewer || fwCmp == fwAmbiguous {
- health -= 5
- }
- }
- if health < 0 {
- health = 0
- }
- isGw := gw != nil && p.cfg.ID == gw.ID
- status := "online"
- if p.temp > thr || p.cpu > 85 {
- status = "warn"
- }
- if p.agentStale {
- status = "offline"
- health = 0
- }
- sparkline := make([]float64, 0, len(history))
- for _, h := range history {
- sparkline = append(sparkline, h.down)
- }
- // #441: SNMP y pushers externos no siempre pueden reportar CPU/RAM/temp.
- // Se marca el router y las vitals van a null (la UI no pinta ceros falsos);
- // las lecturas que la fuente sí confirma (hasCpu/hasRam/hasTemp) se conservan.
- noVitals := p.cfg.SnmpEnabled || p.agentKind == "external"
- r := Router{
- ID: p.cfg.ID, Name: name, Model: model, ModelShort: model,
- IP: p.cfg.Host, Status: status, Health: health,
- CPU: vitalInt(p.hasCpu, p.cpu), RAM: vitalInt(p.hasRam, p.ram), Temp: vitalInt(p.hasTemp, p.temp),
- Uptime: uptimeLabel(p), Clients: len(p.leases),
- Sparkline: sparkline, TempThreshold: thr,
- LatencyMs: p.latencyMs,
- }
- if noVitals {
- r.CPU, r.RAM, r.Temp = nil, nil, nil
- v := resolvePartialVitals(p)
- r.CPU, r.RAM, r.Temp = v.cpu, v.ram, v.temp
- r.VitalsAvailable = bptr(v.available)
- }
- r.SnmpEnabled = p.cfg.SnmpEnabled
- // #1917: de dónde salió este inventario y de cuándo es. Se calcula aquí,
- // donde ya se conoce el agentKind, para no exponer ese detalle interno.
- r.InventorySource = p.inventorySource()
- // #1917: el modo configurado viaja con la tarjeta para que la UI no ofrezca
- // agente en una unidad que se inventaria por SSH.
- r.InventoryMode = p.cfg.InventoryMode
- r.InventoryAt = p.polledAt
- // #2086: la unidad agent-only stale lee offline con sus últimas lecturas.
- // El motivo: las integraciones pusher reciben su código pusher_* más
- // específico desde EnrichOverview; un agent nativo no tiene ninguno, así
- // que lleva agent_stale para que la tarjeta no quede roja sin explicación.
- if p.agentStale {
- r.StatusReason = "agent_stale"
- }
- // #1741: la serie de 24 h de una unidad sin throughput nativo (SNMP o
- // pusher external) sale de sus puertos. Se decide aquí, donde se conoce el
- // agent kind, porque Router no lo expone y VitalsAvailable ya no sirve de
- // proxy: un pusher que confirma CPU/temp la deja en true.
- r.sparklineFromPorts = p.cfg.SnmpEnabled || p.agentKind == "external"
- if p.selfExpose {
- r.SelfExpose = bptr(true)
- }
- // #1892: el badge sale de lo que la unidad demuestra, no de `cfgIsSwitch`,
- // que ademas gobierna los claims de la FDB (#1417) y por eso no se toca.
- r.Role, r.RoleBadge = displayRole(p, p.cfg, isGw)
- if p.brMac != "" {
- r.MAC = p.brMac
- }
- // #1757: bridge VLAN filtering por puerto. nil cuando la unidad no lo
- // reporta, para no publicar una lista vacía como si no hubiera VLANs.
- if len(p.vlans) > 0 {
- r.Vlans = vlanPortsWithNames(p.vlans, p.luci)
- }
- if p.backhaul != "" {
- r.Backhaul = p.backhaul
- }
- if uplink := l.uplinkLldp(p); uplink != nil {
- r.Lldp = uplink
- }
- if p.lldpUnavailable {
- r.LldpAvailable = bptr(false)
- }
- if p.lldpHint != "" {
- r.LldpHint = p.lldpHint
- }
- if p.board != nil {
- r.Firmware = p.board.Release.Description
- }
- // #1767: an SNMP switch has no board; ENTITY-MIB is its own declaration.
- if p.snmpFirmware != "" {
- r.Firmware = p.snmpFirmware
- }
- if p.snmpModelShort != "" {
- r.ModelShort = p.snmpModelShort
- }
- if p.cfg.FirmwareTarget != "" {
- r.FirmwareTarget = p.cfg.FirmwareTarget
- }
- if p.cfg.AgentOnly {
- r.AgentOnly = true
- }
- if p.cfg.Type != "" {
- r.Type = p.cfg.Type
- }
- if p.firmwareAvailable != "" && r.FirmwareTarget == "" {
- r.FirmwareTarget = p.firmwareAvailable
- }
- // #1411/#1412: con target configurado la alerta es UN episodio por unidad
- // (ID estable), no un re-fire por ciclo: se abre al detectar el mismatch,
- // se actualiza si cambia la versión o el target, y se resuelve al
- // coincidir. El downgrade (target más viejo) alerta con wording propio.
- if p.firmwareAvailable != "" {
- r.FirmwareOutdated = true
- l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
- // External pushers keep the per-cycle warning as before #1411; the
- // five-minute dedup bounds it.
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-firmware-%s-%d", p.cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatSystem, Urgent: false,
- Severity: "warn",
- Title: "Firmware outdated",
- Description: fmt.Sprintf("%s: firmware %q does not match the target %q", name, r.Firmware, p.cfg.FirmwareTarget),
- Hint: alerts.HintFor(alerts.HintFirmware),
- Type: alerts.HintFirmware,
- Vars: map[string]string{"router": name, "firmware": r.Firmware, "target": p.cfg.FirmwareTarget},
- Time: "just now", RouterID: p.cfg.ID,
- })
- } else if p.cfg.FirmwareTarget != "" {
- // #1444: el target existe upstream → alerta normal de mismatch.
- // Target desconocido upstream → aviso de configuración y SIN marca
- // de desactualizado (un target inventado no es firmware viejo).
- // Lista vacía (chequeo sin éxito aún) → comportamiento previo.
- l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
- if l.firmwareTargetKnown(p.cfg.FirmwareTarget) {
- if fwCmp == fwNewer || fwCmp == fwAmbiguous {
- r.FirmwareOutdated = true
- }
- if p.board != nil {
- l.evalFirmwareAlert(p.cfg.ID, name, r.Firmware, p.cfg.FirmwareTarget, fwCmp)
- }
- } else {
- l.evalFirmwareUnknownTarget(p.cfg.ID, name, p.cfg.FirmwareTarget)
- }
- } else {
- // Sin target configurado: el aviso de target desconocido queda resuelto.
- l.evalFirmwareUnknownTarget(p.cfg.ID, name, "")
- }
- if p.temp > thr {
- r.HotMetric = "temp"
- }
- return r
- }
- // uplinkLldp: vecino LLDP del router que es OTRO router conocido → el uplink
- // está identificado por LLDP y la app muestra el sufijo "· LLDP". El vecino se
- // casa por chassis-MAC = bridge MAC de otro router (matching original) o, si
- // el chassis-ID que anuncia lldpd difiere de la br-lan (habitual en OpenWrt,
- // issue #252), por su mgmt-IP o nombre del chasis. Si el FDB dice dónde se
- // aprendió esa MAC, el anuncio debe llegar por ese puerto (uplink); sin FDB,
- // la MAC ya es evidencia suficiente. nil si no hay dato.
- func (l *Live) uplinkLldp(p *routerPolled) *LldpInfo {
- if len(p.lldp) == 0 {
- return nil
- }
- l.mu.Lock()
- polled := cloneLastPolled(l.lastPolled)
- l.mu.Unlock()
- routers := routerIdentities(polled)
- for i := range p.lldp {
- nb := &p.lldp[i]
- if neighborIsRouter(nb, routers, p.cfg.ID) == nil {
- continue
- }
- if port, ok := p.fdb[nb.ChassisMac]; ok && port != nb.Port {
- continue
- }
- return nb.info()
- }
- return nil
- }
- // offlineRouter: último bueno marcado offline o placeholder (index.js:251-272).
- // pausedRouter (#1085): una unidad pausada no se sondea ni alerta. Se
- // muestra con la última snapshot conocida (o el esqueleto básico) y el
- // estado "paused", que la UI distingue con la insignia de pausada. Reutiliza
- // offlineRouter para el esqueleto y le pisa el estado: pausar no es estar
- // caído, y los flags de acceso/host key no aplican mientras no se sondea.
- func (l *Live) pausedRouter(cfg RouterConfig) Router {
- r := l.offlineRouter(cfg)
- r.Status = "paused"
- r.AccessMissing = false
- r.HostKeyChanged = false
- r.Disabled = true
- return r
- }
- // issue #257: si el último fallo fue de ACCESO (el router responde pero la
- // clave SSH no está autorizada), el estado es "unreachable" + accessMissing,
- // no un "offline" de apagado/inalcanzable (config issue, no power issue).
- func (l *Live) offlineRouter(cfg RouterConfig) Router {
- l.mu.Lock()
- prev := l.lastGood[cfg.ID]
- gw := l.gatewayCfg
- l.mu.Unlock()
- var r Router
- if prev != nil {
- r = *prev
- } else {
- model := "OpenWrt"
- switch cfg.Type {
- case "glinet":
- model = "GL.iNet"
- case "managed-switch":
- model = "Managed Switch"
- }
- name := cfg.Name
- if name == "" {
- name = cfg.Host
- }
- r = Router{
- ID: cfg.ID, Name: name, Model: model, ModelShort: model,
- IP: cfg.Host, Health: 0,
- CPU: iptr(0), RAM: iptr(0), Temp: iptr(0),
- Uptime: "—", Clients: 0, Sparkline: []float64{},
- Type: cfg.Type,
- }
- r.Role, r.RoleBadge = displayRole(nil, cfg, gw != nil && cfg.ID == gw.ID)
- }
- r.Type = cfg.Type
- r.Status = "offline"
- if l.accessMissing(cfg.ID) {
- r.Status = "unreachable"
- r.AccessMissing = true
- }
- if l.hostKeyChanged(cfg.ID) {
- r.Status = "unreachable"
- r.HostKeyChanged = true
- }
- return r
- }
- // accessMissing: el último fallo de sondeo de este router fue de ACCESO
- // (SSH responde pero la clave no está autorizada / ubus rechaza), es decir
- // el router está vivo pero el servidor no puede entrar (issue #257).
- func (l *Live) accessMissing(routerID string) bool {
- l.mu.Lock()
- defer l.mu.Unlock()
- return isAccessError(l.lastErr[routerID])
- }
- // hostKeyChanged: el último fallo de sondeo fue una clave SSH distinta a la
- // registrada (issue #603). El router está vivo; la conexión se rechaza hasta
- // que el admin confirme el re-onboard.
- func (l *Live) hostKeyChanged(routerID string) bool {
- l.mu.Lock()
- defer l.mu.Unlock()
- return isHostKeyError(l.lastErr[routerID])
- }
- // AcceptHostKey confirma el re-onboard de un router tras una host key cambiada
- // (#603): borra su entrada known_hosts (siguiente sondeo = TOFU) y resetea el
- // error para que el router deje de mostrarse como "host key changed".
- func (l *Live) AcceptHostKey(routerID string) error {
- if l.pool == nil {
- return errors.New("ssh pool not configured")
- }
- l.mu.Lock()
- var cfg *RouterConfig
- for i := range l.routers {
- if l.routers[i].ID == routerID {
- cfg = &l.routers[i]
- break
- }
- }
- l.mu.Unlock()
- if cfg == nil {
- return fmt.Errorf("router %q not configured", routerID)
- }
- // #1524: la entrada known_hosts se escribe con la forma de la dirección
- // que diala el pool ([host]:puerto en puertos no estándar, host pelado en
- // el 22). Se pasan ambas formas: la SSHAddr efectiva y el host pelado, por
- // si queda una entrada vieja de cuando el router no tenía puerto custom.
- if err := l.pool.RemoveHostKey(cfg.SSHAddr(), cfg.Host); err != nil {
- return err
- }
- l.mu.Lock()
- delete(l.lastErr, routerID)
- l.failCount[routerID] = 0
- l.mu.Unlock()
- return nil
- }
- // isAccessError: ¿el error indica que el router RESPONDE pero el acceso
- // SSH/ubus no está configurado? (handshake SSH que rechaza la clave del
- // servidor). Un fallo de conexión (refused/timeout/red) NO es un fallo de
- // acceso: ahí el router puede estar apagado o inalcanzable (issue #257).
- func isAccessError(err error) bool {
- if err == nil {
- return false
- }
- msg := strings.ToLower(err.Error())
- for _, hint := range []string{
- "unable to authenticate",
- "no supported methods",
- "permission denied",
- "authentication failed",
- "not authorized",
- } {
- if strings.Contains(msg, hint) {
- return true
- }
- }
- return false
- }
- // isHostKeyError: el router responde pero su host key no casa con la
- // registrada (issue #603). No es un fallo de acceso ni una caída: requiere
- // confirmación explícita de re-onboard.
- func isHostKeyError(err error) bool {
- if err == nil {
- return false
- }
- var hk *HostKeyChangedError
- return errors.As(err, &hk) || strings.Contains(strings.ToLower(err.Error()), "re-onboard required")
- }
- // pollAll sondea todos los routers en paralelo (Promise.allSettled).
- // issue #1085: las unidades pausadas (disabled) NO se sondean; se limpian
- // sus contadores de fallo y sus alertas de offline abiertas, y quedan con
- // estado "paused" en el overview (ver pausedRouter).
- func (l *Live) pollAll(ctx context.Context) map[string]*routerPolled {
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- l.mu.Unlock()
- active := make([]RouterConfig, 0, len(routers))
- for _, cfg := range routers {
- if cfg.Disabled {
- continue
- }
- active = append(active, cfg)
- }
- type result struct {
- cfg RouterConfig
- p *routerPolled
- err error
- }
- results := make([]result, len(active))
- var wg sync.WaitGroup
- for i, cfg := range active {
- wg.Add(1)
- go func(i int, cfg RouterConfig) {
- defer wg.Done()
- p, err := l.pollRouter(ctx, cfg)
- results[i] = result{cfg, p, err}
- }(i, cfg)
- }
- wg.Wait()
- polled := map[string]*routerPolled{}
- l.mu.Lock()
- defer l.mu.Unlock()
- // #1085: una unidad pausada no se sondea: sus fallos en curso se anulan
- // (al reanudar, el sondeo arranca limpio) y sus alertas de offline se
- // resuelven: pausar no es estar caído.
- for _, cfg := range routers {
- if !cfg.Disabled {
- continue
- }
- l.failCount[cfg.ID] = 0
- delete(l.lastErr, cfg.ID)
- delete(l.lastStatus, cfg.ID)
- l.resolveOfflineAlerts(cfg.ID)
- }
- for _, res := range results {
- if res.err == nil {
- polled[res.cfg.ID] = res.p
- l.failCount[res.cfg.ID] = 0
- delete(l.lastErr, res.cfg.ID)
- // Persiste la bridgeMAC del router (issue #196): la exclusión de
- // "dispositivo desconocido" no debe depender de que este router se
- // sondee bien en el tick actual.
- if l.db != nil && res.p.brMac != "" {
- _, _ = l.db.Exec("UPDATE routers SET mac = ? WHERE id = ?", res.p.brMac, res.cfg.ID)
- if res.p.brMac != "" {
- // #1334: la identidad MAC también se actualiza EN PROCESO;
- // el write a BD solo era útil tras un reinicio, y el
- // matching de agentes (MatchRouter) la consulta en vivo.
- l.routerMacs[res.cfg.ID] = res.p.brMac
- }
- }
- // Router recuperado (offline→online, SPEC-ALERTAS §1). issue #846:
- // con incidente abierto la recuperación debe estabilizarse antes
- // de cerrarlo (un flap breve no rearma ni cierra la alerta).
- if l.offlineOpen[res.cfg.ID] || l.lastStatus[res.cfg.ID] == "offline" {
- l.trackRouterRecovered(&res.cfg)
- }
- l.lastStatus[res.cfg.ID] = "online"
- // WAN/Internet caído: gateway OK pero ping a internet con 100 %
- // de pérdida en 2 sondeos seguidos (mismo debounce que offline).
- if l.gatewayCfg != nil && res.cfg.ID == l.gatewayCfg.ID {
- l.trackWanDown(&res.cfg, res.p)
- }
- // Any router can have two lines; this is not a gateway-only
- // arrangement.
- l.trackUplinkChange(res.cfg, res.p, time.Now())
- continue
- }
- fails := l.failCount[res.cfg.ID] + 1
- l.failCount[res.cfg.ID] = fails
- l.lastErr[res.cfg.ID] = res.err
- log.Printf("[netpulse] router %s inalcanzable (%d): %v", res.cfg.LogLabel(), fails, res.err)
- l.trackRouterOffline(&res.cfg, res.err, fails)
- if fails >= 2 {
- l.lastStatus[res.cfg.ID] = "offline"
- }
- }
- // Reconciliación de huérfanas (issue #846): cada ciclo, los routers que
- // responden SIN incidente abierto se limpian de alertas de offline de
- // procesos anteriores (offlineOpen vive en memoria y no sobrevive a un
- // reinicio; si el router responde, el que estuvo caído fue el servidor).
- // Corre en cada ciclo (no solo en el arranque) para ser auto-sanante
- // aunque el router falle justo en el primer ciclo tras arrancar. Los
- // routers caídos conservan la suya hasta que trackRouterOffline la
- // sustituye por la del incidente nuevo.
- l.reconcileOfflineOrphans(polled)
- l.lastPolled = polled
- return polled
- }
- // reconcileOfflineOrphans retira las alertas de offline huérfanas de los
- // routers que responden sin incidente abierto (issue #846). Debe llamarse
- // con l.mu tomado.
- func (l *Live) reconcileOfflineOrphans(polled map[string]*routerPolled) {
- for id := range polled {
- if !l.offlineOpen[id] {
- l.resolveOfflineAlerts(id)
- }
- }
- }
- // emitRouterRecovered: evento "router recuperado" (offline→online;
- // category router, urgent false, severity ok — SPEC-ALERTAS §1).
- // Debe llamarse con l.mu tomado (mismo contexto que el resto de emisiones).
- func (l *Live) emitRouterRecovered(routerID, name string) {
- if l.suppression != nil {
- l.suppression.MarkUp(routerID)
- }
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-recovered-%s-%d", routerID, time.Now().UnixMilli()),
- Category: alerts.CatRouter, Urgent: false,
- Severity: "ok",
- Title: name + " recovered",
- Description: fmt.Sprintf("%s is responding again", name),
- Type: alerts.TypeRouterRecovered,
- Vars: map[string]string{"router": name},
- Time: "just now", RouterID: routerID,
- })
- }
- // offlineRecoverTicks: sondeos seguidos con éxito necesarios para cerrar un
- // incidente de offline (issue #846). Un flap breve (online transitorio entre
- // fallos) no cierra el incidente: la alerta de caída sigue abierta y no se
- // emite "recuperado" hasta que el router responde de forma estable.
- const offlineRecoverTicks = 3
- // trackRouterOffline (issue #846): alerta crítica de offline tras 2 fallos
- // seguidos. Un fallo de ACCESO (SSH responde pero la clave no está
- // autorizada, #257) o una host key cambiada (#603) no es una caída — el
- // router está vivo; la UI lo marca "sin acceso" y no merece alerta crítica.
- // Mientras el incidente esté abierto NO se re-emite (aunque el estado flapee
- // entre offline y online): un incidente = una alerta = una notificación.
- // Debe llamarse con l.mu tomado.
- func (l *Live) trackRouterOffline(cfg *RouterConfig, err error, fails int) {
- quietErr := isAccessError(err) || isHostKeyError(err)
- if fails < 2 || quietErr || l.offlineOpen[cfg.ID] {
- return
- }
- if l.offlineOpen == nil {
- l.offlineOpen = map[string]bool{}
- l.recoverStreak = map[string]int{}
- }
- name := cfg.Name
- if name == "" {
- name = cfg.Host
- }
- if l.suppression != nil {
- l.suppression.MarkDown(cfg.ID)
- }
- ev := AlertEvent{
- ID: fmt.Sprintf("alert-offline-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatRouter, Urgent: true,
- Severity: "critical",
- Title: name + " offline",
- Description: fmt.Sprintf("No response from %s: %v", cfg.Host, err),
- Hint: alerts.HintFor(alerts.HintDeviceOffline),
- Type: alerts.TypeRouterOffline,
- Vars: map[string]string{"router": name, "host": cfg.Host, "error": fmt.Sprint(err)},
- Time: "just now", RouterID: cfg.ID,
- }
- // Sin dedup de 5 min: al cerrarse, el incidente anterior retiró su alerta
- // del feed (resolveOfflineAlerts) y la ventana bloquearía ésta — el "una
- // alerta por outage" lo garantiza offlineOpen, no el dedup.
- l.engine.EmitNoDedup(ev)
- // Huérfanas de un proceso anterior (reinicio del servidor durante una
- // caída): la alerta del incidente nuevo las sustituye, nunca se acumulan.
- l.removeStaleOfflineAlerts(cfg.ID, ev.ID)
- l.offlineOpen[cfg.ID] = true
- l.recoverStreak[cfg.ID] = 0
- }
- // removeStaleOfflineAlerts elimina las alertas de offline del router salvo
- // keepID (issue #846): al abrir un incidente sustituye las huérfanas que un
- // proceso anterior dejó en alert_log (offlineOpen vive en memoria y no
- // sobrevive a un reinicio). Debe llamarse con l.mu tomado.
- func (l *Live) removeStaleOfflineAlerts(routerID, keepID string) {
- ids := []string{}
- for _, ev := range l.engine.List() {
- if ev.RouterID == routerID && strings.HasPrefix(ev.ID, "alert-offline-") && ev.ID != keepID {
- ids = append(ids, ev.ID)
- }
- }
- if len(ids) > 0 {
- l.engine.Remove(ids...)
- }
- }
- // trackRouterRecovered (issue #846): cierra el incidente de offline cuando la
- // recuperación es estable (offlineRecoverTicks éxitos seguidos): elimina las
- // alertas de caída del router y emite el evento "recuperado" como relevo
- // positivo en el feed. Con incidente abierto, un éxito aislado NO cierra nada
- // (la caída sigue viva y no se insiste). Sin incidente abierto —caída sin
- // alerta por error de acceso (#257/#603)— se resuelve en el primer éxito,
- // como antes. Debe llamarse con l.mu tomado.
- func (l *Live) trackRouterRecovered(cfg *RouterConfig) {
- if l.offlineOpen[cfg.ID] {
- if l.recoverStreak == nil {
- l.recoverStreak = map[string]int{}
- }
- l.recoverStreak[cfg.ID]++
- if l.recoverStreak[cfg.ID] < offlineRecoverTicks {
- return
- }
- delete(l.offlineOpen, cfg.ID)
- delete(l.recoverStreak, cfg.ID)
- }
- name := cfg.Name
- if name == "" {
- name = cfg.Host
- }
- l.resolveOfflineAlerts(cfg.ID)
- l.emitRouterRecovered(cfg.ID, name)
- }
- // resolveOfflineAlerts elimina las alertas de offline pendientes del router
- // (issue #846; antes #256 las marcaba leídas): al volver online la caída se
- // retira del feed en vez de quedar ahí para siempre. El evento "recuperado"
- // (emitRouterRecovered) es el relevo positivo que sustituye la caída. Debe
- // llamarse con l.mu tomado.
- func (l *Live) resolveOfflineAlerts(routerID string) {
- ids := []string{}
- for _, ev := range l.engine.List() {
- if ev.RouterID == routerID && strings.HasPrefix(ev.ID, "alert-offline-") {
- ids = append(ids, ev.ID)
- }
- }
- if len(ids) > 0 {
- l.engine.Remove(ids...)
- }
- }
- // trackWanDown detecta "WAN/Internet caído" (category internet, urgent true,
- // critical — SPEC-ALERTAS §1): el gateway responde por SSH pero su ping a
- // internet da 100 % de pérdida en 2 sondeos seguidos (debounce como offline).
- // Al recuperarse la WAN se resetea el estado (la próxima caída vuelve a
- // alertar). Debe llamarse con l.mu tomado.
- func (l *Live) trackWanDown(cfg *RouterConfig, p *routerPolled) {
- key := cfg.ID + ":wan"
- if p == nil || p.lossPct == nil || *p.lossPct < 100 {
- l.wanDown[cfg.ID] = 0
- l.lastStatus[key] = "up"
- return
- }
- l.wanDown[cfg.ID]++
- if l.wanDown[cfg.ID] >= 2 && l.lastStatus[key] != "down" {
- l.lastStatus[key] = "down"
- name := cfg.Name
- if name == "" {
- name = cfg.Host
- }
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-wan-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatInternet, Urgent: true,
- Severity: "critical",
- Title: "Internet down",
- Description: fmt.Sprintf("%s responds but cannot reach the internet (100%% packet loss)", name),
- Hint: alerts.HintFor(alerts.HintWanDown),
- Type: alerts.HintWanDown,
- Vars: map[string]string{"router": name},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- }
- // normalizeMultiWan makes a reported section safe to serve.
- //
- // Anything holding an agent token can push whatever it likes, and a section
- // without its list of connections would go out as a null the page then
- // reads a length from. A nil slice becomes an empty one, which already
- // means "nothing to show" everywhere downstream.
- func normalizeMultiWan(m *MultiWanInfo) *MultiWanInfo {
- if m == nil {
- return nil
- }
- if m.Uplinks == nil {
- m.Uplinks = []WanUplink{}
- }
- return m
- }
- // uplinkWatch is one router's multi-WAN history, as much of it as an alert
- // needs.
- type uplinkWatch struct {
- active string // the connection last CONFIRMED as carrying traffic
- primary string // the preferred one at that moment, for "moved back"
- candidate string // a different one seen, not yet believed
- since time.Time // when the candidate was first seen
- }
- // uplinkSettle is how long a new connection must hold the traffic before it
- // counts as a change. A failover that bounces straight back — a link
- // renegotiating, a tracker blip while rules reload — then produces no alert
- // at all, which is the point: the interesting event is the one that lasts.
- const uplinkSettle = 45 * time.Second
- // trackUplinkChange alerts when the internet starts going out through a
- // different connection, and again when it comes back to the main one.
- //
- // The first observation of a router is recorded in silence. Otherwise every
- // restart of this server would announce a failover that happened days ago,
- // and the feed would fill with history on each deploy. Must be called with
- // l.mu held.
- func (l *Live) trackUplinkChange(cfg RouterConfig, p *routerPolled, now time.Time) {
- if p == nil || p.multiWan == nil {
- return
- }
- // Fewer than two connections is nothing to fail over between: forget
- // the router, so a second line added later starts from silence.
- if len(p.multiWan.Uplinks) < 2 {
- delete(l.uplinkWatch, cfg.ID)
- return
- }
- active := p.multiWan.Active
- if active == "" {
- // Nothing is steering. Not a move, and not something to guess at.
- return
- }
- w := l.uplinkWatch[cfg.ID]
- if w == nil {
- l.uplinkWatch[cfg.ID] = &uplinkWatch{active: active, primary: p.multiWan.Primary}
- return
- }
- w.primary = p.multiWan.Primary
- if active == w.active {
- w.candidate, w.since = "", time.Time{}
- return
- }
- if active != w.candidate {
- w.candidate, w.since = active, now
- return
- }
- if now.Sub(w.since) < uplinkSettle {
- return
- }
- from := w.active
- w.active, w.candidate, w.since = active, "", time.Time{}
- l.emitUplinkChange(cfg, p.multiWan, from, active)
- }
- // emitUplinkChange reports the move. Coming back to the preferred
- // connection is its own event: after a failover, "it is over" is the part
- // somebody is waiting for. Must be called with l.mu held.
- func (l *Live) emitUplinkChange(cfg RouterConfig, mw *MultiWanInfo, from, to string) {
- name := cfg.Name
- if name == "" {
- name = cfg.Host
- }
- vars := map[string]string{"router": name, "from": from, "to": to}
- restored := to == mw.Primary && mw.Primary != ""
- for _, u := range mw.Uplinks {
- if u.Name == to && u.Metered {
- // Moving onto a pay-per-use line is different news: it starts
- // costing money.
- vars["metered"] = "1"
- }
- }
- ev := AlertEvent{
- ID: fmt.Sprintf("alert-uplink-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatInternet,
- // The internet category only lets urgent events through by
- // default, so a quiet one here would simply never be seen.
- Urgent: true,
- Severity: "warn",
- // The destination is part of the title on purpose: the engine
- // deduplicates on category+title+router, and a failover and its
- // recovery inside that window would otherwise collapse into one.
- Title: "Internet is going out through " + to,
- Description: fmt.Sprintf("%s moved the traffic from %s to %s", name, from, to),
- Hint: alerts.HintFor(alerts.HintUplinkSwitch),
- Type: alerts.HintUplinkSwitch,
- Vars: vars,
- Time: "just now", RouterID: cfg.ID,
- }
- if restored {
- ev.Severity = "ok"
- ev.Title = "Internet is back on " + to
- ev.Description = fmt.Sprintf("%s moved the traffic back to %s", name, to)
- ev.Hint = ""
- ev.Type = alerts.TypeUplinkRestored
- }
- l.engine.Emit(ev)
- }
- // trackUnknownDevices emite "dispositivo desconocido se conecta" cuando un
- // cliente SIN nombre (Name == MAC, sin hostname DHCP ni alias — device_attrib
- // no guarda alias) pasa de no-online a online y PERMANECE nameless durante
- // `unknownGraceNum` ticks seguidos (issue #234): un dispositivo conocido que
- // reconecta resuelve su lease DHCP en 1-2 ticks y nunca alcanza el umbral.
- // La memoria per-MAC persistida (issue #248) garantiza que cada MAC desconocida
- // alerta UNA sola vez en la vida del servidor, hasta que se confíe en
- // Settings (known_macs) o se resete. El primer ciclo de sondeo del proceso
- // NO alerta (evita la avalancha de arranque: todo lo ya conectado sería
- // "nuevo"). Las MAC de la allowlist known_macs (issue #196) nunca alertan,
- // haya alias o no. Toma l.mu internamente.
- // unknownDeviceHasEvidence reports whether an unnamed MAC carries at least
- // one sign that a real host is present: an address resolved by DHCP, ARP, ND
- // or mDNS, a wireless association, or an LLDP neighbour. A row that only
- // exists in a bridge or switch FDB is not enough on its own (#1818): firmware
- // recovery protocols such as Netgear NMRP announce short-lived addresses that
- // way while a unit reboots to flash.
- func unknownDeviceHasEvidence(d Device) bool {
- if d.IP != "" || d.Lldp != nil {
- return true
- }
- return d.Band != "" && d.Band != "cable" && d.Band != "—"
- }
- func (l *Live) trackUnknownDevices(devices []Device, dists []DistributionNode) {
- l.mu.Lock()
- defer l.mu.Unlock()
- // issue #196: MACs de la allowlist (confiables) → nunca "desconocido".
- trusted := map[string]bool{}
- if l.db != nil {
- if rows, err := l.db.Query("SELECT mac FROM known_macs"); err == nil {
- for rows.Next() {
- var mac string
- if rows.Scan(&mac) == nil {
- trusted[mac] = true
- }
- }
- rows.Close()
- }
- }
- nowOnline := map[string]bool{}
- for _, d := range devices {
- if !d.Online {
- continue
- }
- nowOnline[d.MAC] = true
- if trusted[d.MAC] {
- delete(l.unknownGrace, d.MAC)
- delete(l.unverifiedSince, d.MAC)
- continue
- }
- // issue #234: con hostname (lease resuelto) el dispositivo es
- // conocido; se resetea su gracia y nunca alerta.
- if d.Name != d.MAC {
- delete(l.unknownGrace, d.MAC)
- delete(l.unverifiedSince, d.MAC)
- continue
- }
- // issue #1818: una MAC sin ninguna prueba de que hay un host real
- // solo está en una FDB (bridge, AP o switch). Los protocolos de
- // recuperación de firmware (NMRP de Netgear) publican direcciones
- // así durante un reinicio, y alertar de ellas convierte cada
- // actualización en un "dispositivo desconocido".
- if !unknownDeviceHasEvidence(d) {
- delete(l.unknownGrace, d.MAC)
- l.noteUnverifiedMac(d, devices, dists)
- continue
- }
- // issue #248: esta MAC ya alertó alguna vez → no vuelve a hacerlo.
- if l.unknownAlerted[d.MAC] {
- delete(l.unknownGrace, d.MAC)
- delete(l.unverifiedSince, d.MAC)
- continue
- }
- // Solo los dispositivos que ACABAN de conectarse (o que ya estaban en
- // gracia) acumulan ticks; los conectados antes del arranque no entran.
- _, counting := l.unknownGrace[d.MAC]
- if l.seenOnlineMacs && (counting || !l.onlineMacs[d.MAC]) {
- l.unknownGrace[d.MAC]++
- if l.unknownGrace[d.MAC] >= l.unknownGraceNum {
- l.emitUnknownDevice(d, devices, dists)
- l.unknownAlerted[d.MAC] = true
- l.persistUnknownAlerted(d.MAC)
- delete(l.unknownGrace, d.MAC)
- }
- }
- }
- // La gracia solo acumula en estado "online + sin nombre": cualquier otra
- // transición la resetea (una reconexión futura parte de cero).
- for mac := range l.unknownGrace {
- if !nowOnline[mac] {
- delete(l.unknownGrace, mac)
- }
- }
- // #1873: el reloj de la nota solo corre mientras la MAC siga ahí. Si se
- // va, el siguiente avistamiento empieza a contar de cero.
- for mac := range l.unverifiedSince {
- if !nowOnline[mac] {
- delete(l.unverifiedSince, mac)
- }
- }
- l.onlineMacs = nowOnline
- l.seenOnlineMacs = true
- }
- // unverifiedMacNoteAfter es cuánto tiene que persistir una MAC sin ninguna
- // prueba de host antes de dejar su nota (#1873). Diez minutos: suficiente
- // para que un protocolo de recuperación de firmware (NMRP de Netgear dura
- // segundos) no la dispare y poco para una MAC que se ha quedado a vivir en
- // una tabla de reenvío.
- const unverifiedMacNoteAfter int64 = 10 * 60 * 1000
- // unverifiedThreshold devuelve el umbral efectivo en ms. Los Live montados a
- // mano (tests, demo) dejan unverifiedAfterMs a 0 y usan el default.
- // Debe llamarse con l.mu tomado.
- func (l *Live) unverifiedThreshold() int64 {
- if l.unverifiedAfterMs > 0 {
- return l.unverifiedAfterMs
- }
- return unverifiedMacNoteAfter
- }
- // noteUnverifiedMac deja una nota informativa cuando una MAC sin lease, ARP,
- // ND ni mDNS sigue apareciendo en una tabla de reenvío (#1873). No toca el
- // gate de #1818 ni el contador de desconocidos: es el rastro de lo que hasta
- // ahora se descartaba en silencio, que es justo lo que pidió el reportero.
- // Debe llamarse con l.mu tomado.
- func (l *Live) noteUnverifiedMac(d Device, devices []Device, dists []DistributionNode) {
- if l.unverifiedNoted[d.MAC] {
- return
- }
- if l.unverifiedSince == nil {
- l.unverifiedSince = map[string]int64{}
- }
- if l.unverifiedNoted == nil {
- l.unverifiedNoted = map[string]bool{}
- }
- now := time.Now().UnixMilli()
- first, seen := l.unverifiedSince[d.MAC]
- if !seen {
- l.unverifiedSince[d.MAC] = now
- return
- }
- if now-first < l.unverifiedThreshold() {
- return
- }
- l.emitUnverifiedMac(d, devices, dists, (now-first)/60000)
- l.unverifiedNoted[d.MAC] = true
- l.persistUnverifiedNoted(d.MAC)
- delete(l.unverifiedSince, d.MAC)
- }
- // emitUnverifiedMac: nota de baja prioridad (category clients, info, no
- // urgente) para una MAC que persiste sin evidencia. No comparte ID con la
- // alerta de desconocido: esta es informativa y el motor deduplica por ID.
- // Debe llamarse con l.mu tomado.
- func (l *Live) emitUnverifiedMac(d Device, devices []Device, dists []DistributionNode, minutes int64) {
- where, port := l.deviceLocation(d, devices, dists)
- if minutes < 1 {
- minutes = 1
- }
- vars := map[string]string{
- "mac": d.MAC,
- "router": l.routerDisplayName(d.RouterID),
- "where": where,
- "minutes": fmt.Sprintf("%d", minutes),
- }
- if port != "" {
- vars["port"] = port
- }
- desc := fmt.Sprintf("%s has been in %s for %d min with no lease, ARP, ND or mDNS", d.MAC, where, minutes)
- if port != "" {
- desc = fmt.Sprintf("%s has been on %s (%s) for %d min with no lease, ARP, ND or mDNS", d.MAC, where, port, minutes)
- }
- l.engine.Emit(AlertEvent{
- ID: "alert-unverified-mac-" + d.MAC,
- Category: alerts.CatClients, Urgent: false,
- Severity: "info",
- Title: "Unverified device",
- Description: desc,
- Type: alerts.TypeUnverifiedMac,
- Vars: vars,
- Time: "just now", RouterID: d.RouterID,
- })
- }
- // persistUnverifiedNoted guarda en kv que esta MAC ya dejó su nota (#1873),
- // para no repetirla tras un reinicio. Con db nil (demo/tests) es no-op.
- // Debe llamarse con l.mu tomado.
- func (l *Live) persistUnverifiedNoted(mac string) {
- if l.db == nil {
- return
- }
- _, _ = l.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "unverified_mac_noted:"+mac)
- }
- // wifiNoIPNoteAfter es cuánto tiene que persistir un cliente asociado por
- // WiFi sin dirección antes de dejar su nota (#2111). Dos minutos: un cliente
- // que acaba de asociarse pide DHCP en segundos, así que el que sigue sin IP
- // pasado ese rato es el caso que interesa (un equipo que no pide lease, un
- // DHCP agotado, una VLAN sin servidor).
- const wifiNoIPNoteAfter int64 = 2 * 60 * 1000
- // isWirelessBand: la asociación WiFi es la prueba de que el cliente existe.
- func isWirelessBand(band string) bool {
- return band != "" && band != "cable" && band != "—"
- }
- // wifiNoIPThreshold devuelve el umbral efectivo en ms. Los Live montados a
- // mano (tests, demo) dejan wifiNoIPAfterMs a 0 y usan el default.
- // Debe llamarse con l.mu tomado.
- func (l *Live) wifiNoIPThreshold() int64 {
- if l.wifiNoIPAfterMs > 0 {
- return l.wifiNoIPAfterMs
- }
- return wifiNoIPNoteAfter
- }
- // trackWiFiNoIP deja una nota informativa por cliente que lleva un rato
- // asociado por WiFi sin IP (#2111). No alerta, no es urgente y no toca el
- // contador de desconocidos: la asociación ya prueba que el equipo existe, lo
- // que falta es la dirección.
- func (l *Live) trackWiFiNoIP(devices []Device, dists []DistributionNode) {
- l.mu.Lock()
- defer l.mu.Unlock()
- // Los Live montados a mano (tests, demo) pueden no haber inicializado los
- // mapas; se crean aquí como hace noteUnverifiedMac con los suyos.
- if l.wifiNoIPSince == nil {
- l.wifiNoIPSince = map[string]int64{}
- }
- if l.wifiNoIPNoted == nil {
- l.wifiNoIPNoted = map[string]bool{}
- }
- nowOnline := map[string]bool{}
- now := time.Now().UnixMilli()
- for _, d := range devices {
- if !d.Online || !isWirelessBand(d.Band) || d.IP != "" {
- continue
- }
- nowOnline[d.MAC] = true
- if l.wifiNoIPNoted[d.MAC] {
- continue
- }
- first, seen := l.wifiNoIPSince[d.MAC]
- if !seen {
- l.wifiNoIPSince[d.MAC] = now
- continue
- }
- if now-first < l.wifiNoIPThreshold() {
- continue
- }
- l.emitWiFiNoIP(d, devices, dists, (now-first)/60000)
- l.wifiNoIPNoted[d.MAC] = true
- l.persistWiFiNoIPNoted(d.MAC)
- delete(l.wifiNoIPSince, d.MAC)
- }
- // El reloj solo corre mientras el cliente siga asociado sin IP.
- for mac := range l.wifiNoIPSince {
- if !nowOnline[mac] {
- delete(l.wifiNoIPSince, mac)
- }
- }
- }
- // emitWiFiNoIP: nota de baja prioridad (clients, info, no urgente). ID estable
- // por MAC para que el motor la deduplique.
- // Debe llamarse con l.mu tomado.
- func (l *Live) emitWiFiNoIP(d Device, devices []Device, dists []DistributionNode, minutes int64) {
- where, port := l.deviceLocation(d, devices, dists)
- if minutes < 1 {
- minutes = 1
- }
- vars := map[string]string{
- "mac": d.MAC,
- "router": l.routerDisplayName(d.RouterID),
- "where": where,
- "minutes": fmt.Sprintf("%d", minutes),
- "band": d.Band,
- }
- if port != "" {
- vars["port"] = port
- }
- desc := fmt.Sprintf("%s has been associated by Wi-Fi on %s for %d min with no IP address", d.MAC, where, minutes)
- if port != "" {
- 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)
- }
- l.engine.Emit(AlertEvent{
- ID: "alert-wifi-noip-" + d.MAC,
- Category: alerts.CatClients, Urgent: false,
- Severity: "info",
- Title: "Wi-Fi client with no IP",
- Description: desc,
- Type: alerts.TypeWiFiNoIP,
- Vars: vars,
- Time: "just now", RouterID: d.RouterID,
- })
- }
- // persistWiFiNoIPNoted guarda en kv que esta MAC ya dejó su nota (#2111).
- // Con db nil (demo/tests) es no-op.
- // Debe llamarse con l.mu tomado.
- func (l *Live) persistWiFiNoIPNoted(mac string) {
- if l.db == nil {
- return
- }
- _, _ = l.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "wifi_noip_noted:"+mac)
- }
- // persistUnknownAlerted guarda en kv la memoria per-MAC (issue #248) para que
- // sobreviva a reinicios del servidor. Con db nil (demo/tests) es no-op.
- // Debe llamarse con l.mu tomado.
- func (l *Live) persistUnknownAlerted(mac string) {
- if l.db == nil {
- return
- }
- _, _ = l.db.Exec("INSERT INTO kv (key, value) VALUES (?, '1') ON CONFLICT(key) DO NOTHING", "unknown_alerted:"+mac)
- }
- // routerDisplayName: nombre visible de un router por id ("" si no está en la
- // flota). Usado por las alertas para interpolar la clave i18n {{router}}.
- // Debe llamarse con l.mu tomado.
- func (l *Live) routerDisplayName(id string) string {
- for _, r := range l.routers {
- if r.ID == id {
- return r.Name
- }
- }
- return id
- }
- // emitUnknownDevice: evento "dispositivo desconocido se conecta" (category
- // clients, warn, NO urgente — issue #196). "Desconocido" = sin nombre/alias:
- // device_attrib no guarda alias, así que la señal práctica es un cliente sin
- // hostname DHCP (Name == MAC). Debe llamarse con l.mu tomado.
- //
- // The alert has to be actionable: a MAC on its own tells nobody which box to
- // walk up to, so it also carries the IP, what the client hangs off and the
- // port there, when those are known. They are: this runs after the topology
- // pass and the Proxmox/UniFi seals, so AttachTo is already resolved.
- func (l *Live) emitUnknownDevice(d Device, devices []Device, dists []DistributionNode) {
- where, port := l.deviceLocation(d, devices, dists)
- vars := map[string]string{
- "mac": d.MAC,
- "router": l.routerDisplayName(d.RouterID),
- "where": where,
- }
- // Only the facts we actually have: the app renders one row per var and an
- // empty one would read as "we know this and it is blank".
- if d.IP != "" {
- vars["ip"] = d.IP
- }
- if port != "" {
- vars["port"] = port
- }
- if d.Band != "" && d.Band != "—" {
- vars["band"] = d.Band
- }
- if d.SignalDbm != nil {
- vars["signal"] = fmt.Sprintf("%d", *d.SignalDbm)
- }
- desc := fmt.Sprintf("%s connected to %s", d.MAC, where)
- if d.IP != "" {
- desc = fmt.Sprintf("%s · %s connected to %s", d.MAC, d.IP, where)
- }
- if d.Band != "" && d.Band != "cable" {
- desc += " · " + d.Band
- }
- if d.SignalDbm != nil {
- desc += fmt.Sprintf(" · %d dBm", *d.SignalDbm)
- }
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-unknown-%s-%d", d.MAC, time.Now().UnixMilli()),
- Category: alerts.CatClients, Urgent: true,
- Severity: "warn",
- Title: "Unknown device",
- Description: desc,
- Hint: alerts.HintFor(alerts.HintUnknownDevice),
- Type: alerts.HintUnknownDevice,
- Vars: vars,
- Time: "just now", RouterID: d.RouterID,
- })
- }
- // DismissUnknownDevice implementa Snapshotter (#772): marca la MAC como ya
- // avisada para que trackUnknownDevices no vuelva a alertar ("dejar como
- // anónimo"). Persiste en kv (issue #248) para sobrevivir a reinicios.
- func (l *Live) DismissUnknownDevice(mac string) {
- mac = strings.ToUpper(strings.TrimSpace(mac))
- if len(mac) != 17 {
- return
- }
- l.mu.Lock()
- defer l.mu.Unlock()
- l.unknownAlerted[mac] = true
- l.persistUnknownAlerted(mac)
- delete(l.unknownGrace, mac)
- }
- // deviceLocation: where a client is plugged in, as the two strings the alert
- // interpolates. `where` is the box it hangs off — the AP, switch or
- // hypervisor named by AttachTo, which may be a distribution node or another
- // device acting as a hub — falling back to its router, which is always known.
- // `port` is the physical port when the bridge FDB or the controller reports
- // one (empty for wireless clients). Must be called with l.mu held.
- func (l *Live) deviceLocation(d Device, devices []Device, dists []DistributionNode) (where, port string) {
- port = d.PortLabel
- if port == "" {
- port = d.Port
- }
- if d.AttachTo != "" {
- for _, n := range dists {
- if n.ID != d.AttachTo {
- continue
- }
- where = firstNonEmpty(n.Name, n.Ip)
- // A client behind a switch is learnt on the router port that the
- // switch itself hangs off, so that port describes the uplink, not
- // the client: naming it next to the switch would send someone to
- // the wrong socket.
- if n.Port == d.Port {
- port = ""
- }
- break
- }
- if where == "" {
- for _, o := range devices {
- if o.ID == d.AttachTo {
- where = firstNonEmpty(o.Name, o.IP)
- break
- }
- }
- }
- }
- if where == "" {
- where = l.routerDisplayName(d.RouterID)
- }
- return where, port
- }
- func firstNonEmpty(vals ...string) string {
- for _, v := range vals {
- if v != "" {
- return v
- }
- }
- return ""
- }
- // trackDevicePresence emite device_offline/device_online cuando una MAC
- // wireless pasa de vista a no-vista (N ticks) o viceversa (issue #184).
- // Solo se rastrean MACs wireless (Band != "cable"): el FDB de cableados es
- // volátil y daría falsos offline. Anti-falsos positivos: un tick perdido no
- // dispara — hace falta `presenceOfflineAfter` ticks seguidos sin verse.
- // Anti-arranque: el primer ciclo solo puebla el estado (todo lo ya conectado
- // en boot no genera online). Poda: una MAC offline desde hace muchos ticks
- // (dispositivo que se fue para siempre) se elimina de los mapas para que no
- // crezcan sin límite (issue #206). Toma l.mu.
- func (l *Live) trackDevicePresence(devices []Device, nowMs int64) {
- l.mu.Lock()
- defer l.mu.Unlock()
- seen := map[string]bool{}
- for _, d := range devices {
- if !d.Online || d.Band == "cable" {
- continue
- }
- seen[d.MAC] = true
- if l.presenceSeen && !l.devicePresence[d.MAC] {
- l.insertDeviceEvent(d.MAC, d.RouterID, deviceevents.StateOnline, d.SignalDbm, nowMs)
- }
- l.devicePresence[d.MAC] = true
- l.presenceMisses[d.MAC] = 0
- }
- for mac, wasOnline := range l.devicePresence {
- if !wasOnline {
- // Ya offline: la MAC no re-emite, pero el contador sigue
- // creciendo para que la poda pueda eliminarla (issue #206).
- l.presenceMisses[mac]++
- continue
- }
- if seen[mac] {
- continue
- }
- l.presenceMisses[mac]++
- if l.presenceMisses[mac] >= l.presenceOfflineAfter {
- l.insertDeviceEvent(mac, l.lastRouterFor(mac), deviceevents.StateOffline, nil, nowMs)
- l.devicePresence[mac] = false
- }
- }
- // Poda: MACs offline desde hace muchos ticks (se fueron para siempre) se
- // eliminan para que los mapas no crezcan sin límite (issue #206).
- // Zero-value (pruneAfter==0) = poda desactivada.
- if l.presencePruneAfter > 0 {
- for mac, misses := range l.presenceMisses {
- if misses >= l.presencePruneAfter {
- delete(l.presenceMisses, mac)
- delete(l.devicePresence, mac)
- }
- }
- }
- l.presenceSeen = true
- }
- // trackOfflineDevices (#1354): alerta volátil opt-in cuando un dispositivo
- // marcado (override notify_offline) cae de la red. La transición
- // online->offline se CONFIRMA tras offlineAlertNum (default 3) ticks offline
- // seguidos, espejo de trackDevicePresence; un flap corto dentro de la gracia
- // no emite nada. Anti-arranque: solo alerta para MACs vistas online alguna vez
- // (una MAC ya offline al arrancar nunca "se desconecta"). Al volver online se
- // retira la entrada volátil (engine.Remove), de modo que el feed se
- // auto-resuelve. Toma l.mu internamente.
- func (l *Live) trackOfflineDevices(devices []Device) {
- l.mu.Lock()
- defer l.mu.Unlock()
- for _, d := range devices {
- if !d.NotifyOffline {
- continue
- }
- if d.Online {
- l.offlineOnline[d.MAC] = true
- if l.offlineAlerted[d.MAC] {
- l.offlineAlerted[d.MAC] = false
- l.engine.Remove("alert-device-offline-" + d.MAC)
- }
- l.offlineMisses[d.MAC] = 0
- continue
- }
- // Solo transiciones reales: MACs que ya vimos online en un ciclo previo.
- if !l.offlineOnline[d.MAC] {
- continue
- }
- l.offlineMisses[d.MAC]++
- if l.offlineMisses[d.MAC] >= l.offlineAlertNum && !l.offlineAlerted[d.MAC] {
- l.offlineAlerted[d.MAC] = true
- l.emitDeviceOffline(d)
- }
- }
- }
- // emitDeviceOffline emite la alerta volátil de desconexión (category clients,
- // warn, urgente). ID estable por MAC: un incidente = una entrada del feed.
- // Debe llamarse con l.mu tomado.
- func (l *Live) emitDeviceOffline(d Device) {
- name := d.Name
- if name == "" {
- name = d.MAC
- }
- router := l.routerDisplayName(d.RouterID)
- l.engine.EmitVolatile(AlertEvent{
- ID: "alert-device-offline-" + d.MAC,
- Category: alerts.CatClients, Urgent: true,
- Severity: "warn",
- Title: fmt.Sprintf("Device offline: %s", name),
- Description: fmt.Sprintf("%s went offline on %s", name, router),
- Hint: alerts.HintFor(alerts.HintDeviceOffline),
- Type: alerts.TypeDeviceOffline,
- Vars: map[string]string{"device": name, "router": router},
- Time: "just now", RouterID: d.RouterID,
- })
- }
- // insertDeviceEvent persiste una transición de presencia. Con db nil
- // (demo/tests sin BD) es no-op. Debe llamarse con l.mu tomado.
- func (l *Live) insertDeviceEvent(mac, routerID, state string, signalDbm *int, nowMs int64) {
- if l.db == nil {
- return
- }
- _ = deviceevents.Insert(l.db.DB, deviceevents.Event{
- TsMs: nowMs, MAC: mac, RouterID: routerID, State: state,
- SignalDbm: signalDbm,
- })
- }
- // lastRouterFor devuelve el último router conocido de una MAC desde
- // device_attrib (o vacío si no hay registro). Debe llamarse con l.mu tomado.
- func (l *Live) lastRouterFor(mac string) string {
- if l.db == nil {
- return ""
- }
- var routerID string
- _ = l.db.QueryRow("SELECT router_id FROM device_attrib WHERE mac = ?", mac).Scan(&routerID)
- return routerID
- }
- // parseSpeedMbps converts a human speed string ("1 Gbps", "100 Mbps", "2.5G")
- // to Mbps. Returns 0 on unknown formats.
- func parseSpeedMbps(s string) int {
- s = strings.TrimSpace(s)
- if s == "" {
- return 0
- }
- s = strings.ReplaceAll(s, "bps", "")
- s = strings.ReplaceAll(s, "Bps", "")
- s = strings.TrimSpace(s)
- if strings.HasSuffix(s, "G") {
- numStr := strings.TrimSpace(strings.TrimSuffix(s, "G"))
- if v, err := strconv.ParseFloat(numStr, 64); err == nil {
- return int(v * 1000)
- }
- }
- if strings.HasSuffix(s, "M") {
- numStr := strings.TrimSpace(strings.TrimSuffix(s, "M"))
- if v, err := strconv.ParseFloat(numStr, 64); err == nil {
- return int(v)
- }
- }
- return 0
- }
- // recordPortSamples persists per-port time series samples (issue #302).
- // Called after port stats are collected (SSH or agent path).
- func (l *Live) recordPortSamples(routerID string, ports []EthPort) {
- if l.db == nil || l.db.PortSeries == nil || len(ports) == 0 {
- return
- }
- now := time.Now()
- for _, p := range ports {
- if p.ID == "" {
- continue
- }
- _ = l.db.PortSeries.RecordSample(portseries.PortSample{
- RouterID: routerID, PortID: p.ID, TS: now,
- RxBytes: p.RxBytes, TxBytes: p.TxBytes,
- RxErrors: p.RxErrs, TxErrors: p.TxErrs,
- RxBps: p.RxBps, TxBps: p.TxBps,
- SpeedMbps: parseSpeedMbps(p.Speed),
- })
- }
- }
- // AdguardClients expone el cliente configurado (estándar o GL) para la
- // ingesta del query log (#2078). Respeta el toggle de servicios: desactivado
- // devuelve nil, nil. Se resuelve en cada llamada: la integración se puede
- // configurar o apagar en caliente.
- func (l *Live) AdguardClients() (*AdGuardClient, *AdGuardGlinetClient) {
- if l.db != nil {
- var v string
- if err := l.db.QueryRow("SELECT value FROM kv WHERE key = 'settings.services.adguard'").Scan(&v); err == nil && (v == "0" || v == "false") {
- return nil, nil
- }
- }
- return l.getAdguardClient()
- }
- // pollAdGuard: stats del cliente configurado; fallback inactivo si falla.
- func (l *Live) pollAdGuard(ctx context.Context) *AdGuardStats {
- // Servicio desactivado en Ajustes > Servicios (#813): ni sondeo ni
- // penalización. Clave ausente = activo (compat).
- if l.db != nil {
- var v string
- if err := l.db.QueryRow("SELECT value FROM kv WHERE key = 'settings.services.adguard'").Scan(&v); err == nil && (v == "0" || v == "false") {
- return nil
- }
- }
- std, gl := l.getAdguardClient()
- if std == nil && gl == nil {
- return nil
- }
- var stats *AdGuardStats
- var err error
- host := ""
- if std != nil {
- u := std.url
- if i := strings.Index(u, "://"); i >= 0 {
- u = u[i+3:]
- }
- host = strings.SplitN(u, ":", 2)[0]
- stats, err = std.GetStats(ctx)
- if err != nil {
- port := 3000
- if len(u) > len(host)+1 {
- if p, err := strconv.Atoi(u[len(host)+1:]); err == nil && p > 0 {
- port = p
- }
- }
- return &AdGuardStats{
- Host: host, Port: port, Status: "inactive",
- TopBlocked: []TopBlocked{},
- }
- }
- return stats
- } else {
- host = gl.Host
- stats, err = gl.GetStats(ctx)
- }
- if err != nil {
- log.Printf("[netpulse] AdGuard inalcanzable: %v", err)
- return &AdGuardStats{
- Host: host, Port: 3000, Status: "inactive",
- TopBlocked: []TopBlocked{},
- }
- }
- return stats
- }
- // pollWireGuard: gateway WireGuard stats plus connect/disconnect alerts.
- func (l *Live) pollWireGuard(devices []Device) *WireGuardStats {
- l.mu.Lock()
- gw := l.gatewayCfg
- l.mu.Unlock()
- if gw == nil {
- return nil
- }
- peerNames := map[string]WGPeerName{}
- for _, d := range devices {
- if d.IP != "" {
- peerNames[d.IP] = WGPeerName{ID: d.ID, Name: d.Name, Type: d.Type}
- }
- }
- // #1441: copia del conjunto de urgentes para estamparlo en cada peer sin
- // tener el mutex tomado durante el sondeo SSH.
- l.mu.Lock()
- urgent := l.wgUrgentCopyLocked()
- l.mu.Unlock()
- stats, err := GetWireGuardStats(l.pool, gw.SSHAddr(), l.cfg.WGInterface, "", peerNames, urgent)
- if err != nil {
- log.Printf("[netpulse] WireGuard unavailable: %v", err)
- return &WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}, RouterID: gw.ID}
- }
- // #2019: el poller necesita saber de qué router son estos peers para
- // persistir la serie y calcular la ventana de 30 días.
- stats.RouterID = gw.ID
- // Transitions run only on a successful poll: a failed poll would mark every
- // previously active peer as spuriously disconnected.
- l.applyWireGuardTransitions(stats, gw.ID)
- // #1445: recoge los flags urgentes de peers que dejaron de existir.
- l.pruneWGUrgent(stats.Peers)
- return stats
- }
- // wgUrgentPruneMisses (#1445): ausencias consecutivas en el dump antes de
- // recoger un flag urgente. Un dump parcial (una interfaz no respondió, #714)
- // no borra flags de peers vivos; sólo desaparece del router de verdad quien
- // lleva varios sondeos seguidos sin aparecer.
- const wgUrgentPruneMisses = 3
- // pruneWGUrgent recoge las claves urgentes que llevan wgUrgentPruneMisses
- // sondeos seguidos sin casar con ningún peer configurado. Con dumps vacíos no
- // cuenta ausencias (no borra nada): sin peers no hay evidencia de nada.
- func (l *Live) pruneWGUrgent(peers []WGPeer) {
- if len(peers) == 0 {
- return
- }
- present := map[string]bool{}
- for _, p := range peers {
- k := p.Key
- if k == "" {
- k = p.ID
- }
- present[k] = true
- }
- l.mu.Lock()
- defer l.mu.Unlock()
- changed := false
- for k := range l.wgUrgent {
- if present[k] {
- if l.wgUrgentMiss[k] != 0 {
- delete(l.wgUrgentMiss, k)
- changed = true
- }
- continue
- }
- l.wgUrgentMiss[k]++
- if l.wgUrgentMiss[k] >= wgUrgentPruneMisses {
- delete(l.wgUrgent, k)
- delete(l.wgUrgentMiss, k)
- changed = true
- }
- }
- if changed {
- l.saveWGUrgentLocked()
- }
- }
- // applyWireGuardTransitions emits connect (handshake) and disconnect alerts for
- // peers whose active state changed since the last successful poll, and keeps
- // wgActive/wgActiveSince in sync. A peer that was never active cannot emit a
- // disconnect; the first post-boot cycle never emits a connect (warmup).
- //
- // #1443: el tracker se indexa por Key (pubkey base64url estable, #1441) con
- // fallback a ID: WGPeer.ID puede cambiar entre sondeos ("peer-<idx>" según
- // la posición en el dump) y un cambio de identificador simulaba un
- // disconnect+connect fantasma. Los eventos de transición salen por
- // EmitNoDedup: cada uno es un incidente real (un connect y un disconnect
- // del mismo peer llevan el mismo título y el dedup de 5 min se comía los
- // flaps). El warmup es un flag propio (wgPrimed), no len(wgActive)>0: con
- // el guarda viejo, la primera conexión de un túnel iniciado por la unidad
- // local (ciclo previo con 0 peers activos) se perdía para siempre.
- //
- // #1441: la alerta de un peer URGENTE sale con Urgent=true (aviso push); la de
- // un peer normal con Urgent=false (solo queda en el log). La categoría y los
- // IDs no cambian: lo único que distingue a un site-to-site de un portátil es
- // el flag que puso el admin.
- func (l *Live) applyWireGuardTransitions(stats *WireGuardStats, gwID string) {
- // wgTrackKey: identidad estable del peer para el tracker (#1443).
- wgTrackKey := func(p WGPeer) string {
- if p.Key != "" {
- return p.Key
- }
- return p.ID
- }
- activeNow := map[string]bool{}
- peerByKey := map[string]WGPeer{}
- for _, p := range stats.Peers {
- k := wgTrackKey(p)
- peerByKey[k] = p
- if p.Active {
- activeNow[k] = true
- }
- }
- l.mu.Lock()
- defer l.mu.Unlock()
- // Urgencia por peer: el flag viene estampado del sondeo (Urgent) y, por si
- // el llamador construyó los WGPeer a mano, se cruza con el conjunto
- // persistido por Key o por ID.
- urgentNow := map[string]bool{}
- for k, p := range peerByKey {
- urgentNow[k] = p.Urgent || l.wgUrgent[p.Key] || l.wgUrgent[p.ID]
- }
- // Disconnects: previously active peers no longer present in activeNow.
- // #1445: si el peer desapareció del dump en el mismo ciclo de su caída,
- // urgentNow no lo ve: se respalda con el conjunto persistido (la clave
- // trackeada ES la Key, así que l.wgUrgent[id] devuelve su flag aunque el
- // peer no esté en la muestra).
- for id := range l.wgActive {
- if activeNow[id] {
- continue
- }
- name := id
- if p, ok := peerByKey[id]; ok {
- name = p.Name
- }
- dur := wgDuration(time.Since(l.wgActiveSince[id]))
- l.engine.EmitNoDedup(AlertEvent{
- ID: fmt.Sprintf("alert-wg-down-%s-%d", id, time.Now().UnixMilli()),
- Category: alerts.CatVPN,
- Urgent: urgentNow[id] || l.wgUrgent[id],
- Severity: "info",
- Title: "WireGuard disconnect",
- Description: fmt.Sprintf("%s disconnected after %s", name, dur),
- Type: alerts.TypeWireguardDisconnect,
- Vars: map[string]string{"peer": name, "duration": dur},
- Time: "just now",
- RouterID: gwID,
- })
- delete(l.wgActiveSince, id)
- }
- // Connects: newly active peers, skipping the first post-boot cycle
- // (warmup, wgPrimed) y sin dedup de 5 min: cada reconexión es un
- // incidente propio que el operador espera ver (#1443).
- for id := range activeNow {
- if l.wgActive[id] {
- continue
- }
- if l.wgPrimed {
- name := id
- if p, ok := peerByKey[id]; ok {
- name = p.Name
- }
- l.engine.EmitNoDedup(AlertEvent{
- ID: fmt.Sprintf("alert-wg-%s-%d", id, time.Now().UnixMilli()),
- Category: alerts.CatVPN,
- Urgent: urgentNow[id],
- Severity: "info",
- Title: "WireGuard handshake",
- Description: name + " connected",
- Type: alerts.TypeWireguardHandshake,
- Vars: map[string]string{"peer": name},
- Time: "just now",
- RouterID: gwID,
- })
- }
- l.wgActiveSince[id] = time.Now()
- }
- l.wgActive = activeNow
- l.wgPrimed = true
- }
- // roamEchoWindow: durante cuánto tiempo se ignora el salto exactamente inverso
- // al último emitido para la misma MAC (#1740). buildDevices se llama también
- // con la foto cacheada del poll, así que una petición que caiga entre la
- // escritura de la atribución y el refresco de la foto vería el AP anterior y
- // emitiría el salto de vuelta.
- const roamEchoWindow = 10 * time.Minute
- // roamMark: último salto emitido para una MAC.
- type roamMark struct {
- from string
- to string
- at time.Time
- }
- // roamIsEcho: true si (from → to) es el inverso exacto del último salto
- // emitido para esa MAC y está dentro de la ventana de eco.
- func (l *Live) roamIsEcho(mac, from, to string) bool {
- l.roamMu.Lock()
- defer l.roamMu.Unlock()
- m, ok := l.lastRoam[mac]
- if !ok {
- return false
- }
- return m.from == to && m.to == from && time.Since(m.at) < roamEchoWindow
- }
- func (l *Live) markRoam(mac, from, to string, at time.Time) {
- l.roamMu.Lock()
- defer l.roamMu.Unlock()
- if l.lastRoam == nil {
- l.lastRoam = map[string]roamMark{}
- }
- l.lastRoam[mac] = roamMark{from: from, to: to, at: at}
- }
- // wgDuration humanizes a WireGuard session duration as "Xh Ym" (hours and
- // minutes). Negative values collapse to "0h 0m".
- func wgDuration(d time.Duration) string {
- if d < 0 {
- d = 0
- }
- h := int(d.Hours())
- m := int(d.Minutes()) % 60
- return fmt.Sprintf("%dh %dm", h, m)
- }
- // buildDevices: unión de leases + MACs vistas (wireless > FDB satélites >
- // FDB gateway si no hay memoria) + device_attrib (index.js:396-460).
- func (l *Live) buildDevices(polled map[string]*routerPolled, wanPort string) []Device {
- leasesByMac := map[string]DhcpLease{}
- leaseRouter := map[string]string{}
- arpByMac := map[string]string{}
- glByMac := map[string]DhcpLease{}
- resByMac := map[string]DhcpReservation{}
- for rID, p := range polled {
- for mac, ip := range p.arp {
- arpByMac[mac] = ip
- }
- for _, le := range p.leases {
- if le.MAC != "" {
- leasesByMac[le.MAC] = le
- leaseRouter[le.MAC] = rID
- }
- }
- // Static reservations: the name and address pinned in
- // /etc/config/dhcp, and the only ones a client with a fixed address
- // of its own ever gets, since it never takes a lease.
- for _, r := range p.reservations {
- if r.MAC != "" {
- resByMac[r.MAC] = r
- }
- }
- // gl-clients: fallback de IP para MACs sin lease (dnsmasq sin ese
- // cliente). No crea dispositivos: solo enriquece los ya resueltos
- // por wireless/FDB (issue #5 bug 1).
- for _, le := range p.glClients {
- if le.MAC != "" && le.IP != "" {
- glByMac[le.MAC] = le
- }
- }
- }
- // Discovery (#338): aggregate mDNS host-by-IP and random MAC sets from
- // all polled routers. Used to enrich devices below.
- mdnsHostByIP := map[string]string{}
- randomMACs := map[string]bool{}
- mdnsSvcByHost := map[string][]string{}
- for _, p := range polled {
- if p.discovery == nil {
- continue
- }
- for ip, host := range p.discovery.HostByIP {
- mdnsHostByIP[ip] = host
- }
- for _, mac := range p.discovery.RandomMACs {
- randomMACs[mac] = true
- }
- for host, svcs := range p.discovery.Services {
- mdnsSvcByHost[host] = svcs
- }
- }
- type knownInfo struct {
- routerID string
- band string
- signal *int
- }
- known := map[string]knownInfo{}
- if l.db != nil {
- rows, err := l.db.Query("SELECT mac, router_id, band, signal_dbm FROM device_attrib")
- if err == nil {
- defer rows.Close()
- for rows.Next() {
- var mac, routerID, band string
- var signal sql.NullInt64
- if rows.Scan(&mac, &routerID, &band, &signal) == nil {
- k := knownInfo{routerID: routerID, band: band}
- if signal.Valid {
- v := int(signal.Int64)
- k.signal = &v
- }
- known[mac] = k
- }
- }
- }
- }
- now := time.Now().UnixMilli()
- type seenInfo struct {
- routerID string
- band string
- wifiIface string
- ssid string
- signal *int
- }
- seen := map[string]seenInfo{}
- // assocSeen (#1740): en qué routers vio ESTE ciclo a cada MAC. Solo se usa
- // para derivar roams. Si aparece en más de uno el dato es ambiguo (el orden
- // de iteración del mapa decide la atribución), así que no se emite nada.
- assocSeen := map[string][]seenInfo{}
- // (1) wireless de cualquier router: la ÚNICA que se persiste
- for routerID, p := range polled {
- for mac, w := range p.wireless {
- sig := w.SignalDbm
- seen[mac] = seenInfo{routerID: routerID, band: w.Band, wifiIface: w.Iface, ssid: w.SSID, signal: &sig}
- assocSeen[mac] = append(assocSeen[mac], seenInfo{routerID: routerID, band: w.Band, wifiIface: w.Iface, ssid: w.SSID, signal: &sig})
- if l.db != nil {
- _, _ = l.db.Exec(
- `INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(mac) DO UPDATE SET router_id=excluded.router_id, band=excluded.band, signal_dbm=excluded.signal_dbm, last_seen=excluded.last_seen`,
- mac, routerID, w.Band, w.SignalDbm, now)
- }
- }
- }
- // (1c) Roams derivados de la atribución (#1740): una flota agent-only no
- // tiene logread/hostapd que leer, así que el salto de AP se detecta
- // comparando la atribución del ciclo anterior (device_attrib, leída arriba
- // en known) con la de este. El evento entra por roamevents.InsertEvent, el
- // mismo camino que usa el colector SSH, así que la dedup por content_hash
- // y la retención son las mismas.
- if l.db != nil {
- for mac, obs := range assocSeen {
- if len(obs) != 1 {
- continue
- }
- cur := obs[0]
- prev, ok := known[mac]
- if !ok || prev.routerID == "" {
- continue // primera atribución: no es un salto
- }
- var detail string
- switch {
- case prev.routerID != cur.routerID:
- detail = fmt.Sprintf("roamed from %s to %s", prev.routerID, cur.routerID)
- case prev.band != "" && cur.band != "" && prev.band != cur.band:
- detail = fmt.Sprintf("changed band from %s to %s on %s", prev.band, cur.band, cur.routerID)
- default:
- continue
- }
- if l.roamIsEcho(mac, prev.routerID, cur.routerID) {
- continue
- }
- if err := roamevents.InsertEvent(l.db.DB, roamevents.Event{
- TsMs: now,
- RouterID: cur.routerID,
- Type: roamevents.TypeConnected,
- MAC: mac,
- Detail: detail,
- }); err == nil {
- l.markRoam(mac, prev.routerID, cur.routerID, time.UnixMilli(now))
- }
- }
- }
- // (1b) hint wireless-side del FDB (#rotMAC): MACs que el bridge de un
- // router aprende en sus propios puertos de radio pero que la tabla de
- // estaciones no lista (MACs rotadas/aleatorias que siguen emitiendo,
- // clientes en backhaul 4-address). Sin esto la única evidencia que queda
- // es el FDB de tránsito del gateway y su fallback las dibuja como
- // cableadas colgadas del switch. Mandan sobre (2)/(3) pero NO sobre (1):
- // una asociación real de iw es siempre mejor evidencia que un FDB.
- // Orden determinista para MACs vistas por varios routers: ids ordenados y
- // first-wins (cada mapa wirelessSide clavea MACs distintas dentro de un
- // mismo router, así que el único empate posible es entre routers).
- {
- ids := make([]string, 0, len(polled))
- for routerID := range polled {
- ids = append(ids, routerID)
- }
- sort.Strings(ids)
- for _, routerID := range ids {
- p := polled[routerID]
- if p == nil {
- continue
- }
- for mac, band := range p.wirelessSide {
- if _, ok := seen[mac]; ok {
- continue
- }
- seen[mac] = seenInfo{routerID: routerID, band: band}
- // #1818: una MAC local sin IP ni lease no se recuerda.
- _, hasLocalLease := leasesByMac[mac]
- _, localWasKnown := known[mac]
- if l.db != nil && persistLocalMAC(mac, arpByMac[mac], hasLocalLease, localWasKnown) {
- // Sin signal_dbm en el DO UPDATE: el hint no trae RSSI y
- // pisar con NULL el último bueno de una asociación real
- // rompería la serie de señal del dispositivo.
- _, _ = l.db.Exec(
- `INSERT INTO device_attrib (mac, router_id, band, signal_dbm, last_seen) VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(mac) DO UPDATE SET router_id=excluded.router_id, band=excluded.band, last_seen=excluded.last_seen`,
- mac, routerID, band, nil, now)
- }
- }
- }
- }
- l.mu.Lock()
- gw := l.gatewayCfg
- registered := make(map[string]bool, len(l.routers))
- for _, rc := range l.routers {
- registered[rc.ID] = true
- }
- l.mu.Unlock()
- gwID := ""
- if gw != nil {
- gwID = gw.ID
- }
- // A stored attribution outlives the router it names. Deleting a router --
- // or an integration that registered some, as the UniFi scraper did for
- // each AP -- leaves its clients in device_attrib pointing at an id that
- // no longer exists, and every per-router count then attributes them to
- // nothing: the gateway's card showed 18 of the 45 clients it serves.
- // Hand them to the gateway, which is the router actually serving them
- // once the one they remember is gone.
- if gwID != "" {
- for mac, k := range known {
- if k.routerID != "" && !registered[k.routerID] {
- k.routerID = gwID
- known[mac] = k
- }
- }
- }
- // (2) FDB de satélites: pista solo de ESTE tick (no se guarda).
- // REGLA DE RECONCILIACIÓN (issue #656): una MAC aprendida por un satélite
- // en una boca que NO es su uplink (boca no-infra) es un cliente cableado
- // directo de ESE satélite — el FDB la aprendió en un puerto físico suyo.
- // Aunque el gateway también la vea en su FDB (porque el satélite está
- // bridged al mismo segmento L2, como un dumb AP/bridge), la boca local
- // del satélite es la evidencia más específica de dónde va el cable, así
- // que se atribuye al satélite.
- // El uplink queda excluido por infraPorts (boca donde se aprende una MAC
- // de bridge de otro router = tránsito); aquí NO se cuenta.
- // (3) FDB del gateway: solo las MACs que ningún satélite haya reclamado
- // en una boca local, para no quedarse fuera si el gateway las ve en su
- // propio FDB (misma LAN bridged).
- // EXCEPCIÓN preservada: los routers agent-only (switches con agente
- // propio) son la fuente más específica — sus dispositivos se conservan
- // con RouterID del switch (esta ruta ya los trataba por separado).
- // MACs de bridge de todos los routers sondeados: una boca de satélite
- // que aprende una de ellas es un UPLINK (enlaza con otro equipo de red),
- // y lo que aprende por ahí es el resto de la LAN en tránsito, no clientes
- // locales. Sin esto, un switch agent-only (excepción de abajo) se
- // atribuía toda la red vista por su uplink (#291).
- brMacByRouter := map[string]bool{}
- for _, pr := range polled {
- if pr.brMac != "" {
- brMacByRouter[pr.brMac] = true
- }
- }
- for routerID, p := range polled {
- if routerID == gwID {
- continue
- }
- infraPorts := l.uplinkPortsFor(routerID, p.fdb, brMacByRouter)
- for mac, port := range p.fdb {
- if infraPorts[port] {
- continue // uplink: MACs en tránsito, no clientes de este equipo
- }
- if _, ok := seen[mac]; !ok {
- seen[mac] = seenInfo{routerID: routerID, band: "cable"}
- }
- }
- }
- // (3) FDB del gateway: solo si no hay memoria (mala pista; no se guarda)
- if gwID != "" {
- if gwPolled := polled[gwID]; gwPolled != nil {
- for mac := range gwPolled.fdb {
- if _, ok := seen[mac]; !ok {
- if _, ok := known[mac]; !ok {
- seen[mac] = seenInfo{routerID: gwID, band: "cable"}
- }
- }
- }
- }
- }
- // (4) ARP (#507): hosts cableados con IP estática visibles SOLO en la
- // tabla ARP del router (ni wireless, ni FDB, ni lease, ni device_attrib).
- // Se itera en orden de router ID para atribuir deterministamente el
- // RouterID correcto cuando varios routers ven la misma MAC (misma LAN).
- // La exclusión de MACs de router/bridge se aplica en el bucle de
- // dispositivos (routerMacs), igual que para leases/known: aquí no se
- // duplica ese filtro.
- //
- // Presence needs a CONFIRMED neighbour, not merely an entry in the
- // table: the kernel keeps a stale neighbour for minutes after the host
- // has gone, and this branch is the last resort -- the host has no lease,
- // no FDB entry and no wireless association, so nothing else would
- // contradict it. The map then drew a device that is not there, and, with
- // no port either, hung it off the gateway bubble. A host that really is
- // connected answers, so the kernel reconfirms it and it stays; a host
- // that is only remembered drops out on the next tick instead of waiting
- // for the entry to age out. A source that cannot report states (old
- // agent, /proc/net/arp fallback) marks nothing stale and keeps the old
- // behaviour.
- // #1485: el ARP aprendido en el puerto WAN del gateway identifica al
- // primer salto del enlace (ONT/módem en bridge tras PPPoE). Va antes del
- // paso ARP general para que ese MAC no se atribuya como cliente LAN: se
- // marca WanSide y lo dibuja el mapa como peer WAN bajo Internet. Solo si
- // no tiene ya evidencia LAN (la LAN manda) y solo en la boca WAN del
- // gateway, nunca en sus bocas LAN.
- wanSide := map[string]bool{}
- if gwID != "" && wanPort != "" {
- if gwP := polled[gwID]; gwP != nil {
- for mac, dev := range gwP.arpDevs {
- if dev != wanPort {
- continue
- }
- if _, ok := seen[mac]; ok {
- continue
- }
- seen[mac] = seenInfo{routerID: gwID, band: "cable"}
- wanSide[mac] = true
- }
- }
- }
- arpConfirmed := map[string]bool{}
- for _, p := range polled {
- for mac := range p.arp {
- if !p.arpStale[mac] {
- arpConfirmed[mac] = true
- }
- }
- }
- arpRouterIDs := make([]string, 0, len(polled))
- for routerID := range polled {
- arpRouterIDs = append(arpRouterIDs, routerID)
- }
- sort.Strings(arpRouterIDs)
- for _, routerID := range arpRouterIDs {
- for mac := range polled[routerID].arp {
- if _, ok := seen[mac]; ok {
- continue
- }
- if _, ok := known[mac]; ok {
- continue
- }
- if !arpConfirmed[mac] {
- continue
- }
- seen[mac] = seenInfo{routerID: routerID, band: "cable"}
- }
- }
- // (5) Atribución sticky (#678): un cableado que este tick solo aparece en el
- // FDB del gateway por su UPLINK (tránsito) o en la tabla ARP —donde gana el
- // gateway por orden alfabético— recupera el router real donde la memo lo vio
- // por última vez en una boca local. Solo corrige ATRIBUCIÓN: no crea
- // presencia (el dispositivo ya estaba en `seen`). Si el gateway lo ve en una
- // boca NO-uplink, esa evidencia fresca manda y no se toca.
- // Copia bajo l.mu: otras peticiones concurrentes actualizan la memo
- // mientras este bucle la lee.
- l.mu.Lock()
- memo := maps.Clone(l.fdbMemo)
- l.mu.Unlock()
- if gwID != "" && len(memo) > 0 {
- gwPolled := polled[gwID]
- gwInfraPorts := map[string]bool{}
- if gwPolled != nil {
- gwInfraPorts = l.uplinkPortsFor(gwID, gwPolled.fdb, brMacByRouter)
- }
- nowMs := time.Now().UnixMilli()
- ttlMs := fdbStickyTTL.Milliseconds()
- for mac, s := range seen {
- if s.band != "cable" || s.routerID != gwID {
- continue
- }
- m, ok := memo[mac]
- if !ok || nowMs-m.ts > ttlMs || m.routerID == "" || m.routerID == gwID {
- continue
- }
- // El gateway solo lo ve por el uplink (o no lo ve en su FDB): el
- // cable está en el satélite según la última observación local.
- if gwPolled != nil {
- if port, inFdb := gwPolled.fdb[mac]; inFdb && !gwInfraPorts[port] {
- continue // boca local del gateway: evidencia fresca, no tocar
- }
- }
- seen[mac] = seenInfo{routerID: m.routerID, band: "cable"}
- }
- }
- allMacs := map[string]bool{}
- for mac := range leasesByMac {
- allMacs[mac] = true
- }
- for mac := range seen {
- allMacs[mac] = true
- }
- for mac := range known {
- allMacs[mac] = true
- }
- routerMacs := map[string]bool{}
- // issue #196: MACs de bridge de los routers REGISTRADOS (persistidas),
- // no solo las de los routers que sondeó bien en este tick. Un router que
- // falló el sondeo sigue sin ser "cliente desconocido".
- if l.db != nil {
- if rows, err := l.db.Query("SELECT mac FROM routers WHERE mac IS NOT NULL AND mac != ''"); err == nil {
- for rows.Next() {
- var mac string
- if rows.Scan(&mac) == nil {
- routerMacs[mac] = true
- }
- }
- rows.Close()
- }
- }
- // #1206: los BSSID propios de la flota (reportados por los agentes,
- // #1087) son infraestructura, no clientes: sin esto aparecían en la
- // tabla de clientes al dejar de filtrarse por la retención de #1145.
- if l.agents != nil {
- for _, b := range l.agents.LocalBssids() {
- routerMacs[b] = true
- }
- }
- for _, p := range polled {
- if p.brMac != "" {
- routerMacs[p.brMac] = true
- }
- // #1489: identidades del propio switch (MACs de su puerto interno/CPU).
- // Un vecino las aprende al gestionarlo y sin esto salen como clientes.
- for _, mac := range p.selfMacs {
- routerMacs[strings.ToUpper(mac)] = true
- }
- }
- // #1489: la MAC que responde por la IP de gestion de una unidad de flota es
- // la propia unidad (pila de mgmt del switch), no un cliente: su FDB la ve en
- // el puerto interno y las FDB vecinas la aprenden al gestionarla. Se absorbe
- // junto a las MACs de bridge. Si el Host es un nombre, no casa con ninguna IP
- // de ARP y no absorbe nada.
- mgmtHosts := map[string]bool{}
- for _, p := range polled {
- if p.cfg.Host != "" {
- mgmtHosts[p.cfg.Host] = true
- }
- }
- l.mu.Lock()
- for _, rc := range l.routers {
- if rc.Host != "" {
- mgmtHosts[rc.Host] = true
- }
- }
- l.mu.Unlock()
- if len(mgmtHosts) > 0 {
- for _, p := range polled {
- for mac, ip := range p.arp {
- if mgmtHosts[ip] {
- routerMacs[strings.ToUpper(mac)] = true
- }
- }
- }
- }
- // #1791: el vecino de la ruta por defecto del gateway (su siguiente salto
- // WAN) no es un cliente de la LAN. Aparecía en la lista porque su MAC está
- // en la tabla ARP y ninguna otra evidencia lo reclamaba. Se absorbe por la
- // IP de la puerta de enlace WAN, no por un prefijo de MAC ni por un puerto,
- // que en PPPoE no existe.
- defaultRouteMacs := map[string]bool{}
- for _, p := range polled {
- gwIP := strings.TrimSpace(p.wanInfo.Gateway)
- if gwIP == "" {
- continue
- }
- for mac, ip := range p.arp {
- if strings.TrimSpace(ip) == gwIP {
- defaultRouteMacs[strings.ToUpper(mac)] = true
- }
- }
- }
- // issue #196: allowlist de dispositivos confiables (mac → alias).
- knownMacs := map[string]string{}
- if l.db != nil {
- if rows, err := l.db.Query("SELECT mac, name FROM known_macs"); err == nil {
- for rows.Next() {
- var mac, name string
- if rows.Scan(&mac, &name) == nil {
- knownMacs[mac] = name
- }
- }
- rows.Close()
- }
- }
- // issue #437/#797: overrides manuales de dispositivo (icono, nombre
- // visible y tipo) sobre el dispositivo auto-descubierto.
- deviceOverrides := l.loadDeviceOverrides()
- lldpCapsByMac := map[string]string{}
- for _, p := range polled {
- for _, nb := range p.lldp {
- if nb.ChassisMac != "" && len(nb.Caps) > 0 {
- lldpCapsByMac[nb.ChassisMac] = strings.Join(nb.Caps, ",")
- }
- }
- }
- devices := []Device{}
- for mac := range allMacs {
- if routerMacs[mac] || defaultRouteMacs[strings.ToUpper(mac)] {
- continue // los routers y la ruta por defecto no son clientes
- }
- if isBatadvBlaMAC(mac) {
- continue // #1818: sonda LOOP DETECT del mesh, no es un host
- }
- lease, hasLease := leasesByMac[mac]
- s, isSeen := seen[mac]
- // Fabricante desconocido = campo VACÍO, no un literal. El server no
- // tiene idioma: "Desconocido" viajaba tal cual hasta la UI y salía en
- // español en una interfaz en inglés. Quien pinta, traduce.
- manufacturer := oui.Lookup(mac)
- defaultRouterID := gwID
- if defaultRouterID == "" {
- if rID, ok := leaseRouter[mac]; ok {
- defaultRouterID = rID
- }
- }
- d := Device{
- ID: strings.ToLower(strings.ReplaceAll(mac, ":", "-")),
- MAC: mac, Manufacturer: manufacturer,
- TrafficMbps: 0, Sparkline: []float64{},
- RouterID: defaultRouterID, Band: "—",
- Online: isSeen, WanSide: wanSide[mac],
- }
- res, hasRes := resByMac[mac]
- if hasLease {
- switch {
- case lease.Hostname != "":
- d.Name = lease.Hostname
- case hasRes && res.Name != "":
- d.Name = res.Name
- default:
- d.Name = mac
- }
- d.IP = lease.IP
- if lease.LeaseExpiresAt != nil {
- remaining := int(*lease.LeaseExpiresAt - now/1000)
- if remaining < 0 {
- remaining = 0
- }
- d.LeaseRemaining = &remaining
- }
- } else {
- d.Name = mac
- // The name pinned in /etc/config/dhcp: a client with a fixed
- // address of its own never takes a lease, so this is the only
- // name the router has for it.
- if hasRes {
- if res.Name != "" {
- d.Name = res.Name
- }
- d.IP = res.IP
- }
- // Fallback gl-clients (GL.iNet): el cliente no tiene lease pero el
- // firmware sí conoce su IP (y a veces nombre). (issue #5 bug 1)
- if gl, ok := glByMac[mac]; ok {
- d.IP = gl.IP
- if gl.Hostname != "" {
- d.Name = gl.Hostname
- }
- }
- }
- // Fallback ARP (#377): el DHCP vive en otro equipo, pero cualquier
- // router de la flota que enrute la LAN conoce la MAC→IP.
- if d.IP == "" {
- if ip, ok := arpByMac[mac]; ok {
- d.IP = ip
- }
- }
- // issue #196: la allowlist manda sobre el nombre por defecto. Con
- // alias (Name != MAC) el dispositivo deja de ser "desconocido".
- if alias, ok := knownMacs[mac]; ok && alias != "" {
- d.Name = alias
- }
- // issue #437/#797: overrides manuales (icono, nombre) se aplican sobre
- // el dispositivo auto-descubierto; el nombre manual manda incluso
- // sobre el alias de la allowlist.
- if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
- if ov.Icon != "" {
- d.IconOverride = ov.Icon
- }
- if ov.Name != "" {
- d.Name = ov.Name
- d.NameOverride = ov.Name
- }
- }
- vendorClass := ""
- clientID := ""
- if hasLease {
- vendorClass = lease.VendorClass
- clientID = lease.ClientID
- }
- // Tipo estimado con reglas deterministas (hostname, huella DHCP y
- // capacidades LLDP). Con nombre-MAC (sin hostname) queda "desconocido".
- d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
- // mDNS enrichment (#338): resolve hostname from IP → lookup services.
- if d.IP != "" {
- if host, ok := mdnsHostByIP[d.IP]; ok {
- if svcs, ok := mdnsSvcByHost[host]; ok {
- d.MdnsServices = svcs
- }
- // If the device has no name (just MAC), use the mDNS hostname.
- if d.Name == mac {
- d.Name = host
- }
- }
- }
- // Static-IP hosts never take a lease: fall back to their PTR record.
- if d.Name == mac && d.IP != "" {
- if host := l.rdns.Name(d.IP); host != "" {
- d.Name = host
- // The type above was guessed from the MAC, which says
- // nothing. Guess it again now that there is a hostname.
- d.Type = GuessDeviceType(d.Name, d.Manufacturer, vendorClass, clientID, lldpCapsByMac[mac])
- }
- }
- // #1818: el bit localmente administrado se calcula aquí. La lista del
- // agente es una foto del escaneo de discovery, así que una MAC
- // efímera (el NMRP de Netgear al reiniciar para actualizar firmware)
- // vive en el FDB unos segundos y nunca entra en ella.
- if randomMACs[mac] || isLocallyAdministeredMAC(mac) {
- d.RandomMAC = true
- }
- // mDNS-based type refinement (#338): if the hostname/DHCP classification
- // yielded "desconocido" but mDNS services are available, try to classify.
- if d.Type == "desconocido" && len(d.MdnsServices) > 0 {
- d.Type = guessFromMdns(d.MdnsServices)
- }
- // issue #797: el tipo manual manda sobre la clasificación (reglas,
- // huella DHCP y refinación mDNS).
- if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok && ov.DeviceType != "" {
- d.Type = ov.DeviceType
- d.TypeOverride = ov.DeviceType
- }
- // #1354: flag opt-in de alerta por desconexión (override persistido).
- if ov, ok := deviceOverrides[strings.ToLower(mac)]; ok {
- d.NotifyOffline = ov.NotifyOffline
- }
- if isSeen {
- d.RouterID = s.routerID
- d.Band = s.band
- d.WifiIface = s.wifiIface
- d.SSID = s.ssid
- d.SignalDbm = s.signal
- } else if k, ok := known[mac]; ok {
- d.RouterID = k.routerID
- d.Band = k.band
- d.SignalDbm = k.signal
- } else if rID, ok := leaseRouter[mac]; ok && d.RouterID == "" {
- d.RouterID = rID
- }
- // #551: TrafficMbps del cliente desde el rate en memoria (nlbwmon u
- // hostapd) sin consultar la store en cada rebuild. Solo online; los
- // offline no tienen rate (la UI pinta "—").
- if isSeen {
- if rxBps, txBps := l.clientBwRateFor(mac); rxBps+txBps > 0 {
- d.TrafficMbps = (rxBps + txBps) / 1e6
- }
- }
- devices = append(devices, d)
- }
- // #1757: la VLAN de un cliente sale de la evidencia exacta del bridge (la
- // VLAN con la que aprendió su MAC), no del PVID del puerto por el que
- // entró. Solo rellena el hueco: el `tag=` que declara el hipervisor para un
- // invitado manda y se aplica después.
- for i := range devices {
- if devices[i].Vlan > 0 || devices[i].MAC == "" {
- continue
- }
- if p := polled[devices[i].RouterID]; p != nil {
- if v := p.fdbVlans[strings.ToUpper(devices[i].MAC)]; v > 0 {
- devices[i].Vlan = v
- devices[i].VlanKnown = true
- }
- }
- }
- // Give clients learned only in an SNMP switch's FDB a traffic figure from
- // that port's counters (see switchporttraffic.go).
- l.applySnmpSwitchPortTraffic(polled, devices)
- // Orden estable por MAC (issue #656): buildDevices itera un mapa de Go
- // (allMacs), cuyo orden es aleatorio entre ticks. Ese orden llega al
- // frontend y alimenta la asignación de ranuras de los anillos de la
- // topología → los chips saltaban de posición al refrescar. Ordenar por
- // MAC hace el contrato determinista para el mismo set de dispositivos.
- sort.Slice(devices, func(i, j int) bool { return devices[i].MAC < devices[j].MAC })
- // #1151: canónicas + fusión de enlazadas (orden: normalizar -> fusionar).
- return normalizeDevices(mergeLinkedDevices(devices, l.deviceLinks()))
- }
- // normalizeDevices: MACs a formato canónico (mayúsculas, ':') y dedup por
- // MAC. La caché gl-clients de GL.iNet emite MACs con guiones y entradas
- // caducadas: sin normalizar el mismo cliente puede aparecer duplicado
- // (#1145). Gana la entrada online; hostname/IP/fabricante de la descartada
- // enriquecen a la conservada.
- func normalizeDevices(devices []Device) []Device {
- byMac := make(map[string]int, len(devices))
- out := make([]Device, 0, len(devices))
- for _, d := range devices {
- mac := strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(d.MAC), "-", ":"))
- d.MAC = mac
- if i, ok := byMac[mac]; ok {
- a, b := out[i], d
- if b.Online && !a.Online {
- a, b = b, a
- }
- if a.Hostname == "" {
- a.Hostname = b.Hostname
- }
- if a.IP == "" {
- a.IP = b.IP
- }
- if a.Manufacturer == "" {
- a.Manufacturer = b.Manufacturer
- }
- if a.Name == "" {
- a.Name = b.Name
- }
- out[i] = a
- continue
- }
- byMac[mac] = len(out)
- out = append(out, d)
- }
- return out
- }
- // emitTempAlert emite la alerta de temperatura alta UNA vez por proceso
- // (flag, como el JS), usando el umbral del router (issue #716; default 65).
- // Debe llamarse con l.mu tomado.
- func (l *Live) emitTempAlert(cfg RouterConfig, router Router) {
- thr := cfg.TempThresholdValue()
- if router.Temp == nil || *router.Temp <= thr || l.lastStatus[cfg.ID+":temp"] == "warn" {
- return
- }
- l.lastStatus[cfg.ID+":temp"] = "warn"
- l.engine.Emit(AlertEvent{
- ID: fmt.Sprintf("alert-temp-%s-%d", cfg.ID, time.Now().UnixMilli()),
- Category: alerts.CatRouter, Urgent: true,
- Severity: "warn",
- Title: "High temperature on " + router.Name,
- Description: fmt.Sprintf("%d °C, above the threshold (%d °C)", *router.Temp, thr),
- Hint: alerts.HintFor(alerts.HintHighTemp),
- Type: alerts.HintHighTemp,
- Vars: map[string]string{"router": router.Name, "temp": strconv.Itoa(*router.Temp), "threshold": strconv.Itoa(thr)},
- Time: "just now", RouterID: cfg.ID,
- })
- }
- // computeHealth (index.js:462-486).
- func computeHealth(routers []Router, adguard *AdGuardStats, wg *WireGuardStats) HealthScore {
- score := 100
- breakdown := []HealthDelta{}
- wanScore := 100
- wifiScore := 100
- infraScore := 100
- svcScore := 100
- for _, r := range routers {
- if r.Status == "offline" {
- score -= 30
- infraScore -= 40
- breakdown = append(breakdown, HealthDelta{Label: r.Name + " offline", Delta: -30})
- } else if r.Temp != nil {
- thr := r.TempThreshold
- if thr <= 0 {
- thr = DefaultTempThreshold
- }
- if *r.Temp > thr {
- score -= 8
- infraScore -= 10
- breakdown = append(breakdown, HealthDelta{Label: "temp. " + r.Name, Delta: -8})
- }
- }
- }
- if adguard != nil && adguard.Status != "active" {
- score -= 5
- svcScore -= 20
- breakdown = append(breakdown, HealthDelta{Label: "AdGuard inactivo", Delta: -5})
- }
- // #1442: VPN en la nota de salud. "inactive" con interfaces descubiertas
- // = túnel caído (quirk #714: sin interfaces WireGuard en el router el
- // estado también es "inactive", pero Interface queda vacío y NO se
- // penaliza: no hay nada que vigilar). Con la interfaz caída no se
- // cuentan peers: están caídos por ella, no por sí mismos (no doble
- // penalización). Cada peer importante (urgente, #1441) caído resta
- // acotado para que uno solo no domine la nota.
- if wg != nil && wg.Status != "active" && wg.Interface != "" {
- score -= 10
- svcScore -= 15
- breakdown = append(breakdown, HealthDelta{Label: "WireGuard caído", Delta: -10})
- } else if wg != nil {
- urgentDown := []string{}
- for _, p := range wg.Peers {
- if p.Urgent && !p.Active {
- urgentDown = append(urgentDown, p.Name)
- }
- }
- if len(urgentDown) > 0 {
- delta := 6 * len(urgentDown)
- if delta > 12 {
- delta = 12
- }
- score -= delta
- svcScore -= delta + 3
- if len(urgentDown) == 1 {
- breakdown = append(breakdown, HealthDelta{Label: "peer WireGuard " + urgentDown[0] + " caído", Delta: -delta})
- } else {
- breakdown = append(breakdown, HealthDelta{Label: fmt.Sprintf("%d peers WireGuard importantes caídos", len(urgentDown)), Delta: -delta})
- }
- }
- }
- if score < 0 {
- score = 0
- }
- if wanScore < 0 {
- wanScore = 0
- }
- if wifiScore < 0 {
- wifiScore = 0
- }
- if infraScore < 0 {
- infraScore = 0
- }
- if svcScore < 0 {
- svcScore = 0
- }
- label := "Atención"
- if score >= 85 {
- label = "Excelente"
- } else if score >= 65 {
- label = "Bueno"
- }
- note := "Sin penalizaciones."
- if len(breakdown) > 0 {
- labels := make([]string, len(breakdown))
- for i, b := range breakdown {
- labels[i] = b.Label
- }
- note = "Penalizado por: " + strings.Join(labels, ", ") + "."
- }
- return HealthScore{
- Score: score, Label: label, Caption: "Puntuación de salud de la red",
- Note: note, Breakdown: breakdown,
- Subscores: []Subscore{
- {Key: "wan", Label: "WAN", Score: wanScore},
- {Key: "wifi", Label: "WiFi", Score: wifiScore},
- {Key: "infra", Label: "Infra", Score: infraScore},
- {Key: "services", Label: "Servicios", Score: svcScore},
- },
- }
- }
- // defaultWan (index.js:488-503).
- func (l *Live) defaultWan(gw *RouterConfig) WAN {
- l.mu.Lock()
- var p *routerPolled
- if gw != nil {
- p = l.lastPolled[gw.ID]
- }
- l.mu.Unlock()
- wan := WAN{
- Plan: "—", PublicIP: "—", Isp: "—", PeakTodayTime: "—", Total24h: 0,
- }
- if p != nil {
- if p.net != nil {
- wan.DownMbps = mbps(p.net.RxBps)
- wan.UpMbps = mbps(p.net.TxBps)
- }
- if p.latencyMs != nil {
- wan.LatencyMs = *p.latencyMs
- }
- if p.lossPct != nil {
- wan.LossPct = *p.lossPct
- }
- // Conexión WAN real (issue #276): proto/IP/gateway/DNS desde ubus.
- if wi := p.wanInfo; wi.IP != "" || wi.Proto != "" {
- wan.Proto = wi.Proto
- if wi.IP != "" {
- wan.PublicIP = wi.IP
- }
- wan.Gateway = wi.Gateway
- wan.DNS = wi.DNS
- }
- }
- // Resumen del día desde la BD (issue #169): pico de hoy, media y total
- // 24h solo los poblaba el modo demo; aquí se calculan con la tabla raw.
- if gw != nil {
- ds := l.wanDayStats(gw.ID)
- wan.PeakTodayMbps = ds.peakMbps
- wan.PeakTodayTime = ds.peakTime
- wan.AvgDownMbps = ds.avgMbps
- wan.Total24h = ds.totalBytes
- // #2047: el mismo resumen, por rango, para que las cifras de debajo
- // de la gráfica sigan al rango seleccionado.
- wan.RangeStats = l.wanRangeStats(gw.ID)
- }
- return wan
- }
- // GetOverview: single-flight (los llamantes concurrentes comparten sondeo).
- // Si buildOverview paniquea, el líder lo transforma en error y todos los
- // seguidores reciben ese error en vez de bloquear para siempre.
- func (l *Live) GetOverview(ctx context.Context) (ov *Overview, err error) {
- l.sfMu.Lock()
- if c := l.sfCall; c != nil {
- l.sfMu.Unlock()
- <-c.done
- return c.ov, c.err
- }
- c := &sfCall{done: make(chan struct{})}
- l.sfCall = c
- l.sfMu.Unlock()
- defer func() {
- if r := recover(); r != nil {
- err = fmt.Errorf("panic en buildOverview: %v\n%s", r, debug.Stack())
- ov = nil
- }
- c.ov, c.err = ov, err
- close(c.done)
- l.sfMu.Lock()
- l.sfCall = nil
- l.sfMu.Unlock()
- }()
- return l.buildOverview(ctx)
- }
- // fillSparklineFromPorts rellena la línea de 24 h de las unidades que no
- // publican serie propia de throughput (switch beacon, SNMP sin métricas
- // agregadas, pusher external): sale de sus puertos en port_series, no de la
- // tabla metrics (siempre 0 ahí).
- //
- // #1741: la condición no puede colgar de VitalsAvailable (un pusher que
- // confirma CPU/temp la deja en true y el respaldo nunca corría) y un pusher
- // RouterOS/AsusWRT manda tasas por boca en vez de contadores de tramas, así
- // que se prueba primero la serie en bps y se cae a frames solo si está vacía.
- func (l *Live) fillSparklineFromPorts(routerList []Router) {
- for i := range routerList {
- l.fillSparklineFromPortsOne(&routerList[i])
- }
- }
- // fillSparklineFromPortsOne aplica el respaldo de #1741 a un solo router.
- // #1871: el detalle de la unidad construye con buildRouter sin pasar por
- // buildOverview, así que la línea de 24 h del detalle seguía a cero en un
- // pusher aunque la tarjeta de flota ya estuviera bien.
- func (l *Live) fillSparklineFromPortsOne(r *Router) {
- if l.db == nil || l.db.PortSeries == nil || r == nil {
- return
- }
- if !r.sparklineFromPorts || !allZeroF(r.Sparkline) {
- return
- }
- if sp, err := l.db.PortSeries.HourlyBpsTotal(r.ID, len(r.Sparkline)); err == nil && len(sp) > 0 && !allZeroF(sp) {
- r.Sparkline = sp
- return
- }
- if sp, err := l.db.PortSeries.HourlyFpsTotal(r.ID, len(r.Sparkline)); err == nil && len(sp) > 0 && !allZeroF(sp) {
- r.Sparkline = sp
- }
- }
- func (l *Live) buildOverview(ctx context.Context) (*Overview, error) {
- polled := l.pollAll(ctx)
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- gw := l.gatewayCfg
- l.mu.Unlock()
- routerList := make([]Router, 0, len(routers))
- for _, cfg := range routers {
- p := polled[cfg.ID]
- if cfg.Disabled {
- // #1085: unidad pausada: última snapshot conocida (o el
- // esqueleto) con estado "paused"; nunca offline ni alerta.
- routerList = append(routerList, l.pausedRouter(cfg))
- continue
- }
- if p == nil {
- l.mu.Lock()
- prev := l.lastGood[cfg.ID]
- fails := l.failCount[cfg.ID]
- l.mu.Unlock()
- if prev != nil && fails < 2 {
- routerList = append(routerList, *prev)
- } else {
- routerList = append(routerList, l.offlineRouter(cfg))
- }
- continue
- }
- router := l.buildRouter(p, l.metricsHistory(cfg.ID, "24h"))
- l.mu.Lock()
- l.lastGood[cfg.ID] = &router
- l.emitTempAlert(cfg, router)
- l.mu.Unlock()
- routerList = append(routerList, router)
- }
- // #656/#678: refrescar la memo sticky ANTES de buildDevices (su paso 5 la
- // usa para atribuir al satélite los dispositivos callados) y usarla también
- // como overlay de inferTopology (puerto/attachTo).
- nowMs := time.Now().UnixMilli()
- memo := l.updateFdbMemo(polled, nowMs)
- // #1485: buildDevices necesita la boca WAN (ARP del primer salto del
- // enlace); sale del estado WAN del propio sondeo del gateway.
- wanPort := ""
- if gw != nil {
- if gp := polled[gw.ID]; gp != nil {
- wanPort = gp.wanInfo.Port
- }
- }
- devices := l.buildDevices(polled, wanPort)
- stickyPolled := overlayStickyFdb(polled, memo, nowMs)
- devices, distNodes := inferTopology(stickyPolled, devices)
- // Capa 2 manual (issue #142): overrides de topología tras el autodiscover.
- // Sin BD (tests/demo) → no-op.
- var overrides []TopologyOverride
- if l.db != nil {
- overrides = loadTopologyOverrides(l.db)
- devices, distNodes = applyTopologyOverrides(routerList, devices, distNodes, overrides)
- }
- // Capa 3 PVE (#561): si hay cluster Proxmox configurado, el inventario
- // read-only sella hypervisor/ct con attachTo correcto (la relación
- // CT→host no es deducible del L2) y crea los distnodes kind=hypervisor
- // para que el frontend anide los CTs bajo el host. Va DESPUÉS de los
- // overrides manuales: un override explícito del usuario tiene prioridad
- // sobre el sello.
- distNodes = l.sealProxmoxInfra(devices, distNodes)
- // Supresión topológica (#332): actualizar grafo parent→child.
- // Todos los no-gateway cuelgan del gateway.
- l.mu.Lock()
- if gw != nil && l.suppression != nil {
- parents := map[string]string{}
- for _, r := range routers {
- if r.ID != gw.ID {
- parents[r.ID] = gw.ID
- }
- }
- l.suppression.SetTopology(parents)
- }
- l.mu.Unlock()
- // Aviso de señal débil con ciclo de vida completo (#1452): un episodio
- // abierto por MAC, disparo con guarda de 24 h entre episodios y cierre
- // automático cuando la señal se mantiene por encima del umbral + margen
- // de histéresis durante N muestras consecutivas. Un cliente sin datos
- // (offline o sin señal reportada) no cuenta como recuperado. La
- // itinerancia no abre ni cierra nada: se juzga la señal del cliente.
- var weakSignalDB *sql.DB
- if l.db != nil {
- weakSignalDB = l.db.DB
- }
- weakDbm := alerts.WeakSignalDbm(weakSignalDB)
- weakHyst := alerts.WeakSignalHysteresisDbm(weakSignalDB)
- weakSamples := alerts.WeakSignalResolveSamples(weakSignalDB)
- weakNow := time.Now().UnixMilli()
- for i := range devices {
- d := &devices[i]
- l.mu.Lock()
- st := l.weakStates[d.MAC]
- fireID, resolveID, episodeStart := alerts.WeakSignalStep(&st, d.MAC, d.SignalDbm, d.Online, weakDbm, weakHyst, weakSamples, weakNow)
- l.weakStates[d.MAC] = st
- if fireID != "" || resolveID != "" {
- routerName := l.routerDisplayName(d.RouterID)
- if routerName == "" {
- routerName = d.RouterID
- }
- if fireID != "" {
- l.engine.Emit(AlertEvent{
- ID: fireID,
- Category: alerts.CatSignal, Urgent: false,
- Severity: "warn", Title: "Weak signal on " + d.Name,
- Description: fmt.Sprintf("%d dBm on %s - check coverage or move closer to an AP", *d.SignalDbm, routerName),
- Hint: alerts.HintFor(alerts.HintWifiWeak),
- Type: alerts.HintWifiWeak,
- Vars: map[string]string{"device": d.Name, "signal": strconv.Itoa(*d.SignalDbm), "router": routerName},
- Time: "just now", RouterID: d.RouterID,
- })
- }
- if resolveID != "" {
- // El episodio cerrado se conserva en el log con su ts de
- // cierre (#1349); el evento ok referencia qué cierra y lleva
- // el valor de recuperación y la duración del episodio. Si el
- // usuario desestimó la alerta a mano antes, no se emite el
- // cierre (su ID ya no está en el feed).
- wasOpen := l.engine.Has(resolveID)
- l.engine.Resolve(resolveID)
- if wasOpen {
- l.emitWeakRecovered(d, routerName, resolveID, episodeStart, weakNow)
- }
- }
- }
- l.mu.Unlock()
- }
- // #1292: lápidas filtradas de la lista final (una estación stale del AP
- // re-emite la MAC en cada ciclo sin pasar por device_seen).
- devices = l.filterTombstoned(devices)
- // #1818: fuera los MAC que duran menos de un minuto, ANTES de alertar de
- // desconocidos y de escribir en device_seen.
- devices = l.settleTransient(devices, time.Now().UnixMilli())
- l.trackUnknownDevices(devices, distNodes)
- l.trackWiFiNoIP(devices, distNodes)
- l.trackOfflineDevices(devices)
- l.trackDevicePresence(devices, time.Now().UnixMilli())
- // #954: first/last seen persistente de TODOS los clientes online.
- // #1323: los que entran al registro por primera vez CON nombre alertan
- // ("new client"); los sin nombre los cubre unknown-device (#234).
- firstTimers := l.noteDevicesSeen(devices, time.Now().UnixMilli())
- l.trackNewClients(firstTimers, devices, distNodes)
- // #1095: el overview (snapshot SSE del que vive la tabla de clientes)
- // escribía las marcas pero NUNCA las aplicaba: la UI en vivo mostraba
- // "—" aunque la API REST las tuviera (sólo los detalles las aplicaban).
- l.applyDeviceSeen(devices)
- // #1145: retención indefinida - clientes del registro que ya no se ven
- // en ninguna fuente viva salen como offline (con último nombre y seen).
- // El overview es el snapshot SSE del que vive la tabla de clientes.
- devices = append(devices, l.ghostDevices(devices)...)
- // Clientes reales por router (atribución wireless/FDB, no leases)
- countClientsPerRouter(routerList, devices)
- // Sparkline de la tarjeta para fuentes sin throughput bps (#1741).
- l.fillSparklineFromPorts(routerList)
- adguard := l.pollAdGuard(ctx)
- wireguard := l.pollWireGuard(devices)
- gwID := ""
- if gw != nil {
- gwID = gw.ID
- }
- // MACs registradas (routers.mac): permiten a fleetFdbEvidence anclar
- // unidades sin bridge MAC utilizable (DSM: docker0 en bridgeDetect, sin
- // lldpd) desde el FDB del switch que aprende su NIC (p. ej. NAS en xg4).
- registeredMacs := make(map[string]string, len(routerList))
- for _, r := range routerList {
- if r.MAC != "" {
- registeredMacs[r.ID] = r.MAC
- }
- }
- // #1279: uplinks resueltos por LLDP (regla de puerto raíz); mandan sobre
- // la evidencia FDB/device en BuildTopoSemantics. Se calcula ANTES que la
- // FDB para sembrar profundidades: un switch core cuya MAC de chasis nadie
- // aprende no tiene candidato padre por FDB y, sin semilla, su profundidad
- // queda desconocida y las unidades cableadas en él caen al gateway.
- lldpEvidence := fleetLldpEvidence(polled, gwID)
- seedDepth := map[string]int{}
- {
- seedDepth[gwID] = 0
- for pass := 0; pass <= len(lldpEvidence); pass++ {
- changed := false
- for child, ev := range lldpEvidence {
- if d, ok := seedDepth[ev.parent]; ok {
- if _, has := seedDepth[child]; !has || seedDepth[child] > d+1 {
- seedDepth[child] = d + 1
- changed = true
- }
- }
- }
- if !changed {
- break
- }
- }
- }
- fdbEvidence := fleetFdbEvidence(polled, gwID, registeredMacs, seedDepth)
- // #1321: los attaches manuales (#142) cuya MAC es la bridge de una unidad
- // de flota fijan su uplink por encima de toda inferencia.
- overrideUplinks := fleetOverrideEvidence(overrides, routerList)
- wan := l.defaultWan(gw)
- for _, r := range routerList {
- if r.ID == gwID && r.Status == "offline" {
- wan.PublicIP = "—"
- }
- }
- trafficOf := func(rang string) []TrafficPoint {
- h := l.metricsHistory(gwID, rang)
- out := make([]TrafficPoint, 0, len(h))
- for _, p := range h {
- out = append(out, TrafficPoint{T: p.t, Down: p.down, Up: p.up})
- }
- return out
- }
- ag := AdGuardStats{Status: "inactive", TopBlocked: []TopBlocked{}}
- if adguard != nil {
- ag = *adguard
- }
- wgStats := WireGuardStats{Interface: l.cfg.WGInterface, Subnet: "", Status: "inactive", Peers: []WGPeer{}}
- if wireguard != nil {
- wgStats = *wireguard
- }
- online := 0
- for _, d := range devices {
- if d.Online {
- online++
- }
- }
- top := append([]Device(nil), devices...)
- sort.SliceStable(top, func(i, j int) bool { return top[i].TrafficMbps > top[j].TrafficMbps })
- if len(top) > 5 {
- top = top[:5]
- }
- // #1051: evidencia FDB directa para anclar uplinks de flota sin depender
- // de que la unidad aparezca como device (la MAC bridge de cada router
- // aprendida en el FDB de otro miembro dice dónde cuelga).
- // El motor de alertas es el dueño de la lista y del read-state
- // (SPEC-ALERTAS §3-4): UnreadAlerts = no leídas que pasaron config.
- alertsCopy := l.engine.List()
- unread := l.engine.UnreadCount()
- usteerAvailable := l.usteerAvailableCached()
- dawnDetected := dawnDeprecatedFromPolled(polled)
- // #1417: los clientes cableados que la FDB de un switch de flota aprendió
- // en un puerto no-raíz cuelgan físicamente de él (switches SNMP externos
- // de #1137 incluidos). Antes de la semántica: los blobs del gateway que
- // queden vacíos los absorbe después #1374 sin dejar huérfanos.
- claimSwitchFdbClients(polled, devices, distNodes, gwID, fdbEvidence, lldpEvidence, overrideUplinks)
- topo := BuildTopoSemantics(routerList, devices, wgStats, distNodes, wan.Gateway, fdbEvidence, lldpEvidence, overrideUplinks) // SPEC-65 D65-3 + #1042/#1051/#1279/#1321
- // #1374: retirar de la lista que ve el frontend los distnodes absorbidos
- // como sombra de un switch gestionado. Slice NUEVO: filtrar in situ
- // reescribe el backing array compartido y duplica el último (#1378).
- if len(topo.AbsorbedDists) > 0 {
- absorbed := map[string]bool{}
- for _, id := range topo.AbsorbedDists {
- absorbed[id] = true
- }
- filtered := make([]DistributionNode, 0, len(distNodes))
- for _, dn := range distNodes {
- if !absorbed[dn.ID] {
- filtered = append(filtered, dn)
- }
- }
- distNodes = filtered
- }
- fillUplinkSpeeds(polled, distNodes, topo.Links)
- fillWiredSpeeds(polled, distNodes, topo.Links) // #1384
- // #1429/#1471: la boca del hijo sale de la evidencia que resolvió el
- // enlace, sea FDB o LLDP (el vecino LLDP guarda el puerto local). Misma
- // precedencia que BuildTopoSemantics al construir el enlace: LLDP manda y
- // la FDB rellena los huecos.
- childEvidence := make(map[string]topoParent, len(fdbEvidence)+len(lldpEvidence))
- for id, ev := range fdbEvidence {
- childEvidence[id] = ev
- }
- for id, ev := range lldpEvidence {
- childEvidence[id] = ev
- }
- fillUplinkSpeedsFromChild(polled, childEvidence, topo.Links)
- return &Overview{
- Health: computeHealth(routerList, adguard, wireguard),
- WAN: wan,
- Traffic: TrafficByRange{H1: trafficOf("1h"), H24: trafficOf("24h"), D7: trafficOf("7d"), D30: trafficOf("30d")},
- Adguard: ag, Wireguard: wgStats, Routers: routerList,
- DeviceTotals: DeviceTotals{
- Total: len(devices), Online: online, KnownOffline: len(devices) - online,
- NewToday: countNewToday(devices),
- },
- TopDevices: top, Alerts: alertsCopy, UnreadAlerts: unread,
- DistributionNodes: distNodes,
- Topology: topo,
- Devices: devices,
- Usteer: &UsteerOverview{Available: usteerAvailable},
- DawnDeprecated: dawnDetected,
- RoamingDaemon: classifyRoamingDaemon(usteerAvailable, dawnDetected),
- VM: ViewModelVersion, // SPEC-65 D65-4
- Ts: time.Now().Unix(),
- }, nil
- }
- // emitWeakRecovered emite el cierre del episodio de señal débil (#1452).
- // El cierre lleva ID ESTABLE por MAC (alert-weak-<mac>-ok) y va con
- // EmitOrUpdate (#1518): un episodio nuevo del mismo dispositivo REEMPLAZA la
- // entrada anterior en el log en vez de apilar otra "resuelta" idéntica (un
- // cliente que oscila de cobertura dejaba dos cierres iguales a los 27 min).
- // El histórico de episodios no se pierde: queda en los avisos originales
- // (warn), marcados como resueltos por #1349. Se llama con l.mu tomado, igual
- // que el resto de emisiones del bucle de dispositivos.
- func (l *Live) emitWeakRecovered(d *Device, routerName, resolveID string, episodeStart, weakNow int64) {
- recSignal := ""
- if d.SignalDbm != nil {
- recSignal = strconv.Itoa(*d.SignalDbm)
- }
- durMin := int((weakNow - episodeStart) / 60000)
- dur := "<1 min"
- if durMin >= 1 {
- dur = fmt.Sprintf("%d min", durMin)
- }
- l.engine.EmitOrUpdate(AlertEvent{
- ID: fmt.Sprintf("alert-weak-%s-ok", d.MAC),
- Category: alerts.CatSignal, Urgent: false,
- Severity: "ok", Title: "Weak signal resolved on " + d.Name,
- Description: fmt.Sprintf("back to %s dBm on %s after %s", recSignal, routerName, dur),
- Type: alerts.TypeWifiWeakRecovered,
- Vars: map[string]string{"device": d.Name, "signal": recSignal, "router": routerName, "duration": dur},
- Resolves: []string{resolveID},
- Time: "just now", RouterID: d.RouterID,
- })
- }
- // classifyRoamingDaemon decide que daemon de roaming esta activo en la red a
- // partir de los flags recogidos del sondeo (#428).
- func classifyRoamingDaemon(usteerAvailable, dawnDetected bool) RoamingDaemon {
- switch {
- case usteerAvailable && dawnDetected:
- return RoamingDaemonBoth
- case usteerAvailable:
- return RoamingDaemonUsteer
- case dawnDetected:
- return RoamingDaemonDawn
- default:
- return RoamingDaemonNone
- }
- }
- // dawnDeprecatedFromPolled devuelve true si algún router reporta DAWN en
- // el payload del agente. Extraído para poder testearlo sin levantar SSH.
- func dawnDeprecatedFromPolled(polled map[string]*routerPolled) bool {
- for _, p := range polled {
- if p.dawnDetected {
- return true
- }
- }
- return false
- }
- // usteerAvailableCached devuelve si hay usteer en la red (cacheado). Lanza un
- // refresco asíncrono (1 SSH al gateway, TTL 30s) cuando el cache está stale,
- // sin bloquear el overview: la primera llamada devuelve false y el flag llega
- // en el overview siguiente una vez refrescado.
- func (l *Live) usteerAvailableCached() bool {
- l.mu.Lock()
- avail := l.usteerAvailable
- checked := l.usteerCheckedAt
- checking := l.usteerChecking
- gw := l.gatewayCfg
- l.mu.Unlock()
- if gw == nil {
- return false
- }
- if checking || time.Since(checked) < 30*time.Second {
- return avail
- }
- l.mu.Lock()
- l.usteerChecking = true
- host := gw.SSHAddr()
- l.mu.Unlock()
- go func() {
- out, err := l.pool.Run(host, "ubus call usteer local_info", 4*time.Second)
- l.mu.Lock()
- l.usteerChecking = false
- l.usteerCheckedAt = time.Now()
- l.usteerAvailable = err == nil && strings.TrimSpace(out) != ""
- l.mu.Unlock()
- }()
- return avail
- }
- // BoardInfoFor (#477): último ubus system board cacheado del router, ya sea
- // por push del agente (polledFromAgent) o por sondeo SSH. Solo lectura.
- func (l *Live) BoardInfoFor(id string) *BoardInfo {
- l.mu.Lock()
- defer l.mu.Unlock()
- return l.boardCache[id]
- }
- // GetRouters: tarjetas desde la caché del último tick (index.js:600-610).
- func (l *Live) GetRouters(context.Context) []Router {
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- polled := cloneLastPolled(l.lastPolled)
- l.mu.Unlock()
- out := make([]Router, 0, len(routers))
- for _, cfg := range routers {
- p := polled[cfg.ID]
- if cfg.Disabled {
- out = append(out, l.pausedRouter(cfg))
- continue
- }
- if p == nil {
- l.mu.Lock()
- prev := l.lastGood[cfg.ID]
- fails := l.failCount[cfg.ID]
- l.mu.Unlock()
- if prev != nil && fails < 2 {
- out = append(out, *prev)
- } else {
- out = append(out, l.offlineRouter(cfg))
- }
- continue
- }
- out = append(out, l.buildRouter(p, l.metricsHistory(cfg.ID, "24h")))
- }
- // buildRouter leaves Clients as the DHCP lease count, which is not the
- // number the card means: it counts devices that are offline and misses
- // every device without a lease. The overview has always corrected it;
- // this endpoint did not, so the routers page and the map disagreed --
- // 34 against 45 on the same router.
- countClientsPerRouter(out, l.attributedDevices())
- return out
- }
- // countClientsPerRouter sets each router's client count and band split to
- // the online devices attributed to it. Attribution is per router, not per
- // subtree: in a mesh each node counts its own stations, and clients of gear
- // that is not a NetPulse router (a UniFi AP, say) belong to the router that
- // serves them.
- func countClientsPerRouter(routers []Router, devices []Device) {
- counts := make(map[string]int, len(routers))
- splits := make(map[string]*demoBandSplit, len(routers))
- for i := range routers {
- splits[routers[i].ID] = &demoBandSplit{}
- }
- for _, d := range devices {
- if !d.Online {
- continue
- }
- if split, ok := splits[d.RouterID]; ok {
- counts[d.RouterID]++
- countBand(split, d.Band)
- }
- }
- for i := range routers {
- routers[i].Clients = counts[routers[i].ID]
- routers[i].BandSplit = splits[routers[i].ID]
- }
- }
- // liveExtras es el objeto extras del detalle live (index.js:677-700).
- type liveExtras struct {
- MAC string `json:"mac"`
- Firmware string `json:"firmware"`
- FirmwareUpdated bool `json:"firmwareUpdated"`
- FirmwareAvailable string `json:"firmwareAvailable,omitempty"`
- LastReboot string `json:"lastReboot"`
- Soc string `json:"soc"`
- Flash string `json:"flash"`
- RamMb int `json:"ramMb"`
- // Timezone (#1500): nombre IANA del equipo; lo aporta el agente desde
- // /etc/localtime (ubus nunca lo dio y ningún sondeo SSH/SNMP tampoco).
- Timezone string `json:"timezone,omitempty"`
- // UsedMb (#1501): RAM en uso en MiB con la misma fórmula del porcentaje
- // (memUsedBytes); el front la pinta directamente en vez de derivarla de
- // pct × total, que acumulaba el error de redondeo.
- UsedMb int `json:"usedMb,omitempty"`
- BandSplit demoBandSplit `json:"bandSplit"`
- TrafficNow float64 `json:"trafficNow"`
- GatewayLatencySpark []float64 `json:"gatewayLatencySpark"`
- BackhaulSignal []float64 `json:"backhaulSignal"`
- Radios []Radio `json:"radios"`
- Ports []EthPort `json:"ports"`
- EthPorts []EthPort `json:"ethPorts"`
- }
- // GetRouterDetail (index.js:612-715). Id desconocido → (nil, nil).
- func (l *Live) GetRouterDetail(ctx context.Context, id string) (*RouterDetail, error) {
- l.mu.Lock()
- var cfg *RouterConfig
- for i := range l.routers {
- if l.routers[i].ID == id {
- cfg = &l.routers[i]
- break
- }
- }
- p := l.lastPolled[id]
- gw := l.gatewayCfg
- polledAll := cloneLastPolled(l.lastPolled)
- l.mu.Unlock()
- if cfg == nil {
- return nil, nil
- }
- var router Router
- if p != nil {
- router = l.buildRouter(p, l.metricsHistory(id, "24h"))
- } else {
- router = l.offlineRouter(*cfg)
- }
- l.fillSparklineFromPortsOne(&router)
- // Mapa global MAC → lease + MAC de bridge → nombre de router
- leaseMap := map[string]DhcpLease{}
- routerByMac := map[string]string{}
- // Clientes WiFi por MAC → AP que los sirve (#291): si la única MAC de
- // una boca del switch es un cliente WiFi, el equipo ENCHUFADO es el AP,
- // no el cliente. La atribución correcta de la boca es el AP.
- wifiByMac := map[string]string{}
- for _, polled := range polledAll {
- apName := polled.cfg.Name
- if apName == "" {
- apName = polled.cfg.Host
- }
- for mac := range polled.wireless {
- wifiByMac[mac] = apName
- }
- }
- // Alias manuales (Settings > known_macs): fallback de nombre para MACs
- // sin lease (estáticas, equipos sin DHCP), mismo criterio que la lista
- // de dispositivos (#291: match MAC→nombre también en bocas de switch).
- aliasByMac := map[string]string{}
- if l.db != nil {
- if rows, err := l.db.Query("SELECT mac, name FROM known_macs"); err == nil {
- for rows.Next() {
- var mac, name string
- if rows.Scan(&mac, &name) == nil && name != "" {
- aliasByMac[mac] = name
- }
- }
- rows.Close()
- }
- }
- for _, polled := range polledAll {
- for _, le := range polled.leases {
- if le.MAC != "" {
- leaseMap[le.MAC] = le
- }
- }
- if polled.brMac != "" {
- name := polled.cfg.Name
- if name == "" {
- name = polled.cfg.Host
- }
- routerByMac[polled.brMac] = name
- }
- }
- // Boca → MACs aprendidas (vecino inmediato). Indexado por INTERFAZ: el
- // FDB y los vecinos LLDP vienen con el nombre de la interfaz, y el id de
- // la boca no siempre lo es (una boca WAN se llama "wan" aunque su
- // interfaz sea "eth1", o "lan1" cuando el uplink es un PPPoE sobre esa
- // boca). Sin esto, esa boca sale sin el dispositivo que tiene enfrente.
- portMacs := map[string][]string{}
- if p != nil {
- for mac, portName := range p.fdb {
- portMacs[portName] = append(portMacs[portName], mac)
- }
- }
- ports := []EthPort{}
- if p != nil {
- ports = p.ports
- }
- var depsLldp []LldpNeighbor
- if p != nil {
- depsLldp = p.lldp
- }
- unitByMac := map[string]string{}
- fdbByUnit := map[string]map[string]string{}
- for _, pr := range polledAll {
- if pr == nil || pr.brMac == "" {
- continue
- }
- unitByMac[strings.ToUpper(pr.brMac)] = pr.cfg.ID
- fdbByUnit[pr.cfg.ID] = pr.fdb
- }
- selfBrMac := ""
- if p != nil {
- selfBrMac = p.brMac
- }
- deps := portEnrichDeps{
- routerByMac: routerByMac,
- leaseMap: leaseMap,
- aliasByMac: aliasByMac,
- wifiByMac: wifiByMac,
- portMacs: portMacs,
- lldp: depsLldp,
- unitByMac: unitByMac,
- fdbByUnit: fdbByUnit,
- selfBrMac: selfBrMac,
- }
- enriched := make([]EthPort, 0, len(ports))
- for _, port := range ports {
- if !port.Up {
- enriched = append(enriched, port)
- continue
- }
- enriched = append(enriched, enrichEthPort(port, portNetdev(port), deps))
- }
- // Per-port health score (issue #299): compute from recent series + flapping.
- l.enrichPortHealth(id, enriched)
- radios := []Radio{}
- if p != nil && p.radios != nil {
- radios = p.radios
- }
- seriesOf := func(rang string) []PerfPoint {
- h := l.metricsHistory(id, rang)
- out := make([]PerfPoint, 0, len(h))
- for _, hp := range h {
- out = append(out, PerfPoint{T: hp.t, CPU: float64(hp.cpu), RAM: float64(hp.ram), Temp: float64(hp.temp)})
- }
- return out
- }
- clients := []Device{}
- detDevices, _ := inferTopology(polledAll, l.buildDevices(polledAll, ""))
- // #954: first/last seen también en los clientes del detalle del router.
- // #1818: mismo gate de permanencia que el overview.
- detDevices = l.settleTransient(detDevices, time.Now().UnixMilli())
- l.applyDeviceSeen(detDevices)
- for _, d := range detDevices {
- if d.RouterID == id {
- clients = append(clients, d)
- }
- }
- // Desglose por banda de los clientes online (issue #645): mismo criterio
- // que la tarjeta de la flota (solo online; "—" no cae en ninguna banda).
- var bandSplit demoBandSplit
- for _, d := range clients {
- if d.Online {
- countBand(&bandSplit, d.Band)
- }
- }
- extras := liveExtras{
- MAC: "—", Firmware: "—", FirmwareUpdated: true, LastReboot: "—",
- Soc: "—", Flash: "—", RamMb: 0,
- BandSplit: bandSplit,
- GatewayLatencySpark: l.latencySpark24h(id),
- BackhaulSignal: []float64{},
- Radios: radios,
- Ports: enriched,
- EthPorts: enriched,
- }
- if p != nil {
- if p.brMac != "" {
- extras.MAC = p.brMac
- }
- if p.board != nil {
- extras.Firmware = p.board.Release.Description
- extras.Soc = p.board.System
- if extras.Soc == "" {
- extras.Soc = "—"
- }
- }
- // Unidad SNMP sin board (gestionado sin agente): el chip lo declara la
- // MIB privada del fabricante, que es la única fuente posible aquí.
- if extras.Soc == "—" && p.snmpSoC != "" {
- extras.Soc = p.snmpSoC
- }
- if p.firmwareAvailable != "" {
- extras.FirmwareAvailable = p.firmwareAvailable
- extras.FirmwareUpdated = false
- }
- if p.flash != "" {
- extras.Flash = p.flash
- }
- if p.uptimeSec > 0 {
- rb := time.Now().Add(-time.Duration(p.uptimeSec) * time.Second)
- extras.LastReboot = fmt.Sprintf("%02d/%02d/%d, %02d:%02d", rb.Day(), int(rb.Month()), rb.Year(), rb.Hour(), rb.Minute())
- }
- if p.sysInfo != nil && p.sysInfo.Memory.Total > 0 {
- // MiB, no MB SI: un módulo de 2 GiB debe leerse "2048 MB" en el
- // panel, que es como el usuario lee el tamaño del chip (#1501;
- // antes /1e6 daba 2097).
- extras.RamMb = int(math.Round(p.sysInfo.Memory.Total / (1024 * 1024)))
- m := p.sysInfo.Memory
- extras.UsedMb = int(math.Round(memUsedBytes(m.Total, m.Free, m.Buffered, m.Cached, m.Available, m.Used) / (1024 * 1024)))
- }
- if p.sysInfo != nil && p.sysInfo.Timezone != "" {
- extras.Timezone = p.sysInfo.Timezone
- }
- if p.net != nil {
- extras.TrafficNow = mbps(p.net.RxBps)
- }
- }
- var vlans []VlanPort
- if p != nil && len(p.vlans) > 0 {
- vlans = vlanPortsWithNames(p.vlans, p.luci)
- }
- var networks []NetworkInfo
- if p != nil && len(p.networks) > 0 {
- networks = attributeNetworkClients(networkInfos(p.networks, p.ports), clients, p.wifiNet)
- }
- var multiWan *MultiWanInfo
- if p != nil {
- multiWan = p.multiWan
- }
- detail := &RouterDetail{
- Router: router, Ports: enriched, Radios: radios, Backhaul: nil,
- Series: PerfSeries{H1: seriesOf("1h"), H24: seriesOf("24h"), D7: seriesOf("7d")},
- Clients: clients, Extras: extras, Vlans: vlans, Networks: networks, MultiWan: multiWan,
- }
- // #930: contadores de salud SNMP del router (solo si se sondea por SNMP).
- if cfg.SnmpEnabled {
- l.mu.Lock()
- if st := l.snmpPollStats[id]; st != nil {
- detail.SnmpOk = st.Ok
- detail.SnmpFail = st.Fail
- detail.SnmpConsecFail = st.ConsecFail
- detail.LastSnmpErr = st.LastErr
- }
- l.mu.Unlock()
- }
- if gw != nil && id == gw.ID {
- detail.Adguard = l.pollAdGuard(ctx)
- detail.Wireguard = l.pollWireGuard(clients)
- } else {
- // Backhaul real del AP: boca que enlaza con otro router + latencia
- // (la elección de boca vive en backhaul.go).
- uplink := pickBackhaulUplink(enriched)
- speed := "—"
- if uplink != nil && uplink.Speed != "" {
- speed = uplink.Speed
- }
- latency := 0.0
- if p != nil && p.latencyMs != nil {
- latency = *p.latencyMs
- }
- detail.Backhaul = demoBackhaul{
- Kind: "cable", Headline: "Cable · " + speed + " · full duplex", LatencyMs: latency,
- }
- }
- return detail, nil
- }
- // GetDevices: buildDevices sobre el último sondeo (+ inferencia FDB de
- // topología: Port/AttachTo, como en buildOverview).
- func (l *Live) GetDevices(context.Context) []Device {
- return l.attributedDevices()
- }
- // latencySpark24h: serie 24h de latencia de la unidad en buckets horarios
- // (AVG de latency_ms en la tabla metrics, solo muestras con sonda). #1148:
- // alimenta el spark real del detalle; vacía si no hay historial (sin sonda
- // o unidad recién añadida) para que el front pinte "sin datos" y no ceros.
- func (l *Live) latencySpark24h(routerID string) []float64 {
- if l.db == nil || routerID == "" {
- return []float64{}
- }
- rows, err := l.db.Query(
- `SELECT (ts / 3600000) AS bucket, AVG(latency_ms) AS lat
- FROM metrics WHERE router_id = ? AND ts >= ? AND latency_ms IS NOT NULL
- GROUP BY bucket ORDER BY bucket`,
- routerID, l.now().UnixMilli()-86400e3)
- if err != nil {
- return []float64{}
- }
- defer rows.Close()
- out := []float64{}
- for rows.Next() {
- var bucket int64
- var lat float64
- if err := rows.Scan(&bucket, &lat); err != nil {
- continue
- }
- out = append(out, lat)
- }
- return out
- }
- // attributedDevices builds the device list with everything that decides who
- // a device belongs to and whether it is online: inference over the sticky
- // FDB overlay, then the Proxmox and UniFi seals. The seals are not optional
- // for a count -- the UniFi one is what marks a station on a controller AP as
- // online, and without it a router's clients come out short.
- func (l *Live) attributedDevices() []Device {
- l.mu.Lock()
- polled := cloneLastPolled(l.lastPolled)
- l.mu.Unlock()
- // #656/#678: memo sticky fresca ANTES de buildDevices (atribución) y como
- // overlay de inferTopology (paridad con el overview), ANTES del sellado PVE
- // (que sobreescribe attachTo con ground truth del cluster).
- detailNowMs := time.Now().UnixMilli()
- detailMemo := l.updateFdbMemo(polled, detailNowMs)
- // #1485 también en el detalle: sin la boca WAN, el bloque de ARP WAN-side
- // no sella WanSide y /api/devices discrepa del overview (la ONT bridged
- // vuelve como cliente cableado del gateway y el mapa pierde el chip del
- // peer WAN). Misma resolución que en buildOverview.
- detailWanPort := ""
- l.mu.Lock()
- gwCfg := l.gatewayCfg
- l.mu.Unlock()
- if gwCfg != nil {
- if gp := polled[gwCfg.ID]; gp != nil {
- detailWanPort = gp.wanInfo.Port
- }
- }
- devices, _ := inferTopology(
- overlayStickyFdb(polled, detailMemo, detailNowMs),
- l.buildDevices(polled, detailWanPort),
- )
- // #1292: lápidas fuera de la lista del detalle (la fuente viva puede
- // seguir emitiendo la MAC borrada).
- devices = l.filterTombstoned(devices)
- // #561: sellado de infraestructura con el inventario PVE (si configurado).
- // El detalle no consume distnodes, pero el sellado de devices sí corre.
- l.sealProxmoxInfra(devices, nil)
- // #954 + #1095: first/last seen persistente (device_seen) en el payload
- // final. La escritura vivía SOLO en buildOverview: si por lo que fuera
- // esa lista no contenía un cliente (p. ej. flota agent-only), el visto
- // nunca se persistía y aquí se mostraba "—" para siempre. Escribir también
- // desde la lista que la UI realmente consume hace el write-through
- // inevitable; el upsert es idempotente y barato.
- // #1818: mismo gate de permanencia antes de persistir.
- devices = l.settleTransient(devices, time.Now().UnixMilli())
- l.noteDevicesSeen(devices, time.Now().UnixMilli())
- l.applyDeviceSeen(devices)
- // #1145: retención indefinida - clientes del registro que ya no se ven
- // en ninguna fuente viva salen como offline con su último nombre y seen.
- devices = append(devices, l.ghostDevices(devices)...)
- return devices
- }
- // RouterServingDHCP devuelve el id del router cuyo último sondeo reportó la
- // MAC en su tabla de leases DHCP (issue #537). Ese router es el que sirve
- // DHCP al dispositivo (no necesariamente el gateway global: una LAN separada
- // tras un router/AP con su propio dnsmasq, p. ej. rt-lab en 192.168.2.x, es
- // quien concede el lease). Vacío si ningún router la reportó (IP estática o
- // sin lease en el último snapshot).
- func (l *Live) RouterServingDHCP(mac string) string {
- mac = strings.ToUpper(strings.TrimSpace(mac))
- if mac == "" {
- return ""
- }
- l.mu.Lock()
- polled := cloneLastPolled(l.lastPolled)
- l.mu.Unlock()
- for id, p := range polled {
- if p == nil || p.cfg.AgentOnly {
- continue // agent-only no tiene vía SSH para escribir la reserva
- }
- for _, le := range p.leases {
- if strings.ToUpper(le.MAC) == mac {
- return id
- }
- }
- }
- return ""
- }
- // GetAlerts: copia de las alertas en memoria.
- func (l *Live) GetAlerts(context.Context) []AlertEvent {
- return l.engine.List()
- }
- // AlertsEngine: motor de alertas del adapter (SPEC-ALERTAS §3).
- func (l *Live) AlertsEngine() *alerts.Engine { return l.engine }
- // GetMetricsRows: filas para el poller (index.js:725-739).
- func (l *Live) GetMetricsRows(context.Context) []MetricsRow {
- l.mu.Lock()
- polled := l.lastPolled
- rows := []MetricsRow{}
- for id, p := range polled {
- // issue #414: los routers SNMP cacheados repiten el mismo snapshot
- // entre polls reales; no se vuelve a persistir la misma fila.
- if p.cfg.SnmpEnabled && p.polledAt != 0 && p.polledAt <= l.snmpLastMetricsTick[id] {
- continue
- }
- row := MetricsRow{
- RouterID: id,
- CPU: vitalFloat(p.hasCpu, p.cpu),
- RAM: vitalFloat(p.hasRam, p.ram),
- Temp: vitalFloat(p.hasTemp, p.temp),
- LatencyMs: p.latencyMs,
- }
- // #441/#1568: sin lecturas no se persisten ceros falsos, pero una
- // fuente SNMP/external con CPU, memoria o temperatura confirmada sí
- // las conserva.
- if p.cfg.SnmpEnabled || p.agentKind == "external" {
- v := resolvePartialVitals(p)
- row.CPU, row.RAM, row.Temp = nil, nil, nil
- if v.cpu != nil {
- row.CPU = fptr(float64(*v.cpu))
- }
- if v.ram != nil {
- row.RAM = fptr(float64(*v.ram))
- }
- if v.temp != nil {
- row.Temp = fptr(float64(*v.temp))
- }
- }
- if p.net != nil {
- row.RxBps = p.net.RxBps
- row.TxBps = p.net.TxBps
- }
- rows = append(rows, row)
- if p.cfg.SnmpEnabled {
- l.snmpLastMetricsTick[id] = p.polledAt
- }
- }
- l.mu.Unlock()
- return rows
- }
- // GetAdguardClients: solo GL tiene /control/clients (nil si no configurado).
- func (l *Live) GetAdguardClients(ctx context.Context) ([]AdguardClient, error) {
- _, gl := l.getAdguardClient()
- if gl == nil {
- return nil, nil
- }
- return gl.QueryClients(ctx)
- }
- // usteerAPRaw es la forma cruda de una entrada de `ubus call usteer
- // local_info` / `remote_info` (por iface o ip#iface).
- type usteerAPRaw struct {
- BSSID string `json:"bssid"`
- SSID string `json:"ssid"`
- Freq int `json:"freq"`
- NAssoc int `json:"n_assoc"`
- Load int `json:"load"`
- }
- // usteerClientRaw es la forma cruda de una entrada de `ubus call usteer
- // connected_clients` (por MAC).
- type usteerClientRaw struct {
- Signal int `json:"signal"`
- }
- // GetUsteer: red usteer (roaming/steering). nil si ningún router responde.
- //
- // A diferencia de DAWN (que distribuía el hearing map en get_network), usteer
- // expone `local_info` por router (los APs propios) y `connected_clients` por
- // iface. Se sondea cada router con SSH (local_info + connected_clients) y se
- // agregan sus APs locales; el mesh marca por router si usteer está activo y
- // cuántos APs ve. Los clientes se asocian a cada AP por nombre de iface.
- func (l *Live) GetUsteer(context.Context) (*Usteer, error) {
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- reg := l.agents
- macs := make(map[string]string, len(l.routerMacs))
- for k, v := range l.routerMacs {
- macs[k] = v
- }
- l.mu.Unlock()
- aps := []UsteerAP{}
- mesh := []UsteerMesh{}
- for _, cfg := range routers {
- name := cfg.Name
- if name == "" {
- name = cfg.ID
- }
- if cfg.SnmpEnabled {
- mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
- continue
- }
- if cfg.AgentOnly {
- // #1431: en flotas agent-only no hay sondeo SSH; la vista se
- // alimenta del payload que el agente empuja (usteer + wireless).
- apsR, seen := []UsteerAP{}, 0
- if reg != nil {
- if _, p, fresh := reg.MatchRouter(cfg, macs); fresh && p != nil {
- apsR, seen = usteerAPsFromPayload(name, p)
- }
- }
- mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: seen > 0, ApsSeen: seen})
- aps = append(aps, apsR...)
- continue
- }
- localOut, err := l.pool.Run(cfg.SSHAddr(), "ubus call usteer local_info", 0)
- if err != nil {
- mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
- continue
- }
- var local map[string]usteerAPRaw
- if json.Unmarshal([]byte(localOut), &local) != nil {
- mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: false, ApsSeen: 0})
- continue
- }
- clientsOut, _ := l.pool.Run(cfg.SSHAddr(), "ubus call usteer connected_clients", 0)
- clientsByIface := map[string]map[string]usteerClientRaw{}
- _ = json.Unmarshal([]byte(clientsOut), &clientsByIface)
- seen := 0
- for iface, raw := range local {
- if raw.SSID == "" || raw.BSSID == "" {
- continue
- }
- aps = append(aps, buildUsteerAPWithClients(iface, raw, clientsByIface[iface], name, true))
- seen++
- }
- mesh = append(mesh, UsteerMesh{RouterID: cfg.ID, Name: name, Usteer: true, ApsSeen: seen})
- }
- if len(aps) == 0 {
- return nil, nil
- }
- return &Usteer{APs: aps, Mesh: mesh}, nil
- }
- // sshRunner es el subconjunto de *SSHPool que usan las funciones live que
- // ejecutan comandos remotos. Permite inyectar runners falsos en tests.
- type sshRunner interface {
- Run(host, cmd string, timeout time.Duration) (string, error)
- }
- // KickUsteerClient busca la MAC en los connected_clients de cada router y la
- // expulsa del AP hostapd donde esté conectada. El motivo 5 (DISASSOC_DUE_TO_BSS_TRANSITION_PROHIBITED)
- // con deauth=true fuerza al cliente a reasociarse; ban_time corto (120 ms) evita
- // que vuelva inmediatamente al mismo AP sin impedir la reconexión normal.
- //
- // Si el cliente aparece en varios routers (transición de roaming) o un
- // del_client falla por un estado transitorio del AP, intenta expulsarlo de
- // cada uno hasta que un intento tenga éxito. Solo devuelve error cuando el
- // cliente no está en ningún router o cuando todos los intentos fallan.
- func (l *Live) KickUsteerClient(ctx context.Context, mac string) error {
- target := strings.ToUpper(strings.TrimSpace(mac))
- if target == "" || !validMAC(target) {
- return fmt.Errorf("invalid MAC")
- }
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- l.mu.Unlock()
- return kickUsteerClient(target, routers, l.pool)
- }
- func kickUsteerClient(target string, routers []RouterConfig, runner sshRunner) error {
- var failures []string
- for _, cfg := range routers {
- if cfg.AgentOnly {
- continue
- }
- out, err := runner.Run(cfg.Host, "ubus call usteer connected_clients", 0)
- if err != nil {
- continue
- }
- var clients map[string]map[string]usteerClientRaw
- if err := json.Unmarshal([]byte(out), &clients); err != nil {
- continue
- }
- for iface, macs := range clients {
- var found bool
- for m := range macs {
- if strings.ToUpper(m) == target {
- found = true
- break
- }
- }
- if !found {
- continue
- }
- cmd := fmt.Sprintf("ubus call %s del_client '{\"addr\":\"%s\",\"reason\":5,\"deauth\":true,\"ban_time\":120000}'", iface, target)
- if _, err := runner.Run(cfg.Host, cmd, 0); err != nil {
- name := cfg.Name
- if name == "" {
- name = cfg.Host
- }
- failures = append(failures, name)
- continue
- }
- return nil
- }
- }
- if len(failures) > 0 {
- return fmt.Errorf("could not disconnect from %s", strings.Join(failures, "; "))
- }
- return fmt.Errorf("client not found")
- }
- // validMAC acepta MAC con separadores ':' o '-'. Exige 17 caracteres (con
- // separador) porque el llamador pasa target tal cual a usteer sin insertar ':'.
- func validMAC(s string) bool {
- return macaddr.NormalizeSeparated(s) != ""
- }
- // buildUsteerAP construye un UsteerAP desde una entrada cruda de local_info.
- // Band se deriva de freq (>= 5000 MHz → 5 GHz). Función pura para testear.
- func buildUsteerAP(iface string, raw usteerAPRaw, hostname string, local bool) UsteerAP {
- band := "2.4 GHz"
- if raw.Freq >= 5000 {
- band = "5 GHz"
- }
- return UsteerAP{
- SSID: raw.SSID,
- BSSID: strings.ToUpper(raw.BSSID),
- Hostname: hostname,
- Band: band,
- Freq: raw.Freq,
- UtilizationPct: raw.Load,
- ClientCount: raw.NAssoc,
- Clients: []UsteerClient{},
- Local: local,
- Iface: iface,
- }
- }
- // buildUsteerAPWithClients enriquece un AP con los clientes de
- // connected_clients para ese mismo iface. Los clientes se ordenan por MAC
- // para respuestas deterministas.
- func buildUsteerAPWithClients(iface string, raw usteerAPRaw, clients map[string]usteerClientRaw, hostname string, local bool) UsteerAP {
- ap := buildUsteerAP(iface, raw, hostname, local)
- for mac, c := range clients {
- if c.Signal >= 0 {
- continue // señal 0/positiva = sin datos
- }
- ap.Clients = append(ap.Clients, UsteerClient{
- MAC: strings.ToUpper(mac),
- Signal: c.Signal,
- })
- }
- sort.Slice(ap.Clients, func(i, j int) bool { return ap.Clients[i].MAC < ap.Clients[j].MAC })
- return ap
- }
- // ---------------------------------------------------------------------------
- // 802.11r (Fast BSS Transition) — Fase 14.3
- // ---------------------------------------------------------------------------
- // parseUciWireless parsea la salida de `uci show wireless` (líneas
- // `wireless.SECTION.FIELD='VALUE'` y `wireless.SECTION=TYPE`) y devuelve los
- // wifi-iface con sus campos relevantes para 802.11r. Ignora wifi-device y
- // cualquier otra sección que no sea wifi-iface (pero usa wifi-device para
- // mapear device → {channel, band}). Función pura — fácil de testear.
- //
- // Formato uci: las comillas simples envuelven los valores; los campos lista
- // (como rrm_nr_list) se emiten como varias líneas con el mismo nombre — aquí
- // nos quedamos con el último valor escalar (no nos interesan las listas).
- func parseUciWireless(out string) []Dot11rIface {
- type sec struct {
- typ string
- fields map[string]string
- }
- sections := map[string]*sec{}
- order := []string{}
- for _, line := range strings.Split(out, "\n") {
- line = strings.TrimRight(line, "\r")
- if !strings.HasPrefix(line, "wireless.") {
- continue
- }
- rest := line[len("wireless."):]
- // Caso 1: wireless.SECTION=TYPE (declaración de sección, sin punto en SECTION).
- if eq := strings.IndexByte(rest, '='); eq > 0 {
- head := rest[:eq]
- if !strings.Contains(head, ".") {
- if _, ok := sections[head]; !ok {
- sections[head] = &sec{fields: map[string]string{}}
- order = append(order, head)
- }
- sections[head].typ = unquoteUci(rest[eq+1:])
- continue
- }
- }
- // Caso 2: wireless.SECTION.FIELD='VALUE'
- parts := strings.SplitN(rest, ".", 2)
- if len(parts) != 2 {
- continue
- }
- section, field := parts[0], parts[1]
- if _, ok := sections[section]; !ok {
- sections[section] = &sec{fields: map[string]string{}}
- order = append(order, section)
- }
- if eq := strings.IndexByte(field, '='); eq > 0 {
- fname := field[:eq]
- fval := field[eq+1:]
- sections[section].fields[fname] = unquoteUci(fval)
- }
- }
- // device → {channel, band} desde las secciones wifi-device.
- type devInfo struct {
- channel int
- band string
- }
- devMap := map[string]devInfo{}
- for _, name := range order {
- s := sections[name]
- if s.typ != "wifi-device" {
- continue
- }
- ch, _ := strconv.Atoi(s.fields["channel"])
- band := ""
- switch s.fields["band"] {
- case "2g":
- band = "2.4 GHz"
- case "5g":
- band = "5 GHz"
- case "6g":
- band = "6 GHz"
- case "60g":
- band = "60 GHz"
- }
- devMap[name] = devInfo{channel: ch, band: band}
- }
- ifaces := []Dot11rIface{}
- for _, name := range order {
- s := sections[name]
- if s.typ != "wifi-iface" {
- continue
- }
- f := s.fields
- dev := f["device"]
- di := devMap[dev]
- ifaces = append(ifaces, Dot11rIface{
- Section: name,
- Device: dev,
- Ifname: f["ifname"],
- SSID: f["ssid"],
- MAC: f["macaddr"],
- Channel: di.channel,
- Band: di.band,
- Network: f["network"],
- Disabled: f["disabled"] == "1",
- Encryption: f["encryption"],
- Dot11REnabled: f["ieee80211r"] == "1",
- MobilityDomain: f["mobility_domain"],
- FTOverDS: f["ft_over_ds"] == "1",
- FTPSKGenerateLocal: f["ft_psk_generate_local"] == "1",
- PMKR1Push: f["pmk_r1_push"] == "1",
- NASID: f["nasid"],
- Dot11KEnabled: f["ieee80211k"] == "1",
- Dot11VEnabled: f["ieee80211v"] == "1",
- BSSTransition: f["bss_transition"] == "1",
- MFP: f["ieee80211w"] == "1",
- })
- }
- return ifaces
- }
- // dot11rSkip (#541): una iface no debe contar para usteer si pertenece a una
- // red invitada/aislada (guest/iot/wan) o está deshabilitada. La red principal
- // de roaming es "lan" (o la red no aislada). Si no puede determinarse, se deja
- // pasar (mejor mostrar de más que ocultar la principal por un nombre raro).
- func dot11rSkip(ifc Dot11rIface) bool {
- if ifc.Disabled {
- return true
- }
- switch ifc.Network {
- case "guest", "iot", "wan":
- return true
- }
- return false
- }
- // unquoteUci quita las comillas simples que uci envuelve a los valores y
- // desescapa \' → '. `uci show` SIEMPRE envuelve en comillas simples.
- func unquoteUci(s string) string {
- if len(s) >= 2 && s[0] == '\'' && s[len(s)-1] == '\'' {
- return strings.ReplaceAll(s[1:len(s)-1], `\'`, `'`)
- }
- return s
- }
- type dot11rIfaceRef struct {
- routerID string
- iface Dot11rIface
- }
- // GetDot11r: estado 802.11r (Fast BSS Transition) por router y SSID. Recorre
- // los routers (saltando agent-only, que son switches sin wifi) y hace SSH
- // `uci show wireless` a cada uno. Devuelve (nil, nil) si ningún router con
- // wifi tiene 802.11r habilitado -> el handler responde 503.
- func (l *Live) GetDot11r(ctx context.Context) (*Dot11rOverview, error) {
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- reg := l.agents
- macs := make(map[string]string, len(l.routerMacs))
- for k, v := range l.routerMacs {
- macs[k] = v
- }
- l.mu.Unlock()
- out := Dot11rOverview{Routers: []Dot11rRouter{}, SSIDs: []Dot11rSSID{}}
- ssidIfaces := map[string][]dot11rIfaceRef{}
- for _, cfg := range routers {
- name := cfg.Name
- if name == "" {
- name = cfg.ID
- }
- r := Dot11rRouter{RouterID: cfg.ID, Name: name, Ifaces: []Dot11rIface{}}
- // #1450: en flotas agent-only no hay llave SSH. La config sale del
- // último payload del agente (uciWirelessRaw), parseado con la MISMA
- // parseUciWireless del camino SSH. Solo payload fresco (mismo
- // criterio que la vista usteer, #1431): un router que dejó de
- // empujar no debe seguir pintando su config como actual.
- // SNMP (sin SSH en absoluto, #1026) y agentes antiguos sin el campo
- // se listan con Available=false, como antes.
- var ifaces []Dot11rIface
- switch {
- case cfg.AgentOnly:
- if reg != nil {
- if _, p, fresh := reg.MatchRouter(cfg, macs); fresh && p != nil {
- ifaces = dot11rIfacesFromPayload(p)
- }
- }
- if len(ifaces) == 0 {
- out.Routers = append(out.Routers, r)
- continue
- }
- case cfg.SnmpEnabled:
- out.Routers = append(out.Routers, r)
- continue
- default:
- uciOut, err := l.pool.Run(cfg.SSHAddr(), "uci show wireless", 0)
- if err != nil {
- out.Routers = append(out.Routers, r)
- continue
- }
- ifaces = parseUciWireless(uciOut)
- }
- r.Available = true
- r.Ifaces = ifaces
- out.Routers = append(out.Routers, r)
- for _, ifc := range ifaces {
- if ifc.SSID == "" || dot11rSkip(ifc) {
- continue
- }
- ssidIfaces[ifc.SSID] = append(ssidIfaces[ifc.SSID], dot11rIfaceRef{routerID: cfg.ID, iface: ifc})
- }
- }
- // Agregar por SSID.
- ssids := make([]Dot11rSSID, 0, len(ssidIfaces))
- for ssid, refs := range ssidIfaces {
- enabled := 0
- mobilityDomain := ""
- ftOverDS := false
- ftPSK := false
- routerSet := map[string]bool{}
- for _, ref := range refs {
- if ref.iface.Dot11REnabled {
- enabled++
- if mobilityDomain == "" {
- mobilityDomain = ref.iface.MobilityDomain
- ftOverDS = ref.iface.FTOverDS
- ftPSK = ref.iface.FTPSKGenerateLocal
- }
- }
- routerSet[ref.routerID] = true
- }
- routerIDs := make([]string, 0, len(routerSet))
- for id := range routerSet {
- routerIDs = append(routerIDs, id)
- }
- sort.Strings(routerIDs)
- ssids = append(ssids, Dot11rSSID{
- SSID: ssid,
- EnabledEverywhere: enabled > 0 && enabled == len(refs),
- EnabledCount: enabled,
- TotalCount: len(refs),
- MobilityDomain: mobilityDomain,
- FTOverDS: ftOverDS,
- FTPSKGenerateLocal: ftPSK,
- IfaceCount: len(refs),
- RouterIDs: routerIDs,
- })
- }
- sort.Slice(ssids, func(i, j int) bool { return ssids[i].SSID < ssids[j].SSID })
- out.SSIDs = ssids
- for _, s := range ssids {
- if s.EnabledCount > 0 {
- out.Available = true
- break
- }
- }
- // #1450: si la configuración wifi SÍ se pudo leer pero ningún SSID tiene
- // 802.11r, la vista está disponible (el panel pinta el estado "inactivo"
- // en vez de un error de lectura). Antes este caso devolvía (nil, nil) y el
- // handler respondía 503, que la UI mostraba como "no se pudo leer".
- if !out.Available {
- for _, r := range out.Routers {
- if r.Available {
- out.Available = true
- break
- }
- }
- }
- if !out.Available {
- return nil, nil
- }
- out.Anomalies = buildRoamingAnomalies(ssidIfaces)
- return &out, nil
- }
- // buildRoamingAnomalies detecta problemas de configuración de roaming a partir
- // de las interfaces wifi-iface agrupadas por SSID (#428).
- func buildRoamingAnomalies(ssidIfaces map[string][]dot11rIfaceRef) []RoamingAnomaly {
- var anomalies []RoamingAnomaly
- for ssid, refs := range ssidIfaces {
- // Solo consideramos interfaces con 802.11r habilitado para las
- // comprobaciones de consistencia.
- enabled := make([]dot11rIfaceRef, 0, len(refs))
- for _, ref := range refs {
- if ref.iface.Dot11REnabled {
- enabled = append(enabled, ref)
- }
- }
- if len(enabled) == 0 {
- continue
- }
- // 802.11r parcial: algunas interfaces del SSID lo tienen y otras no.
- if len(enabled) < len(refs) {
- anomalies = append(anomalies, RoamingAnomaly{
- Kind: "partial_11r",
- SSID: ssid,
- Message: fmt.Sprintf("802.11r habilitado solo en %d de %d interfaces del SSID %q", len(enabled), len(refs), ssid),
- })
- }
- // Mobility domain inconsistente.
- md := ""
- mdOk := true
- for _, ref := range enabled {
- if md == "" {
- md = ref.iface.MobilityDomain
- } else if ref.iface.MobilityDomain != "" && ref.iface.MobilityDomain != md {
- mdOk = false
- break
- }
- }
- if !mdOk {
- anomalies = append(anomalies, RoamingAnomaly{
- Kind: "mobility_domain_mismatch",
- SSID: ssid,
- Message: fmt.Sprintf("Mobility domain distinto entre routers para el SSID %q", ssid),
- })
- }
- // FT mode inconsistente.
- ftOverDS := enabled[0].iface.FTOverDS
- ftMixed := false
- for _, ref := range enabled[1:] {
- if ref.iface.FTOverDS != ftOverDS {
- ftMixed = true
- break
- }
- }
- if ftMixed {
- anomalies = append(anomalies, RoamingAnomaly{
- Kind: "ft_mode_mismatch",
- SSID: ssid,
- Message: fmt.Sprintf("Modo FT mixto (over-the-DS / over-the-air) para el SSID %q", ssid),
- })
- }
- }
- return anomalies
- }
- // ---------------------------------------------------------------------------
- // WiFi Survey (canal utilization) — Fase 14.4
- // ---------------------------------------------------------------------------
- // freqToChannel mapea frecuencia MHz → número de canal IEEE 802.11.
- // 2.4 GHz: 2412-2472 → 1-13; 2484 → 14. 5 GHz: 5000+5*N → N (5180=36, ...).
- // 60 GHz: 56160+2160*N → N+1.
- func freqToChannel(freq int) int {
- switch {
- case freq >= 2412 && freq <= 2472:
- return (freq-2412)/5 + 1
- case freq == 2484:
- return 14
- case freq >= 5160 && freq <= 5885:
- // Canales UNII: 5160=ch32 ... 5885=ch177. Fórmula general (freq-5000)/5.
- return (freq - 5000) / 5
- case freq >= 5940 && freq <= 7115:
- // 6 GHz (Wi-Fi 6E): 5950=ch1 ... 7115=ch233. Mismo (freq-5000)/5, con offset.
- return (freq-5950)/5 + 1
- case freq == 56160:
- return 1
- case freq >= 56160:
- return (freq-56160)/2160 + 1
- }
- return 0
- }
- // freqToBand devuelve "2.4 GHz"|"5 GHz"|"6 GHz"|"60 GHz"|"" según la frecuencia.
- func freqToBand(freq int) string {
- switch {
- case freq >= 2412 && freq <= 2484:
- return "2.4 GHz"
- case freq >= 5160 && freq <= 5885:
- return "5 GHz"
- case freq >= 5945 && freq <= 7115:
- return "6 GHz"
- case freq >= 56160:
- return "60 GHz"
- }
- return ""
- }
- // parseIwSurvey parsea la salida de `iw dev wlanX survey dump` y devuelve
- // un map device → lista de SurveyChannel (uno por frecuencia). Función pura
- // para testear con fixtures reales sin SSH.
- //
- // Formato (ejemplo Flint2):
- //
- // Survey data from wlan0
- // frequency: 2412 MHz [in use]
- // noise: -90 dBm
- // channel active time: 3632796925 ms
- // channel busy time: 878259766 ms
- // channel receive time: 440957725 ms
- // channel transmit time: 340995043 ms
- // Survey data from wlan0
- // frequency: 2417 MHz
- // noise: -92 dBm
- // channel active time: 72 ms
- // channel busy time: 20 ms
- // ...
- //
- // Cada bloque empieza con "Survey data from <dev>". Los valores están
- // tabulados y separados por ":". El "[in use]" marca el canal operativo.
- // ParseIwSurvey parsea la salida de `iw dev wlanX survey dump` (#1214):
- // exportada para que el httpapi pueda parsear el survey crudo que empuja el
- // agente en unidades agent-only.
- func ParseIwSurvey(out string) map[string][]SurveyChannel {
- type rawChannel struct {
- freq int
- inUse bool
- noise int
- activeMs float64
- busyMs float64
- rxMs float64
- txMs float64
- }
- result := map[string][]SurveyChannel{}
- var currentDev string
- var current *rawChannel
- flush := func() {
- if currentDev == "" || current == nil {
- return
- }
- ch := SurveyChannel{
- Freq: current.freq,
- Channel: freqToChannel(current.freq),
- InUse: current.inUse,
- NoiseDbm: current.noise,
- }
- if current.activeMs > 0 {
- ch.BusyPct = current.busyMs / current.activeMs * 100
- ch.RxPct = current.rxMs / current.activeMs * 100
- ch.TxPct = current.txMs / current.activeMs * 100
- }
- result[currentDev] = append(result[currentDev], ch)
- current = nil
- }
- for _, line := range strings.Split(out, "\n") {
- line = strings.TrimRight(line, "\r")
- trimmed := strings.TrimSpace(line)
- if strings.HasPrefix(trimmed, "Survey data from ") {
- flush()
- currentDev = strings.TrimPrefix(trimmed, "Survey data from ")
- continue
- }
- if currentDev == "" {
- continue
- }
- parts := strings.SplitN(trimmed, ":", 2)
- if len(parts) != 2 {
- continue
- }
- // Solo inicializamos el canal si la línea tiene un campo válido.
- // Evita crear un canal vacío al final de cada bloque (línea "" final).
- if current == nil {
- current = &rawChannel{}
- }
- key := strings.TrimSpace(parts[0])
- val := strings.TrimSpace(parts[1])
- switch key {
- case "frequency":
- fmt.Sscanf(val, "%d MHz", ¤t.freq)
- if strings.Contains(val, "[in use]") {
- current.inUse = true
- }
- case "noise":
- fmt.Sscanf(val, "%d dBm", ¤t.noise)
- case "channel active time":
- fmt.Sscanf(val, "%f ms", ¤t.activeMs)
- case "channel busy time":
- fmt.Sscanf(val, "%f ms", ¤t.busyMs)
- case "channel receive time":
- fmt.Sscanf(val, "%f ms", ¤t.rxMs)
- case "channel transmit time":
- fmt.Sscanf(val, "%f ms", ¤t.txMs)
- }
- }
- flush()
- return result
- }
- // surveyEntry: survey crudo del agente con su marca de tiempo (#1214).
- type surveyEntry struct {
- raw string
- at time.Time
- }
- const agentSurveyTTL = 15 * time.Minute
- // StoreAgentSurvey guarda el texto crudo de `iw survey dump` que empuja un
- // agente (#1214): fuente de la lente "Ahora" en unidades agent-only sin SSH.
- // El httpapi lo llama en cada push que traiga surveyRaw.
- func (l *Live) StoreAgentSurvey(routerID, raw string) {
- if raw == "" {
- return
- }
- l.surveyMu.Lock()
- if l.surveyRaw == nil {
- l.surveyRaw = map[string]surveyEntry{}
- }
- l.surveyRaw[routerID] = surveyEntry{raw: raw, at: time.Now()}
- l.surveyMu.Unlock()
- }
- // agentSurveyRadios parsea el survey crudo del agente si está fresco
- // (agentSurveyTTL); nil si no hay datos o caducaron.
- func (l *Live) agentSurveyRadios(routerID string) []SurveyRadio {
- l.surveyMu.Lock()
- e, ok := l.surveyRaw[routerID]
- l.surveyMu.Unlock()
- if !ok || time.Since(e.at) > agentSurveyTTL {
- return nil
- }
- per := ParseIwSurvey(e.raw)
- radios := []SurveyRadio{}
- for dev, channels := range per {
- if len(channels) == 0 {
- continue
- }
- band := ""
- for _, c := range channels {
- if c.InUse {
- band = freqToBand(c.Freq)
- break
- }
- }
- if band == "" {
- band = freqToBand(channels[0].Freq)
- }
- radios = append(radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
- }
- return radios
- }
- // GetSurvey: utilización por canal wifi (iw survey dump) por router y radio.
- // Recorre los routers (saltando agent-only, que no tienen wifi) y hace SSH
- // `iw dev` para listar interfaces, luego `iw dev wlanX survey dump` por cada
- // una. Devuelve (nil, nil) si ningún router responde → el handler 503.
- func (l *Live) GetSurvey(ctx context.Context) (*SurveyOverview, error) {
- l.mu.Lock()
- routers := append([]RouterConfig(nil), l.routers...)
- l.mu.Unlock()
- out := SurveyOverview{Routers: []SurveyRouter{}}
- any := false
- // #1308: el gateway YA NO se excluye. La exclusión venía de #1214, cuando
- // el survey vivía en la pestaña de roaming (los clientes no reanclan al
- // gateway en flotas con APs). Desde #1229 la lente es de CANALES, donde el
- // gateway es un AP más: su agente empuja iw survey dump igual que los
- // demás (#1270) y su espectro importa para el análisis.
- for _, cfg := range routers {
- name := cfg.Name
- if name == "" {
- name = cfg.ID
- }
- r := SurveyRouter{RouterID: cfg.ID, Name: name, Radios: []SurveyRadio{}}
- // Agent-only y SNMP (#1026): unidades sin SSH. Las agent-only pueden
- // traer survey vía push del agente (#1214); SNMP se lista sin radios.
- if cfg.AgentOnly {
- if radios := l.agentSurveyRadios(cfg.ID); len(radios) > 0 {
- r.Available = true
- r.Radios = radios
- any = true
- } else {
- // #1742: el agente solo empuja iw survey dump si el driver lo
- // expone. En Broadcom/dhd no existe y la unidad queda sin datos
- // sin que se pueda distinguir de "no lo intentó".
- r.Reason = SurveyReasonAgentNoSurvey
- }
- out.Routers = append(out.Routers, r)
- continue
- }
- if cfg.SnmpEnabled {
- r.Reason = SurveyReasonSnmpOnly
- out.Routers = append(out.Routers, r)
- continue
- }
- // Lista de interfaces wifi (wlanX).
- devsOut, err := l.pool.Run(cfg.SSHAddr(), "iw dev 2>/dev/null | awk '/Interface/ {print $2}'", 0)
- if err != nil {
- r.Reason = SurveyReasonSSHUnreachable
- out.Routers = append(out.Routers, r)
- continue
- }
- devs := []string{}
- for _, line := range strings.Split(devsOut, "\n") {
- d := strings.TrimSpace(line)
- // iw dev solo lista interfaces wifi, pero el nombre puede ser
- // wlan0/wlan1 (driver estándar) o phy0-ap0/phy1-ap0 (mt76,
- // Xiaomi AX6). Aceptamos cualquier token no vacío que awk haya
- // extraído de la línea "Interface <name>".
- if d != "" {
- devs = append(devs, d)
- }
- }
- if len(devs) == 0 {
- r.Reason = SurveyReasonNoWifi
- out.Routers = append(out.Routers, r)
- continue
- }
- for _, dev := range devs {
- surveyOut, err := l.pool.Run(cfg.SSHAddr(), "iw dev "+dev+" survey dump 2>/dev/null", 0)
- if err != nil {
- continue
- }
- channels := ParseIwSurvey(surveyOut)[dev]
- if len(channels) == 0 {
- continue
- }
- band := ""
- // El canal in use define la banda del radio.
- for _, c := range channels {
- if c.InUse {
- band = freqToBand(c.Freq)
- break
- }
- }
- if band == "" {
- band = freqToBand(channels[0].Freq)
- }
- r.Radios = append(r.Radios, SurveyRadio{Device: dev, Band: band, Channels: channels})
- }
- // #1742: SSH respondió pero ningún radio devolvió canales (iw survey
- // dump vacío). Se dice, en vez de listar la unidad como participante
- // sin datos.
- if len(r.Radios) > 0 {
- r.Available = true
- any = true
- } else {
- r.Reason = SurveyReasonNoSurveyData
- }
- out.Routers = append(out.Routers, r)
- }
- // #1742: se devuelve SIEMPRE la lista, con el motivo de cada unidad que no
- // aporta. El handler ya no responde 503: la UI explica el caso concreto.
- out.Available = any
- return &out, nil
- }
- // allWifiOfOneAP: ¿todas las MACs de la boca son clientes WiFi del mismo AP?
- func allWifiOfOneAP(macs []string, wifiByMac map[string]string) bool {
- if len(macs) == 0 {
- return false
- }
- ap := wifiByMac[macs[0]]
- if ap == "" {
- return false
- }
- for _, m := range macs[1:] {
- if wifiByMac[m] != ap {
- return false
- }
- }
- return true
- }
- // prefijos OUI de virtualización: la MAC aprendida es una NIC virtual.
- var virtualMACPrefixes = []string{
- "52:54:00", // QEMU/KVM (Proxmox VMs por defecto)
- "BC:24:11", // Proxmox Server Solutions
- "00:15:5D", // Microsoft Hyper-V
- "00:50:56", // VMware ESX
- "00:1C:14", // VMware
- "08:00:27", // VirtualBox
- }
- func isVirtualMAC(mac string) bool {
- m := strings.ToUpper(mac)
- for _, p := range virtualMACPrefixes {
- if strings.HasPrefix(m, p) {
- return true
- }
- }
- return false
- }
- // virtualDetail: nombre legible de la VM/CT detrás del hypervisor.
- func virtualDetail(mac string, leases map[string]DhcpLease, aliases map[string]string) string {
- if n := deviceDisplayName(mac, leases, aliases); n != mac {
- return n + " (VM/CT detrás)"
- }
- return "VM/CT detrás"
- }
- // isCuratedLabel: label renombrada a mano (no el "Port N" por defecto).
- func isCuratedLabel(port EthPort) bool {
- if port.Label == "" {
- return false
- }
- n := strings.TrimPrefix(port.Label, "Port ")
- if n == port.Label {
- return true // no sigue el patrón por defecto
- }
- _, err := strconv.Atoi(n)
- return err != nil // "Port <número>" = default; cualquier otra cosa, curada
- }
- // labelMatchesDevice: ¿la label curada nombra al propio dispositivo
- // aprendido (p. ej. "hikvision") y no a la infraestructura que hay delante?
- func labelMatchesDevice(label, mac string, leases map[string]DhcpLease, aliases map[string]string) bool {
- name := strings.ToLower(deviceDisplayName(mac, leases, aliases))
- l := strings.ToLower(label)
- if name == "" || l == "" {
- return false
- }
- return strings.Contains(name, l) || strings.Contains(l, name)
- }
- // deviceDisplayName: hostname de lease > alias > MAC.
- func deviceDisplayName(mac string, leases map[string]DhcpLease, aliases map[string]string) string {
- if le, ok := leases[mac]; ok && le.Hostname != "" {
- return le.Hostname
- }
- if a := aliases[mac]; a != "" {
- return a
- }
- return mac
- }
- // portEnrichDeps: mapas compartidos del enriquecimiento de bocas del
- // detalle (extraído de GetRouterDetail, #1150, para poder testearlo).
- type portEnrichDeps struct {
- routerByMac map[string]string
- leaseMap map[string]DhcpLease
- aliasByMac map[string]string
- wifiByMac map[string]string
- portMacs map[string][]string
- lldp []LldpNeighbor
- // #1976: para desambiguar cuando una boca ve varias unidades de flota.
- // unitByMac (MAC de bridge → id), fdbByUnit (id → su FDB) y selfBrMac
- // (la MAC de bridge de la unidad que se está enriqueciendo).
- unitByMac map[string]string
- fdbByUnit map[string]map[string]string
- selfBrMac string
- }
- // directFleetPeer (#1976): elige, entre varias unidades de flota visibles en
- // la misma boca, la que tiene a ESTA unidad en un puerto dedicado, es decir,
- // un puerto de su FDB donde no aparece ninguna otra unidad de flota. Es la
- // diferencia entre el cable directo y el uplink que arrastra el tráfico de
- // toda la cadena: sw1 aprende test-gw en el puerto donde solo está test-gw,
- // sw2 lo aprende en el uplink que también lleva a sw1.
- //
- // Sin FDB de las candidatas, sin MAC de bridge propia o con empate, no hay
- // ganador y se devuelve false: la boca se queda sin par antes que con el
- // equivocado.
- func directFleetPeer(d portEnrichDeps, candidates []string) (string, bool) {
- if d.selfBrMac == "" || len(d.fdbByUnit) == 0 {
- return "", false
- }
- best, bestOthers, tie := "", 0, false
- for _, mac := range candidates {
- unit := d.unitByMac[strings.ToUpper(mac)]
- fdb := d.fdbByUnit[unit]
- if unit == "" || len(fdb) == 0 {
- continue
- }
- port, ok := fdbPortOf(fdb, d.selfBrMac)
- if !ok {
- continue
- }
- others := 0
- for otherMac, otherPort := range fdb {
- if otherPort != port || strings.EqualFold(otherMac, d.selfBrMac) {
- continue
- }
- if _, fleet := d.unitByMac[strings.ToUpper(otherMac)]; fleet {
- others++
- }
- }
- switch {
- case best == "" || others < bestOthers:
- best, bestOthers, tie = mac, others, false
- case others == bestOthers:
- tie = true
- }
- }
- if best == "" || tie || bestOthers > 0 {
- return "", false
- }
- return best, true
- }
- // enrichEthPort: enriquece UNA boca encendida con el par que tiene enfrente
- // (router-link, cliente WiFi detrás del AP, dispositivo único, agregación).
- // Mismo comportamiento que el bucle inline que sustituye (#1150).
- func enrichEthPort(port EthPort, netdev string, d portEnrichDeps) EthPort {
- all := d.portMacs[netdev]
- // #1036: d.portMacs se construye iterando el FDB (mapa), así que el
- // ORDEN de las MACs por boca cambia en cada tick. Con 2-3 MACs la
- // heurística de "primera con hostname DHCP" elegía un dispositivo
- // distinto por ciclo y la etiqueta del puerto flappeaba. Orden
- // estable: la selección queda determinista entre polls.
- sort.Strings(all)
- // 1) ¿Otro router al otro lado? (uplink router↔router)
- neighbor := ""
- for _, mac := range all {
- if _, ok := d.routerByMac[mac]; ok {
- neighbor = mac
- break
- }
- }
- if neighbor != "" {
- port.ConnectedTo = d.routerByMac[neighbor]
- // El cliente traduce la plantilla según PeerKind (#1039).
- port.PeerKind = PeerKindRouterLink
- // #1976: sin LLDP, una boca que ve el bridge de VARIAS unidades no
- // puede nombrar a una sin adivinar. La candidata válida es la que
- // aprende a esta unidad en un puerto dedicado; si no hay una clara,
- // la boca se queda sin par antes que con el equivocado.
- if lldpNeighborOnPort(d.lldp, netdev) == nil {
- cands := make([]string, 0, 2)
- for _, mac := range all {
- if _, ok := d.routerByMac[mac]; ok {
- cands = append(cands, mac)
- }
- }
- if len(cands) > 1 {
- if mac, ok := directFleetPeer(d, cands); ok {
- port.ConnectedTo = d.routerByMac[mac]
- port.DeviceMac = mac
- port.PeerKind = PeerKindRouterLink
- } else {
- port.ConnectedTo = ""
- port.PeerKind = ""
- return port
- }
- }
- return port
- }
- // #1150: con switches encadenados la boca aprende las MACs de bridge
- // de VARIAS unidades (el tráfico de sw2 atraviesa sw1) y la primera
- // MAC ordenada puede nombrar al switch LEJANO. El LLDP anuncia al
- // vecino DIRECTO de la boca: su chassis MAC (si es unidad conocida)
- // o su sysName manda sobre la MAC ordenada, y la mgmt-ip va al
- // detalle del hover.
- if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
- port.PeerKind = PeerKindRouterLinkLLDP
- if nb.ChassisMac != "" {
- // La MAC del vecino (su bridge) va al hover como en las bocas
- // de dispositivo único (#1150).
- port.DeviceMac = strings.ToUpper(nb.ChassisMac)
- if name, ok := d.routerByMac[strings.ToUpper(nb.ChassisMac)]; ok {
- port.ConnectedTo = name
- } else if dn := nb.displayName(); dn != "" {
- port.ConnectedTo = dn
- }
- } else if dn := nb.displayName(); dn != "" {
- port.ConnectedTo = dn
- }
- if nb.Mgmt != "" {
- port.Detail = nb.Mgmt + " · LLDP"
- }
- }
- return port
- }
- // 1.5) Cliente WiFi detrás de un AP: la boca del switch lleva al AP
- // (el cliente viaja por su radio). Atribuir la boca al AP y señalar
- // el cliente como "detrás" (#291). Guard de longitud PRIMERO: una
- // boca up sin MACs aprendidas llega con all vacío.
- if len(all) > 0 {
- if ap, isWifi := d.wifiByMac[all[0]]; isWifi && allWifiOfOneAP(all, d.wifiByMac) {
- port.ConnectedTo = ap
- port.DeviceMac = all[0]
- // La pista "cliente WiFi detrás" la traduce el cliente
- // según PeerKind (#1039); el nombre del AP viaja en ConnectedTo.
- port.PeerKind = PeerKindAPWiFi
- return port
- }
- }
- // 2) Un solo dispositivo final
- if len(all) == 1 {
- mac := all[0]
- lease, ok := d.leaseMap[mac]
- // #931: un vecino LLDP en esta boca es el propio equipo
- // anunciándose; su sysName/mgmt-ip son mejor identificación que
- // la MAC pelada cuando no hay hostname DHCP ni alias.
- lldpName, lldpMgmt := "", ""
- if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil {
- lldpName = nb.displayName()
- lldpMgmt = nb.Mgmt
- }
- // MAC de virtualización (QEMU/KVM, Proxmox, VMware, Hyper-V):
- // el equipo enchufado es el hypervisor; lo aprendido es una
- // NIC virtual de una VM/CT (#291).
- if isVirtualMAC(mac) {
- port.ConnectedTo = "Hypervisor"
- port.DeviceMac = mac
- port.Detail = virtualDetail(mac, d.leaseMap, d.aliasByMac)
- return port
- }
- // Label curada que no coincide con el dispositivo resuelto:
- // - si el dispositivo tiene nombre real (lease/alias), la label
- // nombra la infraestructura física y lo aprendido está DETRÁS
- // (p. ej. ngxpm detrás de citadel-02);
- // - si el dispositivo no tiene nombre mejor que su MAC, la label
- // ES su nombre (bautizada a mano: "hikvision"), y la MAC queda
- // como detalle.
- if isCuratedLabel(port) && !labelMatchesDevice(port.Label, mac, d.leaseMap, d.aliasByMac) {
- name := deviceDisplayName(mac, d.leaseMap, d.aliasByMac)
- port.DeviceMac = mac
- if name != mac {
- // El cliente compone "nombre · detrás de <label>" con
- // su i18n (#1039); aquí viaja el nombre a pelo.
- port.ConnectedTo = name
- port.PeerKind = PeerKindCurated
- } else if lldpName != "" {
- // #931: sin nombre mejor, el equipo se anuncia por LLDP.
- port.ConnectedTo = lldpName
- port.PeerKind = PeerKindMAC
- } else {
- port.ConnectedTo = port.Label
- port.PeerKind = PeerKindMAC
- }
- if lease, ok := d.leaseMap[mac]; ok && lease.IP != "" {
- port.Detail = lease.IP
- } else if lldpMgmt != "" && lldpName != "" {
- port.Detail = lldpMgmt + " · LLDP"
- }
- return port
- }
- switch {
- case ok && lease.Hostname != "":
- port.ConnectedTo = lease.Hostname
- case ok && lease.IP != "":
- port.ConnectedTo = lease.IP
- case d.aliasByMac[mac] != "":
- port.ConnectedTo = d.aliasByMac[mac]
- case lldpName != "":
- // #931: sin lease ni alias, el nombre anunciado por el
- // propio equipo (LLDP sysName) es la mejor etiqueta.
- port.ConnectedTo = lldpName
- if lldpMgmt != "" {
- port.Detail = lldpMgmt + " · LLDP"
- }
- default:
- port.ConnectedTo = mac
- }
- port.DeviceMac = mac
- if ok && lease.IP != "" {
- port.Detail = lease.IP + " · full duplex"
- }
- return port
- }
- // 3) Varios: el vecino es un switch/hub/hipervisor
- if len(all) > 1 {
- // Muchas MACs detrás de una boca = agregación (hipervisor Proxmox
- // con CTs, switch tonto): nombrar UN CT al azar engaña (la MAC es
- // virtual, no el equipo enchufado). La label curada del puerto ya
- // identifica el físico; aquí se cuenta lo que hay detrás (#291).
- if len(all) > 3 {
- // deviceCount lo traduce la app; aquí NO se formatea texto (#1036).
- port.DeviceCount = len(all)
- return port
- }
- // Si se anuncia por LLDP, esa identificación (chassis + mgmt-ip)
- // es mejor pista que el hostname DHCP.
- if nb := lldpNeighborOnPort(d.lldp, netdev); nb != nil && nb.displayName() != "" {
- port.ConnectedTo = nb.displayName()
- if nb.Mgmt != "" {
- port.Detail = nb.Mgmt + " · LLDP"
- } else {
- port.Detail = "LLDP"
- }
- return port
- }
- infraMac := ""
- for _, mac := range all {
- if le, ok := d.leaseMap[mac]; ok && le.Hostname != "" {
- infraMac = mac
- break
- }
- }
- if infraMac == "" {
- // Sin hostname DHCP: primer alias manual como pista (#291).
- for _, mac := range all {
- if d.aliasByMac[mac] != "" {
- infraMac = mac
- break
- }
- }
- }
- if infraMac != "" {
- if lease, ok := d.leaseMap[infraMac]; ok && lease.Hostname != "" {
- port.ConnectedTo = lease.Hostname
- port.DeviceMac = infraMac
- if lease.IP != "" {
- port.Detail = lease.IP
- }
- } else if alias := d.aliasByMac[infraMac]; alias != "" {
- port.ConnectedTo = alias
- port.DeviceMac = infraMac
- }
- } else {
- // Switch/bridge tonto inferido: sin lease ni alias que lo
- // nombre. El cliente traduce la etiqueta (#1039/#1040).
- port.PeerKind = PeerKindInferredSwitch
- }
- return port
- }
- return port
- }
- // networkInfos convierte la configuracion UCI en la vista de redes (#1889).
- // El trafico es el del DEVICE de la red (br-iot), que ya llega como puerto
- // virtual con rates: una bridge suma lo de sus puertos y eso no es lo que el
- // operador lee en su panel. Sin contadores la fila simplemente no lo muestra.
- func networkInfos(nets []probe.UciNetwork, ports []EthPort) []NetworkInfo {
- byIface := map[string]EthPort{}
- for _, pt := range ports {
- if pt.Iface != "" {
- byIface[pt.Iface] = pt
- }
- }
- out := make([]NetworkInfo, 0, len(nets))
- for _, n := range nets {
- ni := NetworkInfo{Name: n.Name, Device: n.Device, Proto: n.Proto, Subnet: n.Subnet, Vlan: n.Vlan, Ports: n.Ports}
- if pt, ok := byIface[n.Device]; ok {
- ni.RxBps = pt.RxBps
- ni.TxBps = pt.TxBps
- }
- out = append(out, ni)
- }
- return out
- }
|