live.go 220 KB

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