live.go 213 KB

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