live.go 244 KB

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