live.go 229 KB

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