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