live.go 219 KB

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