live.go 246 KB

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