live.go 226 KB

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