dashboard.js 379 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. // DO NOT EDIT: This file is automatically generated from the source files in src/
  3. // ----------------------------------------------------------------------------
  4. // You can set the following variables before loading this script:
  5. // 'use strict';
  6. /*global netdataNoDygraphs *//* boolean, disable dygraph charts
  7. * (default: false) */
  8. /*global netdataNoSparklines *//* boolean, disable sparkline charts
  9. * (default: false) */
  10. /*global netdataNoPeitys *//* boolean, disable peity charts
  11. * (default: false) */
  12. /*global netdataNoGoogleCharts *//* boolean, disable google charts
  13. * (default: false) */
  14. /*global netdataNoMorris *//* boolean, disable morris charts
  15. * (default: false) */
  16. /*global netdataNoEasyPieChart *//* boolean, disable easypiechart charts
  17. * (default: false) */
  18. /*global netdataNoGauge *//* boolean, disable gauge.js charts
  19. * (default: false) */
  20. /*global netdataNoD3 *//* boolean, disable d3 charts
  21. * (default: false) */
  22. /*global netdataNoC3 *//* boolean, disable c3 charts
  23. * (default: false) */
  24. /*global netdataNoD3pie *//* boolean, disable d3pie charts
  25. * (default: false) */
  26. /*global netdataNoBootstrap *//* boolean, disable bootstrap - disables help too
  27. * (default: false) */
  28. /*global netdataNoFontAwesome *//* boolean, disable fontawesome (do not load it)
  29. * (default: false) */
  30. /*global netdataIcons *//* object, overwrite netdata fontawesome icons
  31. * (default: null) */
  32. /*global netdataDontStart *//* boolean, do not start the thread to process the charts
  33. * (default: false) */
  34. /*global netdataErrorCallback *//* function, callback to be called when the dashboard encounters an error
  35. * (default: null) */
  36. /*global netdataRegistry:true *//* boolean, use the netdata registry
  37. * (default: false) */
  38. /*global netdataNoRegistry *//* boolean, included only for compatibility with existing custom dashboard
  39. * (obsolete - do not use this any more) */
  40. /*global netdataRegistryCallback *//* function, callback that will be invoked with one param: the URLs from the registry
  41. * (default: null) */
  42. /*global netdataShowHelp:true *//* boolean, disable charts help
  43. * (default: true) */
  44. /*global netdataShowAlarms:true *//* boolean, enable alarms checks and notifications
  45. * (default: false) */
  46. /*global netdataRegistryAfterMs:true *//* ms, delay registry use at started
  47. * (default: 1500) */
  48. /*global netdataCallback *//* function, callback to be called when netdata is ready to start
  49. * (default: null)
  50. * netdata will be running while this is called
  51. * (call NETDATA.pause to stop it) */
  52. /*global netdataPrepCallback *//* function, callback to be called before netdata does anything else
  53. * (default: null) */
  54. /*global netdataServer *//* string, the URL of the netdata server to use
  55. * (default: the URL the page is hosted at) */
  56. /*global netdataServerStatic *//* string, the URL of the netdata server to use for static files
  57. * (default: netdataServer) */
  58. /*global netdataSnapshotData *//* object, a netdata snapshot loaded
  59. * (default: null) */
  60. /*global netdataAlarmsRecipients *//* array, an array of alarm recipients to show notifications for
  61. * (default: null) */
  62. /*global netdataAlarmsRemember *//* boolean, keep our position in the alarm log at browser local storage
  63. * (default: true) */
  64. /*global netdataAlarmsActiveCallback *//* function, a hook for the alarm logs
  65. * (default: undefined) */
  66. /*global netdataAlarmsNotifCallback *//* function, a hook for alarm notifications
  67. * (default: undefined) */
  68. /*global netdataIntersectionObserver *//* boolean, enable or disable the use of intersection observer
  69. * (default: true) */
  70. /*global netdataCheckXSS *//* boolean, enable or disable checking for XSS issues
  71. * (default: false) */
  72. // ----------------------------------------------------------------------------
  73. // global namespace
  74. // Should stay var!
  75. var NETDATA = window.NETDATA || {};
  76. (function(window, document, $, undefined) {
  77. // *** src/dashboard.js/utils.js
  78. NETDATA.name2id = function (s) {
  79. return s
  80. .replace(/ /g, '_')
  81. .replace(/:/g, '_')
  82. .replace(/\(/g, '_')
  83. .replace(/\)/g, '_')
  84. .replace(/\./g, '_')
  85. .replace(/\//g, '_');
  86. };
  87. NETDATA.encodeURIComponent = function (s) {
  88. if (typeof(s) === 'string') {
  89. return encodeURIComponent(s);
  90. }
  91. return s;
  92. };
  93. /// A heuristic for detecting slow devices.
  94. let isSlowDeviceResult = undefined;
  95. const isSlowDevice = function () {
  96. if (!isSlowDeviceResult) {
  97. return isSlowDeviceResult;
  98. }
  99. try {
  100. let ua = navigator.userAgent.toLowerCase();
  101. let iOS = /ipad|iphone|ipod/.test(ua) && !window.MSStream;
  102. let android = /android/.test(ua) && !window.MSStream;
  103. isSlowDeviceResult = (iOS || android);
  104. } catch (e) {
  105. isSlowDeviceResult = false;
  106. }
  107. return isSlowDeviceResult;
  108. };
  109. NETDATA.guid = function () {
  110. function s4() {
  111. return Math.floor((1 + Math.random()) * 0x10000)
  112. .toString(16)
  113. .substring(1);
  114. }
  115. return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
  116. };
  117. NETDATA.zeropad = function (x) {
  118. if (x > -10 && x < 10) {
  119. return '0' + x.toString();
  120. } else {
  121. return x.toString();
  122. }
  123. };
  124. NETDATA.seconds4human = function (seconds, options) {
  125. let defaultOptions = {
  126. now: 'now',
  127. space: ' ',
  128. negative_suffix: 'ago',
  129. day: 'day',
  130. days: 'days',
  131. hour: 'hour',
  132. hours: 'hours',
  133. minute: 'min',
  134. minutes: 'mins',
  135. second: 'sec',
  136. seconds: 'secs',
  137. and: 'and'
  138. };
  139. if (typeof options !== 'object') {
  140. options = defaultOptions;
  141. } else {
  142. for (var x in defaultOptions) {
  143. if (typeof options[x] !== 'string') {
  144. options[x] = defaultOptions[x];
  145. }
  146. }
  147. }
  148. if (typeof seconds === 'string') {
  149. seconds = parseInt(seconds, 10);
  150. }
  151. if (seconds === 0) {
  152. return options.now;
  153. }
  154. let suffix = '';
  155. if (seconds < 0) {
  156. seconds = -seconds;
  157. if (options.negative_suffix !== '') {
  158. suffix = options.space + options.negative_suffix;
  159. }
  160. }
  161. let days = Math.floor(seconds / 86400);
  162. seconds -= (days * 86400);
  163. let hours = Math.floor(seconds / 3600);
  164. seconds -= (hours * 3600);
  165. let minutes = Math.floor(seconds / 60);
  166. seconds -= (minutes * 60);
  167. let strings = [];
  168. if (days > 1) {
  169. strings.push(days.toString() + options.space + options.days);
  170. } else if (days === 1) {
  171. strings.push(days.toString() + options.space + options.day);
  172. }
  173. if (hours > 1) {
  174. strings.push(hours.toString() + options.space + options.hours);
  175. } else if (hours === 1) {
  176. strings.push(hours.toString() + options.space + options.hour);
  177. }
  178. if (minutes > 1) {
  179. strings.push(minutes.toString() + options.space + options.minutes);
  180. } else if (minutes === 1) {
  181. strings.push(minutes.toString() + options.space + options.minute);
  182. }
  183. if (seconds > 1) {
  184. strings.push(Math.floor(seconds).toString() + options.space + options.seconds);
  185. } else if (seconds === 1) {
  186. strings.push(Math.floor(seconds).toString() + options.space + options.second);
  187. }
  188. if (strings.length === 1) {
  189. return strings.pop() + suffix;
  190. }
  191. let last = strings.pop();
  192. return strings.join(", ") + " " + options.and + " " + last + suffix;
  193. };
  194. // ----------------------------------------------------------------------------------------------------------------
  195. // element data attributes
  196. NETDATA.dataAttribute = function (element, attribute, def) {
  197. let key = 'data-' + attribute.toString();
  198. if (element.hasAttribute(key)) {
  199. let data = element.getAttribute(key);
  200. if (data === 'true') {
  201. return true;
  202. }
  203. if (data === 'false') {
  204. return false;
  205. }
  206. if (data === 'null') {
  207. return null;
  208. }
  209. // Only convert to a number if it doesn't change the string
  210. if (data === +data + '') {
  211. return +data;
  212. }
  213. if (/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/.test(data)) {
  214. return JSON.parse(data);
  215. }
  216. return data;
  217. } else {
  218. return def;
  219. }
  220. };
  221. NETDATA.dataAttributeBoolean = function (element, attribute, def) {
  222. let value = NETDATA.dataAttribute(element, attribute, def);
  223. if (value === true || value === false) // gmosx: Love this :)
  224. {
  225. return value;
  226. }
  227. if (typeof(value) === 'string') {
  228. if (value === 'yes' || value === 'on') {
  229. return true;
  230. }
  231. if (value === '' || value === 'no' || value === 'off' || value === 'null') {
  232. return false;
  233. }
  234. return def;
  235. }
  236. if (typeof(value) === 'number') {
  237. return value !== 0;
  238. }
  239. return def;
  240. };
  241. // ----------------------------------------------------------------------------------------------------------------
  242. // fast numbers formatting
  243. NETDATA.fastNumberFormat = {
  244. formattersFixed: [],
  245. formattersZeroBased: [],
  246. // this is the fastest and the preferred
  247. getIntlNumberFormat: function (min, max) {
  248. let key = max;
  249. if (min === max) {
  250. if (typeof this.formattersFixed[key] === 'undefined') {
  251. this.formattersFixed[key] = new Intl.NumberFormat(undefined, {
  252. // style: 'decimal',
  253. // minimumIntegerDigits: 1,
  254. // minimumSignificantDigits: 1,
  255. // maximumSignificantDigits: 1,
  256. useGrouping: true,
  257. minimumFractionDigits: min,
  258. maximumFractionDigits: max
  259. });
  260. }
  261. return this.formattersFixed[key];
  262. } else if (min === 0) {
  263. if (typeof this.formattersZeroBased[key] === 'undefined') {
  264. this.formattersZeroBased[key] = new Intl.NumberFormat(undefined, {
  265. // style: 'decimal',
  266. // minimumIntegerDigits: 1,
  267. // minimumSignificantDigits: 1,
  268. // maximumSignificantDigits: 1,
  269. useGrouping: true,
  270. minimumFractionDigits: min,
  271. maximumFractionDigits: max
  272. });
  273. }
  274. return this.formattersZeroBased[key];
  275. } else {
  276. // this is never used
  277. // it is added just for completeness
  278. return new Intl.NumberFormat(undefined, {
  279. // style: 'decimal',
  280. // minimumIntegerDigits: 1,
  281. // minimumSignificantDigits: 1,
  282. // maximumSignificantDigits: 1,
  283. useGrouping: true,
  284. minimumFractionDigits: min,
  285. maximumFractionDigits: max
  286. });
  287. }
  288. },
  289. // this respects locale
  290. getLocaleString: function (min, max) {
  291. let key = max;
  292. if (min === max) {
  293. if (typeof this.formattersFixed[key] === 'undefined') {
  294. this.formattersFixed[key] = {
  295. format: function (value) {
  296. return value.toLocaleString(undefined, {
  297. // style: 'decimal',
  298. // minimumIntegerDigits: 1,
  299. // minimumSignificantDigits: 1,
  300. // maximumSignificantDigits: 1,
  301. useGrouping: true,
  302. minimumFractionDigits: min,
  303. maximumFractionDigits: max
  304. });
  305. }
  306. };
  307. }
  308. return this.formattersFixed[key];
  309. } else if (min === 0) {
  310. if (typeof this.formattersZeroBased[key] === 'undefined') {
  311. this.formattersZeroBased[key] = {
  312. format: function (value) {
  313. return value.toLocaleString(undefined, {
  314. // style: 'decimal',
  315. // minimumIntegerDigits: 1,
  316. // minimumSignificantDigits: 1,
  317. // maximumSignificantDigits: 1,
  318. useGrouping: true,
  319. minimumFractionDigits: min,
  320. maximumFractionDigits: max
  321. });
  322. }
  323. };
  324. }
  325. return this.formattersZeroBased[key];
  326. } else {
  327. return {
  328. format: function (value) {
  329. return value.toLocaleString(undefined, {
  330. // style: 'decimal',
  331. // minimumIntegerDigits: 1,
  332. // minimumSignificantDigits: 1,
  333. // maximumSignificantDigits: 1,
  334. useGrouping: true,
  335. minimumFractionDigits: min,
  336. maximumFractionDigits: max
  337. });
  338. }
  339. };
  340. }
  341. },
  342. // the fallback
  343. getFixed: function (min, max) {
  344. let key = max;
  345. if (min === max) {
  346. if (typeof this.formattersFixed[key] === 'undefined') {
  347. this.formattersFixed[key] = {
  348. format: function (value) {
  349. if (value === 0) {
  350. return "0";
  351. }
  352. return value.toFixed(max);
  353. }
  354. };
  355. }
  356. return this.formattersFixed[key];
  357. } else if (min === 0) {
  358. if (typeof this.formattersZeroBased[key] === 'undefined') {
  359. this.formattersZeroBased[key] = {
  360. format: function (value) {
  361. if (value === 0) {
  362. return "0";
  363. }
  364. return value.toFixed(max);
  365. }
  366. };
  367. }
  368. return this.formattersZeroBased[key];
  369. } else {
  370. return {
  371. format: function (value) {
  372. if (value === 0) {
  373. return "0";
  374. }
  375. return value.toFixed(max);
  376. }
  377. };
  378. }
  379. },
  380. testIntlNumberFormat: function () {
  381. let value = 1.12345;
  382. let e1 = "1.12", e2 = "1,12";
  383. let s = "";
  384. try {
  385. let x = new Intl.NumberFormat(undefined, {
  386. useGrouping: true,
  387. minimumFractionDigits: 2,
  388. maximumFractionDigits: 2
  389. });
  390. s = x.format(value);
  391. } catch (e) {
  392. s = "";
  393. }
  394. // console.log('NumberFormat: ', s);
  395. return (s === e1 || s === e2);
  396. },
  397. testLocaleString: function () {
  398. let value = 1.12345;
  399. let e1 = "1.12", e2 = "1,12";
  400. let s = "";
  401. try {
  402. s = value.toLocaleString(undefined, {
  403. useGrouping: true,
  404. minimumFractionDigits: 2,
  405. maximumFractionDigits: 2
  406. });
  407. } catch (e) {
  408. s = "";
  409. }
  410. // console.log('localeString: ', s);
  411. return (s === e1 || s === e2);
  412. },
  413. // on first run we decide which formatter to use
  414. get: function (min, max) {
  415. if (this.testIntlNumberFormat()) {
  416. // console.log('numberformat');
  417. this.get = this.getIntlNumberFormat;
  418. } else if (this.testLocaleString()) {
  419. // console.log('localestring');
  420. this.get = this.getLocaleString;
  421. } else {
  422. // console.log('fixed');
  423. this.get = this.getFixed;
  424. }
  425. return this.get(min, max);
  426. }
  427. };
  428. // ----------------------------------------------------------------------------------------------------------------
  429. // Detect the netdata server
  430. // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
  431. // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
  432. NETDATA._scriptSource = function () {
  433. let script = null;
  434. if (typeof document.currentScript !== 'undefined') {
  435. script = document.currentScript;
  436. } else {
  437. const all_scripts = document.getElementsByTagName('script');
  438. script = all_scripts[all_scripts.length - 1];
  439. }
  440. if (typeof script.getAttribute.length !== 'undefined') {
  441. script = script.src;
  442. } else {
  443. script = script.getAttribute('src', -1);
  444. }
  445. return script;
  446. };
  447. // *** src/dashboard.js/server-detection.js
  448. if (typeof netdataServer !== 'undefined') {
  449. NETDATA.serverDefault = netdataServer;
  450. } else {
  451. let s = NETDATA._scriptSource();
  452. if (s) {
  453. NETDATA.serverDefault = s.replace(/\/dashboard.js(\?.*)?$/g, "");
  454. } else {
  455. console.log('WARNING: Cannot detect the URL of the netdata server.');
  456. NETDATA.serverDefault = null;
  457. }
  458. }
  459. if (NETDATA.serverDefault === null) {
  460. NETDATA.serverDefault = '';
  461. } else if (NETDATA.serverDefault.slice(-1) !== '/') {
  462. NETDATA.serverDefault += '/';
  463. }
  464. if (typeof netdataServerStatic !== 'undefined' && netdataServerStatic !== null && netdataServerStatic !== '') {
  465. NETDATA.serverStatic = netdataServerStatic;
  466. if (NETDATA.serverStatic.slice(-1) !== '/') {
  467. NETDATA.serverStatic += '/';
  468. }
  469. } else {
  470. NETDATA.serverStatic = NETDATA.serverDefault;
  471. }
  472. // *** src/dashboard.js/dependencies.js
  473. // default URLs for all the external files we need
  474. // make them RELATIVE so that the whole thing can also be
  475. // installed under a web server
  476. NETDATA.jQuery = NETDATA.serverStatic + 'lib/jquery-3.6.0.min.js';
  477. NETDATA.peity_js = NETDATA.serverStatic + 'lib/jquery.peity-3.2.0.min.js';
  478. NETDATA.sparkline_js = NETDATA.serverStatic + 'lib/jquery.sparkline-2.1.2.min.js';
  479. NETDATA.easypiechart_js = NETDATA.serverStatic + 'lib/jquery.easypiechart-97b5824.min.js';
  480. NETDATA.gauge_js = NETDATA.serverStatic + 'lib/gauge-1.3.2.min.js';
  481. NETDATA.dygraph_js = NETDATA.serverStatic + 'lib/dygraph-c91c859.min.js';
  482. NETDATA.dygraph_smooth_js = NETDATA.serverStatic + 'lib/dygraph-smooth-plotter-c91c859.js';
  483. // NETDATA.raphael_js = NETDATA.serverStatic + 'lib/raphael-2.2.4-min.js';
  484. // NETDATA.c3_js = NETDATA.serverStatic + 'lib/c3-0.4.18.min.js';
  485. // NETDATA.c3_css = NETDATA.serverStatic + 'css/c3-0.4.18.min.css';
  486. NETDATA.d3pie_js = NETDATA.serverStatic + 'lib/d3pie-0.2.1-netdata-3.js';
  487. NETDATA.d3_js = NETDATA.serverStatic + 'lib/d3-4.12.2.min.js';
  488. // NETDATA.morris_js = NETDATA.serverStatic + 'lib/morris-0.5.1.min.js';
  489. // NETDATA.morris_css = NETDATA.serverStatic + 'css/morris-0.5.1.css';
  490. NETDATA.google_js = 'https://www.google.com/jsapi';
  491. // Error Handling
  492. NETDATA.errorCodes = {
  493. 100: {message: "Cannot load chart library", alert: true},
  494. 101: {message: "Cannot load jQuery", alert: true},
  495. 402: {message: "Chart library not found", alert: false},
  496. 403: {message: "Chart library not enabled/is failed", alert: false},
  497. 404: {message: "Chart not found", alert: false},
  498. 405: {message: "Cannot download charts index from server", alert: true},
  499. 406: {message: "Invalid charts index downloaded from server", alert: true},
  500. 407: {message: "Cannot HELLO netdata server", alert: false},
  501. 408: {message: "Netdata servers sent invalid response to HELLO", alert: false},
  502. 409: {message: "Cannot ACCESS netdata registry", alert: false},
  503. 410: {message: "Netdata registry ACCESS failed", alert: false},
  504. 411: {message: "Netdata registry server send invalid response to DELETE ", alert: false},
  505. 412: {message: "Netdata registry DELETE failed", alert: false},
  506. 413: {message: "Netdata registry server send invalid response to SWITCH ", alert: false},
  507. 414: {message: "Netdata registry SWITCH failed", alert: false},
  508. 415: {message: "Netdata alarms download failed", alert: false},
  509. 416: {message: "Netdata alarms log download failed", alert: false},
  510. 417: {message: "Netdata registry server send invalid response to SEARCH ", alert: false},
  511. 418: {message: "Netdata registry SEARCH failed", alert: false}
  512. };
  513. NETDATA.errorLast = {
  514. code: 0,
  515. message: "",
  516. datetime: 0
  517. };
  518. NETDATA.error = function (code, msg) {
  519. NETDATA.errorLast.code = code;
  520. NETDATA.errorLast.message = msg;
  521. NETDATA.errorLast.datetime = Date.now();
  522. console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
  523. let ret = true;
  524. if (typeof netdataErrorCallback === 'function') {
  525. ret = netdataErrorCallback('system', code, msg);
  526. }
  527. if (ret && NETDATA.errorCodes[code].alert) {
  528. alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
  529. }
  530. };
  531. NETDATA.errorReset = function () {
  532. NETDATA.errorLast.code = 0;
  533. NETDATA.errorLast.message = "You are doing fine!";
  534. NETDATA.errorLast.datetime = 0;
  535. };
  536. // *** src/dashboard.js/compatibility.js
  537. // Compatibility fixes.
  538. // fix IE issue with console
  539. if (!window.console) {
  540. window.console = {
  541. log: function () {
  542. }
  543. };
  544. }
  545. // if string.endsWith is not defined, define it
  546. if (typeof String.prototype.endsWith !== 'function') {
  547. String.prototype.endsWith = function (s) {
  548. if (s.length > this.length) {
  549. return false;
  550. }
  551. return this.slice(-s.length) === s;
  552. };
  553. }
  554. // if string.startsWith is not defined, define it
  555. if (typeof String.prototype.startsWith !== 'function') {
  556. String.prototype.startsWith = function (s) {
  557. if (s.length > this.length) {
  558. return false;
  559. }
  560. return this.slice(s.length) === s;
  561. };
  562. }
  563. // ----------------------------------------------------------------------------------------------------------------
  564. // XSS checks
  565. NETDATA.xss = {
  566. enabled: (typeof netdataCheckXSS === 'undefined') ? false : netdataCheckXSS,
  567. enabled_for_data: (typeof netdataCheckXSS === 'undefined') ? false : netdataCheckXSS,
  568. string: function (s) {
  569. return s.toString()
  570. .replace(/</g, '&lt;')
  571. .replace(/>/g, '&gt;')
  572. .replace(/"/g, '&quot;')
  573. .replace(/'/g, '&#39;');
  574. },
  575. object: function (name, obj, ignore_regex) {
  576. if (typeof ignore_regex !== 'undefined' && ignore_regex.test(name)) {
  577. // console.log('XSS: ignoring "' + name + '"');
  578. return obj;
  579. }
  580. switch (typeof(obj)) {
  581. case 'string':
  582. const ret = this.string(obj);
  583. if (ret !== obj) {
  584. console.log('XSS protection changed string ' + name + ' from "' + obj + '" to "' + ret + '"');
  585. }
  586. return ret;
  587. case 'object':
  588. if (obj === null) {
  589. return obj;
  590. }
  591. if (Array.isArray(obj)) {
  592. // console.log('checking array "' + name + '"');
  593. let len = obj.length;
  594. while (len--) {
  595. obj[len] = this.object(name + '[' + len + ']', obj[len], ignore_regex);
  596. }
  597. } else {
  598. // console.log('checking object "' + name + '"');
  599. for (var i in obj) {
  600. if (obj.hasOwnProperty(i) === false) {
  601. continue;
  602. }
  603. if (this.string(i) !== i) {
  604. console.log('XSS protection removed invalid object member "' + name + '.' + i + '"');
  605. delete obj[i];
  606. } else {
  607. obj[i] = this.object(name + '.' + i, obj[i], ignore_regex);
  608. }
  609. }
  610. }
  611. return obj;
  612. default:
  613. return obj;
  614. }
  615. },
  616. checkOptional: function (name, obj, ignore_regex) {
  617. if (this.enabled) {
  618. //console.log('XSS: checking optional "' + name + '"...');
  619. return this.object(name, obj, ignore_regex);
  620. }
  621. return obj;
  622. },
  623. checkAlways: function (name, obj, ignore_regex) {
  624. //console.log('XSS: checking always "' + name + '"...');
  625. return this.object(name, obj, ignore_regex);
  626. },
  627. checkData: function (name, obj, ignore_regex) {
  628. if (this.enabled_for_data) {
  629. //console.log('XSS: checking data "' + name + '"...');
  630. return this.object(name, obj, ignore_regex);
  631. }
  632. return obj;
  633. }
  634. };
  635. NETDATA.colorHex2Rgb = function (hex) {
  636. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  637. let shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  638. hex = hex.replace(shorthandRegex, function (m, r, g, b) {
  639. return r + r + g + g + b + b;
  640. });
  641. let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  642. return result ? {
  643. r: parseInt(result[1], 16),
  644. g: parseInt(result[2], 16),
  645. b: parseInt(result[3], 16)
  646. } : null;
  647. };
  648. NETDATA.colorLuminance = function (hex, lum) {
  649. // validate hex string
  650. hex = String(hex).replace(/[^0-9a-f]/gi, '');
  651. if (hex.length < 6) {
  652. hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
  653. }
  654. lum = lum || 0;
  655. // convert to decimal and change luminosity
  656. let rgb = "#";
  657. for (let i = 0; i < 3; i++) {
  658. let c = parseInt(hex.substr(i * 2, 2), 16);
  659. c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
  660. rgb += ("00" + c).substr(c.length);
  661. }
  662. return rgb;
  663. };
  664. NETDATA.unitsConversion = {
  665. keys: {}, // keys for data-common-units
  666. latest: {}, // latest selected units for data-common-units
  667. globalReset: function () {
  668. this.keys = {};
  669. this.latest = {};
  670. },
  671. scalableUnits: {
  672. 'packets/s': {
  673. 'pps': 1,
  674. 'Kpps': 1000,
  675. 'Mpps': 1000000
  676. },
  677. 'pps': {
  678. 'pps': 1,
  679. 'Kpps': 1000,
  680. 'Mpps': 1000000
  681. },
  682. 'kilobits/s': {
  683. 'bits/s': 1 / 1000,
  684. 'kilobits/s': 1,
  685. 'megabits/s': 1000,
  686. 'gigabits/s': 1000000,
  687. 'terabits/s': 1000000000
  688. },
  689. 'bytes/s': {
  690. 'bytes/s': 1,
  691. 'kilobytes/s': 1024,
  692. 'megabytes/s': 1024 * 1024,
  693. 'gigabytes/s': 1024 * 1024 * 1024,
  694. 'terabytes/s': 1024 * 1024 * 1024 * 1024
  695. },
  696. 'kilobytes/s': {
  697. 'bytes/s': 1 / 1024,
  698. 'kilobytes/s': 1,
  699. 'megabytes/s': 1024,
  700. 'gigabytes/s': 1024 * 1024,
  701. 'terabytes/s': 1024 * 1024 * 1024
  702. },
  703. 'B/s': {
  704. 'B/s': 1,
  705. 'KiB/s': 1024,
  706. 'MiB/s': 1024 * 1024,
  707. 'GiB/s': 1024 * 1024 * 1024,
  708. 'TiB/s': 1024 * 1024 * 1024 * 1024
  709. },
  710. 'KB/s': {
  711. 'B/s': 1 / 1024,
  712. 'KB/s': 1,
  713. 'MB/s': 1024,
  714. 'GB/s': 1024 * 1024,
  715. 'TB/s': 1024 * 1024 * 1024
  716. },
  717. 'KiB/s': {
  718. 'B/s': 1 / 1024,
  719. 'KiB/s': 1,
  720. 'MiB/s': 1024,
  721. 'GiB/s': 1024 * 1024,
  722. 'TiB/s': 1024 * 1024 * 1024
  723. },
  724. 'bytes': {
  725. 'bytes': 1,
  726. 'kilobytes': 1024,
  727. 'megabytes': 1024 * 1024,
  728. 'gigabytes': 1024 * 1024 * 1024,
  729. 'terabytes': 1024 * 1024 * 1024 * 1024
  730. },
  731. 'B': {
  732. 'B': 1,
  733. 'KiB': 1024,
  734. 'MiB': 1024 * 1024,
  735. 'GiB': 1024 * 1024 * 1024,
  736. 'TiB': 1024 * 1024 * 1024 * 1024,
  737. 'PiB': 1024 * 1024 * 1024 * 1024 * 1024
  738. },
  739. 'KB': {
  740. 'B': 1 / 1024,
  741. 'KB': 1,
  742. 'MB': 1024,
  743. 'GB': 1024 * 1024,
  744. 'TB': 1024 * 1024 * 1024
  745. },
  746. 'KiB': {
  747. 'B': 1 / 1024,
  748. 'KiB': 1,
  749. 'MiB': 1024,
  750. 'GiB': 1024 * 1024,
  751. 'TiB': 1024 * 1024 * 1024
  752. },
  753. 'MB': {
  754. 'B': 1 / (1024 * 1024),
  755. 'KB': 1 / 1024,
  756. 'MB': 1,
  757. 'GB': 1024,
  758. 'TB': 1024 * 1024,
  759. 'PB': 1024 * 1024 * 1024
  760. },
  761. 'MiB': {
  762. 'B': 1 / (1024 * 1024),
  763. 'KiB': 1 / 1024,
  764. 'MiB': 1,
  765. 'GiB': 1024,
  766. 'TiB': 1024 * 1024,
  767. 'PiB': 1024 * 1024 * 1024
  768. },
  769. 'GB': {
  770. 'B': 1 / (1024 * 1024 * 1024),
  771. 'KB': 1 / (1024 * 1024),
  772. 'MB': 1 / 1024,
  773. 'GB': 1,
  774. 'TB': 1024,
  775. 'PB': 1024 * 1024,
  776. 'EB': 1024 * 1024 * 1024
  777. },
  778. 'GiB': {
  779. 'B': 1 / (1024 * 1024 * 1024),
  780. 'KiB': 1 / (1024 * 1024),
  781. 'MiB': 1 / 1024,
  782. 'GiB': 1,
  783. 'TiB': 1024,
  784. 'PiB': 1024 * 1024,
  785. 'EiB': 1024 * 1024 * 1024
  786. },
  787. 'num': {
  788. 'num': 1,
  789. 'num (K)': 1000,
  790. 'num (M)': 1000000,
  791. 'num (G)': 1000000000,
  792. 'num (T)': 1000000000000
  793. },
  794. 'Hz': {
  795. 'Hz': 1,
  796. 'kHz': 10 ** 3,
  797. 'MHz': 10 ** 6,
  798. 'GHz': 10 ** 9,
  799. 'THz': 10 ** 12,
  800. 'PHz': 10 ** 15,
  801. 'EHz': 10 ** 18,
  802. 'ZHz': 10 ** 21,
  803. },
  804. /*
  805. 'milliseconds': {
  806. 'seconds': 1000
  807. },
  808. 'seconds': {
  809. 'milliseconds': 0.001,
  810. 'seconds': 1,
  811. 'minutes': 60,
  812. 'hours': 3600,
  813. 'days': 86400
  814. }
  815. */
  816. },
  817. convertibleUnits: {
  818. 'Celsius': {
  819. 'Fahrenheit': {
  820. check: function (max) {
  821. void(max);
  822. return NETDATA.options.current.temperature === 'fahrenheit';
  823. },
  824. convert: function (value) {
  825. return value * 9 / 5 + 32;
  826. }
  827. }
  828. },
  829. 'celsius': {
  830. 'fahrenheit': {
  831. check: function (max) {
  832. void(max);
  833. return NETDATA.options.current.temperature === 'fahrenheit';
  834. },
  835. convert: function (value) {
  836. return value * 9 / 5 + 32;
  837. }
  838. }
  839. },
  840. 'seconds': {
  841. 'time': {
  842. check: function (max) {
  843. void(max);
  844. return NETDATA.options.current.seconds_as_time;
  845. },
  846. convert: function (seconds) {
  847. return NETDATA.unitsConversion.seconds2time(seconds);
  848. }
  849. }
  850. },
  851. 'milliseconds': {
  852. 'milliseconds': {
  853. check: function (max) {
  854. return NETDATA.options.current.seconds_as_time && max < 1000;
  855. },
  856. convert: function (milliseconds) {
  857. let tms = Math.round(milliseconds * 10);
  858. milliseconds = Math.floor(tms / 10);
  859. tms -= milliseconds * 10;
  860. return (milliseconds).toString() + '.' + tms.toString();
  861. }
  862. },
  863. 'seconds': {
  864. check: function (max) {
  865. return NETDATA.options.current.seconds_as_time && max >= 1000 && max < 60000;
  866. },
  867. convert: function (milliseconds) {
  868. milliseconds = Math.round(milliseconds);
  869. let seconds = Math.floor(milliseconds / 1000);
  870. milliseconds -= seconds * 1000;
  871. milliseconds = Math.round(milliseconds / 10);
  872. return seconds.toString() + '.'
  873. + NETDATA.zeropad(milliseconds);
  874. }
  875. },
  876. 'M:SS.ms': {
  877. check: function (max) {
  878. return NETDATA.options.current.seconds_as_time && max >= 60000;
  879. },
  880. convert: function (milliseconds) {
  881. milliseconds = Math.round(milliseconds);
  882. let minutes = Math.floor(milliseconds / 60000);
  883. milliseconds -= minutes * 60000;
  884. let seconds = Math.floor(milliseconds / 1000);
  885. milliseconds -= seconds * 1000;
  886. milliseconds = Math.round(milliseconds / 10);
  887. return minutes.toString() + ':'
  888. + NETDATA.zeropad(seconds) + '.'
  889. + NETDATA.zeropad(milliseconds);
  890. }
  891. }
  892. },
  893. 'nanoseconds': {
  894. 'nanoseconds': {
  895. check: function (max) {
  896. return NETDATA.options.current.seconds_as_time && max < 1000;
  897. },
  898. convert: function (nanoseconds) {
  899. let tms = Math.round(nanoseconds * 10);
  900. nanoseconds = Math.floor(tms / 10);
  901. tms -= nanoseconds * 10;
  902. return (nanoseconds).toString() + '.' + tms.toString();
  903. }
  904. },
  905. 'microseconds': {
  906. check: function (max) {
  907. return NETDATA.options.current.seconds_as_time
  908. && max >= 1000 && max < 1000 * 1000;
  909. },
  910. convert: function (nanoseconds) {
  911. nanoseconds = Math.round(nanoseconds);
  912. let microseconds = Math.floor(nanoseconds / 1000);
  913. nanoseconds -= microseconds * 1000;
  914. nanoseconds = Math.round(nanoseconds / 10 );
  915. return microseconds.toString() + '.'
  916. + NETDATA.zeropad(nanoseconds);
  917. }
  918. },
  919. 'milliseconds': {
  920. check: function (max) {
  921. return NETDATA.options.current.seconds_as_time
  922. && max >= 1000 * 1000 && max < 1000 * 1000 * 1000;
  923. },
  924. convert: function (nanoseconds) {
  925. nanoseconds = Math.round(nanoseconds);
  926. let milliseconds = Math.floor(nanoseconds / 1000 / 1000);
  927. nanoseconds -= milliseconds * 1000 * 1000;
  928. nanoseconds = Math.round(nanoseconds / 1000 / 10);
  929. return milliseconds.toString() + '.'
  930. + NETDATA.zeropad(nanoseconds);
  931. }
  932. },
  933. 'seconds': {
  934. check: function (max) {
  935. return NETDATA.options.current.seconds_as_time
  936. && max >= 1000 * 1000 * 1000;
  937. },
  938. convert: function (nanoseconds) {
  939. nanoseconds = Math.round(nanoseconds);
  940. let seconds = Math.floor(nanoseconds / 1000 / 1000 / 1000);
  941. nanoseconds -= seconds * 1000 * 1000 * 1000;
  942. nanoseconds = Math.round(nanoseconds / 1000 / 1000 / 10);
  943. return seconds.toString() + '.'
  944. + NETDATA.zeropad(nanoseconds);
  945. }
  946. },
  947. }
  948. },
  949. seconds2time: function (seconds) {
  950. seconds = Math.abs(seconds);
  951. let days = Math.floor(seconds / 86400);
  952. seconds -= days * 86400;
  953. let hours = Math.floor(seconds / 3600);
  954. seconds -= hours * 3600;
  955. let minutes = Math.floor(seconds / 60);
  956. seconds -= minutes * 60;
  957. seconds = Math.round(seconds);
  958. let ms_txt = '';
  959. /*
  960. let ms = seconds - Math.floor(seconds);
  961. seconds -= ms;
  962. ms = Math.round(ms * 1000);
  963. if (ms > 1) {
  964. if (ms < 10)
  965. ms_txt = '.00' + ms.toString();
  966. else if (ms < 100)
  967. ms_txt = '.0' + ms.toString();
  968. else
  969. ms_txt = '.' + ms.toString();
  970. }
  971. */
  972. return ((days > 0) ? days.toString() + 'd:' : '').toString()
  973. + NETDATA.zeropad(hours) + ':'
  974. + NETDATA.zeropad(minutes) + ':'
  975. + NETDATA.zeropad(seconds)
  976. + ms_txt;
  977. },
  978. // get a function that converts the units
  979. // + every time units are switched call the callback
  980. get: function (uuid, min, max, units, desired_units, common_units_name, switch_units_callback) {
  981. // validate the parameters
  982. if (typeof units === 'undefined') {
  983. units = 'undefined';
  984. }
  985. // check if we support units conversion
  986. if (typeof this.scalableUnits[units] === 'undefined' && typeof this.convertibleUnits[units] === 'undefined') {
  987. // we can't convert these units
  988. //console.log('DEBUG: ' + uuid.toString() + ' can\'t convert units: ' + units.toString());
  989. return function (value) {
  990. return value;
  991. };
  992. }
  993. // check if the caller wants the original units
  994. if (typeof desired_units === 'undefined' || desired_units === null || desired_units === 'original' || desired_units === units) {
  995. //console.log('DEBUG: ' + uuid.toString() + ' original units wanted');
  996. switch_units_callback(units);
  997. return function (value) {
  998. return value;
  999. };
  1000. }
  1001. // now we know we can convert the units
  1002. // and the caller wants some kind of conversion
  1003. let tunits = null;
  1004. let tdivider = 0;
  1005. if (typeof this.scalableUnits[units] !== 'undefined') {
  1006. // units that can be scaled
  1007. // we decide a divider
  1008. // console.log('NETDATA.unitsConversion.get(' + units.toString() + ', ' + desired_units.toString() + ', function()) decide divider with min = ' + min.toString() + ', max = ' + max.toString());
  1009. if (desired_units === 'auto') {
  1010. // the caller wants to auto-scale the units
  1011. // find the absolute maximum value that is rendered on the chart
  1012. // based on this we decide the scale
  1013. min = Math.abs(min);
  1014. max = Math.abs(max);
  1015. if (min > max) {
  1016. max = min;
  1017. }
  1018. // find the smallest scale that provides integers
  1019. // for (x in this.scalableUnits[units]) {
  1020. // if (this.scalableUnits[units].hasOwnProperty(x)) {
  1021. // let m = this.scalableUnits[units][x];
  1022. // if (m <= max && m > tdivider) {
  1023. // tunits = x;
  1024. // tdivider = m;
  1025. // }
  1026. // }
  1027. // }
  1028. const sunit = this.scalableUnits[units];
  1029. for (var x of Object.keys(sunit)) {
  1030. let m = sunit[x];
  1031. if (m <= max && m > tdivider) {
  1032. tunits = x;
  1033. tdivider = m;
  1034. }
  1035. }
  1036. if (tunits === null || tdivider <= 0) {
  1037. // we couldn't find one
  1038. //console.log('DEBUG: ' + uuid.toString() + ' cannot find an auto-scaling candidate for units: ' + units.toString() + ' (max: ' + max.toString() + ')');
  1039. switch_units_callback(units);
  1040. return function (value) {
  1041. return value;
  1042. };
  1043. }
  1044. if (typeof common_units_name === 'string' && typeof uuid === 'string') {
  1045. // the caller wants several charts to have the same units
  1046. // data-common-units
  1047. let common_units_key = common_units_name + '-' + units;
  1048. // add our divider into the list of keys
  1049. let t = this.keys[common_units_key];
  1050. if (typeof t === 'undefined') {
  1051. this.keys[common_units_key] = {};
  1052. t = this.keys[common_units_key];
  1053. }
  1054. t[uuid] = {
  1055. units: tunits,
  1056. divider: tdivider
  1057. };
  1058. // find the max divider of all charts
  1059. let common_units = t[uuid];
  1060. for (var x in t) {
  1061. if (t.hasOwnProperty(x) && t[x].divider > common_units.divider) {
  1062. common_units = t[x];
  1063. }
  1064. }
  1065. // save our common_max to the latest keys
  1066. let latest = this.latest[common_units_key];
  1067. if (typeof latest === 'undefined') {
  1068. this.latest[common_units_key] = {};
  1069. latest = this.latest[common_units_key];
  1070. }
  1071. latest.units = common_units.units;
  1072. latest.divider = common_units.divider;
  1073. tunits = latest.units;
  1074. tdivider = latest.divider;
  1075. //console.log('DEBUG: ' + uuid.toString() + ' converted units: ' + units.toString() + ' to units: ' + tunits.toString() + ' with divider ' + tdivider.toString() + ', common-units=' + common_units_name.toString() + ((t[uuid].divider !== tdivider)?' USED COMMON, mine was ' + t[uuid].units:' set common').toString());
  1076. // apply it to this chart
  1077. switch_units_callback(tunits);
  1078. return function (value) {
  1079. if (tdivider !== latest.divider) {
  1080. // another chart switched our common units
  1081. // we should switch them too
  1082. //console.log('DEBUG: ' + uuid + ' switching units due to a common-units change, from ' + tunits.toString() + ' to ' + latest.units.toString());
  1083. tunits = latest.units;
  1084. tdivider = latest.divider;
  1085. switch_units_callback(tunits);
  1086. }
  1087. return value / tdivider;
  1088. };
  1089. } else {
  1090. // the caller did not give data-common-units
  1091. // this chart auto-scales independently of all others
  1092. //console.log('DEBUG: ' + uuid.toString() + ' converted units: ' + units.toString() + ' to units: ' + tunits.toString() + ' with divider ' + tdivider.toString() + ', autonomously');
  1093. switch_units_callback(tunits);
  1094. return function (value) {
  1095. return value / tdivider;
  1096. };
  1097. }
  1098. } else {
  1099. // the caller wants specific units
  1100. if (typeof this.scalableUnits[units][desired_units] !== 'undefined') {
  1101. // all good, set the new units
  1102. tdivider = this.scalableUnits[units][desired_units];
  1103. // console.log('DEBUG: ' + uuid.toString() + ' converted units: ' + units.toString() + ' to units: ' + desired_units.toString() + ' with divider ' + tdivider.toString() + ', by reference');
  1104. switch_units_callback(desired_units);
  1105. return function (value) {
  1106. return value / tdivider;
  1107. };
  1108. } else {
  1109. // oops! switch back to original units
  1110. console.log('Units conversion from ' + units.toString() + ' to ' + desired_units.toString() + ' is not supported.');
  1111. switch_units_callback(units);
  1112. return function (value) {
  1113. return value;
  1114. };
  1115. }
  1116. }
  1117. } else if (typeof this.convertibleUnits[units] !== 'undefined') {
  1118. // units that can be converted
  1119. if (desired_units === 'auto') {
  1120. for (var x in this.convertibleUnits[units]) {
  1121. if (this.convertibleUnits[units].hasOwnProperty(x)) {
  1122. if (this.convertibleUnits[units][x].check(max)) {
  1123. //console.log('DEBUG: ' + uuid.toString() + ' converting ' + units.toString() + ' to: ' + x.toString());
  1124. switch_units_callback(x);
  1125. return this.convertibleUnits[units][x].convert;
  1126. }
  1127. }
  1128. }
  1129. // none checked ok
  1130. //console.log('DEBUG: ' + uuid.toString() + ' no conversion available for ' + units.toString() + ' to: ' + desired_units.toString());
  1131. switch_units_callback(units);
  1132. return function (value) {
  1133. return value;
  1134. };
  1135. } else if (typeof this.convertibleUnits[units][desired_units] !== 'undefined') {
  1136. switch_units_callback(desired_units);
  1137. return this.convertibleUnits[units][desired_units].convert;
  1138. } else {
  1139. console.log('Units conversion from ' + units.toString() + ' to ' + desired_units.toString() + ' is not supported.');
  1140. switch_units_callback(units);
  1141. return function (value) {
  1142. return value;
  1143. };
  1144. }
  1145. } else {
  1146. // hm... did we forget to implement the new type?
  1147. console.log(`Unmatched unit conversion method for units ${units.toString()}`);
  1148. switch_units_callback(units);
  1149. return function (value) {
  1150. return value;
  1151. };
  1152. }
  1153. }
  1154. };
  1155. NETDATA.icons = {
  1156. left: '<i class="fas fa-backward"></i>',
  1157. reset: '<i class="fas fa-play"></i>',
  1158. right: '<i class="fas fa-forward"></i>',
  1159. zoomIn: '<i class="fas fa-plus"></i>',
  1160. zoomOut: '<i class="fas fa-minus"></i>',
  1161. resize: '<i class="fas fa-sort"></i>',
  1162. lineChart: '<i class="fas fa-chart-line"></i>',
  1163. areaChart: '<i class="fas fa-chart-area"></i>',
  1164. noChart: '<i class="fas fa-chart-area"></i>',
  1165. loading: '<i class="fas fa-sync-alt"></i>',
  1166. noData: '<i class="fas fa-exclamation-triangle"></i>'
  1167. };
  1168. if (typeof netdataIcons === 'object') {
  1169. // for (let icon in NETDATA.icons) {
  1170. // if (NETDATA.icons.hasOwnProperty(icon) && typeof(netdataIcons[icon]) === 'string')
  1171. // NETDATA.icons[icon] = netdataIcons[icon];
  1172. // }
  1173. for (var icon of Object.keys(NETDATA.icons)) {
  1174. if (typeof(netdataIcons[icon]) === 'string') {
  1175. NETDATA.icons[icon] = netdataIcons[icon]
  1176. }
  1177. }
  1178. }
  1179. if (typeof netdataSnapshotData === 'undefined') {
  1180. netdataSnapshotData = null;
  1181. }
  1182. if (typeof netdataShowHelp === 'undefined') {
  1183. netdataShowHelp = true;
  1184. }
  1185. if (typeof netdataShowAlarms === 'undefined') {
  1186. netdataShowAlarms = false;
  1187. }
  1188. if (typeof netdataRegistryAfterMs !== 'number' || netdataRegistryAfterMs < 0) {
  1189. netdataRegistryAfterMs = 0; // 1500;
  1190. }
  1191. if (typeof netdataRegistry === 'undefined') {
  1192. // backward compatibility
  1193. netdataRegistry = (typeof netdataNoRegistry !== 'undefined' && netdataNoRegistry === false);
  1194. }
  1195. if (netdataRegistry === false && typeof netdataRegistryCallback === 'function') {
  1196. netdataRegistry = true;
  1197. }
  1198. // ----------------------------------------------------------------------------------------------------------------
  1199. // the defaults for all charts
  1200. // if the user does not specify any of these, the following will be used
  1201. NETDATA.chartDefaults = {
  1202. width: '100%', // the chart width - can be null
  1203. height: '100%', // the chart height - can be null
  1204. min_width: null, // the chart minimum width - can be null
  1205. library: 'dygraph', // the graphing library to use
  1206. method: 'average', // the grouping method
  1207. before: 0, // panning
  1208. after: -600, // panning
  1209. pixels_per_point: 1, // the detail of the chart
  1210. fill_luminance: 0.8 // luminance of colors in solid areas
  1211. };
  1212. // ----------------------------------------------------------------------------------------------------------------
  1213. // global options
  1214. NETDATA.options = {
  1215. pauseCallback: null, // a callback when we are really paused
  1216. pause: false, // when enabled we don't auto-refresh the charts
  1217. targets: [], // an array of all the state objects that are
  1218. // currently active (independently of their
  1219. // viewport visibility)
  1220. updated_dom: true, // when true, the DOM has been updated with
  1221. // new elements we have to check.
  1222. auto_refresher_fast_weight: 0, // this is the current time in ms, spent
  1223. // rendering charts continuously.
  1224. // used with .current.fast_render_timeframe
  1225. page_is_visible: true, // when true, this page is visible
  1226. auto_refresher_stop_until: 0, // timestamp in ms - used internally, to stop the
  1227. // auto-refresher for some time (when a chart is
  1228. // performing pan or zoom, we need to stop refreshing
  1229. // all other charts, to have the maximum speed for
  1230. // rendering the chart that is panned or zoomed).
  1231. // Used with .current.global_pan_sync_time
  1232. on_scroll_refresher_stop_until: 0, // timestamp in ms - used to stop evaluating
  1233. // charts for some time, after a page scroll
  1234. last_page_resize: Date.now(), // the timestamp of the last resize request
  1235. last_page_scroll: 0, // the timestamp the last time the page was scrolled
  1236. browser_timezone: 'unknown', // timezone detected by javascript
  1237. server_timezone: 'unknown', // timezone reported by the server
  1238. force_data_points: 0, // force the number of points to be returned for charts
  1239. fake_chart_rendering: false, // when set to true, the dashboard will download data but will not render the charts
  1240. passive_events: null, // true if the browser supports passive events
  1241. // the current profile
  1242. // we may have many...
  1243. current: {
  1244. units: 'auto', // can be 'auto' or 'original'
  1245. temperature: 'celsius', // can be 'celsius' or 'fahrenheit'
  1246. seconds_as_time: true, // show seconds as DDd:HH:MM:SS ?
  1247. timezone: 'default', // the timezone to use, or 'default'
  1248. user_set_server_timezone: 'default', // as set by the user on the dashboard
  1249. legend_toolbox: true, // show the legend toolbox on charts
  1250. resize_charts: true, // show the resize handler on charts
  1251. pixels_per_point: isSlowDevice() ? 5 : 1, // the minimum pixels per point for all charts
  1252. // increase this to speed javascript up
  1253. // each chart library has its own limit too
  1254. // the max of this and the chart library is used
  1255. // the final is calculated every time, so a change
  1256. // here will have immediate effect on the next chart
  1257. // update
  1258. idle_between_charts: 100, // ms - how much time to wait between chart updates
  1259. fast_render_timeframe: 200, // ms - render continuously until this time of continuous
  1260. // rendering has been reached
  1261. // this setting is used to make it render e.g. 10
  1262. // charts at once, sleep idle_between_charts time
  1263. // and continue for another 10 charts.
  1264. idle_between_loops: 500, // ms - if all charts have been updated, wait this
  1265. // time before starting again.
  1266. idle_parallel_loops: 100, // ms - the time between parallel refresher updates
  1267. idle_lost_focus: 500, // ms - when the window does not have focus, check
  1268. // if focus has been regained, every this time
  1269. global_pan_sync_time: 300, // ms - when you pan or zoom a chart, the background
  1270. // auto-refreshing of charts is paused for this amount
  1271. // of time
  1272. sync_selection_delay: 400, // ms - when you pan or zoom a chart, wait this amount
  1273. // of time before setting up synchronized selections
  1274. // on hover.
  1275. sync_selection: true, // enable or disable selection sync
  1276. pan_and_zoom_delay: 50, // when panning or zooming, how often to update the chart
  1277. sync_pan_and_zoom: true, // enable or disable pan and zoom sync
  1278. pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming
  1279. update_only_visible: true, // enable or disable visibility management / used for printing
  1280. parallel_refresher: !isSlowDevice(), // enable parallel refresh of charts
  1281. concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
  1282. destroy_on_hide: isSlowDevice(), // destroy charts when they are not visible
  1283. show_help: netdataShowHelp, // when enabled the charts will show some help
  1284. show_help_delay_show_ms: 500,
  1285. show_help_delay_hide_ms: 0,
  1286. eliminate_zero_dimensions: true, // do not show dimensions with just zeros
  1287. stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
  1288. stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
  1289. double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
  1290. smooth_plot: !isSlowDevice(), // enable smooth plot, where possible
  1291. color_fill_opacity_line: 1.0,
  1292. color_fill_opacity_area: 0.2,
  1293. color_fill_opacity_stacked: 0.8,
  1294. pan_and_zoom_factor: 0.25, // the increment when panning and zooming with the toolbox
  1295. pan_and_zoom_factor_multiplier_control: 2.0,
  1296. pan_and_zoom_factor_multiplier_shift: 3.0,
  1297. pan_and_zoom_factor_multiplier_alt: 4.0,
  1298. abort_ajax_on_scroll: false, // kill pending ajax page scroll
  1299. async_on_scroll: false, // sync/async onscroll handler
  1300. onscroll_worker_duration_threshold: 30, // time in ms, for async scroll handler
  1301. retries_on_data_failures: 3, // how many retries to make if we can't fetch chart data from the server
  1302. setOptionCallback: function () {
  1303. }
  1304. },
  1305. debug: {
  1306. show_boxes: false,
  1307. main_loop: false,
  1308. focus: false,
  1309. visibility: false,
  1310. chart_data_url: false,
  1311. chart_errors: true, // remember to set it to false before merging
  1312. chart_timing: false,
  1313. chart_calls: false,
  1314. libraries: false,
  1315. dygraph: false,
  1316. globalSelectionSync: false,
  1317. globalPanAndZoom: false
  1318. }
  1319. };
  1320. NETDATA.statistics = {
  1321. refreshes_total: 0,
  1322. refreshes_active: 0,
  1323. refreshes_active_max: 0
  1324. };
  1325. // local storage options
  1326. NETDATA.localStorage = {
  1327. default: {},
  1328. current: {},
  1329. callback: {} // only used for resetting back to defaults
  1330. };
  1331. NETDATA.localStorageTested = -1;
  1332. NETDATA.localStorageTest = function () {
  1333. if (NETDATA.localStorageTested !== -1) {
  1334. return NETDATA.localStorageTested;
  1335. }
  1336. if (typeof Storage !== "undefined" && typeof localStorage === 'object') {
  1337. let test = 'test';
  1338. try {
  1339. localStorage.setItem(test, test);
  1340. localStorage.removeItem(test);
  1341. NETDATA.localStorageTested = true;
  1342. } catch (e) {
  1343. NETDATA.localStorageTested = false;
  1344. }
  1345. } else {
  1346. NETDATA.localStorageTested = false;
  1347. }
  1348. return NETDATA.localStorageTested;
  1349. };
  1350. NETDATA.localStorageGet = function (key, def, callback) {
  1351. let ret = def;
  1352. if (typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
  1353. NETDATA.localStorage.default[key.toString()] = def;
  1354. NETDATA.localStorage.callback[key.toString()] = callback;
  1355. }
  1356. if (NETDATA.localStorageTest()) {
  1357. try {
  1358. // console.log('localStorage: loading "' + key.toString() + '"');
  1359. ret = localStorage.getItem(key.toString());
  1360. // console.log('netdata loaded: ' + key.toString() + ' = ' + ret.toString());
  1361. if (ret === null || ret === 'undefined') {
  1362. // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
  1363. localStorage.setItem(key.toString(), JSON.stringify(def));
  1364. ret = def;
  1365. } else {
  1366. // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
  1367. ret = JSON.parse(ret);
  1368. // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
  1369. }
  1370. } catch (error) {
  1371. console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
  1372. ret = def;
  1373. }
  1374. }
  1375. if (typeof ret === 'undefined' || ret === 'undefined') {
  1376. console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
  1377. ret = def;
  1378. }
  1379. NETDATA.localStorage.current[key.toString()] = ret;
  1380. return ret;
  1381. };
  1382. NETDATA.localStorageSet = function (key, value, callback) {
  1383. if (typeof value === 'undefined' || value === 'undefined') {
  1384. console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
  1385. }
  1386. if (typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
  1387. NETDATA.localStorage.default[key.toString()] = value;
  1388. NETDATA.localStorage.current[key.toString()] = value;
  1389. NETDATA.localStorage.callback[key.toString()] = callback;
  1390. }
  1391. if (NETDATA.localStorageTest()) {
  1392. // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
  1393. try {
  1394. localStorage.setItem(key.toString(), JSON.stringify(value));
  1395. } catch (e) {
  1396. console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
  1397. }
  1398. }
  1399. NETDATA.localStorage.current[key.toString()] = value;
  1400. return value;
  1401. };
  1402. NETDATA.localStorageGetRecursive = function (obj, prefix, callback) {
  1403. let keys = Object.keys(obj);
  1404. let len = keys.length;
  1405. while (len--) {
  1406. let i = keys[len];
  1407. if (typeof obj[i] === 'object') {
  1408. //console.log('object ' + prefix + '.' + i.toString());
  1409. NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
  1410. continue;
  1411. }
  1412. obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
  1413. }
  1414. };
  1415. NETDATA.setOption = function (key, value) {
  1416. if (key.toString() === 'setOptionCallback') {
  1417. if (typeof NETDATA.options.current.setOptionCallback === 'function') {
  1418. NETDATA.options.current[key.toString()] = value;
  1419. NETDATA.options.current.setOptionCallback();
  1420. }
  1421. } else if (NETDATA.options.current[key.toString()] !== value) {
  1422. let name = 'options.' + key.toString();
  1423. if (typeof NETDATA.localStorage.default[name.toString()] === 'undefined') {
  1424. console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
  1425. }
  1426. //console.log(NETDATA.localStorage);
  1427. //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
  1428. //console.log(NETDATA.options);
  1429. NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
  1430. if (typeof NETDATA.options.current.setOptionCallback === 'function') {
  1431. NETDATA.options.current.setOptionCallback();
  1432. }
  1433. }
  1434. return true;
  1435. };
  1436. NETDATA.getOption = function (key) {
  1437. return NETDATA.options.current[key.toString()];
  1438. };
  1439. // read settings from local storage
  1440. NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
  1441. // always start with this option enabled.
  1442. NETDATA.setOption('stop_updates_when_focus_is_lost', true);
  1443. NETDATA.resetOptions = function () {
  1444. let keys = Object.keys(NETDATA.localStorage.default);
  1445. let len = keys.length;
  1446. while (len--) {
  1447. let i = keys[len];
  1448. let a = i.split('.');
  1449. if (a[0] === 'options') {
  1450. if (a[1] === 'setOptionCallback') {
  1451. continue;
  1452. }
  1453. if (typeof NETDATA.localStorage.default[i] === 'undefined') {
  1454. continue;
  1455. }
  1456. if (NETDATA.options.current[i] === NETDATA.localStorage.default[i]) {
  1457. continue;
  1458. }
  1459. NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
  1460. } else if (a[0] === 'chart_heights') {
  1461. if (typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
  1462. NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
  1463. }
  1464. }
  1465. }
  1466. NETDATA.dateTime.init(NETDATA.options.current.timezone);
  1467. };
  1468. // *** src/dashboard.js/timeout.js
  1469. // TODO: Better name needed
  1470. NETDATA.timeout = {
  1471. // by default, these are just wrappers to setTimeout() / clearTimeout()
  1472. step: function (callback) {
  1473. return window.setTimeout(callback, 1000 / 60);
  1474. },
  1475. set: function (callback, delay) {
  1476. return window.setTimeout(callback, delay);
  1477. },
  1478. clear: function (id) {
  1479. return window.clearTimeout(id);
  1480. },
  1481. init: function () {
  1482. let custom = true;
  1483. if (window.requestAnimationFrame) {
  1484. this.step = function (callback) {
  1485. return window.requestAnimationFrame(callback);
  1486. };
  1487. this.clear = function (handle) {
  1488. return window.cancelAnimationFrame(handle.value);
  1489. };
  1490. // } else if (window.webkitRequestAnimationFrame) {
  1491. // this.step = function (callback) {
  1492. // return window.webkitRequestAnimationFrame(callback);
  1493. // };
  1494. // if (window.webkitCancelAnimationFrame) {
  1495. // this.clear = function (handle) {
  1496. // return window.webkitCancelAnimationFrame(handle.value);
  1497. // };
  1498. // } else if (window.webkitCancelRequestAnimationFrame) {
  1499. // this.clear = function (handle) {
  1500. // return window.webkitCancelRequestAnimationFrame(handle.value);
  1501. // };
  1502. // }
  1503. // } else if (window.mozRequestAnimationFrame) {
  1504. // this.step = function (callback) {
  1505. // return window.mozRequestAnimationFrame(callback);
  1506. // };
  1507. // this.clear = function (handle) {
  1508. // return window.mozCancelRequestAnimationFrame(handle.value);
  1509. // };
  1510. // } else if (window.oRequestAnimationFrame) {
  1511. // this.step = function (callback) {
  1512. // return window.oRequestAnimationFrame(callback);
  1513. // };
  1514. // this.clear = function (handle) {
  1515. // return window.oCancelRequestAnimationFrame(handle.value);
  1516. // };
  1517. // } else if (window.msRequestAnimationFrame) {
  1518. // this.step = function (callback) {
  1519. // return window.msRequestAnimationFrame(callback);
  1520. // };
  1521. // this.clear = function (handle) {
  1522. // return window.msCancelRequestAnimationFrame(handle.value);
  1523. // };
  1524. } else {
  1525. custom = false;
  1526. }
  1527. if (custom) {
  1528. // we have installed custom .step() / .clear() functions
  1529. // overwrite the .set() too
  1530. this.set = function (callback, delay) {
  1531. let start = Date.now(),
  1532. handle = new Object();
  1533. const loop = () => {
  1534. let current = Date.now(),
  1535. delta = current - start;
  1536. if (delta >= delay) {
  1537. callback.call();
  1538. } else {
  1539. handle.value = this.step(loop);
  1540. }
  1541. }
  1542. handle.value = this.step(loop);
  1543. return handle;
  1544. };
  1545. }
  1546. }
  1547. };
  1548. NETDATA.timeout.init();
  1549. // Codacy declarations
  1550. /* global netdataTheme */
  1551. NETDATA.themes = {
  1552. white: {
  1553. bootstrap_css: NETDATA.serverStatic + 'css/bootstrap-3.3.7.css',
  1554. dashboard_css: NETDATA.serverStatic + 'dashboard.css?v20190902-0',
  1555. background: '#FFFFFF',
  1556. foreground: '#000000',
  1557. grid: '#F0F0F0',
  1558. axis: '#F0F0F0',
  1559. highlight: '#F5F5F5',
  1560. colors: ['#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477',
  1561. '#3B3EAC', '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6',
  1562. '#994499', '#22AA99', '#6633CC', '#E67300', '#316395', '#8B0707',
  1563. '#329262', '#3B3EAC'],
  1564. easypiechart_track: '#f0f0f0',
  1565. easypiechart_scale: '#dfe0e0',
  1566. gauge_pointer: '#C0C0C0',
  1567. gauge_stroke: '#F0F0F0',
  1568. gauge_gradient: false,
  1569. d3pie: {
  1570. title: '#333333',
  1571. subtitle: '#666666',
  1572. footer: '#888888',
  1573. other: '#aaaaaa',
  1574. mainlabel: '#333333',
  1575. percentage: '#dddddd',
  1576. value: '#aaaa22',
  1577. tooltip_bg: '#000000',
  1578. tooltip_fg: '#efefef',
  1579. segment_stroke: "#ffffff",
  1580. gradient_color: '#000000'
  1581. }
  1582. },
  1583. slate: {
  1584. bootstrap_css: NETDATA.serverStatic + 'css/bootstrap-slate-flat-3.3.7.css?v20161229-1',
  1585. dashboard_css: NETDATA.serverStatic + 'dashboard.slate.css?v20190902-0',
  1586. background: '#272b30',
  1587. foreground: '#C8C8C8',
  1588. grid: '#283236',
  1589. axis: '#283236',
  1590. highlight: '#383838',
  1591. /* colors: [ '#55bb33', '#ff2222', '#0099C6', '#faa11b', '#adbce0', '#DDDD00',
  1592. '#4178ba', '#f58122', '#a5cc39', '#f58667', '#f5ef89', '#cf93c0',
  1593. '#a5d18a', '#b8539d', '#3954a3', '#c8a9cf', '#c7de8a', '#fad20a',
  1594. '#a6a479', '#a66da8' ],
  1595. */
  1596. colors: ['#66AA00', '#FE3912', '#3366CC', '#D66300', '#0099C6', '#DDDD00',
  1597. '#5054e6', '#EE9911', '#BB44CC', '#e45757', '#ef0aef', '#CC7700',
  1598. '#22AA99', '#109618', '#905bfd', '#f54882', '#4381bf', '#ff3737',
  1599. '#329262', '#3B3EFF'],
  1600. easypiechart_track: '#373b40',
  1601. easypiechart_scale: '#373b40',
  1602. gauge_pointer: '#474b50',
  1603. gauge_stroke: '#373b40',
  1604. gauge_gradient: false,
  1605. d3pie: {
  1606. title: '#C8C8C8',
  1607. subtitle: '#283236',
  1608. footer: '#283236',
  1609. other: '#283236',
  1610. mainlabel: '#C8C8C8',
  1611. percentage: '#dddddd',
  1612. value: '#cccc44',
  1613. tooltip_bg: '#272b30',
  1614. tooltip_fg: '#C8C8C8',
  1615. segment_stroke: "#283236",
  1616. gradient_color: '#000000'
  1617. }
  1618. }
  1619. };
  1620. if (typeof netdataTheme !== 'undefined' && typeof NETDATA.themes[netdataTheme] !== 'undefined') {
  1621. NETDATA.themes.current = NETDATA.themes[netdataTheme];
  1622. } else {
  1623. NETDATA.themes.current = NETDATA.themes.white;
  1624. }
  1625. NETDATA.colors = NETDATA.themes.current.colors;
  1626. // these are the colors Google Charts are using
  1627. // we have them here to attempt emulate their look and feel on the other chart libraries
  1628. // http://there4.io/2012/05/02/google-chart-color-list/
  1629. //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
  1630. // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
  1631. // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
  1632. // an alternative set
  1633. // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
  1634. // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
  1635. //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
  1636. // dygraph
  1637. // Codacy declarations
  1638. /* global smoothPlotter */
  1639. /* global Dygraph */
  1640. NETDATA.dygraph = {
  1641. smooth: false
  1642. };
  1643. NETDATA.dygraphToolboxPanAndZoom = function (state, after, before) {
  1644. if (after < state.netdata_first) {
  1645. after = state.netdata_first;
  1646. }
  1647. if (before > state.netdata_last) {
  1648. before = state.netdata_last;
  1649. }
  1650. state.setMode('zoom');
  1651. NETDATA.globalSelectionSync.stop();
  1652. NETDATA.globalSelectionSync.delay();
  1653. state.tmp.dygraph_user_action = true;
  1654. state.tmp.dygraph_force_zoom = true;
  1655. // state.log('toolboxPanAndZoom');
  1656. state.updateChartPanOrZoom(after, before);
  1657. NETDATA.globalPanAndZoom.setMaster(state, after, before);
  1658. };
  1659. NETDATA.dygraphSetSelection = function (state, t) {
  1660. if (typeof state.tmp.dygraph_instance !== 'undefined') {
  1661. let r = state.calculateRowForTime(t);
  1662. if (r !== -1) {
  1663. state.tmp.dygraph_instance.setSelection(r);
  1664. return true;
  1665. } else {
  1666. state.tmp.dygraph_instance.clearSelection();
  1667. state.legendShowUndefined();
  1668. }
  1669. }
  1670. return false;
  1671. };
  1672. NETDATA.dygraphClearSelection = function (state) {
  1673. if (typeof state.tmp.dygraph_instance !== 'undefined') {
  1674. state.tmp.dygraph_instance.clearSelection();
  1675. }
  1676. return true;
  1677. };
  1678. NETDATA.dygraphSmoothInitialize = function (callback) {
  1679. $.ajax({
  1680. url: NETDATA.dygraph_smooth_js,
  1681. cache: true,
  1682. dataType: "script",
  1683. xhrFields: {withCredentials: true} // required for the cookie
  1684. })
  1685. .done(function () {
  1686. NETDATA.dygraph.smooth = true;
  1687. smoothPlotter.smoothing = 0.3;
  1688. })
  1689. .fail(function () {
  1690. NETDATA.dygraph.smooth = false;
  1691. })
  1692. .always(function () {
  1693. if (typeof callback === "function") {
  1694. return callback();
  1695. }
  1696. });
  1697. };
  1698. NETDATA.dygraphInitialize = function (callback) {
  1699. if (typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
  1700. $.ajax({
  1701. url: NETDATA.dygraph_js,
  1702. cache: true,
  1703. dataType: "script",
  1704. xhrFields: {withCredentials: true} // required for the cookie
  1705. })
  1706. .done(function () {
  1707. NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
  1708. })
  1709. .fail(function () {
  1710. NETDATA.chartLibraries.dygraph.enabled = false;
  1711. NETDATA.error(100, NETDATA.dygraph_js);
  1712. })
  1713. .always(function () {
  1714. if (NETDATA.chartLibraries.dygraph.enabled && NETDATA.options.current.smooth_plot) {
  1715. NETDATA.dygraphSmoothInitialize(callback);
  1716. } else if (typeof callback === "function") {
  1717. return callback();
  1718. }
  1719. });
  1720. } else {
  1721. NETDATA.chartLibraries.dygraph.enabled = false;
  1722. if (typeof callback === "function") {
  1723. return callback();
  1724. }
  1725. }
  1726. };
  1727. NETDATA.dygraphChartUpdate = function (state, data) {
  1728. let dygraph = state.tmp.dygraph_instance;
  1729. if (typeof dygraph === 'undefined') {
  1730. return NETDATA.dygraphChartCreate(state, data);
  1731. }
  1732. // when the chart is not visible, and hidden
  1733. // if there is a window resize, dygraph detects
  1734. // its element size as 0x0.
  1735. // this will make it re-appear properly
  1736. if (state.tm.last_unhidden > state.tmp.dygraph_last_rendered) {
  1737. dygraph.resize();
  1738. }
  1739. let options = {
  1740. file: data.result.data,
  1741. colors: state.chartColors(),
  1742. labels: data.result.labels,
  1743. //labelsDivWidth: state.chartWidth() - 70,
  1744. includeZero: state.tmp.dygraph_include_zero,
  1745. visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
  1746. };
  1747. if (state.tmp.dygraph_chart_type === 'stacked') {
  1748. if (options.includeZero && state.dimensions_visibility.countSelected() < options.visibility.length) {
  1749. options.includeZero = 0;
  1750. }
  1751. }
  1752. if (!NETDATA.chartLibraries.dygraph.isSparkline(state)) {
  1753. options.ylabel = state.units_current; // (state.units_desired === 'auto')?"":state.units_current;
  1754. }
  1755. if (state.tmp.dygraph_force_zoom) {
  1756. if (NETDATA.options.debug.dygraph || state.debug) {
  1757. state.log('dygraphChartUpdate() forced zoom update');
  1758. }
  1759. options.dateWindow = (state.requested_padding !== null) ? [state.view_after, state.view_before] : null;
  1760. //options.isZoomedIgnoreProgrammaticZoom = true;
  1761. state.tmp.dygraph_force_zoom = false;
  1762. } else if (state.current.name !== 'auto') {
  1763. if (NETDATA.options.debug.dygraph || state.debug) {
  1764. state.log('dygraphChartUpdate() loose update');
  1765. }
  1766. } else {
  1767. if (NETDATA.options.debug.dygraph || state.debug) {
  1768. state.log('dygraphChartUpdate() strict update');
  1769. }
  1770. options.dateWindow = (state.requested_padding !== null) ? [state.view_after, state.view_before] : null;
  1771. //options.isZoomedIgnoreProgrammaticZoom = true;
  1772. }
  1773. options.valueRange = state.tmp.dygraph_options.valueRange;
  1774. let oldMax = null, oldMin = null;
  1775. if (state.tmp.__commonMin !== null) {
  1776. state.data.min = state.tmp.dygraph_instance.axes_[0].extremeRange[0];
  1777. oldMin = options.valueRange[0] = NETDATA.commonMin.get(state);
  1778. }
  1779. if (state.tmp.__commonMax !== null) {
  1780. state.data.max = state.tmp.dygraph_instance.axes_[0].extremeRange[1];
  1781. oldMax = options.valueRange[1] = NETDATA.commonMax.get(state);
  1782. }
  1783. if (state.tmp.dygraph_smooth_eligible) {
  1784. if ((NETDATA.options.current.smooth_plot && state.tmp.dygraph_options.plotter !== smoothPlotter)
  1785. || (NETDATA.options.current.smooth_plot === false && state.tmp.dygraph_options.plotter === smoothPlotter)) {
  1786. NETDATA.dygraphChartCreate(state, data);
  1787. return;
  1788. }
  1789. }
  1790. if (netdataSnapshotData !== null && NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(state) === false) {
  1791. // pan and zoom on snapshots
  1792. options.dateWindow = [NETDATA.globalPanAndZoom.force_after_ms, NETDATA.globalPanAndZoom.force_before_ms];
  1793. //options.isZoomedIgnoreProgrammaticZoom = true;
  1794. }
  1795. if (NETDATA.chartLibraries.dygraph.isLogScale(state)) {
  1796. if (Array.isArray(options.valueRange) && options.valueRange[0] <= 0) {
  1797. options.valueRange[0] = null;
  1798. }
  1799. }
  1800. dygraph.updateOptions(options);
  1801. let redraw = false;
  1802. if (oldMin !== null && oldMin > state.tmp.dygraph_instance.axes_[0].extremeRange[0]) {
  1803. state.data.min = state.tmp.dygraph_instance.axes_[0].extremeRange[0];
  1804. options.valueRange[0] = NETDATA.commonMin.get(state);
  1805. redraw = true;
  1806. }
  1807. if (oldMax !== null && oldMax < state.tmp.dygraph_instance.axes_[0].extremeRange[1]) {
  1808. state.data.max = state.tmp.dygraph_instance.axes_[0].extremeRange[1];
  1809. options.valueRange[1] = NETDATA.commonMax.get(state);
  1810. redraw = true;
  1811. }
  1812. if (redraw) {
  1813. // state.log('forcing redraw to adapt to common- min/max');
  1814. dygraph.updateOptions(options);
  1815. }
  1816. state.tmp.dygraph_last_rendered = Date.now();
  1817. return true;
  1818. };
  1819. NETDATA.dygraphChartCreate = function (state, data) {
  1820. if (NETDATA.options.debug.dygraph || state.debug) {
  1821. state.log('dygraphChartCreate()');
  1822. }
  1823. state.tmp.dygraph_chart_type = NETDATA.dataAttribute(state.element, 'dygraph-type', state.chart.chart_type);
  1824. if (state.tmp.dygraph_chart_type === 'stacked' && data.dimensions === 1) {
  1825. state.tmp.dygraph_chart_type = 'area';
  1826. }
  1827. if (state.tmp.dygraph_chart_type === 'stacked' && NETDATA.chartLibraries.dygraph.isLogScale(state)) {
  1828. state.tmp.dygraph_chart_type = 'area';
  1829. }
  1830. let highlightCircleSize = NETDATA.chartLibraries.dygraph.isSparkline(state) ? 3 : 4;
  1831. let smooth = NETDATA.dygraph.smooth
  1832. ? (NETDATA.dataAttributeBoolean(state.element, 'dygraph-smooth', (state.tmp.dygraph_chart_type === 'line' && NETDATA.chartLibraries.dygraph.isSparkline(state) === false)))
  1833. : false;
  1834. state.tmp.dygraph_include_zero = NETDATA.dataAttribute(state.element, 'dygraph-includezero', (state.tmp.dygraph_chart_type === 'stacked'));
  1835. let drawAxis = NETDATA.dataAttributeBoolean(state.element, 'dygraph-drawaxis', true);
  1836. state.tmp.dygraph_options = {
  1837. colors: NETDATA.dataAttribute(state.element, 'dygraph-colors', state.chartColors()),
  1838. // leave a few pixels empty on the right of the chart
  1839. rightGap: NETDATA.dataAttribute(state.element, 'dygraph-rightgap', 5),
  1840. showRangeSelector: NETDATA.dataAttributeBoolean(state.element, 'dygraph-showrangeselector', false),
  1841. showRoller: NETDATA.dataAttributeBoolean(state.element, 'dygraph-showroller', false),
  1842. title: NETDATA.dataAttribute(state.element, 'dygraph-title', state.title),
  1843. titleHeight: NETDATA.dataAttribute(state.element, 'dygraph-titleheight', 19),
  1844. legend: NETDATA.dataAttribute(state.element, 'dygraph-legend', 'always'), // we need this to get selection events
  1845. labels: data.result.labels,
  1846. labelsDiv: NETDATA.dataAttribute(state.element, 'dygraph-labelsdiv', state.element_legend_childs.hidden),
  1847. //labelsDivStyles: NETDATA.dataAttribute(state.element, 'dygraph-labelsdivstyles', { 'fontSize':'1px' }),
  1848. //labelsDivWidth: NETDATA.dataAttribute(state.element, 'dygraph-labelsdivwidth', state.chartWidth() - 70),
  1849. labelsSeparateLines: NETDATA.dataAttributeBoolean(state.element, 'dygraph-labelsseparatelines', true),
  1850. labelsShowZeroValues: NETDATA.chartLibraries.dygraph.isLogScale(state) ? false : NETDATA.dataAttributeBoolean(state.element, 'dygraph-labelsshowzerovalues', true),
  1851. labelsKMB: false,
  1852. labelsKMG2: false,
  1853. showLabelsOnHighlight: NETDATA.dataAttributeBoolean(state.element, 'dygraph-showlabelsonhighlight', true),
  1854. hideOverlayOnMouseOut: NETDATA.dataAttributeBoolean(state.element, 'dygraph-hideoverlayonmouseout', true),
  1855. includeZero: state.tmp.dygraph_include_zero,
  1856. xRangePad: NETDATA.dataAttribute(state.element, 'dygraph-xrangepad', 0),
  1857. yRangePad: NETDATA.dataAttribute(state.element, 'dygraph-yrangepad', 1),
  1858. valueRange: NETDATA.dataAttribute(state.element, 'dygraph-valuerange', [null, null]),
  1859. ylabel: state.units_current, // (state.units_desired === 'auto')?"":state.units_current,
  1860. yLabelWidth: NETDATA.dataAttribute(state.element, 'dygraph-ylabelwidth', 12),
  1861. // the function to plot the chart
  1862. plotter: null,
  1863. // The width of the lines connecting data points.
  1864. // This can be used to increase the contrast or some graphs.
  1865. strokeWidth: NETDATA.dataAttribute(state.element, 'dygraph-strokewidth', ((state.tmp.dygraph_chart_type === 'stacked') ? 0.1 : ((smooth === true) ? 1.5 : 0.7))),
  1866. strokePattern: NETDATA.dataAttribute(state.element, 'dygraph-strokepattern', undefined),
  1867. // The size of the dot to draw on each point in pixels (see drawPoints).
  1868. // A dot is always drawn when a point is "isolated",
  1869. // i.e. there is a missing point on either side of it.
  1870. // This also controls the size of those dots.
  1871. drawPoints: NETDATA.dataAttributeBoolean(state.element, 'dygraph-drawpoints', false),
  1872. // Draw points at the edges of gaps in the data.
  1873. // This improves visibility of small data segments or other data irregularities.
  1874. drawGapEdgePoints: NETDATA.dataAttributeBoolean(state.element, 'dygraph-drawgapedgepoints', true),
  1875. connectSeparatedPoints: NETDATA.chartLibraries.dygraph.isLogScale(state) ? false : NETDATA.dataAttributeBoolean(state.element, 'dygraph-connectseparatedpoints', false),
  1876. pointSize: NETDATA.dataAttribute(state.element, 'dygraph-pointsize', 1),
  1877. // enabling this makes the chart with little square lines
  1878. stepPlot: NETDATA.dataAttributeBoolean(state.element, 'dygraph-stepplot', false),
  1879. // Draw a border around graph lines to make crossing lines more easily
  1880. // distinguishable. Useful for graphs with many lines.
  1881. strokeBorderColor: NETDATA.dataAttribute(state.element, 'dygraph-strokebordercolor', NETDATA.themes.current.background),
  1882. strokeBorderWidth: NETDATA.dataAttribute(state.element, 'dygraph-strokeborderwidth', (state.tmp.dygraph_chart_type === 'stacked') ? 0.0 : 0.0),
  1883. fillGraph: NETDATA.dataAttribute(state.element, 'dygraph-fillgraph', (state.tmp.dygraph_chart_type === 'area' || state.tmp.dygraph_chart_type === 'stacked')),
  1884. fillAlpha: NETDATA.dataAttribute(state.element, 'dygraph-fillalpha',
  1885. ((state.tmp.dygraph_chart_type === 'stacked')
  1886. ? NETDATA.options.current.color_fill_opacity_stacked
  1887. : NETDATA.options.current.color_fill_opacity_area)
  1888. ),
  1889. stackedGraph: NETDATA.dataAttribute(state.element, 'dygraph-stackedgraph', (state.tmp.dygraph_chart_type === 'stacked')),
  1890. stackedGraphNaNFill: NETDATA.dataAttribute(state.element, 'dygraph-stackedgraphnanfill', 'none'),
  1891. drawAxis: drawAxis,
  1892. axisLabelFontSize: NETDATA.dataAttribute(state.element, 'dygraph-axislabelfontsize', 10),
  1893. axisLineColor: NETDATA.dataAttribute(state.element, 'dygraph-axislinecolor', NETDATA.themes.current.axis),
  1894. axisLineWidth: NETDATA.dataAttribute(state.element, 'dygraph-axislinewidth', 1.0),
  1895. drawGrid: NETDATA.dataAttributeBoolean(state.element, 'dygraph-drawgrid', true),
  1896. gridLinePattern: NETDATA.dataAttribute(state.element, 'dygraph-gridlinepattern', null),
  1897. gridLineWidth: NETDATA.dataAttribute(state.element, 'dygraph-gridlinewidth', 1.0),
  1898. gridLineColor: NETDATA.dataAttribute(state.element, 'dygraph-gridlinecolor', NETDATA.themes.current.grid),
  1899. maxNumberWidth: NETDATA.dataAttribute(state.element, 'dygraph-maxnumberwidth', 8),
  1900. sigFigs: NETDATA.dataAttribute(state.element, 'dygraph-sigfigs', null),
  1901. digitsAfterDecimal: NETDATA.dataAttribute(state.element, 'dygraph-digitsafterdecimal', 2),
  1902. valueFormatter: NETDATA.dataAttribute(state.element, 'dygraph-valueformatter', undefined),
  1903. highlightCircleSize: NETDATA.dataAttribute(state.element, 'dygraph-highlightcirclesize', highlightCircleSize),
  1904. highlightSeriesOpts: NETDATA.dataAttribute(state.element, 'dygraph-highlightseriesopts', null), // TOO SLOW: { strokeWidth: 1.5 },
  1905. highlightSeriesBackgroundAlpha: NETDATA.dataAttribute(state.element, 'dygraph-highlightseriesbackgroundalpha', null), // TOO SLOW: (state.tmp.dygraph_chart_type === 'stacked')?0.7:0.5,
  1906. pointClickCallback: NETDATA.dataAttribute(state.element, 'dygraph-pointclickcallback', undefined),
  1907. visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
  1908. logscale: NETDATA.chartLibraries.dygraph.isLogScale(state) ? 'y' : undefined,
  1909. axes: {
  1910. x: {
  1911. pixelsPerLabel: NETDATA.dataAttribute(state.element, 'dygraph-xpixelsperlabel', 50),
  1912. ticker: Dygraph.dateTicker,
  1913. axisLabelWidth: NETDATA.dataAttribute(state.element, 'dygraph-xaxislabelwidth', 60),
  1914. drawAxis: NETDATA.dataAttributeBoolean(state.element, 'dygraph-drawxaxis', drawAxis),
  1915. axisLabelFormatter: function (d, gran) {
  1916. void(gran);
  1917. return NETDATA.dateTime.xAxisTimeString(d);
  1918. }
  1919. },
  1920. y: {
  1921. logscale: NETDATA.chartLibraries.dygraph.isLogScale(state) ? true : undefined,
  1922. pixelsPerLabel: NETDATA.dataAttribute(state.element, 'dygraph-ypixelsperlabel', 15),
  1923. axisLabelWidth: NETDATA.dataAttribute(state.element, 'dygraph-yaxislabelwidth', 50),
  1924. drawAxis: NETDATA.dataAttributeBoolean(state.element, 'dygraph-drawyaxis', drawAxis),
  1925. axisLabelFormatter: function (y) {
  1926. // unfortunately, we have to call this every single time
  1927. state.legendFormatValueDecimalsFromMinMax(
  1928. this.axes_[0].extremeRange[0],
  1929. this.axes_[0].extremeRange[1]
  1930. );
  1931. let old_units = this.user_attrs_.ylabel;
  1932. let v = state.legendFormatValue(y);
  1933. let new_units = state.units_current;
  1934. if (state.units_desired === 'auto' && typeof old_units !== 'undefined' && new_units !== old_units && !NETDATA.chartLibraries.dygraph.isSparkline(state)) {
  1935. // console.log(this);
  1936. // state.log('units discrepancy: old = ' + old_units + ', new = ' + new_units);
  1937. let len = this.plugins_.length;
  1938. while (len--) {
  1939. // console.log(this.plugins_[len]);
  1940. if (typeof this.plugins_[len].plugin.ylabel_div_ !== 'undefined'
  1941. && this.plugins_[len].plugin.ylabel_div_ !== null
  1942. && typeof this.plugins_[len].plugin.ylabel_div_.children !== 'undefined'
  1943. && this.plugins_[len].plugin.ylabel_div_.children !== null
  1944. && typeof this.plugins_[len].plugin.ylabel_div_.children[0].children !== 'undefined'
  1945. && this.plugins_[len].plugin.ylabel_div_.children[0].children !== null
  1946. ) {
  1947. this.plugins_[len].plugin.ylabel_div_.children[0].children[0].innerHTML = new_units;
  1948. this.user_attrs_.ylabel = new_units;
  1949. break;
  1950. }
  1951. }
  1952. if (len < 0) {
  1953. state.log('units discrepancy, but cannot find dygraphs div to change: old = ' + old_units + ', new = ' + new_units);
  1954. }
  1955. }
  1956. return v;
  1957. }
  1958. }
  1959. },
  1960. legendFormatter: function (data) {
  1961. if (state.tmp.dygraph_mouse_down) {
  1962. return;
  1963. }
  1964. let elements = state.element_legend_childs;
  1965. // if the hidden div is not there
  1966. // we are not managing the legend
  1967. if (elements.hidden === null) {
  1968. return;
  1969. }
  1970. if (typeof data.x !== 'undefined') {
  1971. state.legendSetDate(data.x);
  1972. let i = data.series.length;
  1973. while (i--) {
  1974. let series = data.series[i];
  1975. if (series.isVisible) {
  1976. state.legendSetLabelValue(series.label, series.y);
  1977. } else {
  1978. state.legendSetLabelValue(series.label, null);
  1979. }
  1980. }
  1981. }
  1982. return '';
  1983. },
  1984. drawCallback: function (dygraph, is_initial) {
  1985. // the user has panned the chart and this is called to re-draw the chart
  1986. // 1. refresh this chart by adding data to it
  1987. // 2. notify all the other charts about the update they need
  1988. // to prevent an infinite loop (feedback), we use
  1989. // state.tmp.dygraph_user_action
  1990. // - when true, this is initiated by a user
  1991. // - when false, this is feedback
  1992. if (state.current.name !== 'auto' && state.tmp.dygraph_user_action) {
  1993. state.tmp.dygraph_user_action = false;
  1994. let x_range = dygraph.xAxisRange();
  1995. let after = Math.round(x_range[0]);
  1996. let before = Math.round(x_range[1]);
  1997. if (NETDATA.options.debug.dygraph) {
  1998. state.log('dygraphDrawCallback(dygraph, ' + is_initial + '): mode ' + state.current.name + ' ' + (after / 1000).toString() + ' - ' + (before / 1000).toString());
  1999. //console.log(state);
  2000. }
  2001. if (before <= state.netdata_last && after >= state.netdata_first) {
  2002. // update only when we are within the data limits
  2003. state.updateChartPanOrZoom(after, before);
  2004. }
  2005. }
  2006. },
  2007. zoomCallback: function (minDate, maxDate, yRanges) {
  2008. // the user has selected a range on the chart
  2009. // 1. refresh this chart by adding data to it
  2010. // 2. notify all the other charts about the update they need
  2011. void(yRanges);
  2012. if (NETDATA.options.debug.dygraph) {
  2013. state.log('dygraphZoomCallback(): ' + state.current.name);
  2014. }
  2015. NETDATA.globalSelectionSync.stop();
  2016. NETDATA.globalSelectionSync.delay();
  2017. state.setMode('zoom');
  2018. // refresh it to the greatest possible zoom level
  2019. state.tmp.dygraph_user_action = true;
  2020. state.tmp.dygraph_force_zoom = true;
  2021. state.updateChartPanOrZoom(minDate, maxDate);
  2022. },
  2023. highlightCallback: function (event, x, points, row, seriesName) {
  2024. void(seriesName);
  2025. state.pauseChart();
  2026. // there is a bug in dygraph when the chart is zoomed enough
  2027. // the time it thinks is selected is wrong
  2028. // here we calculate the time t based on the row number selected
  2029. // which is ok
  2030. // let t = state.data_after + row * state.data_update_every;
  2031. // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every);
  2032. if (state.tmp.dygraph_mouse_down !== true) {
  2033. NETDATA.globalSelectionSync.sync(state, x);
  2034. }
  2035. // fix legend zIndex using the internal structures of dygraph legend module
  2036. // this works, but it is a hack!
  2037. // state.tmp.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
  2038. },
  2039. unhighlightCallback: function (event) {
  2040. void(event);
  2041. if (state.tmp.dygraph_mouse_down) {
  2042. return;
  2043. }
  2044. if (NETDATA.options.debug.dygraph || state.debug) {
  2045. state.log('dygraphUnhighlightCallback()');
  2046. }
  2047. state.unpauseChart();
  2048. NETDATA.globalSelectionSync.stop();
  2049. },
  2050. underlayCallback: function (canvas, area, g) {
  2051. // the chart is about to be drawn
  2052. // update history_tip_element
  2053. if (state.tmp.dygraph_history_tip_element) {
  2054. const xHookRightSide = g.toDomXCoord(state.netdata_first);
  2055. if (xHookRightSide > area.x) {
  2056. state.tmp.dygraph_history_tip_element_displayed = true;
  2057. // group the styles for possible better performance
  2058. state.tmp.dygraph_history_tip_element.setAttribute(
  2059. 'style',
  2060. `display: block; left: ${area.x}px; right: calc(100% - ${xHookRightSide}px);`
  2061. )
  2062. } else {
  2063. if (state.tmp.dygraph_history_tip_element_displayed) {
  2064. // additional check just for performance
  2065. // don't update the DOM when it's not needed
  2066. state.tmp.dygraph_history_tip_element.style.display = 'none';
  2067. state.tmp.dygraph_history_tip_element_displayed = false;
  2068. }
  2069. }
  2070. }
  2071. // this function renders global highlighted time-frame
  2072. if (NETDATA.globalChartUnderlay.isActive()) {
  2073. let after = NETDATA.globalChartUnderlay.after;
  2074. let before = NETDATA.globalChartUnderlay.before;
  2075. if (after < state.view_after) {
  2076. after = state.view_after;
  2077. }
  2078. if (before > state.view_before) {
  2079. before = state.view_before;
  2080. }
  2081. if (after < before) {
  2082. let bottom_left = g.toDomCoords(after, -20);
  2083. let top_right = g.toDomCoords(before, +20);
  2084. let left = bottom_left[0];
  2085. let right = top_right[0];
  2086. canvas.fillStyle = NETDATA.themes.current.highlight;
  2087. canvas.fillRect(left, area.y, right - left, area.h);
  2088. }
  2089. }
  2090. },
  2091. interactionModel: {
  2092. mousedown: function (event, dygraph, context) {
  2093. if (NETDATA.options.debug.dygraph || state.debug) {
  2094. state.log('interactionModel.mousedown()');
  2095. }
  2096. state.tmp.dygraph_user_action = true;
  2097. if (NETDATA.options.debug.dygraph) {
  2098. state.log('dygraphMouseDown()');
  2099. }
  2100. // Right-click should not initiate anything.
  2101. if (event.button && event.button === 2) {
  2102. return;
  2103. }
  2104. NETDATA.globalSelectionSync.stop();
  2105. NETDATA.globalSelectionSync.delay();
  2106. state.tmp.dygraph_mouse_down = true;
  2107. context.initializeMouseDown(event, dygraph, context);
  2108. //console.log(event);
  2109. if (event.button && event.button === 1) {
  2110. if (event.shiftKey) {
  2111. //console.log('middle mouse button dragging (PAN)');
  2112. state.setMode('pan');
  2113. // NETDATA.globalSelectionSync.delay();
  2114. state.tmp.dygraph_highlight_after = null;
  2115. Dygraph.startPan(event, dygraph, context);
  2116. } else if (event.altKey || event.ctrlKey || event.metaKey) {
  2117. //console.log('middle mouse button highlight');
  2118. if (!(event.offsetX && event.offsetY)) {
  2119. event.offsetX = event.layerX - event.target.offsetLeft;
  2120. event.offsetY = event.layerY - event.target.offsetTop;
  2121. }
  2122. state.tmp.dygraph_highlight_after = dygraph.toDataXCoord(event.offsetX);
  2123. Dygraph.startZoom(event, dygraph, context);
  2124. } else {
  2125. //console.log('middle mouse button selection for zoom (ZOOM)');
  2126. state.setMode('zoom');
  2127. // NETDATA.globalSelectionSync.delay();
  2128. state.tmp.dygraph_highlight_after = null;
  2129. Dygraph.startZoom(event, dygraph, context);
  2130. }
  2131. } else {
  2132. if (event.shiftKey) {
  2133. //console.log('left mouse button selection for zoom (ZOOM)');
  2134. state.setMode('zoom');
  2135. // NETDATA.globalSelectionSync.delay();
  2136. state.tmp.dygraph_highlight_after = null;
  2137. Dygraph.startZoom(event, dygraph, context);
  2138. } else if (event.altKey || event.ctrlKey || event.metaKey) {
  2139. //console.log('left mouse button highlight');
  2140. if (!(event.offsetX && event.offsetY)) {
  2141. event.offsetX = event.layerX - event.target.offsetLeft;
  2142. event.offsetY = event.layerY - event.target.offsetTop;
  2143. }
  2144. state.tmp.dygraph_highlight_after = dygraph.toDataXCoord(event.offsetX);
  2145. Dygraph.startZoom(event, dygraph, context);
  2146. } else {
  2147. //console.log('left mouse button dragging (PAN)');
  2148. state.setMode('pan');
  2149. // NETDATA.globalSelectionSync.delay();
  2150. state.tmp.dygraph_highlight_after = null;
  2151. Dygraph.startPan(event, dygraph, context);
  2152. }
  2153. }
  2154. },
  2155. mousemove: function (event, dygraph, context) {
  2156. if (NETDATA.options.debug.dygraph || state.debug) {
  2157. state.log('interactionModel.mousemove()');
  2158. }
  2159. if (state.tmp.dygraph_highlight_after !== null) {
  2160. //console.log('highlight selection...');
  2161. NETDATA.globalSelectionSync.stop();
  2162. NETDATA.globalSelectionSync.delay();
  2163. state.tmp.dygraph_user_action = true;
  2164. Dygraph.moveZoom(event, dygraph, context);
  2165. event.preventDefault();
  2166. } else if (context.isPanning) {
  2167. //console.log('panning...');
  2168. NETDATA.globalSelectionSync.stop();
  2169. NETDATA.globalSelectionSync.delay();
  2170. state.tmp.dygraph_user_action = true;
  2171. //NETDATA.globalSelectionSync.stop();
  2172. //NETDATA.globalSelectionSync.delay();
  2173. state.setMode('pan');
  2174. context.is2DPan = false;
  2175. Dygraph.movePan(event, dygraph, context);
  2176. } else if (context.isZooming) {
  2177. //console.log('zooming...');
  2178. NETDATA.globalSelectionSync.stop();
  2179. NETDATA.globalSelectionSync.delay();
  2180. state.tmp.dygraph_user_action = true;
  2181. //NETDATA.globalSelectionSync.stop();
  2182. //NETDATA.globalSelectionSync.delay();
  2183. state.setMode('zoom');
  2184. Dygraph.moveZoom(event, dygraph, context);
  2185. }
  2186. },
  2187. mouseup: function (event, dygraph, context) {
  2188. state.tmp.dygraph_mouse_down = false;
  2189. if (NETDATA.options.debug.dygraph || state.debug) {
  2190. state.log('interactionModel.mouseup()');
  2191. }
  2192. if (state.tmp.dygraph_highlight_after !== null) {
  2193. //console.log('done highlight selection');
  2194. NETDATA.globalSelectionSync.stop();
  2195. NETDATA.globalSelectionSync.delay();
  2196. if (!(event.offsetX && event.offsetY)) {
  2197. event.offsetX = event.layerX - event.target.offsetLeft;
  2198. event.offsetY = event.layerY - event.target.offsetTop;
  2199. }
  2200. NETDATA.globalChartUnderlay.set(state
  2201. , state.tmp.dygraph_highlight_after
  2202. , dygraph.toDataXCoord(event.offsetX)
  2203. , state.view_after
  2204. , state.view_before
  2205. );
  2206. state.tmp.dygraph_highlight_after = null;
  2207. context.isZooming = false;
  2208. dygraph.clearZoomRect_();
  2209. dygraph.drawGraph_(false);
  2210. // refresh all the charts immediately
  2211. NETDATA.options.auto_refresher_stop_until = 0;
  2212. } else if (context.isPanning) {
  2213. //console.log('done panning');
  2214. NETDATA.globalSelectionSync.stop();
  2215. NETDATA.globalSelectionSync.delay();
  2216. state.tmp.dygraph_user_action = true;
  2217. Dygraph.endPan(event, dygraph, context);
  2218. // refresh all the charts immediately
  2219. NETDATA.options.auto_refresher_stop_until = 0;
  2220. } else if (context.isZooming) {
  2221. //console.log('done zomming');
  2222. NETDATA.globalSelectionSync.stop();
  2223. NETDATA.globalSelectionSync.delay();
  2224. state.tmp.dygraph_user_action = true;
  2225. Dygraph.endZoom(event, dygraph, context);
  2226. // refresh all the charts immediately
  2227. NETDATA.options.auto_refresher_stop_until = 0;
  2228. }
  2229. },
  2230. click: function (event, dygraph, context) {
  2231. void(dygraph);
  2232. void(context);
  2233. if (NETDATA.options.debug.dygraph || state.debug) {
  2234. state.log('interactionModel.click()');
  2235. }
  2236. event.preventDefault();
  2237. },
  2238. dblclick: function (event, dygraph, context) {
  2239. void(event);
  2240. void(dygraph);
  2241. void(context);
  2242. if (NETDATA.options.debug.dygraph || state.debug) {
  2243. state.log('interactionModel.dblclick()');
  2244. }
  2245. NETDATA.resetAllCharts(state);
  2246. },
  2247. wheel: function (event, dygraph, context) {
  2248. void(context);
  2249. if (NETDATA.options.debug.dygraph || state.debug) {
  2250. state.log('interactionModel.wheel()');
  2251. }
  2252. // Take the offset of a mouse event on the dygraph canvas and
  2253. // convert it to a pair of percentages from the bottom left.
  2254. // (Not top left, bottom is where the lower value is.)
  2255. function offsetToPercentage(g, offsetX, offsetY) {
  2256. // This is calculating the pixel offset of the leftmost date.
  2257. let xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
  2258. let yar0 = g.yAxisRange(0);
  2259. // This is calculating the pixel of the highest value. (Top pixel)
  2260. let yOffset = g.toDomCoords(null, yar0[1])[1];
  2261. // x y w and h are relative to the corner of the drawing area,
  2262. // so that the upper corner of the drawing area is (0, 0).
  2263. let x = offsetX - xOffset;
  2264. let y = offsetY - yOffset;
  2265. // This is computing the rightmost pixel, effectively defining the
  2266. // width.
  2267. let w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
  2268. // This is computing the lowest pixel, effectively defining the height.
  2269. let h = g.toDomCoords(null, yar0[0])[1] - yOffset;
  2270. // Percentage from the left.
  2271. let xPct = w === 0 ? 0 : (x / w);
  2272. // Percentage from the top.
  2273. let yPct = h === 0 ? 0 : (y / h);
  2274. // The (1-) part below changes it from "% distance down from the top"
  2275. // to "% distance up from the bottom".
  2276. return [xPct, (1 - yPct)];
  2277. }
  2278. // Adjusts [x, y] toward each other by zoomInPercentage%
  2279. // Split it so the left/bottom axis gets xBias/yBias of that change and
  2280. // tight/top gets (1-xBias)/(1-yBias) of that change.
  2281. //
  2282. // If a bias is missing it splits it down the middle.
  2283. function zoomRange(g, zoomInPercentage, xBias, yBias) {
  2284. xBias = xBias || 0.5;
  2285. yBias = yBias || 0.5;
  2286. function adjustAxis(axis, zoomInPercentage, bias) {
  2287. let delta = axis[1] - axis[0];
  2288. let increment = delta * zoomInPercentage;
  2289. let foo = [increment * bias, increment * (1 - bias)];
  2290. return [axis[0] + foo[0], axis[1] - foo[1]];
  2291. }
  2292. let yAxes = g.yAxisRanges();
  2293. let newYAxes = [];
  2294. for (let i = 0; i < yAxes.length; i++) {
  2295. newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
  2296. }
  2297. return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
  2298. }
  2299. if (event.altKey || event.shiftKey) {
  2300. state.tmp.dygraph_user_action = true;
  2301. NETDATA.globalSelectionSync.stop();
  2302. NETDATA.globalSelectionSync.delay();
  2303. // http://dygraphs.com/gallery/interaction-api.js
  2304. let normal_def;
  2305. if (typeof event.wheelDelta === 'number' && !isNaN(event.wheelDelta))
  2306. // chrome
  2307. {
  2308. normal_def = event.wheelDelta / 40;
  2309. } else
  2310. // firefox
  2311. {
  2312. normal_def = event.deltaY * -1.2;
  2313. }
  2314. let normal = (event.detail) ? event.detail * -1 : normal_def;
  2315. let percentage = normal / 50;
  2316. if (!(event.offsetX && event.offsetY)) {
  2317. event.offsetX = event.layerX - event.target.offsetLeft;
  2318. event.offsetY = event.layerY - event.target.offsetTop;
  2319. }
  2320. let percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
  2321. let xPct = percentages[0];
  2322. let yPct = percentages[1];
  2323. let new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
  2324. let after = new_x_range[0];
  2325. let before = new_x_range[1];
  2326. let first = state.netdata_first + state.data_update_every;
  2327. let last = state.netdata_last + state.data_update_every;
  2328. if (before > last) {
  2329. after -= (before - last);
  2330. before = last;
  2331. }
  2332. if (after < first) {
  2333. after = first;
  2334. }
  2335. state.setMode('zoom');
  2336. state.updateChartPanOrZoom(after, before, function () {
  2337. dygraph.updateOptions({dateWindow: [after, before]});
  2338. });
  2339. event.preventDefault();
  2340. }
  2341. },
  2342. touchstart: function (event, dygraph, context) {
  2343. state.tmp.dygraph_mouse_down = true;
  2344. if (NETDATA.options.debug.dygraph || state.debug) {
  2345. state.log('interactionModel.touchstart()');
  2346. }
  2347. state.tmp.dygraph_user_action = true;
  2348. state.setMode('zoom');
  2349. state.pauseChart();
  2350. NETDATA.globalSelectionSync.stop();
  2351. NETDATA.globalSelectionSync.delay();
  2352. Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
  2353. // we overwrite the touch directions at the end, to overwrite
  2354. // the internal default of dygraph
  2355. context.touchDirections = {x: true, y: false};
  2356. state.dygraph_last_touch_start = Date.now();
  2357. state.dygraph_last_touch_move = 0;
  2358. if (typeof event.touches[0].pageX === 'number') {
  2359. state.dygraph_last_touch_page_x = event.touches[0].pageX;
  2360. } else {
  2361. state.dygraph_last_touch_page_x = 0;
  2362. }
  2363. },
  2364. touchmove: function (event, dygraph, context) {
  2365. if (NETDATA.options.debug.dygraph || state.debug) {
  2366. state.log('interactionModel.touchmove()');
  2367. }
  2368. NETDATA.globalSelectionSync.stop();
  2369. NETDATA.globalSelectionSync.delay();
  2370. state.tmp.dygraph_user_action = true;
  2371. Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
  2372. state.dygraph_last_touch_move = Date.now();
  2373. },
  2374. touchend: function (event, dygraph, context) {
  2375. state.tmp.dygraph_mouse_down = false;
  2376. if (NETDATA.options.debug.dygraph || state.debug) {
  2377. state.log('interactionModel.touchend()');
  2378. }
  2379. NETDATA.globalSelectionSync.stop();
  2380. NETDATA.globalSelectionSync.delay();
  2381. state.tmp.dygraph_user_action = true;
  2382. Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
  2383. // if it didn't move, it is a selection
  2384. if (state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
  2385. NETDATA.globalSelectionSync.dontSyncBefore = 0;
  2386. NETDATA.globalSelectionSync.setMaster(state);
  2387. // internal api of dygraph
  2388. let pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
  2389. console.log('pct: ' + pct.toString());
  2390. let t = Math.round(state.view_after + (state.view_before - state.view_after) * pct);
  2391. if (NETDATA.dygraphSetSelection(state, t)) {
  2392. NETDATA.globalSelectionSync.sync(state, t);
  2393. }
  2394. }
  2395. // if it was double tap within double click time, reset the charts
  2396. let now = Date.now();
  2397. if (typeof state.dygraph_last_touch_end !== 'undefined') {
  2398. if (state.dygraph_last_touch_move === 0) {
  2399. let dt = now - state.dygraph_last_touch_end;
  2400. if (dt <= NETDATA.options.current.double_click_speed) {
  2401. NETDATA.resetAllCharts(state);
  2402. }
  2403. }
  2404. }
  2405. // remember the timestamp of the last touch end
  2406. state.dygraph_last_touch_end = now;
  2407. // refresh all the charts immediately
  2408. NETDATA.options.auto_refresher_stop_until = 0;
  2409. }
  2410. }
  2411. };
  2412. if (NETDATA.chartLibraries.dygraph.isLogScale(state)) {
  2413. if (Array.isArray(state.tmp.dygraph_options.valueRange) && state.tmp.dygraph_options.valueRange[0] <= 0) {
  2414. state.tmp.dygraph_options.valueRange[0] = null;
  2415. }
  2416. }
  2417. if (NETDATA.chartLibraries.dygraph.isSparkline(state)) {
  2418. state.tmp.dygraph_options.drawGrid = false;
  2419. state.tmp.dygraph_options.drawAxis = false;
  2420. state.tmp.dygraph_options.title = undefined;
  2421. state.tmp.dygraph_options.ylabel = undefined;
  2422. state.tmp.dygraph_options.yLabelWidth = 0;
  2423. //state.tmp.dygraph_options.labelsDivWidth = 120;
  2424. //state.tmp.dygraph_options.labelsDivStyles.width = '120px';
  2425. state.tmp.dygraph_options.labelsSeparateLines = true;
  2426. state.tmp.dygraph_options.rightGap = 0;
  2427. state.tmp.dygraph_options.yRangePad = 1;
  2428. state.tmp.dygraph_options.axes.x.drawAxis = false;
  2429. state.tmp.dygraph_options.axes.y.drawAxis = false;
  2430. }
  2431. if (smooth) {
  2432. state.tmp.dygraph_smooth_eligible = true;
  2433. if (NETDATA.options.current.smooth_plot) {
  2434. state.tmp.dygraph_options.plotter = smoothPlotter;
  2435. }
  2436. }
  2437. else {
  2438. state.tmp.dygraph_smooth_eligible = false;
  2439. }
  2440. if (netdataSnapshotData !== null && NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(state) === false) {
  2441. // pan and zoom on snapshots
  2442. state.tmp.dygraph_options.dateWindow = [NETDATA.globalPanAndZoom.force_after_ms, NETDATA.globalPanAndZoom.force_before_ms];
  2443. //state.tmp.dygraph_options.isZoomedIgnoreProgrammaticZoom = true;
  2444. }
  2445. state.tmp.dygraph_instance = new Dygraph(state.element_chart,
  2446. data.result.data, state.tmp.dygraph_options);
  2447. state.tmp.dygraph_history_tip_element = document.createElement('div');
  2448. state.tmp.dygraph_history_tip_element.innerHTML = `
  2449. <span class="dygraph__history-tip-content">
  2450. Want to extend your history of real-time metrics?
  2451. <br />
  2452. <a href="https://learn.netdata.cloud/guides/longer-metrics-storage/" target=_blank>
  2453. Configure Netdata's <b>history</b></a>
  2454. or use the <a href="https://learn.netdata.cloud/docs/agent/database/engine/" target=_blank>DB engine</a>.
  2455. </span>
  2456. `;
  2457. state.tmp.dygraph_history_tip_element.className = 'dygraph__history-tip';
  2458. state.element_chart.appendChild(state.tmp.dygraph_history_tip_element);
  2459. state.tmp.dygraph_force_zoom = false;
  2460. state.tmp.dygraph_user_action = false;
  2461. state.tmp.dygraph_last_rendered = Date.now();
  2462. state.tmp.dygraph_highlight_after = null;
  2463. if (state.tmp.dygraph_options.valueRange[0] === null && state.tmp.dygraph_options.valueRange[1] === null) {
  2464. if (typeof state.tmp.dygraph_instance.axes_[0].extremeRange !== 'undefined') {
  2465. state.tmp.__commonMin = NETDATA.dataAttribute(state.element, 'common-min', null);
  2466. state.tmp.__commonMax = NETDATA.dataAttribute(state.element, 'common-max', null);
  2467. } else {
  2468. state.log('incompatible version of Dygraph detected');
  2469. state.tmp.__commonMin = null;
  2470. state.tmp.__commonMax = null;
  2471. }
  2472. } else {
  2473. // if the user gave a valueRange, respect it
  2474. state.tmp.__commonMin = null;
  2475. state.tmp.__commonMax = null;
  2476. }
  2477. return true;
  2478. };
  2479. // ----------------------------------------------------------------------------------------------------------------
  2480. // sparkline
  2481. NETDATA.sparklineInitialize = function (callback) {
  2482. if (typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
  2483. $.ajax({
  2484. url: NETDATA.sparkline_js,
  2485. cache: true,
  2486. dataType: "script",
  2487. xhrFields: {withCredentials: true} // required for the cookie
  2488. })
  2489. .done(function () {
  2490. NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
  2491. })
  2492. .fail(function () {
  2493. NETDATA.chartLibraries.sparkline.enabled = false;
  2494. NETDATA.error(100, NETDATA.sparkline_js);
  2495. })
  2496. .always(function () {
  2497. if (typeof callback === "function") {
  2498. return callback();
  2499. }
  2500. });
  2501. } else {
  2502. NETDATA.chartLibraries.sparkline.enabled = false;
  2503. if (typeof callback === "function") {
  2504. return callback();
  2505. }
  2506. }
  2507. };
  2508. NETDATA.sparklineChartUpdate = function (state, data) {
  2509. state.sparkline_options.width = state.chartWidth();
  2510. state.sparkline_options.height = state.chartHeight();
  2511. $(state.element_chart).sparkline(data.result, state.sparkline_options);
  2512. return true;
  2513. };
  2514. NETDATA.sparklineChartCreate = function (state, data) {
  2515. let type = NETDATA.dataAttribute(state.element, 'sparkline-type', 'line');
  2516. let lineColor = NETDATA.dataAttribute(state.element, 'sparkline-linecolor', state.chartCustomColors()[0]);
  2517. let fillColor = NETDATA.dataAttribute(state.element, 'sparkline-fillcolor', ((state.chart.chart_type === 'line') ? NETDATA.themes.current.background : NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance)));
  2518. let chartRangeMin = NETDATA.dataAttribute(state.element, 'sparkline-chartrangemin', undefined);
  2519. let chartRangeMax = NETDATA.dataAttribute(state.element, 'sparkline-chartrangemax', undefined);
  2520. let composite = NETDATA.dataAttribute(state.element, 'sparkline-composite', undefined);
  2521. let enableTagOptions = NETDATA.dataAttribute(state.element, 'sparkline-enabletagoptions', undefined);
  2522. let tagOptionPrefix = NETDATA.dataAttribute(state.element, 'sparkline-tagoptionprefix', undefined);
  2523. let tagValuesAttribute = NETDATA.dataAttribute(state.element, 'sparkline-tagvaluesattribute', undefined);
  2524. let disableHiddenCheck = NETDATA.dataAttribute(state.element, 'sparkline-disablehiddencheck', undefined);
  2525. let defaultPixelsPerValue = NETDATA.dataAttribute(state.element, 'sparkline-defaultpixelspervalue', undefined);
  2526. let spotColor = NETDATA.dataAttribute(state.element, 'sparkline-spotcolor', undefined);
  2527. let minSpotColor = NETDATA.dataAttribute(state.element, 'sparkline-minspotcolor', undefined);
  2528. let maxSpotColor = NETDATA.dataAttribute(state.element, 'sparkline-maxspotcolor', undefined);
  2529. let spotRadius = NETDATA.dataAttribute(state.element, 'sparkline-spotradius', undefined);
  2530. let valueSpots = NETDATA.dataAttribute(state.element, 'sparkline-valuespots', undefined);
  2531. let highlightSpotColor = NETDATA.dataAttribute(state.element, 'sparkline-highlightspotcolor', undefined);
  2532. let highlightLineColor = NETDATA.dataAttribute(state.element, 'sparkline-highlightlinecolor', undefined);
  2533. let lineWidth = NETDATA.dataAttribute(state.element, 'sparkline-linewidth', undefined);
  2534. let normalRangeMin = NETDATA.dataAttribute(state.element, 'sparkline-normalrangemin', undefined);
  2535. let normalRangeMax = NETDATA.dataAttribute(state.element, 'sparkline-normalrangemax', undefined);
  2536. let drawNormalOnTop = NETDATA.dataAttribute(state.element, 'sparkline-drawnormalontop', undefined);
  2537. let xvalues = NETDATA.dataAttribute(state.element, 'sparkline-xvalues', undefined);
  2538. let chartRangeClip = NETDATA.dataAttribute(state.element, 'sparkline-chartrangeclip', undefined);
  2539. let chartRangeMinX = NETDATA.dataAttribute(state.element, 'sparkline-chartrangeminx', undefined);
  2540. let chartRangeMaxX = NETDATA.dataAttribute(state.element, 'sparkline-chartrangemaxx', undefined);
  2541. let disableInteraction = NETDATA.dataAttributeBoolean(state.element, 'sparkline-disableinteraction', false);
  2542. let disableTooltips = NETDATA.dataAttributeBoolean(state.element, 'sparkline-disabletooltips', false);
  2543. let disableHighlight = NETDATA.dataAttributeBoolean(state.element, 'sparkline-disablehighlight', false);
  2544. let highlightLighten = NETDATA.dataAttribute(state.element, 'sparkline-highlightlighten', 1.4);
  2545. let highlightColor = NETDATA.dataAttribute(state.element, 'sparkline-highlightcolor', undefined);
  2546. let tooltipContainer = NETDATA.dataAttribute(state.element, 'sparkline-tooltipcontainer', undefined);
  2547. let tooltipClassname = NETDATA.dataAttribute(state.element, 'sparkline-tooltipclassname', undefined);
  2548. let tooltipFormat = NETDATA.dataAttribute(state.element, 'sparkline-tooltipformat', undefined);
  2549. let tooltipPrefix = NETDATA.dataAttribute(state.element, 'sparkline-tooltipprefix', undefined);
  2550. let tooltipSuffix = NETDATA.dataAttribute(state.element, 'sparkline-tooltipsuffix', ' ' + state.units_current);
  2551. let tooltipSkipNull = NETDATA.dataAttributeBoolean(state.element, 'sparkline-tooltipskipnull', true);
  2552. let tooltipValueLookups = NETDATA.dataAttribute(state.element, 'sparkline-tooltipvaluelookups', undefined);
  2553. let tooltipFormatFieldlist = NETDATA.dataAttribute(state.element, 'sparkline-tooltipformatfieldlist', undefined);
  2554. let tooltipFormatFieldlistKey = NETDATA.dataAttribute(state.element, 'sparkline-tooltipformatfieldlistkey', undefined);
  2555. let numberFormatter = NETDATA.dataAttribute(state.element, 'sparkline-numberformatter', function (n) {
  2556. return n.toFixed(2);
  2557. });
  2558. let numberDigitGroupSep = NETDATA.dataAttribute(state.element, 'sparkline-numberdigitgroupsep', undefined);
  2559. let numberDecimalMark = NETDATA.dataAttribute(state.element, 'sparkline-numberdecimalmark', undefined);
  2560. let numberDigitGroupCount = NETDATA.dataAttribute(state.element, 'sparkline-numberdigitgroupcount', undefined);
  2561. let animatedZooms = NETDATA.dataAttributeBoolean(state.element, 'sparkline-animatedzooms', false);
  2562. if (spotColor === 'disable') {
  2563. spotColor = '';
  2564. }
  2565. if (minSpotColor === 'disable') {
  2566. minSpotColor = '';
  2567. }
  2568. if (maxSpotColor === 'disable') {
  2569. maxSpotColor = '';
  2570. }
  2571. // state.log('sparkline type ' + type + ', lineColor: ' + lineColor + ', fillColor: ' + fillColor);
  2572. state.sparkline_options = {
  2573. type: type,
  2574. lineColor: lineColor,
  2575. fillColor: fillColor,
  2576. chartRangeMin: chartRangeMin,
  2577. chartRangeMax: chartRangeMax,
  2578. composite: composite,
  2579. enableTagOptions: enableTagOptions,
  2580. tagOptionPrefix: tagOptionPrefix,
  2581. tagValuesAttribute: tagValuesAttribute,
  2582. disableHiddenCheck: disableHiddenCheck,
  2583. defaultPixelsPerValue: defaultPixelsPerValue,
  2584. spotColor: spotColor,
  2585. minSpotColor: minSpotColor,
  2586. maxSpotColor: maxSpotColor,
  2587. spotRadius: spotRadius,
  2588. valueSpots: valueSpots,
  2589. highlightSpotColor: highlightSpotColor,
  2590. highlightLineColor: highlightLineColor,
  2591. lineWidth: lineWidth,
  2592. normalRangeMin: normalRangeMin,
  2593. normalRangeMax: normalRangeMax,
  2594. drawNormalOnTop: drawNormalOnTop,
  2595. xvalues: xvalues,
  2596. chartRangeClip: chartRangeClip,
  2597. chartRangeMinX: chartRangeMinX,
  2598. chartRangeMaxX: chartRangeMaxX,
  2599. disableInteraction: disableInteraction,
  2600. disableTooltips: disableTooltips,
  2601. disableHighlight: disableHighlight,
  2602. highlightLighten: highlightLighten,
  2603. highlightColor: highlightColor,
  2604. tooltipContainer: tooltipContainer,
  2605. tooltipClassname: tooltipClassname,
  2606. tooltipChartTitle: state.title,
  2607. tooltipFormat: tooltipFormat,
  2608. tooltipPrefix: tooltipPrefix,
  2609. tooltipSuffix: tooltipSuffix,
  2610. tooltipSkipNull: tooltipSkipNull,
  2611. tooltipValueLookups: tooltipValueLookups,
  2612. tooltipFormatFieldlist: tooltipFormatFieldlist,
  2613. tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
  2614. numberFormatter: numberFormatter,
  2615. numberDigitGroupSep: numberDigitGroupSep,
  2616. numberDecimalMark: numberDecimalMark,
  2617. numberDigitGroupCount: numberDigitGroupCount,
  2618. animatedZooms: animatedZooms,
  2619. width: state.chartWidth(),
  2620. height: state.chartHeight()
  2621. };
  2622. $(state.element_chart).sparkline(data.result, state.sparkline_options);
  2623. return true;
  2624. };
  2625. // google charts
  2626. // Codacy declarations
  2627. /* global google */
  2628. NETDATA.googleInitialize = function (callback) {
  2629. if (typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
  2630. $.ajax({
  2631. url: NETDATA.google_js,
  2632. cache: true,
  2633. dataType: "script",
  2634. xhrFields: {withCredentials: true} // required for the cookie
  2635. })
  2636. .done(function () {
  2637. NETDATA.registerChartLibrary('google', NETDATA.google_js);
  2638. google.load('visualization', '1.1', {
  2639. 'packages': ['corechart', 'controls'],
  2640. 'callback': callback
  2641. });
  2642. })
  2643. .fail(function () {
  2644. NETDATA.chartLibraries.google.enabled = false;
  2645. NETDATA.error(100, NETDATA.google_js);
  2646. if (typeof callback === "function") {
  2647. return callback();
  2648. }
  2649. });
  2650. } else {
  2651. NETDATA.chartLibraries.google.enabled = false;
  2652. if (typeof callback === "function") {
  2653. return callback();
  2654. }
  2655. }
  2656. };
  2657. NETDATA.googleChartUpdate = function (state, data) {
  2658. let datatable = new google.visualization.DataTable(data.result);
  2659. state.google_instance.draw(datatable, state.google_options);
  2660. return true;
  2661. };
  2662. NETDATA.googleChartCreate = function (state, data) {
  2663. let datatable = new google.visualization.DataTable(data.result);
  2664. state.google_options = {
  2665. colors: state.chartColors(),
  2666. // do not set width, height - the chart resizes itself
  2667. //width: state.chartWidth(),
  2668. //height: state.chartHeight(),
  2669. lineWidth: 1,
  2670. title: state.title,
  2671. fontSize: 11,
  2672. hAxis: {
  2673. // title: "Time of Day",
  2674. // format:'HH:mm:ss',
  2675. viewWindowMode: 'maximized',
  2676. slantedText: false,
  2677. format: 'HH:mm:ss',
  2678. textStyle: {
  2679. fontSize: 9
  2680. },
  2681. gridlines: {
  2682. color: '#EEE'
  2683. }
  2684. },
  2685. vAxis: {
  2686. title: state.units_current,
  2687. viewWindowMode: 'pretty',
  2688. minValue: -0.1,
  2689. maxValue: 0.1,
  2690. direction: 1,
  2691. textStyle: {
  2692. fontSize: 9
  2693. },
  2694. gridlines: {
  2695. color: '#EEE'
  2696. }
  2697. },
  2698. chartArea: {
  2699. width: '65%',
  2700. height: '80%'
  2701. },
  2702. focusTarget: 'category',
  2703. annotation: {
  2704. '1': {
  2705. style: 'line'
  2706. }
  2707. },
  2708. pointsVisible: 0,
  2709. titlePosition: 'out',
  2710. titleTextStyle: {
  2711. fontSize: 11
  2712. },
  2713. tooltip: {
  2714. isHtml: false,
  2715. ignoreBounds: true,
  2716. textStyle: {
  2717. fontSize: 9
  2718. }
  2719. },
  2720. curveType: 'function',
  2721. areaOpacity: 0.3,
  2722. isStacked: false
  2723. };
  2724. switch (state.chart.chart_type) {
  2725. case "area":
  2726. state.google_options.vAxis.viewWindowMode = 'maximized';
  2727. state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
  2728. state.google_instance = new google.visualization.AreaChart(state.element_chart);
  2729. break;
  2730. case "stacked":
  2731. state.google_options.isStacked = true;
  2732. state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
  2733. state.google_options.vAxis.viewWindowMode = 'maximized';
  2734. state.google_options.vAxis.minValue = null;
  2735. state.google_options.vAxis.maxValue = null;
  2736. state.google_instance = new google.visualization.AreaChart(state.element_chart);
  2737. break;
  2738. default:
  2739. case "line":
  2740. state.google_options.lineWidth = 2;
  2741. state.google_instance = new google.visualization.LineChart(state.element_chart);
  2742. break;
  2743. }
  2744. state.google_instance.draw(datatable, state.google_options);
  2745. return true;
  2746. };
  2747. // gauge.js
  2748. NETDATA.gaugeInitialize = function (callback) {
  2749. if (typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
  2750. $.ajax({
  2751. url: NETDATA.gauge_js,
  2752. cache: true,
  2753. dataType: "script",
  2754. xhrFields: {withCredentials: true} // required for the cookie
  2755. })
  2756. .done(function () {
  2757. NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
  2758. })
  2759. .fail(function () {
  2760. NETDATA.chartLibraries.gauge.enabled = false;
  2761. NETDATA.error(100, NETDATA.gauge_js);
  2762. })
  2763. .always(function () {
  2764. if (typeof callback === "function") {
  2765. return callback();
  2766. }
  2767. })
  2768. }
  2769. else {
  2770. NETDATA.chartLibraries.gauge.enabled = false;
  2771. if (typeof callback === "function") {
  2772. return callback();
  2773. }
  2774. }
  2775. };
  2776. NETDATA.gaugeAnimation = function (state, status) {
  2777. let speed = 32;
  2778. if (typeof status === 'boolean' && status === false) {
  2779. speed = 1000000000;
  2780. } else if (typeof status === 'number') {
  2781. speed = status;
  2782. }
  2783. // console.log('gauge speed ' + speed);
  2784. state.tmp.gauge_instance.animationSpeed = speed;
  2785. state.tmp.___gaugeOld__.speed = speed;
  2786. };
  2787. NETDATA.gaugeSet = function (state, value, min, max) {
  2788. if (typeof value !== 'number') {
  2789. value = 0;
  2790. }
  2791. if (typeof min !== 'number') {
  2792. min = 0;
  2793. }
  2794. if (typeof max !== 'number') {
  2795. max = 0;
  2796. }
  2797. if (value > max) {
  2798. max = value;
  2799. }
  2800. if (value < min) {
  2801. min = value;
  2802. }
  2803. if (min > max) {
  2804. let t = min;
  2805. min = max;
  2806. max = t;
  2807. }
  2808. else if (min === max) {
  2809. max = min + 1;
  2810. }
  2811. state.legendFormatValueDecimalsFromMinMax(min, max);
  2812. // gauge.js has an issue if the needle
  2813. // is smaller than min or larger than max
  2814. // when we set the new values
  2815. // the needle will go crazy
  2816. // to prevent it, we always feed it
  2817. // with a percentage, so that the needle
  2818. // is always between min and max
  2819. let pcent = (value - min) * 100 / (max - min);
  2820. // bug fix for gauge.js 1.3.1
  2821. // if the value is the absolute min or max, the chart is broken
  2822. if (pcent < 0.001) {
  2823. pcent = 0.001;
  2824. }
  2825. if (pcent > 99.999) {
  2826. pcent = 99.999;
  2827. }
  2828. state.tmp.gauge_instance.set(pcent);
  2829. // console.log('gauge set ' + pcent + ', value ' + value + ', min ' + min + ', max ' + max);
  2830. state.tmp.___gaugeOld__.value = value;
  2831. state.tmp.___gaugeOld__.min = min;
  2832. state.tmp.___gaugeOld__.max = max;
  2833. };
  2834. NETDATA.gaugeSetLabels = function (state, value, min, max) {
  2835. if (state.tmp.___gaugeOld__.valueLabel !== value) {
  2836. state.tmp.___gaugeOld__.valueLabel = value;
  2837. state.tmp.gaugeChartLabel.innerText = state.legendFormatValue(value);
  2838. }
  2839. if (state.tmp.___gaugeOld__.minLabel !== min) {
  2840. state.tmp.___gaugeOld__.minLabel = min;
  2841. state.tmp.gaugeChartMin.innerText = state.legendFormatValue(min);
  2842. }
  2843. if (state.tmp.___gaugeOld__.maxLabel !== max) {
  2844. state.tmp.___gaugeOld__.maxLabel = max;
  2845. state.tmp.gaugeChartMax.innerText = state.legendFormatValue(max);
  2846. }
  2847. };
  2848. NETDATA.gaugeClearSelection = function (state, force) {
  2849. if (typeof state.tmp.gaugeEvent !== 'undefined' && typeof state.tmp.gaugeEvent.timer !== 'undefined') {
  2850. NETDATA.timeout.clear(state.tmp.gaugeEvent.timer);
  2851. state.tmp.gaugeEvent.timer = undefined;
  2852. }
  2853. if (state.isAutoRefreshable() && state.data !== null && force !== true) {
  2854. NETDATA.gaugeChartUpdate(state, state.data);
  2855. } else {
  2856. NETDATA.gaugeAnimation(state, false);
  2857. NETDATA.gaugeSetLabels(state, null, null, null);
  2858. NETDATA.gaugeSet(state, null, null, null);
  2859. }
  2860. NETDATA.gaugeAnimation(state, true);
  2861. return true;
  2862. };
  2863. NETDATA.gaugeSetSelection = function (state, t) {
  2864. if (state.timeIsVisible(t) !== true) {
  2865. return NETDATA.gaugeClearSelection(state, true);
  2866. }
  2867. let slot = state.calculateRowForTime(t);
  2868. if (slot < 0 || slot >= state.data.result.length) {
  2869. return NETDATA.gaugeClearSelection(state, true);
  2870. }
  2871. if (typeof state.tmp.gaugeEvent === 'undefined') {
  2872. state.tmp.gaugeEvent = {
  2873. timer: undefined,
  2874. value: 0,
  2875. min: 0,
  2876. max: 0
  2877. };
  2878. }
  2879. let value = state.data.result[state.data.result.length - 1 - slot];
  2880. let min = (state.tmp.gaugeMin === null) ? NETDATA.commonMin.get(state) : state.tmp.gaugeMin;
  2881. let max = (state.tmp.gaugeMax === null) ? NETDATA.commonMax.get(state) : state.tmp.gaugeMax;
  2882. // make sure it is zero based
  2883. // but only if it has not been set by the user
  2884. if (state.tmp.gaugeMin === null && min > 0) {
  2885. min = 0;
  2886. }
  2887. if (state.tmp.gaugeMax === null && max < 0) {
  2888. max = 0;
  2889. }
  2890. state.tmp.gaugeEvent.value = value;
  2891. state.tmp.gaugeEvent.min = min;
  2892. state.tmp.gaugeEvent.max = max;
  2893. NETDATA.gaugeSetLabels(state, value, min, max);
  2894. if (state.tmp.gaugeEvent.timer === undefined) {
  2895. NETDATA.gaugeAnimation(state, false);
  2896. state.tmp.gaugeEvent.timer = NETDATA.timeout.set(function () {
  2897. state.tmp.gaugeEvent.timer = undefined;
  2898. NETDATA.gaugeSet(state, state.tmp.gaugeEvent.value, state.tmp.gaugeEvent.min, state.tmp.gaugeEvent.max);
  2899. }, 0);
  2900. }
  2901. return true;
  2902. };
  2903. NETDATA.gaugeChartUpdate = function (state, data) {
  2904. let value, min, max;
  2905. if (NETDATA.globalPanAndZoom.isActive() || state.isAutoRefreshable() === false) {
  2906. NETDATA.gaugeSetLabels(state, null, null, null);
  2907. state.tmp.gauge_instance.set(0);
  2908. } else {
  2909. value = data.result[0];
  2910. min = (state.tmp.gaugeMin === null) ? NETDATA.commonMin.get(state) : state.tmp.gaugeMin;
  2911. max = (state.tmp.gaugeMax === null) ? NETDATA.commonMax.get(state) : state.tmp.gaugeMax;
  2912. if (value < min) {
  2913. min = value;
  2914. }
  2915. if (value > max) {
  2916. max = value;
  2917. }
  2918. // make sure it is zero based
  2919. // but only if it has not been set by the user
  2920. if (state.tmp.gaugeMin === null && min > 0) {
  2921. min = 0;
  2922. }
  2923. if (state.tmp.gaugeMax === null && max < 0) {
  2924. max = 0;
  2925. }
  2926. NETDATA.gaugeSet(state, value, min, max);
  2927. NETDATA.gaugeSetLabels(state, value, min, max);
  2928. }
  2929. return true;
  2930. };
  2931. NETDATA.gaugeChartCreate = function (state, data) {
  2932. // let chart = $(state.element_chart);
  2933. let value = data.result[0];
  2934. let min = NETDATA.dataAttribute(state.element, 'gauge-min-value', null);
  2935. let max = NETDATA.dataAttribute(state.element, 'gauge-max-value', null);
  2936. // let adjust = NETDATA.dataAttribute(state.element, 'gauge-adjust', null);
  2937. let pointerColor = NETDATA.dataAttribute(state.element, 'gauge-pointer-color', NETDATA.themes.current.gauge_pointer);
  2938. let strokeColor = NETDATA.dataAttribute(state.element, 'gauge-stroke-color', NETDATA.themes.current.gauge_stroke);
  2939. let startColor = NETDATA.dataAttribute(state.element, 'gauge-start-color', state.chartCustomColors()[0]);
  2940. let stopColor = NETDATA.dataAttribute(state.element, 'gauge-stop-color', void 0);
  2941. let generateGradient = NETDATA.dataAttribute(state.element, 'gauge-generate-gradient', false);
  2942. if (min === null) {
  2943. min = NETDATA.commonMin.get(state);
  2944. state.tmp.gaugeMin = null;
  2945. } else {
  2946. state.tmp.gaugeMin = min;
  2947. }
  2948. if (max === null) {
  2949. max = NETDATA.commonMax.get(state);
  2950. state.tmp.gaugeMax = null;
  2951. } else {
  2952. state.tmp.gaugeMax = max;
  2953. }
  2954. // make sure it is zero based
  2955. // but only if it has not been set by the user
  2956. if (state.tmp.gaugeMin === null && min > 0) {
  2957. min = 0;
  2958. }
  2959. if (state.tmp.gaugeMax === null && max < 0) {
  2960. max = 0;
  2961. }
  2962. let width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
  2963. // console.log('gauge width: ' + width.toString() + ', height: ' + height.toString());
  2964. //switch(adjust) {
  2965. // case 'width': width = height * ratio; break;
  2966. // case 'height':
  2967. // default: height = width / ratio; break;
  2968. //}
  2969. //state.element.style.width = width.toString() + 'px';
  2970. //state.element.style.height = height.toString() + 'px';
  2971. let lum_d = 0.05;
  2972. let options = {
  2973. lines: 12, // The number of lines to draw
  2974. angle: 0.14, // The span of the gauge arc
  2975. lineWidth: 0.57, // The line thickness
  2976. radiusScale: 1.0, // Relative radius
  2977. pointer: {
  2978. length: 0.85, // 0.9 The radius of the inner circle
  2979. strokeWidth: 0.045, // The rotation offset
  2980. color: pointerColor // Fill color
  2981. },
  2982. limitMax: true, // If false, the max value of the gauge will be updated if value surpass max
  2983. limitMin: true, // If true, the min value of the gauge will be fixed unless you set it manually
  2984. colorStart: startColor, // Colors
  2985. colorStop: stopColor, // just experiment with them
  2986. strokeColor: strokeColor, // to see which ones work best for you
  2987. generateGradient: (generateGradient === true), // gmosx:
  2988. gradientType: 0,
  2989. highDpiSupport: true // High resolution support
  2990. };
  2991. if (generateGradient.constructor === Array) {
  2992. // example options:
  2993. // data-gauge-generate-gradient="[0, 50, 100]"
  2994. // data-gauge-gradient-percent-color-0="#FFFFFF"
  2995. // data-gauge-gradient-percent-color-50="#999900"
  2996. // data-gauge-gradient-percent-color-100="#000000"
  2997. options.percentColors = [];
  2998. let len = generateGradient.length;
  2999. while (len--) {
  3000. let pcent = generateGradient[len];
  3001. let color = NETDATA.dataAttribute(state.element, 'gauge-gradient-percent-color-' + pcent.toString(), false);
  3002. if (color !== false) {
  3003. let a = [];
  3004. a[0] = pcent / 100;
  3005. a[1] = color;
  3006. options.percentColors.unshift(a);
  3007. }
  3008. }
  3009. if (options.percentColors.length === 0) {
  3010. delete options.percentColors;
  3011. }
  3012. } else if (generateGradient === false && NETDATA.themes.current.gauge_gradient) {
  3013. //noinspection PointlessArithmeticExpressionJS
  3014. options.percentColors = [
  3015. [0.0, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 0))],
  3016. [0.1, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 1))],
  3017. [0.2, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 2))],
  3018. [0.3, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 3))],
  3019. [0.4, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 4))],
  3020. [0.5, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 5))],
  3021. [0.6, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 6))],
  3022. [0.7, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 7))],
  3023. [0.8, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 8))],
  3024. [0.9, NETDATA.colorLuminance(startColor, (lum_d * 10) - (lum_d * 9))],
  3025. [1.0, NETDATA.colorLuminance(startColor, 0.0)]];
  3026. }
  3027. state.tmp.gauge_canvas = document.createElement('canvas');
  3028. state.tmp.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
  3029. state.tmp.gauge_canvas.className = 'gaugeChart';
  3030. state.tmp.gauge_canvas.width = width;
  3031. state.tmp.gauge_canvas.height = height;
  3032. state.element_chart.appendChild(state.tmp.gauge_canvas);
  3033. let valuefontsize = Math.floor(height / 5);
  3034. let valuetop = Math.round((height - valuefontsize) / 3.2);
  3035. state.tmp.gaugeChartLabel = document.createElement('span');
  3036. state.tmp.gaugeChartLabel.className = 'gaugeChartLabel';
  3037. state.tmp.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
  3038. state.tmp.gaugeChartLabel.style.top = valuetop.toString() + 'px';
  3039. state.element_chart.appendChild(state.tmp.gaugeChartLabel);
  3040. let titlefontsize = Math.round(valuefontsize / 2.1);
  3041. let titletop = 0;
  3042. state.tmp.gaugeChartTitle = document.createElement('span');
  3043. state.tmp.gaugeChartTitle.className = 'gaugeChartTitle';
  3044. state.tmp.gaugeChartTitle.innerText = state.title;
  3045. state.tmp.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
  3046. state.tmp.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
  3047. state.tmp.gaugeChartTitle.style.top = titletop.toString() + 'px';
  3048. state.element_chart.appendChild(state.tmp.gaugeChartTitle);
  3049. let unitfontsize = Math.round(titlefontsize * 0.9);
  3050. state.tmp.gaugeChartUnits = document.createElement('span');
  3051. state.tmp.gaugeChartUnits.className = 'gaugeChartUnits';
  3052. state.tmp.gaugeChartUnits.innerText = state.units_current;
  3053. state.tmp.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
  3054. state.element_chart.appendChild(state.tmp.gaugeChartUnits);
  3055. state.tmp.gaugeChartMin = document.createElement('span');
  3056. state.tmp.gaugeChartMin.className = 'gaugeChartMin';
  3057. state.tmp.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
  3058. state.element_chart.appendChild(state.tmp.gaugeChartMin);
  3059. state.tmp.gaugeChartMax = document.createElement('span');
  3060. state.tmp.gaugeChartMax.className = 'gaugeChartMax';
  3061. state.tmp.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
  3062. state.element_chart.appendChild(state.tmp.gaugeChartMax);
  3063. // when we just re-create the chart
  3064. // do not animate the first update
  3065. let animate = true;
  3066. if (typeof state.tmp.gauge_instance !== 'undefined') {
  3067. animate = false;
  3068. }
  3069. state.tmp.gauge_instance = new Gauge(state.tmp.gauge_canvas).setOptions(options); // create sexy gauge!
  3070. state.tmp.___gaugeOld__ = {
  3071. value: value,
  3072. min: min,
  3073. max: max,
  3074. valueLabel: null,
  3075. minLabel: null,
  3076. maxLabel: null
  3077. };
  3078. // we will always feed a percentage
  3079. state.tmp.gauge_instance.minValue = 0;
  3080. state.tmp.gauge_instance.maxValue = 100;
  3081. NETDATA.gaugeAnimation(state, animate);
  3082. NETDATA.gaugeSet(state, value, min, max);
  3083. NETDATA.gaugeSetLabels(state, value, min, max);
  3084. NETDATA.gaugeAnimation(state, true);
  3085. state.legendSetUnitsString = function (units) {
  3086. if (typeof state.tmp.gaugeChartUnits !== 'undefined' && state.tmp.units !== units) {
  3087. state.tmp.gaugeChartUnits.innerText = units;
  3088. state.tmp.___gaugeOld__.valueLabel = null;
  3089. state.tmp.___gaugeOld__.minLabel = null;
  3090. state.tmp.___gaugeOld__.maxLabel = null;
  3091. state.tmp.units = units;
  3092. }
  3093. };
  3094. state.legendShowUndefined = function () {
  3095. if (typeof state.tmp.gauge_instance !== 'undefined') {
  3096. NETDATA.gaugeClearSelection(state);
  3097. }
  3098. };
  3099. return true;
  3100. };
  3101. // ----------------------------------------------------------------------------------------------------------------
  3102. NETDATA.easypiechartPercentFromValueMinMax = function (state, value, min, max) {
  3103. if (typeof value !== 'number') {
  3104. value = 0;
  3105. }
  3106. if (typeof min !== 'number') {
  3107. min = 0;
  3108. }
  3109. if (typeof max !== 'number') {
  3110. max = 0;
  3111. }
  3112. if (min > max) {
  3113. let t = min;
  3114. min = max;
  3115. max = t;
  3116. }
  3117. if (min > value) {
  3118. min = value;
  3119. }
  3120. if (max < value) {
  3121. max = value;
  3122. }
  3123. state.legendFormatValueDecimalsFromMinMax(min, max);
  3124. if (state.tmp.easyPieChartMin === null && min > 0) {
  3125. min = 0;
  3126. }
  3127. if (state.tmp.easyPieChartMax === null && max < 0) {
  3128. max = 0;
  3129. }
  3130. let pcent;
  3131. if (min < 0 && max > 0) {
  3132. // it is both positive and negative
  3133. // zero at the top center of the chart
  3134. max = (-min > max) ? -min : max;
  3135. pcent = Math.round(value * 100 / max);
  3136. } else if (value >= 0 && min >= 0 && max >= 0) {
  3137. // clockwise
  3138. pcent = Math.round((value - min) * 100 / (max - min));
  3139. if (pcent === 0) {
  3140. pcent = 0.1;
  3141. }
  3142. } else {
  3143. // counter clockwise
  3144. pcent = Math.round((value - max) * 100 / (max - min));
  3145. if (pcent === 0) {
  3146. pcent = -0.1;
  3147. }
  3148. }
  3149. return pcent;
  3150. };
  3151. // ----------------------------------------------------------------------------------------------------------------
  3152. // easy-pie-chart
  3153. NETDATA.easypiechartInitialize = function (callback) {
  3154. if (typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
  3155. $.ajax({
  3156. url: NETDATA.easypiechart_js,
  3157. cache: true,
  3158. dataType: "script",
  3159. xhrFields: {withCredentials: true} // required for the cookie
  3160. })
  3161. .done(function () {
  3162. NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
  3163. })
  3164. .fail(function () {
  3165. NETDATA.chartLibraries.easypiechart.enabled = false;
  3166. NETDATA.error(100, NETDATA.easypiechart_js);
  3167. })
  3168. .always(function () {
  3169. if (typeof callback === "function") {
  3170. return callback();
  3171. }
  3172. })
  3173. } else {
  3174. NETDATA.chartLibraries.easypiechart.enabled = false;
  3175. if (typeof callback === "function") {
  3176. return callback();
  3177. }
  3178. }
  3179. };
  3180. NETDATA.easypiechartClearSelection = function (state, force) {
  3181. if (typeof state.tmp.easyPieChartEvent !== 'undefined' && typeof state.tmp.easyPieChartEvent.timer !== 'undefined') {
  3182. NETDATA.timeout.clear(state.tmp.easyPieChartEvent.timer);
  3183. state.tmp.easyPieChartEvent.timer = undefined;
  3184. }
  3185. if (state.isAutoRefreshable() && state.data !== null && force !== true) {
  3186. NETDATA.easypiechartChartUpdate(state, state.data);
  3187. }
  3188. else {
  3189. state.tmp.easyPieChartLabel.innerText = state.legendFormatValue(null);
  3190. state.tmp.easyPieChart_instance.update(0);
  3191. }
  3192. state.tmp.easyPieChart_instance.enableAnimation();
  3193. return true;
  3194. };
  3195. NETDATA.easypiechartSetSelection = function (state, t) {
  3196. if (state.timeIsVisible(t) !== true) {
  3197. return NETDATA.easypiechartClearSelection(state, true);
  3198. }
  3199. let slot = state.calculateRowForTime(t);
  3200. if (slot < 0 || slot >= state.data.result.length) {
  3201. return NETDATA.easypiechartClearSelection(state, true);
  3202. }
  3203. if (typeof state.tmp.easyPieChartEvent === 'undefined') {
  3204. state.tmp.easyPieChartEvent = {
  3205. timer: undefined,
  3206. value: 0,
  3207. pcent: 0
  3208. };
  3209. }
  3210. let value = state.data.result[state.data.result.length - 1 - slot];
  3211. let min = (state.tmp.easyPieChartMin === null) ? NETDATA.commonMin.get(state) : state.tmp.easyPieChartMin;
  3212. let max = (state.tmp.easyPieChartMax === null) ? NETDATA.commonMax.get(state) : state.tmp.easyPieChartMax;
  3213. let pcent = NETDATA.easypiechartPercentFromValueMinMax(state, value, min, max);
  3214. state.tmp.easyPieChartEvent.value = value;
  3215. state.tmp.easyPieChartEvent.pcent = pcent;
  3216. state.tmp.easyPieChartLabel.innerText = state.legendFormatValue(value);
  3217. if (state.tmp.easyPieChartEvent.timer === undefined) {
  3218. state.tmp.easyPieChart_instance.disableAnimation();
  3219. state.tmp.easyPieChartEvent.timer = NETDATA.timeout.set(function () {
  3220. state.tmp.easyPieChartEvent.timer = undefined;
  3221. state.tmp.easyPieChart_instance.update(state.tmp.easyPieChartEvent.pcent);
  3222. }, 0);
  3223. }
  3224. return true;
  3225. };
  3226. NETDATA.easypiechartChartUpdate = function (state, data) {
  3227. let value, min, max, pcent;
  3228. if (NETDATA.globalPanAndZoom.isActive() || state.isAutoRefreshable() === false) {
  3229. value = null;
  3230. pcent = 0;
  3231. }
  3232. else {
  3233. value = data.result[0];
  3234. min = (state.tmp.easyPieChartMin === null) ? NETDATA.commonMin.get(state) : state.tmp.easyPieChartMin;
  3235. max = (state.tmp.easyPieChartMax === null) ? NETDATA.commonMax.get(state) : state.tmp.easyPieChartMax;
  3236. pcent = NETDATA.easypiechartPercentFromValueMinMax(state, value, min, max);
  3237. }
  3238. state.tmp.easyPieChartLabel.innerText = state.legendFormatValue(value);
  3239. state.tmp.easyPieChart_instance.update(pcent);
  3240. return true;
  3241. };
  3242. NETDATA.easypiechartChartCreate = function (state, data) {
  3243. let chart = $(state.element_chart);
  3244. let value = data.result[0];
  3245. let min = NETDATA.dataAttribute(state.element, 'easypiechart-min-value', null);
  3246. let max = NETDATA.dataAttribute(state.element, 'easypiechart-max-value', null);
  3247. if (min === null) {
  3248. min = NETDATA.commonMin.get(state);
  3249. state.tmp.easyPieChartMin = null;
  3250. }
  3251. else {
  3252. state.tmp.easyPieChartMin = min;
  3253. }
  3254. if (max === null) {
  3255. max = NETDATA.commonMax.get(state);
  3256. state.tmp.easyPieChartMax = null;
  3257. }
  3258. else {
  3259. state.tmp.easyPieChartMax = max;
  3260. }
  3261. let size = state.chartWidth();
  3262. let stroke = Math.floor(size / 22);
  3263. if (stroke < 3) {
  3264. stroke = 2;
  3265. }
  3266. let valuefontsize = Math.floor((size * 2 / 3) / 5);
  3267. let valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
  3268. state.tmp.easyPieChartLabel = document.createElement('span');
  3269. state.tmp.easyPieChartLabel.className = 'easyPieChartLabel';
  3270. state.tmp.easyPieChartLabel.innerText = state.legendFormatValue(value);
  3271. state.tmp.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
  3272. state.tmp.easyPieChartLabel.style.top = valuetop.toString() + 'px';
  3273. state.element_chart.appendChild(state.tmp.easyPieChartLabel);
  3274. let titlefontsize = Math.round(valuefontsize * 1.6 / 3);
  3275. let titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
  3276. state.tmp.easyPieChartTitle = document.createElement('span');
  3277. state.tmp.easyPieChartTitle.className = 'easyPieChartTitle';
  3278. state.tmp.easyPieChartTitle.innerText = state.title;
  3279. state.tmp.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
  3280. state.tmp.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
  3281. state.tmp.easyPieChartTitle.style.top = titletop.toString() + 'px';
  3282. state.element_chart.appendChild(state.tmp.easyPieChartTitle);
  3283. let unitfontsize = Math.round(titlefontsize * 0.9);
  3284. let unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
  3285. state.tmp.easyPieChartUnits = document.createElement('span');
  3286. state.tmp.easyPieChartUnits.className = 'easyPieChartUnits';
  3287. state.tmp.easyPieChartUnits.innerText = state.units_current;
  3288. state.tmp.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
  3289. state.tmp.easyPieChartUnits.style.top = unittop.toString() + 'px';
  3290. state.element_chart.appendChild(state.tmp.easyPieChartUnits);
  3291. let barColor = NETDATA.dataAttribute(state.element, 'easypiechart-barcolor', undefined);
  3292. if (typeof barColor === 'undefined' || barColor === null) {
  3293. barColor = state.chartCustomColors()[0];
  3294. } else {
  3295. // <div ... data-easypiechart-barcolor="(function(percent){return(percent < 50 ? '#5cb85c' : percent < 85 ? '#f0ad4e' : '#cb3935');})" ...></div>
  3296. let tmp = eval(barColor);
  3297. if (typeof tmp === 'function') {
  3298. barColor = tmp;
  3299. }
  3300. }
  3301. let pcent = NETDATA.easypiechartPercentFromValueMinMax(state, value, min, max);
  3302. chart.data('data-percent', pcent);
  3303. chart.easyPieChart({
  3304. barColor: barColor,
  3305. trackColor: NETDATA.dataAttribute(state.element, 'easypiechart-trackcolor', NETDATA.themes.current.easypiechart_track),
  3306. scaleColor: NETDATA.dataAttribute(state.element, 'easypiechart-scalecolor', NETDATA.themes.current.easypiechart_scale),
  3307. scaleLength: NETDATA.dataAttribute(state.element, 'easypiechart-scalelength', 5),
  3308. lineCap: NETDATA.dataAttribute(state.element, 'easypiechart-linecap', 'round'),
  3309. lineWidth: NETDATA.dataAttribute(state.element, 'easypiechart-linewidth', stroke),
  3310. trackWidth: NETDATA.dataAttribute(state.element, 'easypiechart-trackwidth', undefined),
  3311. size: NETDATA.dataAttribute(state.element, 'easypiechart-size', size),
  3312. rotate: NETDATA.dataAttribute(state.element, 'easypiechart-rotate', 0),
  3313. animate: NETDATA.dataAttribute(state.element, 'easypiechart-animate', {duration: 500, enabled: true}),
  3314. easing: NETDATA.dataAttribute(state.element, 'easypiechart-easing', undefined)
  3315. });
  3316. // when we just re-create the chart
  3317. // do not animate the first update
  3318. let animate = true;
  3319. if (typeof state.tmp.easyPieChart_instance !== 'undefined') {
  3320. animate = false;
  3321. }
  3322. state.tmp.easyPieChart_instance = chart.data('easyPieChart');
  3323. if (animate === false) {
  3324. state.tmp.easyPieChart_instance.disableAnimation();
  3325. }
  3326. state.tmp.easyPieChart_instance.update(pcent);
  3327. if (animate === false) {
  3328. state.tmp.easyPieChart_instance.enableAnimation();
  3329. }
  3330. state.legendSetUnitsString = function (units) {
  3331. if (typeof state.tmp.easyPieChartUnits !== 'undefined' && state.tmp.units !== units) {
  3332. state.tmp.easyPieChartUnits.innerText = units;
  3333. state.tmp.units = units;
  3334. }
  3335. };
  3336. state.legendShowUndefined = function () {
  3337. if (typeof state.tmp.easyPieChart_instance !== 'undefined') {
  3338. NETDATA.easypiechartClearSelection(state);
  3339. }
  3340. };
  3341. return true;
  3342. };
  3343. // d3pie
  3344. NETDATA.d3pieInitialize = function (callback) {
  3345. if (typeof netdataNoD3pie === 'undefined' || !netdataNoD3pie) {
  3346. // d3pie requires D3
  3347. if (!NETDATA.chartLibraries.d3.initialized) {
  3348. if (NETDATA.chartLibraries.d3.enabled) {
  3349. NETDATA.d3Initialize(function () {
  3350. NETDATA.d3pieInitialize(callback);
  3351. });
  3352. } else {
  3353. NETDATA.chartLibraries.d3pie.enabled = false;
  3354. if (typeof callback === "function") {
  3355. return callback();
  3356. }
  3357. }
  3358. } else {
  3359. $.ajax({
  3360. url: NETDATA.d3pie_js,
  3361. cache: true,
  3362. dataType: "script",
  3363. xhrFields: {withCredentials: true} // required for the cookie
  3364. })
  3365. .done(function () {
  3366. NETDATA.registerChartLibrary('d3pie', NETDATA.d3pie_js);
  3367. })
  3368. .fail(function () {
  3369. NETDATA.chartLibraries.d3pie.enabled = false;
  3370. NETDATA.error(100, NETDATA.d3pie_js);
  3371. })
  3372. .always(function () {
  3373. if (typeof callback === "function") {
  3374. return callback();
  3375. }
  3376. });
  3377. }
  3378. } else {
  3379. NETDATA.chartLibraries.d3pie.enabled = false;
  3380. if (typeof callback === "function") {
  3381. return callback();
  3382. }
  3383. }
  3384. };
  3385. NETDATA.d3pieSetContent = function (state, data, index) {
  3386. state.legendFormatValueDecimalsFromMinMax(
  3387. data.min,
  3388. data.max
  3389. );
  3390. let content = [];
  3391. let colors = state.chartColors();
  3392. let len = data.result.labels.length;
  3393. for (let i = 1; i < len; i++) {
  3394. let label = data.result.labels[i];
  3395. let value = data.result.data[index][label];
  3396. let color = colors[i - 1];
  3397. if (value !== null && value > 0) {
  3398. content.push({
  3399. label: label,
  3400. value: value,
  3401. color: color
  3402. });
  3403. }
  3404. }
  3405. if (content.length === 0) {
  3406. content.push({
  3407. label: 'no data',
  3408. value: 100,
  3409. color: '#666666'
  3410. });
  3411. }
  3412. state.tmp.d3pie_last_slot = index;
  3413. return content;
  3414. };
  3415. NETDATA.d3pieDateRange = function (state, data, index) {
  3416. let dt = Math.round((data.before - data.after + 1) / data.points);
  3417. let dt_str = NETDATA.seconds4human(dt);
  3418. let before = data.result.data[index].time;
  3419. let after = before - (dt * 1000);
  3420. let d1 = NETDATA.dateTime.localeDateString(after);
  3421. let t1 = NETDATA.dateTime.localeTimeString(after);
  3422. let d2 = NETDATA.dateTime.localeDateString(before);
  3423. let t2 = NETDATA.dateTime.localeTimeString(before);
  3424. if (d1 === d2) {
  3425. return d1 + ' ' + t1 + ' to ' + t2 + ', ' + dt_str;
  3426. }
  3427. return d1 + ' ' + t1 + ' to ' + d2 + ' ' + t2 + ', ' + dt_str;
  3428. };
  3429. NETDATA.d3pieSetSelection = function (state, t) {
  3430. if (state.timeIsVisible(t) !== true) {
  3431. return NETDATA.d3pieClearSelection(state, true);
  3432. }
  3433. let slot = state.calculateRowForTime(t);
  3434. slot = state.data.result.data.length - slot - 1;
  3435. if (slot < 0 || slot >= state.data.result.length) {
  3436. return NETDATA.d3pieClearSelection(state, true);
  3437. }
  3438. if (state.tmp.d3pie_last_slot === slot) {
  3439. // we already show this slot, don't do anything
  3440. return true;
  3441. }
  3442. if (state.tmp.d3pie_timer === undefined) {
  3443. state.tmp.d3pie_timer = NETDATA.timeout.set(function () {
  3444. state.tmp.d3pie_timer = undefined;
  3445. NETDATA.d3pieChange(state, NETDATA.d3pieSetContent(state, state.data, slot), NETDATA.d3pieDateRange(state, state.data, slot));
  3446. }, 0);
  3447. }
  3448. return true;
  3449. };
  3450. NETDATA.d3pieClearSelection = function (state, force) {
  3451. if (typeof state.tmp.d3pie_timer !== 'undefined') {
  3452. NETDATA.timeout.clear(state.tmp.d3pie_timer);
  3453. state.tmp.d3pie_timer = undefined;
  3454. }
  3455. if (state.isAutoRefreshable() && state.data !== null && force !== true) {
  3456. NETDATA.d3pieChartUpdate(state, state.data);
  3457. } else {
  3458. if (state.tmp.d3pie_last_slot !== -1) {
  3459. state.tmp.d3pie_last_slot = -1;
  3460. NETDATA.d3pieChange(state, [{label: 'no data', value: 1, color: '#666666'}], 'no data available');
  3461. }
  3462. }
  3463. return true;
  3464. };
  3465. NETDATA.d3pieChange = function (state, content, footer) {
  3466. if (state.d3pie_forced_subtitle === null) {
  3467. //state.d3pie_instance.updateProp("header.subtitle.text", state.units_current);
  3468. state.d3pie_instance.options.header.subtitle.text = state.units_current;
  3469. }
  3470. if (state.d3pie_forced_footer === null) {
  3471. //state.d3pie_instance.updateProp("footer.text", footer);
  3472. state.d3pie_instance.options.footer.text = footer;
  3473. }
  3474. //state.d3pie_instance.updateProp("data.content", content);
  3475. state.d3pie_instance.options.data.content = content;
  3476. state.d3pie_instance.destroy();
  3477. state.d3pie_instance.recreate();
  3478. return true;
  3479. };
  3480. NETDATA.d3pieChartUpdate = function (state, data) {
  3481. return NETDATA.d3pieChange(state, NETDATA.d3pieSetContent(state, data, 0), NETDATA.d3pieDateRange(state, data, 0));
  3482. };
  3483. NETDATA.d3pieChartCreate = function (state, data) {
  3484. state.element_chart.id = 'd3pie-' + state.uuid;
  3485. // console.log('id = ' + state.element_chart.id);
  3486. let content = NETDATA.d3pieSetContent(state, data, 0);
  3487. state.d3pie_forced_title = NETDATA.dataAttribute(state.element, 'd3pie-title', null);
  3488. state.d3pie_forced_subtitle = NETDATA.dataAttribute(state.element, 'd3pie-subtitle', null);
  3489. state.d3pie_forced_footer = NETDATA.dataAttribute(state.element, 'd3pie-footer', null);
  3490. state.d3pie_options = {
  3491. header: {
  3492. title: {
  3493. text: (state.d3pie_forced_title !== null) ? state.d3pie_forced_title : state.title,
  3494. color: NETDATA.dataAttribute(state.element, 'd3pie-title-color', NETDATA.themes.current.d3pie.title),
  3495. fontSize: NETDATA.dataAttribute(state.element, 'd3pie-title-fontsize', 12),
  3496. fontWeight: NETDATA.dataAttribute(state.element, 'd3pie-title-fontweight', "bold"),
  3497. font: NETDATA.dataAttribute(state.element, 'd3pie-title-font', "arial")
  3498. },
  3499. subtitle: {
  3500. text: (state.d3pie_forced_subtitle !== null) ? state.d3pie_forced_subtitle : state.units_current,
  3501. color: NETDATA.dataAttribute(state.element, 'd3pie-subtitle-color', NETDATA.themes.current.d3pie.subtitle),
  3502. fontSize: NETDATA.dataAttribute(state.element, 'd3pie-subtitle-fontsize', 10),
  3503. fontWeight: NETDATA.dataAttribute(state.element, 'd3pie-subtitle-fontweight', "normal"),
  3504. font: NETDATA.dataAttribute(state.element, 'd3pie-subtitle-font', "arial")
  3505. },
  3506. titleSubtitlePadding: 1
  3507. },
  3508. footer: {
  3509. text: (state.d3pie_forced_footer !== null) ? state.d3pie_forced_footer : NETDATA.d3pieDateRange(state, data, 0),
  3510. color: NETDATA.dataAttribute(state.element, 'd3pie-footer-color', NETDATA.themes.current.d3pie.footer),
  3511. fontSize: NETDATA.dataAttribute(state.element, 'd3pie-footer-fontsize', 9),
  3512. fontWeight: NETDATA.dataAttribute(state.element, 'd3pie-footer-fontweight', "bold"),
  3513. font: NETDATA.dataAttribute(state.element, 'd3pie-footer-font', "arial"),
  3514. location: NETDATA.dataAttribute(state.element, 'd3pie-footer-location', "bottom-center") // bottom-left, bottom-center, bottom-right
  3515. },
  3516. size: {
  3517. canvasHeight: state.chartHeight(),
  3518. canvasWidth: state.chartWidth(),
  3519. pieInnerRadius: NETDATA.dataAttribute(state.element, 'd3pie-pieinnerradius', "45%"),
  3520. pieOuterRadius: NETDATA.dataAttribute(state.element, 'd3pie-pieouterradius', "80%")
  3521. },
  3522. data: {
  3523. // none, random, value-asc, value-desc, label-asc, label-desc
  3524. sortOrder: NETDATA.dataAttribute(state.element, 'd3pie-sortorder', "value-desc"),
  3525. smallSegmentGrouping: {
  3526. enabled: NETDATA.dataAttributeBoolean(state.element, "d3pie-smallsegmentgrouping-enabled", false),
  3527. value: NETDATA.dataAttribute(state.element, 'd3pie-smallsegmentgrouping-value', 1),
  3528. // percentage, value
  3529. valueType: NETDATA.dataAttribute(state.element, 'd3pie-smallsegmentgrouping-valuetype', "percentage"),
  3530. label: NETDATA.dataAttribute(state.element, 'd3pie-smallsegmentgrouping-label', "other"),
  3531. color: NETDATA.dataAttribute(state.element, 'd3pie-smallsegmentgrouping-color', NETDATA.themes.current.d3pie.other)
  3532. },
  3533. // REQUIRED! This is where you enter your pie data; it needs to be an array of objects
  3534. // of this form: { label: "label", value: 1.5, color: "#000000" } - color is optional
  3535. content: content
  3536. },
  3537. labels: {
  3538. outer: {
  3539. // label, value, percentage, label-value1, label-value2, label-percentage1, label-percentage2
  3540. format: NETDATA.dataAttribute(state.element, 'd3pie-labels-outer-format', "label-value1"),
  3541. hideWhenLessThanPercentage: NETDATA.dataAttribute(state.element, 'd3pie-labels-outer-hidewhenlessthanpercentage', null),
  3542. pieDistance: NETDATA.dataAttribute(state.element, 'd3pie-labels-outer-piedistance', 15)
  3543. },
  3544. inner: {
  3545. // label, value, percentage, label-value1, label-value2, label-percentage1, label-percentage2
  3546. format: NETDATA.dataAttribute(state.element, 'd3pie-labels-inner-format', "percentage"),
  3547. hideWhenLessThanPercentage: NETDATA.dataAttribute(state.element, 'd3pie-labels-inner-hidewhenlessthanpercentage', 2)
  3548. },
  3549. mainLabel: {
  3550. color: NETDATA.dataAttribute(state.element, 'd3pie-labels-mainLabel-color', NETDATA.themes.current.d3pie.mainlabel), // or 'segment' for dynamic color
  3551. font: NETDATA.dataAttribute(state.element, 'd3pie-labels-mainLabel-font', "arial"),
  3552. fontSize: NETDATA.dataAttribute(state.element, 'd3pie-labels-mainLabel-fontsize', 10),
  3553. fontWeight: NETDATA.dataAttribute(state.element, 'd3pie-labels-mainLabel-fontweight', "normal")
  3554. },
  3555. percentage: {
  3556. color: NETDATA.dataAttribute(state.element, 'd3pie-labels-percentage-color', NETDATA.themes.current.d3pie.percentage),
  3557. font: NETDATA.dataAttribute(state.element, 'd3pie-labels-percentage-font', "arial"),
  3558. fontSize: NETDATA.dataAttribute(state.element, 'd3pie-labels-percentage-fontsize', 10),
  3559. fontWeight: NETDATA.dataAttribute(state.element, 'd3pie-labels-percentage-fontweight', "bold"),
  3560. decimalPlaces: 0
  3561. },
  3562. value: {
  3563. color: NETDATA.dataAttribute(state.element, 'd3pie-labels-value-color', NETDATA.themes.current.d3pie.value),
  3564. font: NETDATA.dataAttribute(state.element, 'd3pie-labels-value-font', "arial"),
  3565. fontSize: NETDATA.dataAttribute(state.element, 'd3pie-labels-value-fontsize', 10),
  3566. fontWeight: NETDATA.dataAttribute(state.element, 'd3pie-labels-value-fontweight', "bold")
  3567. },
  3568. lines: {
  3569. enabled: NETDATA.dataAttributeBoolean(state.element, 'd3pie-labels-lines-enabled', true),
  3570. style: NETDATA.dataAttribute(state.element, 'd3pie-labels-lines-style', "curved"),
  3571. color: NETDATA.dataAttribute(state.element, 'd3pie-labels-lines-color', "segment") // "segment" or a hex color
  3572. },
  3573. truncation: {
  3574. enabled: NETDATA.dataAttributeBoolean(state.element, 'd3pie-labels-truncation-enabled', false),
  3575. truncateLength: NETDATA.dataAttribute(state.element, 'd3pie-labels-truncation-truncatelength', 30)
  3576. },
  3577. formatter: function (context) {
  3578. // console.log(context);
  3579. if (context.part === 'value') {
  3580. return state.legendFormatValue(context.value);
  3581. }
  3582. if (context.part === 'percentage') {
  3583. return context.label + '%';
  3584. }
  3585. return context.label;
  3586. }
  3587. },
  3588. effects: {
  3589. load: {
  3590. effect: "none", // none / default
  3591. speed: 0 // commented in the d3pie code to speed it up
  3592. },
  3593. pullOutSegmentOnClick: {
  3594. effect: "bounce", // none / linear / bounce / elastic / back
  3595. speed: 400,
  3596. size: 5
  3597. },
  3598. highlightSegmentOnMouseover: true,
  3599. highlightLuminosity: -0.2
  3600. },
  3601. tooltips: {
  3602. enabled: false,
  3603. type: "placeholder", // caption|placeholder
  3604. string: "",
  3605. placeholderParser: null, // function
  3606. styles: {
  3607. fadeInSpeed: 250,
  3608. backgroundColor: NETDATA.themes.current.d3pie.tooltip_bg,
  3609. backgroundOpacity: 0.5,
  3610. color: NETDATA.themes.current.d3pie.tooltip_fg,
  3611. borderRadius: 2,
  3612. font: "arial",
  3613. fontSize: 12,
  3614. padding: 4
  3615. }
  3616. },
  3617. misc: {
  3618. colors: {
  3619. background: 'transparent', // transparent or color #
  3620. // segments: state.chartColors(),
  3621. segmentStroke: NETDATA.dataAttribute(state.element, 'd3pie-misc-colors-segmentstroke', NETDATA.themes.current.d3pie.segment_stroke)
  3622. },
  3623. gradient: {
  3624. enabled: NETDATA.dataAttributeBoolean(state.element, 'd3pie-misc-gradient-enabled', false),
  3625. percentage: NETDATA.dataAttribute(state.element, 'd3pie-misc-colors-percentage', 95),
  3626. color: NETDATA.dataAttribute(state.element, 'd3pie-misc-gradient-color', NETDATA.themes.current.d3pie.gradient_color)
  3627. },
  3628. canvasPadding: {
  3629. top: 5,
  3630. right: 5,
  3631. bottom: 5,
  3632. left: 5
  3633. },
  3634. pieCenterOffset: {
  3635. x: 0,
  3636. y: 0
  3637. },
  3638. cssPrefix: NETDATA.dataAttribute(state.element, 'd3pie-cssprefix', null)
  3639. },
  3640. callbacks: {
  3641. onload: null,
  3642. onMouseoverSegment: null,
  3643. onMouseoutSegment: null,
  3644. onClickSegment: null
  3645. }
  3646. };
  3647. state.d3pie_instance = new d3pie(state.element_chart, state.d3pie_options);
  3648. return true;
  3649. };
  3650. // ----------------------------------------------------------------------------------------------------------------
  3651. // D3
  3652. NETDATA.d3Initialize = function(callback) {
  3653. if (typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
  3654. $.ajax({
  3655. url: NETDATA.d3_js,
  3656. cache: true,
  3657. dataType: "script",
  3658. xhrFields: { withCredentials: true } // required for the cookie
  3659. })
  3660. .done(function() {
  3661. NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
  3662. })
  3663. .fail(function() {
  3664. NETDATA.chartLibraries.d3.enabled = false;
  3665. NETDATA.error(100, NETDATA.d3_js);
  3666. })
  3667. .always(function() {
  3668. if (typeof callback === "function")
  3669. return callback();
  3670. });
  3671. } else {
  3672. NETDATA.chartLibraries.d3.enabled = false;
  3673. if (typeof callback === "function")
  3674. return callback();
  3675. }
  3676. };
  3677. NETDATA.d3ChartUpdate = function(state, data) {
  3678. void(state);
  3679. void(data);
  3680. return false;
  3681. };
  3682. NETDATA.d3ChartCreate = function(state, data) {
  3683. void(state);
  3684. void(data);
  3685. return false;
  3686. };
  3687. // peity
  3688. NETDATA.peityInitialize = function (callback) {
  3689. if (typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
  3690. $.ajax({
  3691. url: NETDATA.peity_js,
  3692. cache: true,
  3693. dataType: "script",
  3694. xhrFields: {withCredentials: true} // required for the cookie
  3695. })
  3696. .done(function () {
  3697. NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
  3698. })
  3699. .fail(function () {
  3700. NETDATA.chartLibraries.peity.enabled = false;
  3701. NETDATA.error(100, NETDATA.peity_js);
  3702. })
  3703. .always(function () {
  3704. if (typeof callback === "function") {
  3705. return callback();
  3706. }
  3707. });
  3708. } else {
  3709. NETDATA.chartLibraries.peity.enabled = false;
  3710. if (typeof callback === "function") {
  3711. return callback();
  3712. }
  3713. }
  3714. };
  3715. NETDATA.peityChartUpdate = function (state, data) {
  3716. state.peity_instance.innerHTML = data.result;
  3717. if (state.peity_options.stroke !== state.chartCustomColors()[0]) {
  3718. state.peity_options.stroke = state.chartCustomColors()[0];
  3719. if (state.chart.chart_type === 'line') {
  3720. state.peity_options.fill = NETDATA.themes.current.background;
  3721. } else {
  3722. state.peity_options.fill = NETDATA.colorLuminance(state.chartCustomColors()[0], NETDATA.chartDefaults.fill_luminance);
  3723. }
  3724. }
  3725. $(state.peity_instance).peity('line', state.peity_options);
  3726. return true;
  3727. };
  3728. NETDATA.peityChartCreate = function (state, data) {
  3729. state.peity_instance = document.createElement('div');
  3730. state.element_chart.appendChild(state.peity_instance);
  3731. state.peity_options = {
  3732. stroke: NETDATA.themes.current.foreground,
  3733. strokeWidth: NETDATA.dataAttribute(state.element, 'peity-strokewidth', 1),
  3734. width: state.chartWidth(),
  3735. height: state.chartHeight(),
  3736. fill: NETDATA.themes.current.foreground
  3737. };
  3738. NETDATA.peityChartUpdate(state, data);
  3739. return true;
  3740. };
  3741. // ----------------------------------------------------------------------------------------------------------------
  3742. // "Text-only" chart - Just renders the raw value to the DOM
  3743. NETDATA.textOnlyCreate = function(state, data) {
  3744. var decimalPlaces = NETDATA.dataAttribute(state.element, 'textonly-decimal-places', 1);
  3745. var prefix = NETDATA.dataAttribute(state.element, 'textonly-prefix', '');
  3746. var suffix = NETDATA.dataAttribute(state.element, 'textonly-suffix', '');
  3747. // Round based on number of decimal places to show
  3748. var precision = Math.pow(10, decimalPlaces);
  3749. var value = Math.round(data.result[0] * precision) / precision;
  3750. state.element.textContent = prefix + value + suffix;
  3751. return true;
  3752. }
  3753. NETDATA.textOnlyUpdate = NETDATA.textOnlyCreate;
  3754. // Charts Libraries Registration
  3755. NETDATA.chartLibraries = {
  3756. "dygraph": {
  3757. initialize: NETDATA.dygraphInitialize,
  3758. create: NETDATA.dygraphChartCreate,
  3759. update: NETDATA.dygraphChartUpdate,
  3760. resize: function (state) {
  3761. if (typeof state.tmp.dygraph_instance !== 'undefined' && typeof state.tmp.dygraph_instance.resize === 'function') {
  3762. state.tmp.dygraph_instance.resize();
  3763. }
  3764. },
  3765. setSelection: NETDATA.dygraphSetSelection,
  3766. clearSelection: NETDATA.dygraphClearSelection,
  3767. toolboxPanAndZoom: NETDATA.dygraphToolboxPanAndZoom,
  3768. initialized: false,
  3769. enabled: true,
  3770. xssRegexIgnore: new RegExp('^/api/v1/data\.result.data$'),
  3771. format: function (state) {
  3772. void(state);
  3773. return 'json';
  3774. },
  3775. options: function (state) {
  3776. return 'ms' + '%7C' + 'flip' + (this.isLogScale(state) ? ('%7C' + 'abs') : '').toString();
  3777. },
  3778. legend: function (state) {
  3779. return (this.isSparkline(state) === false && NETDATA.dataAttributeBoolean(state.element, 'legend', true) === true) ? 'right-side' : null;
  3780. },
  3781. autoresize: function (state) {
  3782. void(state);
  3783. return true;
  3784. },
  3785. max_updates_to_recreate: function (state) {
  3786. void(state);
  3787. return 5000;
  3788. },
  3789. track_colors: function (state) {
  3790. void(state);
  3791. return true;
  3792. },
  3793. pixels_per_point: function (state) {
  3794. return (this.isSparkline(state) === false) ? 3 : 2;
  3795. },
  3796. isSparkline: function (state) {
  3797. if (typeof state.tmp.dygraph_sparkline === 'undefined') {
  3798. state.tmp.dygraph_sparkline = (this.theme(state) === 'sparkline');
  3799. }
  3800. return state.tmp.dygraph_sparkline;
  3801. },
  3802. isLogScale: function (state) {
  3803. if (typeof state.tmp.dygraph_logscale === 'undefined') {
  3804. state.tmp.dygraph_logscale = (this.theme(state) === 'logscale');
  3805. }
  3806. return state.tmp.dygraph_logscale;
  3807. },
  3808. theme: function (state) {
  3809. if (typeof state.tmp.dygraph_theme === 'undefined') {
  3810. state.tmp.dygraph_theme = NETDATA.dataAttribute(state.element, 'dygraph-theme', 'default');
  3811. }
  3812. return state.tmp.dygraph_theme;
  3813. },
  3814. container_class: function (state) {
  3815. if (this.legend(state) !== null) {
  3816. return 'netdata-container-with-legend';
  3817. }
  3818. return 'netdata-container';
  3819. }
  3820. },
  3821. "sparkline": {
  3822. initialize: NETDATA.sparklineInitialize,
  3823. create: NETDATA.sparklineChartCreate,
  3824. update: NETDATA.sparklineChartUpdate,
  3825. resize: null,
  3826. setSelection: undefined, // function(state, t) { void(state); return true; },
  3827. clearSelection: undefined, // function(state) { void(state); return true; },
  3828. toolboxPanAndZoom: null,
  3829. initialized: false,
  3830. enabled: true,
  3831. xssRegexIgnore: new RegExp('^/api/v1/data\.result$'),
  3832. format: function (state) {
  3833. void(state);
  3834. return 'array';
  3835. },
  3836. options: function (state) {
  3837. void(state);
  3838. return 'flip' + '%7C' + 'abs';
  3839. },
  3840. legend: function (state) {
  3841. void(state);
  3842. return null;
  3843. },
  3844. autoresize: function (state) {
  3845. void(state);
  3846. return false;
  3847. },
  3848. max_updates_to_recreate: function (state) {
  3849. void(state);
  3850. return 5000;
  3851. },
  3852. track_colors: function (state) {
  3853. void(state);
  3854. return false;
  3855. },
  3856. pixels_per_point: function (state) {
  3857. void(state);
  3858. return 3;
  3859. },
  3860. container_class: function (state) {
  3861. void(state);
  3862. return 'netdata-container';
  3863. }
  3864. },
  3865. "peity": {
  3866. initialize: NETDATA.peityInitialize,
  3867. create: NETDATA.peityChartCreate,
  3868. update: NETDATA.peityChartUpdate,
  3869. resize: null,
  3870. setSelection: undefined, // function(state, t) { void(state); return true; },
  3871. clearSelection: undefined, // function(state) { void(state); return true; },
  3872. toolboxPanAndZoom: null,
  3873. initialized: false,
  3874. enabled: true,
  3875. xssRegexIgnore: new RegExp('^/api/v1/data\.result$'),
  3876. format: function (state) {
  3877. void(state);
  3878. return 'ssvcomma';
  3879. },
  3880. options: function (state) {
  3881. void(state);
  3882. return 'null2zero' + '%7C' + 'flip' + '%7C' + 'abs';
  3883. },
  3884. legend: function (state) {
  3885. void(state);
  3886. return null;
  3887. },
  3888. autoresize: function (state) {
  3889. void(state);
  3890. return false;
  3891. },
  3892. max_updates_to_recreate: function (state) {
  3893. void(state);
  3894. return 5000;
  3895. },
  3896. track_colors: function (state) {
  3897. void(state);
  3898. return false;
  3899. },
  3900. pixels_per_point: function (state) {
  3901. void(state);
  3902. return 3;
  3903. },
  3904. container_class: function (state) {
  3905. void(state);
  3906. return 'netdata-container';
  3907. }
  3908. },
  3909. // "morris": {
  3910. // initialize: NETDATA.morrisInitialize,
  3911. // create: NETDATA.morrisChartCreate,
  3912. // update: NETDATA.morrisChartUpdate,
  3913. // resize: null,
  3914. // setSelection: undefined, // function(state, t) { void(state); return true; },
  3915. // clearSelection: undefined, // function(state) { void(state); return true; },
  3916. // toolboxPanAndZoom: null,
  3917. // initialized: false,
  3918. // enabled: true,
  3919. // xssRegexIgnore: new RegExp('^/api/v1/data\.result.data$'),
  3920. // format: function(state) { void(state); return 'json'; },
  3921. // options: function(state) { void(state); return 'objectrows' + '%7C' + 'ms'; },
  3922. // legend: function(state) { void(state); return null; },
  3923. // autoresize: function(state) { void(state); return false; },
  3924. // max_updates_to_recreate: function(state) { void(state); return 50; },
  3925. // track_colors: function(state) { void(state); return false; },
  3926. // pixels_per_point: function(state) { void(state); return 15; },
  3927. // container_class: function(state) { void(state); return 'netdata-container'; }
  3928. // },
  3929. "google": {
  3930. initialize: NETDATA.googleInitialize,
  3931. create: NETDATA.googleChartCreate,
  3932. update: NETDATA.googleChartUpdate,
  3933. resize: null,
  3934. setSelection: undefined, //function(state, t) { void(state); return true; },
  3935. clearSelection: undefined, //function(state) { void(state); return true; },
  3936. toolboxPanAndZoom: null,
  3937. initialized: false,
  3938. enabled: true,
  3939. xssRegexIgnore: new RegExp('^/api/v1/data\.result.rows$'),
  3940. format: function (state) {
  3941. void(state);
  3942. return 'datatable';
  3943. },
  3944. options: function (state) {
  3945. void(state);
  3946. return '';
  3947. },
  3948. legend: function (state) {
  3949. void(state);
  3950. return null;
  3951. },
  3952. autoresize: function (state) {
  3953. void(state);
  3954. return false;
  3955. },
  3956. max_updates_to_recreate: function (state) {
  3957. void(state);
  3958. return 300;
  3959. },
  3960. track_colors: function (state) {
  3961. void(state);
  3962. return false;
  3963. },
  3964. pixels_per_point: function (state) {
  3965. void(state);
  3966. return 4;
  3967. },
  3968. container_class: function (state) {
  3969. void(state);
  3970. return 'netdata-container';
  3971. }
  3972. },
  3973. // "raphael": {
  3974. // initialize: NETDATA.raphaelInitialize,
  3975. // create: NETDATA.raphaelChartCreate,
  3976. // update: NETDATA.raphaelChartUpdate,
  3977. // resize: null,
  3978. // setSelection: undefined, // function(state, t) { void(state); return true; },
  3979. // clearSelection: undefined, // function(state) { void(state); return true; },
  3980. // toolboxPanAndZoom: null,
  3981. // initialized: false,
  3982. // enabled: true,
  3983. // xssRegexIgnore: new RegExp('^/api/v1/data\.result.data$'),
  3984. // format: function(state) { void(state); return 'json'; },
  3985. // options: function(state) { void(state); return ''; },
  3986. // legend: function(state) { void(state); return null; },
  3987. // autoresize: function(state) { void(state); return false; },
  3988. // max_updates_to_recreate: function(state) { void(state); return 5000; },
  3989. // track_colors: function(state) { void(state); return false; },
  3990. // pixels_per_point: function(state) { void(state); return 3; },
  3991. // container_class: function(state) { void(state); return 'netdata-container'; }
  3992. // },
  3993. // "c3": {
  3994. // initialize: NETDATA.c3Initialize,
  3995. // create: NETDATA.c3ChartCreate,
  3996. // update: NETDATA.c3ChartUpdate,
  3997. // resize: null,
  3998. // setSelection: undefined, // function(state, t) { void(state); return true; },
  3999. // clearSelection: undefined, // function(state) { void(state); return true; },
  4000. // toolboxPanAndZoom: null,
  4001. // initialized: false,
  4002. // enabled: true,
  4003. // xssRegexIgnore: new RegExp('^/api/v1/data\.result$'),
  4004. // format: function(state) { void(state); return 'csvjsonarray'; },
  4005. // options: function(state) { void(state); return 'milliseconds'; },
  4006. // legend: function(state) { void(state); return null; },
  4007. // autoresize: function(state) { void(state); return false; },
  4008. // max_updates_to_recreate: function(state) { void(state); return 5000; },
  4009. // track_colors: function(state) { void(state); return false; },
  4010. // pixels_per_point: function(state) { void(state); return 15; },
  4011. // container_class: function(state) { void(state); return 'netdata-container'; }
  4012. // },
  4013. "d3pie": {
  4014. initialize: NETDATA.d3pieInitialize,
  4015. create: NETDATA.d3pieChartCreate,
  4016. update: NETDATA.d3pieChartUpdate,
  4017. resize: null,
  4018. setSelection: NETDATA.d3pieSetSelection,
  4019. clearSelection: NETDATA.d3pieClearSelection,
  4020. toolboxPanAndZoom: null,
  4021. initialized: false,
  4022. enabled: true,
  4023. xssRegexIgnore: new RegExp('^/api/v1/data\.result.data$'),
  4024. format: function (state) {
  4025. void(state);
  4026. return 'json';
  4027. },
  4028. options: function (state) {
  4029. void(state);
  4030. return 'objectrows' + '%7C' + 'ms';
  4031. },
  4032. legend: function (state) {
  4033. void(state);
  4034. return null;
  4035. },
  4036. autoresize: function (state) {
  4037. void(state);
  4038. return false;
  4039. },
  4040. max_updates_to_recreate: function (state) {
  4041. void(state);
  4042. return 5000;
  4043. },
  4044. track_colors: function (state) {
  4045. void(state);
  4046. return false;
  4047. },
  4048. pixels_per_point: function (state) {
  4049. void(state);
  4050. return 15;
  4051. },
  4052. container_class: function (state) {
  4053. void(state);
  4054. return 'netdata-container';
  4055. }
  4056. },
  4057. "d3": {
  4058. initialize: NETDATA.d3Initialize,
  4059. create: NETDATA.d3ChartCreate,
  4060. update: NETDATA.d3ChartUpdate,
  4061. resize: null,
  4062. setSelection: undefined, // function(state, t) { void(state); return true; },
  4063. clearSelection: undefined, // function(state) { void(state); return true; },
  4064. toolboxPanAndZoom: null,
  4065. initialized: false,
  4066. enabled: true,
  4067. xssRegexIgnore: new RegExp('^/api/v1/data\.result.data$'),
  4068. format: function (state) {
  4069. void(state);
  4070. return 'json';
  4071. },
  4072. options: function (state) {
  4073. void(state);
  4074. return '';
  4075. },
  4076. legend: function (state) {
  4077. void(state);
  4078. return null;
  4079. },
  4080. autoresize: function (state) {
  4081. void(state);
  4082. return false;
  4083. },
  4084. max_updates_to_recreate: function (state) {
  4085. void(state);
  4086. return 5000;
  4087. },
  4088. track_colors: function (state) {
  4089. void(state);
  4090. return false;
  4091. },
  4092. pixels_per_point: function (state) {
  4093. void(state);
  4094. return 3;
  4095. },
  4096. container_class: function (state) {
  4097. void(state);
  4098. return 'netdata-container';
  4099. }
  4100. },
  4101. "easypiechart": {
  4102. initialize: NETDATA.easypiechartInitialize,
  4103. create: NETDATA.easypiechartChartCreate,
  4104. update: NETDATA.easypiechartChartUpdate,
  4105. resize: null,
  4106. setSelection: NETDATA.easypiechartSetSelection,
  4107. clearSelection: NETDATA.easypiechartClearSelection,
  4108. toolboxPanAndZoom: null,
  4109. initialized: false,
  4110. enabled: true,
  4111. xssRegexIgnore: new RegExp('^/api/v1/data\.result$'),
  4112. format: function (state) {
  4113. void(state);
  4114. return 'array';
  4115. },
  4116. options: function (state) {
  4117. void(state);
  4118. return 'absolute';
  4119. },
  4120. legend: function (state) {
  4121. void(state);
  4122. return null;
  4123. },
  4124. autoresize: function (state) {
  4125. void(state);
  4126. return false;
  4127. },
  4128. max_updates_to_recreate: function (state) {
  4129. void(state);
  4130. return 5000;
  4131. },
  4132. track_colors: function (state) {
  4133. void(state);
  4134. return true;
  4135. },
  4136. pixels_per_point: function (state) {
  4137. void(state);
  4138. return 3;
  4139. },
  4140. aspect_ratio: 100,
  4141. container_class: function (state) {
  4142. void(state);
  4143. return 'netdata-container-easypiechart';
  4144. }
  4145. },
  4146. "gauge": {
  4147. initialize: NETDATA.gaugeInitialize,
  4148. create: NETDATA.gaugeChartCreate,
  4149. update: NETDATA.gaugeChartUpdate,
  4150. resize: null,
  4151. setSelection: NETDATA.gaugeSetSelection,
  4152. clearSelection: NETDATA.gaugeClearSelection,
  4153. toolboxPanAndZoom: null,
  4154. initialized: false,
  4155. enabled: true,
  4156. xssRegexIgnore: new RegExp('^/api/v1/data\.result$'),
  4157. format: function (state) {
  4158. void(state);
  4159. return 'array';
  4160. },
  4161. options: function (state) {
  4162. void(state);
  4163. return 'absolute';
  4164. },
  4165. legend: function (state) {
  4166. void(state);
  4167. return null;
  4168. },
  4169. autoresize: function (state) {
  4170. void(state);
  4171. return false;
  4172. },
  4173. max_updates_to_recreate: function (state) {
  4174. void(state);
  4175. return 5000;
  4176. },
  4177. track_colors: function (state) {
  4178. void(state);
  4179. return true;
  4180. },
  4181. pixels_per_point: function (state) {
  4182. void(state);
  4183. return 3;
  4184. },
  4185. aspect_ratio: 60,
  4186. container_class: function (state) {
  4187. void(state);
  4188. return 'netdata-container-gauge';
  4189. }
  4190. },
  4191. "textonly": {
  4192. autoresize: function (state) {
  4193. void(state);
  4194. return false;
  4195. },
  4196. container_class: function (state) {
  4197. void(state);
  4198. return 'netdata-container';
  4199. },
  4200. create: NETDATA.textOnlyCreate,
  4201. enabled: true,
  4202. format: function (state) {
  4203. void(state);
  4204. return 'array';
  4205. },
  4206. initialized: true,
  4207. initialize: function (callback) {
  4208. callback();
  4209. },
  4210. legend: function (state) {
  4211. void(state);
  4212. return null;
  4213. },
  4214. max_updates_to_recreate: function (state) {
  4215. void(state);
  4216. return 5000;
  4217. },
  4218. options: function (state) {
  4219. void(state);
  4220. return 'absolute';
  4221. },
  4222. pixels_per_point: function (state) {
  4223. void(state);
  4224. return 3;
  4225. },
  4226. track_colors: function (state) {
  4227. void(state);
  4228. return false;
  4229. },
  4230. update: NETDATA.textOnlyUpdate,
  4231. xssRegexIgnore: new RegExp('^/api/v1/data\.result$'),
  4232. }
  4233. };
  4234. NETDATA.registerChartLibrary = function (library, url) {
  4235. if (NETDATA.options.debug.libraries) {
  4236. console.log("registering chart library: " + library);
  4237. }
  4238. NETDATA.chartLibraries[library].url = url;
  4239. NETDATA.chartLibraries[library].initialized = true;
  4240. NETDATA.chartLibraries[library].enabled = true;
  4241. };
  4242. // *** src/dashboard.js/chart-registry.js
  4243. // Chart Registry
  4244. // When multiple charts need the same chart, we avoid downloading it
  4245. // multiple times (and having it in browser memory multiple time)
  4246. // by using this registry.
  4247. // Every time we download a chart definition, we save it here with .add()
  4248. // Then we try to get it back with .get(). If that fails, we download it.
  4249. NETDATA.fixHost = function (host) {
  4250. while (host.slice(-1) === '/') {
  4251. host = host.substring(0, host.length - 1);
  4252. }
  4253. return host;
  4254. };
  4255. NETDATA.chartRegistry = {
  4256. charts: {},
  4257. globalReset: function () {
  4258. this.charts = {};
  4259. },
  4260. add: function (host, id, data) {
  4261. if (typeof this.charts[host] === 'undefined') {
  4262. this.charts[host] = {};
  4263. }
  4264. //console.log('added ' + host + '/' + id);
  4265. this.charts[host][id] = data;
  4266. },
  4267. get: function (host, id) {
  4268. if (typeof this.charts[host] === 'undefined') {
  4269. return null;
  4270. }
  4271. if (typeof this.charts[host][id] === 'undefined') {
  4272. return null;
  4273. }
  4274. //console.log('cached ' + host + '/' + id);
  4275. return this.charts[host][id];
  4276. },
  4277. downloadAll: function (host, callback) {
  4278. host = NETDATA.fixHost(host);
  4279. let self = this;
  4280. function got_data(h, data, callback) {
  4281. if (data !== null) {
  4282. self.charts[h] = data.charts;
  4283. // update the server timezone in our options
  4284. if (typeof data.timezone === 'string') {
  4285. NETDATA.options.server_timezone = data.timezone;
  4286. }
  4287. } else {
  4288. NETDATA.error(406, h + '/api/v1/charts');
  4289. }
  4290. if (typeof callback === 'function') {
  4291. callback(data);
  4292. }
  4293. }
  4294. if (netdataSnapshotData !== null) {
  4295. got_data(host, netdataSnapshotData.charts, callback);
  4296. } else {
  4297. $.ajax({
  4298. url: host + '/api/v1/charts',
  4299. async: true,
  4300. cache: false,
  4301. xhrFields: {withCredentials: true} // required for the cookie
  4302. })
  4303. .done(function (data) {
  4304. data = NETDATA.xss.checkOptional('/api/v1/charts', data);
  4305. got_data(host, data, callback);
  4306. })
  4307. .fail(function () {
  4308. NETDATA.error(405, host + '/api/v1/charts');
  4309. if (typeof callback === 'function') {
  4310. callback(null);
  4311. }
  4312. });
  4313. }
  4314. }
  4315. };
  4316. // Compute common (joint) values over multiple charts.
  4317. // commonMin & commonMax
  4318. NETDATA.commonMin = {
  4319. keys: {},
  4320. latest: {},
  4321. globalReset: function () {
  4322. this.keys = {};
  4323. this.latest = {};
  4324. },
  4325. get: function (state) {
  4326. if (typeof state.tmp.__commonMin === 'undefined') {
  4327. // get the commonMin setting
  4328. state.tmp.__commonMin = NETDATA.dataAttribute(state.element, 'common-min', null);
  4329. }
  4330. let min = state.data.min;
  4331. let name = state.tmp.__commonMin;
  4332. if (name === null) {
  4333. // we don't need commonMin
  4334. //state.log('no need for commonMin');
  4335. return min;
  4336. }
  4337. let t = this.keys[name];
  4338. if (typeof t === 'undefined') {
  4339. // add our commonMin
  4340. this.keys[name] = {};
  4341. t = this.keys[name];
  4342. }
  4343. let uuid = state.uuid;
  4344. if (typeof t[uuid] !== 'undefined') {
  4345. if (t[uuid] === min) {
  4346. //state.log('commonMin ' + state.tmp.__commonMin + ' not changed: ' + this.latest[name]);
  4347. return this.latest[name];
  4348. } else if (min < this.latest[name]) {
  4349. //state.log('commonMin ' + state.tmp.__commonMin + ' increased: ' + min);
  4350. t[uuid] = min;
  4351. this.latest[name] = min;
  4352. return min;
  4353. }
  4354. }
  4355. // add our min
  4356. t[uuid] = min;
  4357. // find the common min
  4358. let m = min;
  4359. // for (let i in t) {
  4360. // if (t.hasOwnProperty(i) && t[i] < m) m = t[i];
  4361. // }
  4362. for (var ti of Object.values(t)) {
  4363. if (ti < m) {
  4364. m = ti;
  4365. }
  4366. }
  4367. //state.log('commonMin ' + state.tmp.__commonMin + ' updated: ' + m);
  4368. this.latest[name] = m;
  4369. return m;
  4370. }
  4371. };
  4372. NETDATA.commonMax = {
  4373. keys: {},
  4374. latest: {},
  4375. globalReset: function () {
  4376. this.keys = {};
  4377. this.latest = {};
  4378. },
  4379. get: function (state) {
  4380. if (typeof state.tmp.__commonMax === 'undefined') {
  4381. // get the commonMax setting
  4382. state.tmp.__commonMax = NETDATA.dataAttribute(state.element, 'common-max', null);
  4383. }
  4384. let max = state.data.max;
  4385. let name = state.tmp.__commonMax;
  4386. if (name === null) {
  4387. // we don't need commonMax
  4388. //state.log('no need for commonMax');
  4389. return max;
  4390. }
  4391. let t = this.keys[name];
  4392. if (typeof t === 'undefined') {
  4393. // add our commonMax
  4394. this.keys[name] = {};
  4395. t = this.keys[name];
  4396. }
  4397. let uuid = state.uuid;
  4398. if (typeof t[uuid] !== 'undefined') {
  4399. if (t[uuid] === max) {
  4400. //state.log('commonMax ' + state.tmp.__commonMax + ' not changed: ' + this.latest[name]);
  4401. return this.latest[name];
  4402. } else if (max > this.latest[name]) {
  4403. //state.log('commonMax ' + state.tmp.__commonMax + ' increased: ' + max);
  4404. t[uuid] = max;
  4405. this.latest[name] = max;
  4406. return max;
  4407. }
  4408. }
  4409. // add our max
  4410. t[uuid] = max;
  4411. // find the common max
  4412. let m = max;
  4413. // for (let i in t) {
  4414. // if (t.hasOwnProperty(i) && t[i] > m) m = t[i];
  4415. // }
  4416. for (var ti of Object.values(t)) {
  4417. if (ti > m) {
  4418. m = ti;
  4419. }
  4420. }
  4421. //state.log('commonMax ' + state.tmp.__commonMax + ' updated: ' + m);
  4422. this.latest[name] = m;
  4423. return m;
  4424. }
  4425. };
  4426. NETDATA.commonColors = {
  4427. keys: {},
  4428. globalReset: function () {
  4429. this.keys = {};
  4430. },
  4431. get: function (state, label) {
  4432. let ret = this.refill(state);
  4433. if (typeof ret.assigned[label] === 'undefined') {
  4434. ret.assigned[label] = ret.available.shift();
  4435. }
  4436. return ret.assigned[label];
  4437. },
  4438. refill: function (state) {
  4439. let ret, len;
  4440. if (typeof state.tmp.__commonColors === 'undefined') {
  4441. ret = this.prepare(state);
  4442. } else {
  4443. ret = this.keys[state.tmp.__commonColors];
  4444. if (typeof ret === 'undefined') {
  4445. ret = this.prepare(state);
  4446. }
  4447. }
  4448. if (ret.available.length === 0) {
  4449. if (ret.copy_theme || ret.custom.length === 0) {
  4450. // copy the theme colors
  4451. len = NETDATA.themes.current.colors.length;
  4452. while (len--) {
  4453. ret.available.unshift(NETDATA.themes.current.colors[len]);
  4454. }
  4455. }
  4456. // copy the custom colors
  4457. len = ret.custom.length;
  4458. while (len--) {
  4459. ret.available.unshift(ret.custom[len]);
  4460. }
  4461. }
  4462. state.colors_assigned = ret.assigned;
  4463. state.colors_available = ret.available;
  4464. state.colors_custom = ret.custom;
  4465. return ret;
  4466. },
  4467. __read_custom_colors: function (state, ret) {
  4468. // add the user supplied colors
  4469. let c = NETDATA.dataAttribute(state.element, 'colors', undefined);
  4470. if (typeof c === 'string' && c.length > 0) {
  4471. c = c.split(' ');
  4472. let len = c.length;
  4473. if (len > 0 && c[len - 1] === 'ONLY') {
  4474. len--;
  4475. ret.copy_theme = false;
  4476. }
  4477. while (len--) {
  4478. ret.custom.unshift(c[len]);
  4479. }
  4480. }
  4481. },
  4482. prepare: function (state) {
  4483. let has_custom_colors = false;
  4484. if (typeof state.tmp.__commonColors === 'undefined') {
  4485. let defname = state.chart.context;
  4486. // if this chart has data-colors=""
  4487. // we should use the chart uuid as the default key (private palette)
  4488. // (data-common-colors="NAME" will be used anyways)
  4489. let c = NETDATA.dataAttribute(state.element, 'colors', undefined);
  4490. if (typeof c === 'string' && c.length > 0) {
  4491. defname = state.uuid;
  4492. has_custom_colors = true;
  4493. }
  4494. // get the commonColors setting
  4495. state.tmp.__commonColors = NETDATA.dataAttribute(state.element, 'common-colors', defname);
  4496. }
  4497. let name = state.tmp.__commonColors;
  4498. let ret = this.keys[name];
  4499. if (typeof ret === 'undefined') {
  4500. // add our commonMax
  4501. this.keys[name] = {
  4502. assigned: {}, // name-value of dimensions and their colors
  4503. available: [], // an array of colors available to be used
  4504. custom: [], // the array of colors defined by the user
  4505. charts: {}, // the charts linked to this
  4506. copy_theme: true
  4507. };
  4508. ret = this.keys[name];
  4509. }
  4510. if (typeof ret.charts[state.uuid] === 'undefined') {
  4511. ret.charts[state.uuid] = state;
  4512. if (has_custom_colors) {
  4513. this.__read_custom_colors(state, ret);
  4514. }
  4515. }
  4516. return ret;
  4517. }
  4518. };
  4519. // *** src/dashboard.js/main.js
  4520. // Codacy declarations
  4521. /* global clipboard */
  4522. /* global Ps */
  4523. if (NETDATA.options.debug.main_loop) {
  4524. console.log('welcome to NETDATA');
  4525. }
  4526. NETDATA.onresizeCallback = null;
  4527. NETDATA.onresize = function () {
  4528. NETDATA.options.last_page_resize = Date.now();
  4529. NETDATA.onscroll();
  4530. if (typeof NETDATA.onresizeCallback === 'function') {
  4531. NETDATA.onresizeCallback();
  4532. }
  4533. };
  4534. NETDATA.abortAllRefreshes = function () {
  4535. let targets = NETDATA.options.targets;
  4536. let len = targets.length;
  4537. while (len--) {
  4538. if (targets[len].fetching_data) {
  4539. if (typeof targets[len].xhr !== 'undefined') {
  4540. targets[len].xhr.abort();
  4541. targets[len].running = false;
  4542. targets[len].fetching_data = false;
  4543. }
  4544. }
  4545. }
  4546. };
  4547. NETDATA.onscrollStartDelay = function () {
  4548. NETDATA.options.last_page_scroll = Date.now();
  4549. NETDATA.options.on_scroll_refresher_stop_until =
  4550. NETDATA.options.last_page_scroll
  4551. + (NETDATA.options.current.async_on_scroll ? 1000 : 0);
  4552. };
  4553. NETDATA.onscrollEndDelay = function () {
  4554. NETDATA.options.on_scroll_refresher_stop_until =
  4555. Date.now()
  4556. + (NETDATA.options.current.async_on_scroll ? NETDATA.options.current.onscroll_worker_duration_threshold : 0);
  4557. };
  4558. NETDATA.onscroll_updater_timeout_id = undefined;
  4559. NETDATA.onscrollUpdater = function () {
  4560. NETDATA.globalSelectionSync.stop();
  4561. if (NETDATA.options.abort_ajax_on_scroll) {
  4562. NETDATA.abortAllRefreshes();
  4563. }
  4564. // when the user scrolls he sees that we have
  4565. // hidden all the not-visible charts
  4566. // using this little function we try to switch
  4567. // the charts back to visible quickly
  4568. if (!NETDATA.intersectionObserver.enabled()) {
  4569. if (!NETDATA.options.current.parallel_refresher) {
  4570. let targets = NETDATA.options.targets;
  4571. let len = targets.length;
  4572. while (len--) {
  4573. if (!targets[len].running) {
  4574. targets[len].isVisible();
  4575. }
  4576. }
  4577. }
  4578. }
  4579. NETDATA.onscrollEndDelay();
  4580. };
  4581. NETDATA.scrollUp = false;
  4582. NETDATA.scrollY = window.scrollY;
  4583. NETDATA.onscroll = function () {
  4584. //console.log('onscroll() begin');
  4585. NETDATA.onscrollStartDelay();
  4586. NETDATA.chartRefresherReschedule();
  4587. NETDATA.scrollUp = (window.scrollY > NETDATA.scrollY);
  4588. NETDATA.scrollY = window.scrollY;
  4589. if (NETDATA.onscroll_updater_timeout_id) {
  4590. NETDATA.timeout.clear(NETDATA.onscroll_updater_timeout_id);
  4591. }
  4592. NETDATA.onscroll_updater_timeout_id = NETDATA.timeout.set(NETDATA.onscrollUpdater, 0);
  4593. //console.log('onscroll() end');
  4594. };
  4595. NETDATA.supportsPassiveEvents = function () {
  4596. if (NETDATA.options.passive_events === null) {
  4597. let supportsPassive = false;
  4598. try {
  4599. let opts = Object.defineProperty({}, 'passive', {
  4600. get: function () {
  4601. supportsPassive = true;
  4602. }
  4603. });
  4604. window.addEventListener("test", null, opts);
  4605. } catch (e) {
  4606. console.log('browser does not support passive events');
  4607. }
  4608. NETDATA.options.passive_events = supportsPassive;
  4609. }
  4610. // console.log('passive ' + NETDATA.options.passive_events);
  4611. return NETDATA.options.passive_events;
  4612. };
  4613. window.addEventListener('resize', NETDATA.onresize, NETDATA.supportsPassiveEvents() ? {passive: true} : false);
  4614. window.addEventListener('scroll', NETDATA.onscroll, NETDATA.supportsPassiveEvents() ? {passive: true} : false);
  4615. // window.onresize = NETDATA.onresize;
  4616. // window.onscroll = NETDATA.onscroll;
  4617. // ----------------------------------------------------------------------------------------------------------------
  4618. // Global Pan and Zoom on charts
  4619. // Using this structure are synchronize all the charts, so that
  4620. // when you pan or zoom one, all others are automatically refreshed
  4621. // to the same timespan.
  4622. NETDATA.globalPanAndZoom = {
  4623. seq: 0, // timestamp ms
  4624. // every time a chart is panned or zoomed
  4625. // we set the timestamp here
  4626. // then we use it as a sequence number
  4627. // to find if other charts are synchronized
  4628. // to this time-range
  4629. master: null, // the master chart (state), to which all others
  4630. // are synchronized
  4631. force_before_ms: null, // the timespan to sync all other charts
  4632. force_after_ms: null,
  4633. callback: null,
  4634. globalReset: function () {
  4635. this.clearMaster();
  4636. this.seq = 0;
  4637. this.master = null;
  4638. this.force_after_ms = null;
  4639. this.force_before_ms = null;
  4640. this.callback = null;
  4641. },
  4642. delay: function () {
  4643. if (NETDATA.options.debug.globalPanAndZoom) {
  4644. console.log('globalPanAndZoom.delay()');
  4645. }
  4646. NETDATA.options.auto_refresher_stop_until = Date.now() + NETDATA.options.current.global_pan_sync_time;
  4647. },
  4648. // set a new master
  4649. setMaster: function (state, after, before) {
  4650. this.delay();
  4651. if (!NETDATA.options.current.sync_pan_and_zoom) {
  4652. return;
  4653. }
  4654. if (this.master === null) {
  4655. if (NETDATA.options.debug.globalPanAndZoom) {
  4656. console.log('globalPanAndZoom.setMaster(' + state.id + ', ' + after + ', ' + before + ') SET MASTER');
  4657. }
  4658. } else if (this.master !== state) {
  4659. if (NETDATA.options.debug.globalPanAndZoom) {
  4660. console.log('globalPanAndZoom.setMaster(' + state.id + ', ' + after + ', ' + before + ') CHANGED MASTER');
  4661. }
  4662. this.master.resetChart(true, true);
  4663. }
  4664. let now = Date.now();
  4665. this.master = state;
  4666. this.seq = now;
  4667. this.force_after_ms = after;
  4668. this.force_before_ms = before;
  4669. if (typeof this.callback === 'function') {
  4670. this.callback(true, after, before);
  4671. }
  4672. },
  4673. // clear the master
  4674. clearMaster: function () {
  4675. // if (NETDATA.options.debug.globalPanAndZoom === true)
  4676. // console.log('globalPanAndZoom.clearMaster()');
  4677. if (NETDATA.options.debug.globalPanAndZoom) {
  4678. console.log('globalPanAndZoom.clearMaster()');
  4679. }
  4680. if (this.master !== null) {
  4681. let st = this.master;
  4682. this.master = null;
  4683. st.resetChart();
  4684. }
  4685. this.master = null;
  4686. this.seq = 0;
  4687. this.force_after_ms = null;
  4688. this.force_before_ms = null;
  4689. NETDATA.options.auto_refresher_stop_until = 0;
  4690. if (typeof this.callback === 'function') {
  4691. this.callback(false, 0, 0);
  4692. }
  4693. },
  4694. // is the given state the master of the global
  4695. // pan and zoom sync?
  4696. isMaster: function (state) {
  4697. return (this.master === state);
  4698. },
  4699. // are we currently have a global pan and zoom sync?
  4700. isActive: function () {
  4701. return (this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0);
  4702. },
  4703. // check if a chart, other than the master
  4704. // needs to be refreshed, due to the global pan and zoom
  4705. shouldBeAutoRefreshed: function (state) {
  4706. if (this.master === null || this.seq === 0) {
  4707. return false;
  4708. }
  4709. //if (state.needsRecreation())
  4710. // return true;
  4711. return (state.tm.pan_and_zoom_seq !== this.seq);
  4712. }
  4713. };
  4714. // ----------------------------------------------------------------------------------------------------------------
  4715. // global chart underlay (time-frame highlighting)
  4716. NETDATA.globalChartUnderlay = {
  4717. callback: null, // what to call when a highlighted range is setup
  4718. after: null, // highlight after this time
  4719. before: null, // highlight before this time
  4720. view_after: null, // the charts after_ms viewport when the highlight was setup
  4721. view_before: null, // the charts before_ms viewport, when the highlight was setup
  4722. state: null, // the chart the highlight was setup
  4723. isActive: function () {
  4724. return (this.after !== null && this.before !== null);
  4725. },
  4726. hasViewport: function () {
  4727. return (this.state !== null && this.view_after !== null && this.view_before !== null);
  4728. },
  4729. init: function (state, after, before, view_after, view_before) {
  4730. this.state = (typeof state !== 'undefined') ? state : null;
  4731. this.after = (typeof after !== 'undefined' && after !== null && after > 0) ? after : null;
  4732. this.before = (typeof before !== 'undefined' && before !== null && before > 0) ? before : null;
  4733. this.view_after = (typeof view_after !== 'undefined' && view_after !== null && view_after > 0) ? view_after : null;
  4734. this.view_before = (typeof view_before !== 'undefined' && view_before !== null && view_before > 0) ? view_before : null;
  4735. },
  4736. setup: function () {
  4737. if (this.isActive()) {
  4738. if (this.state === null) {
  4739. this.state = NETDATA.options.targets[0];
  4740. }
  4741. if (typeof this.callback === 'function') {
  4742. this.callback(true, this.after, this.before);
  4743. }
  4744. } else {
  4745. if (typeof this.callback === 'function') {
  4746. this.callback(false, 0, 0);
  4747. }
  4748. }
  4749. },
  4750. set: function (state, after, before, view_after, view_before) {
  4751. if (after > before) {
  4752. let t = after;
  4753. after = before;
  4754. before = t;
  4755. }
  4756. this.init(state, after, before, view_after, view_before);
  4757. // if (this.hasViewport() === true)
  4758. // NETDATA.globalPanAndZoom.setMaster(this.state, this.view_after, this.view_before);
  4759. if (this.hasViewport()) {
  4760. NETDATA.globalPanAndZoom.setMaster(this.state, this.view_after, this.view_before);
  4761. }
  4762. this.setup();
  4763. },
  4764. clear: function () {
  4765. this.after = null;
  4766. this.before = null;
  4767. this.state = null;
  4768. this.view_after = null;
  4769. this.view_before = null;
  4770. if (typeof this.callback === 'function') {
  4771. this.callback(false, 0, 0);
  4772. }
  4773. },
  4774. focus: function () {
  4775. if (this.isActive() && this.hasViewport()) {
  4776. if (this.state === null) {
  4777. this.state = NETDATA.options.targets[0];
  4778. }
  4779. if (NETDATA.globalPanAndZoom.isMaster(this.state)) {
  4780. NETDATA.globalPanAndZoom.clearMaster();
  4781. }
  4782. NETDATA.globalPanAndZoom.setMaster(this.state, this.view_after, this.view_before, true);
  4783. }
  4784. }
  4785. };
  4786. // ----------------------------------------------------------------------------------------------------------------
  4787. // dimensions selection
  4788. // TODO
  4789. // move color assignment to dimensions, here
  4790. let dimensionStatus = function (parent, label, name_div, value_div, color) {
  4791. this.enabled = false;
  4792. this.parent = parent;
  4793. this.label = label;
  4794. this.name_div = null;
  4795. this.value_div = null;
  4796. this.color = NETDATA.themes.current.foreground;
  4797. this.selected = (parent.unselected_count === 0);
  4798. this.setOptions(name_div, value_div, color);
  4799. };
  4800. dimensionStatus.prototype.invalidate = function () {
  4801. this.name_div = null;
  4802. this.value_div = null;
  4803. this.enabled = false;
  4804. };
  4805. dimensionStatus.prototype.setOptions = function (name_div, value_div, color) {
  4806. this.color = color;
  4807. if (this.name_div !== name_div) {
  4808. this.name_div = name_div;
  4809. this.name_div.title = this.label;
  4810. this.name_div.style.setProperty('color', this.color, 'important');
  4811. if (!this.selected) {
  4812. this.name_div.className = 'netdata-legend-name not-selected';
  4813. } else {
  4814. this.name_div.className = 'netdata-legend-name selected';
  4815. }
  4816. }
  4817. if (this.value_div !== value_div) {
  4818. this.value_div = value_div;
  4819. this.value_div.title = this.label;
  4820. this.value_div.style.setProperty('color', this.color, 'important');
  4821. if (!this.selected) {
  4822. this.value_div.className = 'netdata-legend-value not-selected';
  4823. } else {
  4824. this.value_div.className = 'netdata-legend-value selected';
  4825. }
  4826. }
  4827. this.enabled = true;
  4828. this.setHandler();
  4829. };
  4830. dimensionStatus.prototype.setHandler = function () {
  4831. if (!this.enabled) {
  4832. return;
  4833. }
  4834. let ds = this;
  4835. // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
  4836. this.name_div.onclick = this.value_div.onclick = function (e) {
  4837. e.preventDefault();
  4838. if (ds.isSelected()) {
  4839. // this is selected
  4840. if (e.shiftKey || e.ctrlKey) {
  4841. // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
  4842. ds.unselect();
  4843. if (ds.parent.countSelected() === 0) {
  4844. ds.parent.selectAll();
  4845. }
  4846. } else {
  4847. // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
  4848. if (ds.parent.countSelected() === 1) {
  4849. ds.parent.selectAll();
  4850. } else {
  4851. ds.parent.selectNone();
  4852. ds.select();
  4853. }
  4854. }
  4855. }
  4856. else {
  4857. // this is not selected
  4858. if (e.shiftKey || e.ctrlKey) {
  4859. // control or shift key is pressed -> select this too
  4860. ds.select();
  4861. } else {
  4862. // no key is pressed -> select only this
  4863. ds.parent.selectNone();
  4864. ds.select();
  4865. }
  4866. }
  4867. ds.parent.state.redrawChart();
  4868. }
  4869. };
  4870. dimensionStatus.prototype.select = function () {
  4871. if (!this.enabled) {
  4872. return;
  4873. }
  4874. this.name_div.className = 'netdata-legend-name selected';
  4875. this.value_div.className = 'netdata-legend-value selected';
  4876. this.selected = true;
  4877. };
  4878. dimensionStatus.prototype.unselect = function () {
  4879. if (!this.enabled) {
  4880. return;
  4881. }
  4882. this.name_div.className = 'netdata-legend-name not-selected';
  4883. this.value_div.className = 'netdata-legend-value hidden';
  4884. this.selected = false;
  4885. };
  4886. dimensionStatus.prototype.isSelected = function () {
  4887. // return(this.enabled === true && this.selected === true);
  4888. return this.enabled && this.selected;
  4889. };
  4890. // ----------------------------------------------------------------------------------------------------------------
  4891. let dimensionsVisibility = function (state) {
  4892. this.state = state;
  4893. this.len = 0;
  4894. this.dimensions = {};
  4895. this.selected_count = 0;
  4896. this.unselected_count = 0;
  4897. };
  4898. dimensionsVisibility.prototype.dimensionAdd = function (label, name_div, value_div, color) {
  4899. if (typeof this.dimensions[label] === 'undefined') {
  4900. this.len++;
  4901. this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
  4902. } else {
  4903. this.dimensions[label].setOptions(name_div, value_div, color);
  4904. }
  4905. return this.dimensions[label];
  4906. };
  4907. dimensionsVisibility.prototype.dimensionGet = function (label) {
  4908. return this.dimensions[label];
  4909. };
  4910. dimensionsVisibility.prototype.invalidateAll = function () {
  4911. let keys = Object.keys(this.dimensions);
  4912. let len = keys.length;
  4913. while (len--) {
  4914. this.dimensions[keys[len]].invalidate();
  4915. }
  4916. };
  4917. dimensionsVisibility.prototype.selectAll = function () {
  4918. let keys = Object.keys(this.dimensions);
  4919. let len = keys.length;
  4920. while (len--) {
  4921. this.dimensions[keys[len]].select();
  4922. }
  4923. };
  4924. dimensionsVisibility.prototype.countSelected = function () {
  4925. let selected = 0;
  4926. let keys = Object.keys(this.dimensions);
  4927. let len = keys.length;
  4928. while (len--) {
  4929. if (this.dimensions[keys[len]].isSelected()) {
  4930. selected++;
  4931. }
  4932. }
  4933. return selected;
  4934. };
  4935. dimensionsVisibility.prototype.selectNone = function () {
  4936. let keys = Object.keys(this.dimensions);
  4937. let len = keys.length;
  4938. while (len--) {
  4939. this.dimensions[keys[len]].unselect();
  4940. }
  4941. };
  4942. dimensionsVisibility.prototype.selected2BooleanArray = function (array) {
  4943. let ret = [];
  4944. this.selected_count = 0;
  4945. this.unselected_count = 0;
  4946. let len = array.length;
  4947. while (len--) {
  4948. let ds = this.dimensions[array[len]];
  4949. if (typeof ds === 'undefined') {
  4950. // console.log(array[i] + ' is not found');
  4951. ret.unshift(false);
  4952. } else if (ds.isSelected()) {
  4953. ret.unshift(true);
  4954. this.selected_count++;
  4955. } else {
  4956. ret.unshift(false);
  4957. this.unselected_count++;
  4958. }
  4959. }
  4960. if (this.selected_count === 0 && this.unselected_count !== 0) {
  4961. this.selectAll();
  4962. return this.selected2BooleanArray(array);
  4963. }
  4964. return ret;
  4965. };
  4966. // ----------------------------------------------------------------------------------------------------------------
  4967. // date/time conversion
  4968. NETDATA.dateTime = {
  4969. using_timezone: false,
  4970. // these are the old netdata functions
  4971. // we fallback to these, if the new ones fail
  4972. localeDateStringNative: function (d) {
  4973. return d.toLocaleDateString();
  4974. },
  4975. localeTimeStringNative: function (d) {
  4976. return d.toLocaleTimeString();
  4977. },
  4978. xAxisTimeStringNative: function (d) {
  4979. return NETDATA.zeropad(d.getHours()) + ":"
  4980. + NETDATA.zeropad(d.getMinutes()) + ":"
  4981. + NETDATA.zeropad(d.getSeconds());
  4982. },
  4983. // initialize the new date/time conversion
  4984. // functions.
  4985. // if this fails, we fallback to the above
  4986. init: function (timezone) {
  4987. //console.log('init with timezone: ' + timezone);
  4988. // detect browser timezone
  4989. try {
  4990. NETDATA.options.browser_timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  4991. } catch (e) {
  4992. console.log('failed to detect browser timezone: ' + e.toString());
  4993. NETDATA.options.browser_timezone = 'cannot-detect-it';
  4994. }
  4995. let ret = false;
  4996. try {
  4997. let dateOptions = {
  4998. localeMatcher: 'best fit',
  4999. formatMatcher: 'best fit',
  5000. weekday: 'short',
  5001. year: 'numeric',
  5002. month: 'short',
  5003. day: '2-digit'
  5004. };
  5005. let timeOptions = {
  5006. localeMatcher: 'best fit',
  5007. hour12: false,
  5008. formatMatcher: 'best fit',
  5009. hour: '2-digit',
  5010. minute: '2-digit',
  5011. second: '2-digit'
  5012. };
  5013. let xAxisOptions = {
  5014. localeMatcher: 'best fit',
  5015. hour12: false,
  5016. formatMatcher: 'best fit',
  5017. hour: '2-digit',
  5018. minute: '2-digit',
  5019. second: '2-digit'
  5020. };
  5021. if (typeof timezone === 'string' && timezone !== '' && timezone !== 'default') {
  5022. dateOptions.timeZone = timezone;
  5023. timeOptions.timeZone = timezone;
  5024. timeOptions.timeZoneName = 'short';
  5025. xAxisOptions.timeZone = timezone;
  5026. this.using_timezone = true;
  5027. } else {
  5028. timezone = 'default';
  5029. this.using_timezone = false;
  5030. }
  5031. this.dateFormat = new Intl.DateTimeFormat(navigator.language, dateOptions);
  5032. this.timeFormat = new Intl.DateTimeFormat(navigator.language, timeOptions);
  5033. this.xAxisFormat = new Intl.DateTimeFormat(navigator.language, xAxisOptions);
  5034. this.localeDateString = function (d) {
  5035. return this.dateFormat.format(d);
  5036. };
  5037. this.localeTimeString = function (d) {
  5038. return this.timeFormat.format(d);
  5039. };
  5040. this.xAxisTimeString = function (d) {
  5041. return this.xAxisFormat.format(d);
  5042. };
  5043. //let d = new Date();
  5044. //let t = this.dateFormat.format(d) + ' ' + this.timeFormat.format(d) + ' ' + this.xAxisFormat.format(d);
  5045. ret = true;
  5046. } catch (e) {
  5047. console.log('Cannot setup Date/Time formatting: ' + e.toString());
  5048. timezone = 'default';
  5049. this.localeDateString = this.localeDateStringNative;
  5050. this.localeTimeString = this.localeTimeStringNative;
  5051. this.xAxisTimeString = this.xAxisTimeStringNative;
  5052. this.using_timezone = false;
  5053. ret = false;
  5054. }
  5055. // save it
  5056. //console.log('init setOption timezone: ' + timezone);
  5057. NETDATA.setOption('timezone', timezone);
  5058. return ret;
  5059. }
  5060. };
  5061. NETDATA.dateTime.init(NETDATA.options.current.timezone);
  5062. // ----------------------------------------------------------------------------------------------------------------
  5063. // global selection sync
  5064. NETDATA.globalSelectionSync = {
  5065. state: null,
  5066. dontSyncBefore: 0,
  5067. last_t: 0,
  5068. slaves: [],
  5069. timeoutId: undefined,
  5070. globalReset: function () {
  5071. this.stop();
  5072. this.state = null;
  5073. this.dontSyncBefore = 0;
  5074. this.last_t = 0;
  5075. this.slaves = [];
  5076. this.timeoutId = undefined;
  5077. },
  5078. active: function () {
  5079. return (this.state !== null);
  5080. },
  5081. // return true if global selection sync can be enabled now
  5082. enabled: function () {
  5083. // console.log('enabled()');
  5084. // can we globally apply selection sync?
  5085. if (!NETDATA.options.current.sync_selection) {
  5086. return false;
  5087. }
  5088. return (this.dontSyncBefore <= Date.now());
  5089. },
  5090. // set the global selection sync master
  5091. setMaster: function (state) {
  5092. if (!this.enabled()) {
  5093. this.stop();
  5094. return;
  5095. }
  5096. if (this.state === state) {
  5097. return;
  5098. }
  5099. if (this.state !== null) {
  5100. this.stop();
  5101. }
  5102. if (NETDATA.options.debug.globalSelectionSync) {
  5103. console.log('globalSelectionSync.setMaster(' + state.id + ')');
  5104. }
  5105. state.selected = true;
  5106. this.state = state;
  5107. this.last_t = 0;
  5108. // find all slaves
  5109. let targets = NETDATA.intersectionObserver.targets();
  5110. this.slaves = [];
  5111. let len = targets.length;
  5112. while (len--) {
  5113. let st = targets[len];
  5114. if (this.state !== st && st.globalSelectionSyncIsEligible()) {
  5115. this.slaves.push(st);
  5116. }
  5117. }
  5118. // this.delay(100);
  5119. },
  5120. // stop global selection sync
  5121. stop: function () {
  5122. if (this.state !== null) {
  5123. if (NETDATA.options.debug.globalSelectionSync) {
  5124. console.log('globalSelectionSync.stop()');
  5125. }
  5126. let len = this.slaves.length;
  5127. while (len--) {
  5128. this.slaves[len].clearSelection();
  5129. }
  5130. this.state.clearSelection();
  5131. this.last_t = 0;
  5132. this.slaves = [];
  5133. this.state = null;
  5134. }
  5135. },
  5136. // delay global selection sync for some time
  5137. delay: function (ms) {
  5138. if (NETDATA.options.current.sync_selection) {
  5139. // if (NETDATA.options.debug.globalSelectionSync === true) {
  5140. if (NETDATA.options.debug.globalSelectionSync) {
  5141. console.log('globalSelectionSync.delay()');
  5142. }
  5143. if (typeof ms === 'number') {
  5144. this.dontSyncBefore = Date.now() + ms;
  5145. } else {
  5146. this.dontSyncBefore = Date.now() + NETDATA.options.current.sync_selection_delay;
  5147. }
  5148. }
  5149. },
  5150. __syncSlaves: function () {
  5151. // if (NETDATA.globalSelectionSync.enabled() === true) {
  5152. if (NETDATA.globalSelectionSync.enabled()) {
  5153. // if (NETDATA.options.debug.globalSelectionSync === true)
  5154. if (NETDATA.options.debug.globalSelectionSync) {
  5155. console.log('globalSelectionSync.__syncSlaves()');
  5156. }
  5157. let t = NETDATA.globalSelectionSync.last_t;
  5158. let len = NETDATA.globalSelectionSync.slaves.length;
  5159. while (len--) {
  5160. NETDATA.globalSelectionSync.slaves[len].setSelection(t);
  5161. }
  5162. this.timeoutId = undefined;
  5163. }
  5164. },
  5165. // sync all the visible charts to the given time
  5166. // this is to be called from the chart libraries
  5167. sync: function (state, t) {
  5168. // if (NETDATA.options.current.sync_selection === true) {
  5169. if (NETDATA.options.current.sync_selection) {
  5170. // if (NETDATA.options.debug.globalSelectionSync === true)
  5171. if (NETDATA.options.debug.globalSelectionSync) {
  5172. console.log('globalSelectionSync.sync(' + state.id + ', ' + t.toString() + ')');
  5173. }
  5174. this.setMaster(state);
  5175. if (t === this.last_t) {
  5176. return;
  5177. }
  5178. this.last_t = t;
  5179. if (state.foreignElementSelection !== null) {
  5180. state.foreignElementSelection.innerText = NETDATA.dateTime.localeDateString(t) + ' ' + NETDATA.dateTime.localeTimeString(t);
  5181. }
  5182. if (this.timeoutId) {
  5183. NETDATA.timeout.clear(this.timeoutId);
  5184. }
  5185. this.timeoutId = NETDATA.timeout.set(this.__syncSlaves, 0);
  5186. }
  5187. }
  5188. };
  5189. NETDATA.intersectionObserver = {
  5190. observer: null,
  5191. visible_targets: [],
  5192. options: {
  5193. root: null,
  5194. rootMargin: "0px",
  5195. threshold: null
  5196. },
  5197. enabled: function () {
  5198. return this.observer !== null;
  5199. },
  5200. globalReset: function () {
  5201. if (this.observer !== null) {
  5202. this.visible_targets = [];
  5203. this.observer.disconnect();
  5204. this.init();
  5205. }
  5206. },
  5207. targets: function () {
  5208. if (this.enabled() && this.visible_targets.length > 0) {
  5209. return this.visible_targets;
  5210. } else {
  5211. return NETDATA.options.targets;
  5212. }
  5213. },
  5214. switchChartVisibility: function () {
  5215. let old = this.__visibilityRatioOld;
  5216. if (old !== this.__visibilityRatio) {
  5217. if (old === 0 && this.__visibilityRatio > 0) {
  5218. this.unhideChart();
  5219. } else if (old > 0 && this.__visibilityRatio === 0) {
  5220. this.hideChart();
  5221. }
  5222. this.__visibilityRatioOld = this.__visibilityRatio;
  5223. }
  5224. },
  5225. handler: function (entries, observer) {
  5226. entries.forEach(function (entry) {
  5227. let state = NETDATA.chartState(entry.target);
  5228. let idx;
  5229. if (entry.intersectionRatio > 0) {
  5230. idx = NETDATA.intersectionObserver.visible_targets.indexOf(state);
  5231. if (idx === -1) {
  5232. if (NETDATA.scrollUp) {
  5233. NETDATA.intersectionObserver.visible_targets.push(state);
  5234. } else {
  5235. NETDATA.intersectionObserver.visible_targets.unshift(state);
  5236. }
  5237. }
  5238. else if (state.__visibilityRatio === 0) {
  5239. state.log("was not visible until now, but was already in visible_targets");
  5240. }
  5241. } else {
  5242. idx = NETDATA.intersectionObserver.visible_targets.indexOf(state);
  5243. if (idx !== -1) {
  5244. NETDATA.intersectionObserver.visible_targets.splice(idx, 1);
  5245. } else if (state.__visibilityRatio > 0) {
  5246. state.log("was visible, but not found in visible_targets");
  5247. }
  5248. }
  5249. state.__visibilityRatio = entry.intersectionRatio;
  5250. if (!NETDATA.options.current.async_on_scroll) {
  5251. if (window.requestIdleCallback) {
  5252. window.requestIdleCallback(function () {
  5253. NETDATA.intersectionObserver.switchChartVisibility.call(state);
  5254. }, {timeout: 100});
  5255. } else {
  5256. NETDATA.intersectionObserver.switchChartVisibility.call(state);
  5257. }
  5258. }
  5259. });
  5260. },
  5261. observe: function (state) {
  5262. if (this.enabled()) {
  5263. state.__visibilityRatioOld = 0;
  5264. state.__visibilityRatio = 0;
  5265. this.observer.observe(state.element);
  5266. state.isVisible = function () {
  5267. if (!NETDATA.options.current.update_only_visible) {
  5268. return true;
  5269. }
  5270. NETDATA.intersectionObserver.switchChartVisibility.call(this);
  5271. return this.__visibilityRatio > 0;
  5272. }
  5273. }
  5274. },
  5275. init: function () {
  5276. if (typeof netdataIntersectionObserver === 'undefined' || netdataIntersectionObserver) {
  5277. try {
  5278. this.observer = new IntersectionObserver(this.handler, this.options);
  5279. } catch (e) {
  5280. console.log("IntersectionObserver is not supported on this browser");
  5281. this.observer = null;
  5282. }
  5283. }
  5284. //else {
  5285. // console.log("IntersectionObserver is disabled");
  5286. //}
  5287. }
  5288. };
  5289. NETDATA.intersectionObserver.init();
  5290. // ----------------------------------------------------------------------------------------------------------------
  5291. // Our state object, where all per-chart values are stored
  5292. let chartState = function (element) {
  5293. this.element = element;
  5294. // IMPORTANT:
  5295. // all private functions should use 'that', instead of 'this'
  5296. // Alternatively, you can use arrow functions (related issue #4514)
  5297. let that = this;
  5298. // ============================================================================================================
  5299. // ERROR HANDLING
  5300. /* error() - private
  5301. * show an error instead of the chart
  5302. */
  5303. let error = (msg) => {
  5304. let ret = true;
  5305. if (typeof netdataErrorCallback === 'function') {
  5306. ret = netdataErrorCallback('chart', this.id, msg);
  5307. }
  5308. if (ret) {
  5309. this.element.innerHTML = this.id + ': ' + msg;
  5310. this.enabled = false;
  5311. this.current = this.pan;
  5312. }
  5313. };
  5314. // console logging
  5315. this.log = function (msg) {
  5316. console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
  5317. };
  5318. this.debugLog = function (msg) {
  5319. if (this.debug) {
  5320. this.log(msg);
  5321. }
  5322. };
  5323. // ============================================================================================================
  5324. // EARLY INITIALIZATION
  5325. // These are variables that should exist even if the chart is never to be rendered.
  5326. // Be careful what you add here - there may be thousands of charts on the page.
  5327. // GUID - a unique identifier for the chart
  5328. this.uuid = NETDATA.guid();
  5329. // string - the name of chart
  5330. this.id = NETDATA.dataAttribute(this.element, 'netdata', undefined);
  5331. if (typeof this.id === 'undefined') {
  5332. error("netdata elements need data-netdata");
  5333. return;
  5334. }
  5335. // string - the key for localStorage settings
  5336. this.settings_id = NETDATA.dataAttribute(this.element, 'id', null);
  5337. // the user given dimensions of the element
  5338. this.width = NETDATA.dataAttribute(this.element, 'width', NETDATA.chartDefaults.width);
  5339. this.height = NETDATA.dataAttribute(this.element, 'height', NETDATA.chartDefaults.height);
  5340. this.height_original = this.height;
  5341. if (this.settings_id !== null) {
  5342. this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function (height) {
  5343. // this is the callback that will be called
  5344. // if and when the user resets all localStorage variables
  5345. // to their defaults
  5346. resizeChartToHeight(height);
  5347. });
  5348. }
  5349. // the chart library requested by the user
  5350. this.library_name = NETDATA.dataAttribute(this.element, 'chart-library', NETDATA.chartDefaults.library);
  5351. // check the requested library is available
  5352. // we don't initialize it here - it will be initialized when
  5353. // this chart will be first used
  5354. if (typeof NETDATA.chartLibraries[this.library_name] === 'undefined') {
  5355. NETDATA.error(402, this.library_name);
  5356. error('chart library "' + this.library_name + '" is not found');
  5357. this.enabled = false;
  5358. } else if (!NETDATA.chartLibraries[this.library_name].enabled) {
  5359. NETDATA.error(403, this.library_name);
  5360. error('chart library "' + this.library_name + '" is not enabled');
  5361. this.enabled = false;
  5362. } else {
  5363. this.library = NETDATA.chartLibraries[this.library_name];
  5364. }
  5365. this.auto = {
  5366. name: 'auto',
  5367. autorefresh: true,
  5368. force_update_at: 0, // the timestamp to force the update at
  5369. force_before_ms: null,
  5370. force_after_ms: null
  5371. };
  5372. this.pan = {
  5373. name: 'pan',
  5374. autorefresh: false,
  5375. force_update_at: 0, // the timestamp to force the update at
  5376. force_before_ms: null,
  5377. force_after_ms: null
  5378. };
  5379. this.zoom = {
  5380. name: 'zoom',
  5381. autorefresh: false,
  5382. force_update_at: 0, // the timestamp to force the update at
  5383. force_before_ms: null,
  5384. force_after_ms: null
  5385. };
  5386. // this is a pointer to one of the sub-classes below
  5387. // auto, pan, zoom
  5388. this.current = this.auto;
  5389. this.running = false; // boolean - true when the chart is being refreshed now
  5390. this.enabled = true; // boolean - is the chart enabled for refresh?
  5391. this.force_update_every = null; // number - overwrite the visualization update frequency of the chart
  5392. this.tmp = {};
  5393. this.foreignElementBefore = null;
  5394. this.foreignElementAfter = null;
  5395. this.foreignElementDuration = null;
  5396. this.foreignElementUpdateEvery = null;
  5397. this.foreignElementSelection = null;
  5398. // ============================================================================================================
  5399. // PRIVATE FUNCTIONS
  5400. // reset the runtime status variables to their defaults
  5401. const runtimeInit = () => {
  5402. this.paused = false; // boolean - is the chart paused for any reason?
  5403. this.selected = false; // boolean - is the chart shown a selection?
  5404. this.chart_created = false; // boolean - is the library.create() been called?
  5405. this.dom_created = false; // boolean - is the chart DOM been created?
  5406. this.fetching_data = false; // boolean - true while we fetch data via ajax
  5407. this.updates_counter = 0; // numeric - the number of refreshes made so far
  5408. this.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden
  5409. this.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
  5410. this.tm = {
  5411. last_initialized: 0, // milliseconds - the timestamp it was last initialized
  5412. last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
  5413. last_mode_switch: 0, // milliseconds - the timestamp it switched modes
  5414. last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
  5415. last_updated: 0, // the timestamp the chart last updated with data
  5416. pan_and_zoom_seq: 0, // the sequence number of the global synchronization
  5417. // between chart.
  5418. // Used with NETDATA.globalPanAndZoom.seq
  5419. last_visible_check: 0, // the time we last checked if it is visible
  5420. last_resized: 0, // the time the chart was resized
  5421. last_hidden: 0, // the time the chart was hidden
  5422. last_unhidden: 0, // the time the chart was unhidden
  5423. last_autorefreshed: 0 // the time the chart was last refreshed
  5424. };
  5425. this.data = null; // the last data as downloaded from the netdata server
  5426. this.data_url = 'invalid://'; // string - the last url used to update the chart
  5427. this.data_points = 0; // number - the number of points returned from netdata
  5428. this.data_after = 0; // milliseconds - the first timestamp of the data
  5429. this.data_before = 0; // milliseconds - the last timestamp of the data
  5430. this.data_update_every = 0; // milliseconds - the frequency to update the data
  5431. this.tmp = {}; // members that can be destroyed to save memory
  5432. };
  5433. // initialize all the variables that are required for the chart to be rendered
  5434. const lateInitialization = () => {
  5435. if (typeof this.host !== 'undefined') {
  5436. return;
  5437. }
  5438. // string - the netdata server URL, without any path
  5439. this.host = NETDATA.dataAttribute(this.element, 'host', NETDATA.serverDefault);
  5440. // make sure the host does not end with /
  5441. // all netdata API requests use absolute paths
  5442. while (this.host.slice(-1) === '/') {
  5443. this.host = this.host.substring(0, this.host.length - 1);
  5444. }
  5445. // string - the grouping method requested by the user
  5446. this.method = NETDATA.dataAttribute(this.element, 'method', NETDATA.chartDefaults.method);
  5447. this.gtime = NETDATA.dataAttribute(this.element, 'gtime', 0);
  5448. // the time-range requested by the user
  5449. this.after = NETDATA.dataAttribute(this.element, 'after', NETDATA.chartDefaults.after);
  5450. this.before = NETDATA.dataAttribute(this.element, 'before', NETDATA.chartDefaults.before);
  5451. // the pixels per point requested by the user
  5452. this.pixels_per_point = NETDATA.dataAttribute(this.element, 'pixels-per-point', 1);
  5453. this.points = NETDATA.dataAttribute(this.element, 'points', null);
  5454. // the forced update_every
  5455. this.force_update_every = NETDATA.dataAttribute(this.element, 'update-every', null);
  5456. if (typeof this.force_update_every !== 'number' || this.force_update_every <= 1) {
  5457. if (this.force_update_every !== null) {
  5458. this.log('ignoring invalid value of property data-update-every');
  5459. }
  5460. this.force_update_every = null;
  5461. } else {
  5462. this.force_update_every *= 1000;
  5463. }
  5464. // the dimensions requested by the user
  5465. this.dimensions = NETDATA.encodeURIComponent(NETDATA.dataAttribute(this.element, 'dimensions', null));
  5466. this.title = NETDATA.dataAttribute(this.element, 'title', null); // the title of the chart
  5467. this.units = NETDATA.dataAttribute(this.element, 'units', null); // the units of the chart dimensions
  5468. this.units_desired = NETDATA.dataAttribute(this.element, 'desired-units', NETDATA.options.current.units); // the units of the chart dimensions
  5469. this.units_current = this.units;
  5470. this.units_common = NETDATA.dataAttribute(this.element, 'common-units', null);
  5471. // additional options to pass to netdata
  5472. this.append_options = NETDATA.encodeURIComponent(NETDATA.dataAttribute(this.element, 'append-options', null));
  5473. // override options to pass to netdata
  5474. this.override_options = NETDATA.encodeURIComponent(NETDATA.dataAttribute(this.element, 'override-options', null));
  5475. this.debug = NETDATA.dataAttributeBoolean(this.element, 'debug', false);
  5476. this.value_decimal_detail = -1;
  5477. let d = NETDATA.dataAttribute(this.element, 'decimal-digits', -1);
  5478. if (typeof d === 'number') {
  5479. this.value_decimal_detail = d;
  5480. } else if (typeof d !== 'undefined') {
  5481. this.log('ignoring decimal-digits value: ' + d.toString());
  5482. }
  5483. // if we need to report the rendering speed
  5484. // find the element that needs to be updated
  5485. let refresh_dt_element_name = NETDATA.dataAttribute(this.element, 'dt-element-name', null); // string - the element to print refresh_dt_ms
  5486. if (refresh_dt_element_name !== null) {
  5487. this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
  5488. }
  5489. else {
  5490. this.refresh_dt_element = null;
  5491. }
  5492. this.dimensions_visibility = new dimensionsVisibility(that);
  5493. this.netdata_first = 0; // milliseconds - the first timestamp in netdata
  5494. this.netdata_last = 0; // milliseconds - the last timestamp in netdata
  5495. this.requested_after = null; // milliseconds - the timestamp of the request after param
  5496. this.requested_before = null; // milliseconds - the timestamp of the request before param
  5497. this.requested_padding = null;
  5498. this.view_after = 0;
  5499. this.view_before = 0;
  5500. this.refresh_dt_ms = 0; // milliseconds - the time the last refresh took
  5501. // how many retries we have made to load chart data from the server
  5502. this.retries_on_data_failures = 0;
  5503. // color management
  5504. this.colors = null;
  5505. this.colors_assigned = null;
  5506. this.colors_available = null;
  5507. this.colors_custom = null;
  5508. this.element_message = null; // the element already created by the user
  5509. this.element_chart = null; // the element with the chart
  5510. this.element_legend = null; // the element with the legend of the chart (if created by us)
  5511. this.element_legend_childs = {
  5512. content: null,
  5513. hidden: null,
  5514. title_date: null,
  5515. title_time: null,
  5516. title_units: null,
  5517. perfect_scroller: null, // the container to apply perfect scroller to
  5518. series: null
  5519. };
  5520. this.chart_url = null; // string - the url to download chart info
  5521. this.chart = null; // object - the chart as downloaded from the server
  5522. const getForeignElementById = (opt) => {
  5523. let id = NETDATA.dataAttribute(this.element, opt, null);
  5524. if (id === null) {
  5525. //this.log('option "' + opt + '" is undefined');
  5526. return null;
  5527. }
  5528. let el = document.getElementById(id);
  5529. if (typeof el === 'undefined') {
  5530. this.log('cannot find an element with name "' + id.toString() + '"');
  5531. return null;
  5532. }
  5533. return el;
  5534. };
  5535. this.foreignElementBefore = getForeignElementById('show-before-at');
  5536. this.foreignElementAfter = getForeignElementById('show-after-at');
  5537. this.foreignElementDuration = getForeignElementById('show-duration-at');
  5538. this.foreignElementUpdateEvery = getForeignElementById('show-update-every-at');
  5539. this.foreignElementSelection = getForeignElementById('show-selection-at');
  5540. };
  5541. const destroyDOM = () => {
  5542. if (!this.enabled) {
  5543. return;
  5544. }
  5545. if (this.debug) {
  5546. this.log('destroyDOM()');
  5547. }
  5548. // this.element.className = 'netdata-message icon';
  5549. // this.element.innerHTML = '<i class="fas fa-sync"></i> netdata';
  5550. this.element.innerHTML = '';
  5551. this.element_message = null;
  5552. this.element_legend = null;
  5553. this.element_chart = null;
  5554. this.element_legend_childs.series = null;
  5555. this.chart_created = false;
  5556. this.dom_created = false;
  5557. this.tm.last_resized = 0;
  5558. this.tm.last_dom_created = 0;
  5559. };
  5560. const maxMessageFontSize = () => {
  5561. let screenHeight = screen.height;
  5562. let el = this.element;
  5563. // normally we want a font size, as tall as the element
  5564. let h = el.clientHeight;
  5565. // but give it some air, 20% let's say, or 5 pixels min
  5566. let lost = Math.max(h * 0.2, 5);
  5567. h -= lost;
  5568. // center the text, vertically
  5569. let paddingTop = (lost - 5) / 2;
  5570. // but check the width too
  5571. // it should fit 10 characters in it
  5572. let w = el.clientWidth / 10;
  5573. if (h > w) {
  5574. paddingTop += (h - w) / 2;
  5575. h = w;
  5576. }
  5577. // and don't make it too huge
  5578. // 5% of the screen size is good
  5579. if (h > screenHeight / 20) {
  5580. paddingTop += (h - (screenHeight / 20)) / 2;
  5581. h = screenHeight / 20;
  5582. }
  5583. // set it
  5584. this.element_message.style.fontSize = h.toString() + 'px';
  5585. this.element_message.style.paddingTop = paddingTop.toString() + 'px';
  5586. };
  5587. const showMessageIcon = (icon) => {
  5588. this.element_message.innerHTML = icon;
  5589. maxMessageFontSize();
  5590. $(this.element_message).removeClass('hidden');
  5591. this.tmp.___messageHidden___ = undefined;
  5592. };
  5593. const showLoading = () => {
  5594. if (!this.chart_created) {
  5595. showMessageIcon(NETDATA.icons.loading + ' netdata');
  5596. return true;
  5597. }
  5598. return false;
  5599. };
  5600. let createDOM = () => {
  5601. if (!this.enabled) {
  5602. return;
  5603. }
  5604. lateInitialization();
  5605. destroyDOM();
  5606. if (this.debug) {
  5607. this.log('createDOM()');
  5608. }
  5609. this.element_message = document.createElement('div');
  5610. this.element_message.className = 'netdata-message icon hidden';
  5611. this.element.appendChild(this.element_message);
  5612. this.dom_created = true;
  5613. this.chart_created = false;
  5614. this.tm.last_dom_created = this.tm.last_resized = Date.now();
  5615. showLoading();
  5616. };
  5617. const initDOM = () => {
  5618. this.element.className = this.library.container_class(that);
  5619. if (typeof(this.width) === 'string') {
  5620. this.element.style.width = this.width;
  5621. } else if (typeof(this.width) === 'number') {
  5622. this.element.style.width = this.width.toString() + 'px';
  5623. }
  5624. if (typeof(this.library.aspect_ratio) === 'undefined') {
  5625. if (typeof(this.height) === 'string') {
  5626. this.element.style.height = this.height;
  5627. } else if (typeof(this.height) === 'number') {
  5628. this.element.style.height = this.height.toString() + 'px';
  5629. }
  5630. }
  5631. if (NETDATA.chartDefaults.min_width !== null) {
  5632. this.element.style.min_width = NETDATA.chartDefaults.min_width;
  5633. }
  5634. };
  5635. const invisibleSearchableText = () => {
  5636. return '<span style="position:absolute; opacity: 0; width: 0px;">' + this.id + '</span>';
  5637. };
  5638. /* init() private
  5639. * initialize state variables
  5640. * destroy all (possibly) created state elements
  5641. * create the basic DOM for a chart
  5642. */
  5643. const init = (opt) => {
  5644. if (!this.enabled) {
  5645. return;
  5646. }
  5647. runtimeInit();
  5648. this.element.innerHTML = invisibleSearchableText();
  5649. this.tm.last_initialized = Date.now();
  5650. this.setMode('auto');
  5651. if (opt !== 'fast') {
  5652. if (this.isVisible(true) || opt === 'force') {
  5653. createDOM();
  5654. }
  5655. }
  5656. };
  5657. const hideMessage = () => {
  5658. if (typeof this.tmp.___messageHidden___ === 'undefined') {
  5659. this.tmp.___messageHidden___ = true;
  5660. $(this.element_message).addClass('hidden');
  5661. }
  5662. };
  5663. const showRendering = () => {
  5664. let icon;
  5665. if (this.chart !== null) {
  5666. if (this.chart.chart_type === 'line') {
  5667. icon = NETDATA.icons.lineChart;
  5668. } else {
  5669. icon = NETDATA.icons.areaChart;
  5670. }
  5671. }
  5672. else {
  5673. icon = NETDATA.icons.noChart;
  5674. }
  5675. showMessageIcon(icon + ' netdata' + invisibleSearchableText());
  5676. };
  5677. const isHidden = () => {
  5678. return (typeof this.tmp.___chartIsHidden___ !== 'undefined');
  5679. };
  5680. // hide the chart, when it is not visible - called from isVisible()
  5681. this.hideChart = function () {
  5682. // hide it, if it is not already hidden
  5683. if (isHidden()) {
  5684. return;
  5685. }
  5686. if (this.chart_created) {
  5687. if (NETDATA.options.current.show_help) {
  5688. if (this.element_legend_childs.toolbox !== null) {
  5689. if (this.debug) {
  5690. this.log('hideChart(): hiding legend popovers');
  5691. }
  5692. $(this.element_legend_childs.toolbox_left).popover('hide');
  5693. $(this.element_legend_childs.toolbox_reset).popover('hide');
  5694. $(this.element_legend_childs.toolbox_right).popover('hide');
  5695. $(this.element_legend_childs.toolbox_zoomin).popover('hide');
  5696. $(this.element_legend_childs.toolbox_zoomout).popover('hide');
  5697. }
  5698. if (this.element_legend_childs.resize_handler !== null) {
  5699. $(this.element_legend_childs.resize_handler).popover('hide');
  5700. }
  5701. if (this.element_legend_childs.content !== null) {
  5702. $(this.element_legend_childs.content).popover('hide');
  5703. }
  5704. }
  5705. if (NETDATA.options.current.destroy_on_hide) {
  5706. if (this.debug) {
  5707. this.log('hideChart(): initializing chart');
  5708. }
  5709. // we should destroy it
  5710. init('force');
  5711. } else {
  5712. if (this.debug) {
  5713. this.log('hideChart(): hiding chart');
  5714. }
  5715. showRendering();
  5716. this.element_chart.style.display = 'none';
  5717. this.element.style.willChange = 'auto';
  5718. if (this.element_legend !== null) {
  5719. this.element_legend.style.display = 'none';
  5720. }
  5721. if (this.element_legend_childs.toolbox !== null) {
  5722. this.element_legend_childs.toolbox.style.display = 'none';
  5723. }
  5724. if (this.element_legend_childs.resize_handler !== null) {
  5725. this.element_legend_childs.resize_handler.style.display = 'none';
  5726. }
  5727. this.tm.last_hidden = Date.now();
  5728. // de-allocate data
  5729. // This works, but I not sure there are no corner cases somewhere
  5730. // so it is commented - if the user has memory issues he can
  5731. // set Destroy on Hide for all charts
  5732. // this.data = null;
  5733. }
  5734. }
  5735. this.tmp.___chartIsHidden___ = true;
  5736. };
  5737. // unhide the chart, when it is visible - called from isVisible()
  5738. this.unhideChart = function () {
  5739. if (!isHidden()) {
  5740. return;
  5741. }
  5742. this.tmp.___chartIsHidden___ = undefined;
  5743. this.updates_since_last_unhide = 0;
  5744. if (!this.chart_created) {
  5745. if (this.debug) {
  5746. this.log('unhideChart(): initializing chart');
  5747. }
  5748. // we need to re-initialize it, to show our background
  5749. // logo in bootstrap tabs, until the chart loads
  5750. init('force');
  5751. } else {
  5752. if (this.debug) {
  5753. this.log('unhideChart(): unhiding chart');
  5754. }
  5755. this.element.style.willChange = 'transform';
  5756. this.tm.last_unhidden = Date.now();
  5757. this.element_chart.style.display = '';
  5758. if (this.element_legend !== null) {
  5759. this.element_legend.style.display = '';
  5760. }
  5761. if (this.element_legend_childs.toolbox !== null) {
  5762. this.element_legend_childs.toolbox.style.display = '';
  5763. }
  5764. if (this.element_legend_childs.resize_handler !== null) {
  5765. this.element_legend_childs.resize_handler.style.display = '';
  5766. }
  5767. resizeChart();
  5768. hideMessage();
  5769. }
  5770. if (this.__redraw_on_unhide) {
  5771. if (this.debug) {
  5772. this.log("redrawing chart on unhide");
  5773. }
  5774. this.__redraw_on_unhide = undefined;
  5775. this.redrawChart();
  5776. }
  5777. };
  5778. const canBeRendered = (uncached_visibility) => {
  5779. if (this.debug) {
  5780. this.log('canBeRendered() called');
  5781. }
  5782. if (!NETDATA.options.current.update_only_visible) {
  5783. return true;
  5784. }
  5785. let ret = (
  5786. (
  5787. NETDATA.options.page_is_visible ||
  5788. NETDATA.options.current.stop_updates_when_focus_is_lost === false ||
  5789. this.updates_since_last_unhide === 0
  5790. )
  5791. && isHidden() === false && this.isVisible(uncached_visibility)
  5792. );
  5793. if (this.debug) {
  5794. this.log('canBeRendered(): ' + ret);
  5795. }
  5796. return ret;
  5797. };
  5798. // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
  5799. const callChartLibraryUpdateSafely = (data) => {
  5800. let status;
  5801. // we should not do this here
  5802. // if we prevent rendering the chart then:
  5803. // 1. globalSelectionSync will be wrong
  5804. // 2. globalPanAndZoom will be wrong
  5805. //if (canBeRendered(true) === false)
  5806. // return false;
  5807. if (NETDATA.options.fake_chart_rendering) {
  5808. return true;
  5809. }
  5810. this.updates_counter++;
  5811. this.updates_since_last_unhide++;
  5812. this.updates_since_last_creation++;
  5813. if (NETDATA.options.debug.chart_errors) {
  5814. status = this.library.update(that, data);
  5815. } else {
  5816. try {
  5817. status = this.library.update(that, data);
  5818. } catch (err) {
  5819. status = false;
  5820. }
  5821. }
  5822. if (!status) {
  5823. error('chart failed to be updated as ' + this.library_name);
  5824. return false;
  5825. }
  5826. return true;
  5827. };
  5828. // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
  5829. const callChartLibraryCreateSafely = (data) => {
  5830. let status;
  5831. // we should not do this here
  5832. // if we prevent rendering the chart then:
  5833. // 1. globalSelectionSync will be wrong
  5834. // 2. globalPanAndZoom will be wrong
  5835. //if (canBeRendered(true) === false)
  5836. // return false;
  5837. if (NETDATA.options.fake_chart_rendering) {
  5838. return true;
  5839. }
  5840. this.updates_counter++;
  5841. this.updates_since_last_unhide++;
  5842. this.updates_since_last_creation++;
  5843. if (NETDATA.options.debug.chart_errors) {
  5844. status = this.library.create(that, data);
  5845. } else {
  5846. try {
  5847. status = this.library.create(that, data);
  5848. } catch (err) {
  5849. status = false;
  5850. }
  5851. }
  5852. if (!status) {
  5853. error('chart failed to be created as ' + this.library_name);
  5854. return false;
  5855. }
  5856. this.chart_created = true;
  5857. this.updates_since_last_creation = 0;
  5858. return true;
  5859. };
  5860. // ----------------------------------------------------------------------------------------------------------------
  5861. // Chart Resize
  5862. // resizeChart() - private
  5863. // to be called just before the chart library to make sure that
  5864. // a properly sized dom is available
  5865. const resizeChart = () => {
  5866. if (this.tm.last_resized < NETDATA.options.last_page_resize) {
  5867. if (!this.chart_created) {
  5868. return;
  5869. }
  5870. if (this.needsRecreation()) {
  5871. if (this.debug) {
  5872. this.log('resizeChart(): initializing chart');
  5873. }
  5874. init('force');
  5875. } else if (typeof this.library.resize === 'function') {
  5876. if (this.debug) {
  5877. this.log('resizeChart(): resizing chart');
  5878. }
  5879. this.library.resize(that);
  5880. if (this.element_legend_childs.perfect_scroller !== null) {
  5881. Ps.update(this.element_legend_childs.perfect_scroller);
  5882. }
  5883. maxMessageFontSize();
  5884. }
  5885. this.tm.last_resized = Date.now();
  5886. }
  5887. };
  5888. // this is the actual chart resize algorithm
  5889. // it will:
  5890. // - resize the entire container
  5891. // - update the internal states
  5892. // - resize the chart as the div changes height
  5893. // - update the scrollbar of the legend
  5894. const resizeChartToHeight = (h) => {
  5895. // console.log(h);
  5896. this.element.style.height = h;
  5897. if (this.settings_id !== null) {
  5898. NETDATA.localStorageSet('chart_heights.' + this.settings_id, h);
  5899. }
  5900. let now = Date.now();
  5901. NETDATA.options.last_page_scroll = now;
  5902. NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
  5903. // force a resize
  5904. this.tm.last_resized = 0;
  5905. resizeChart();
  5906. };
  5907. this.resizeForPrint = function () {
  5908. if (typeof this.element_legend_childs !== 'undefined' && this.element_legend_childs.perfect_scroller !== null) {
  5909. let current = this.element.clientHeight;
  5910. let optimal = current
  5911. + this.element_legend_childs.perfect_scroller.scrollHeight
  5912. - this.element_legend_childs.perfect_scroller.clientHeight;
  5913. if (optimal > current) {
  5914. // this.log('resized');
  5915. this.element.style.height = optimal + 'px';
  5916. this.library.resize(this);
  5917. }
  5918. }
  5919. };
  5920. this.resizeHandler = function (e) {
  5921. e.preventDefault();
  5922. if (typeof this.event_resize === 'undefined'
  5923. || this.event_resize.chart_original_w === 'undefined'
  5924. || this.event_resize.chart_original_h === 'undefined') {
  5925. this.event_resize = {
  5926. chart_original_w: this.element.clientWidth,
  5927. chart_original_h: this.element.clientHeight,
  5928. last: 0
  5929. };
  5930. }
  5931. if (e.type === 'touchstart') {
  5932. this.event_resize.mouse_start_x = e.touches.item(0).pageX;
  5933. this.event_resize.mouse_start_y = e.touches.item(0).pageY;
  5934. } else {
  5935. this.event_resize.mouse_start_x = e.clientX;
  5936. this.event_resize.mouse_start_y = e.clientY;
  5937. }
  5938. this.event_resize.chart_start_w = this.element.clientWidth;
  5939. this.event_resize.chart_start_h = this.element.clientHeight;
  5940. this.event_resize.chart_last_w = this.element.clientWidth;
  5941. this.event_resize.chart_last_h = this.element.clientHeight;
  5942. let now = Date.now();
  5943. if (now - this.event_resize.last <= NETDATA.options.current.double_click_speed && this.element_legend_childs.perfect_scroller !== null) {
  5944. // double click / double tap event
  5945. // console.dir(this.element_legend_childs.content);
  5946. // console.dir(this.element_legend_childs.perfect_scroller);
  5947. // the optimal height of the chart
  5948. // showing the entire legend
  5949. let optimal = this.event_resize.chart_last_h
  5950. + this.element_legend_childs.perfect_scroller.scrollHeight
  5951. - this.element_legend_childs.perfect_scroller.clientHeight;
  5952. // if we are not optimal, be optimal
  5953. if (this.event_resize.chart_last_h !== optimal) {
  5954. // this.log('resize to optimal, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString());
  5955. resizeChartToHeight(optimal.toString() + 'px');
  5956. }
  5957. // else if the current height is not the original/saved height
  5958. // reset to the original/saved height
  5959. else if (this.event_resize.chart_last_h !== this.event_resize.chart_original_h) {
  5960. // this.log('resize to original, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString());
  5961. resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
  5962. }
  5963. // else if the current height is not the internal default height
  5964. // reset to the internal default height
  5965. else if ((this.event_resize.chart_last_h.toString() + 'px') !== this.height_original) {
  5966. // this.log('resize to internal default, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString());
  5967. resizeChartToHeight(this.height_original.toString());
  5968. }
  5969. // else if the current height is not the firstchild's clientheight
  5970. // resize to it
  5971. else if (typeof this.element_legend_childs.perfect_scroller.firstChild !== 'undefined') {
  5972. let parent_rect = this.element.getBoundingClientRect();
  5973. let content_rect = this.element_legend_childs.perfect_scroller.firstElementChild.getBoundingClientRect();
  5974. let wanted = content_rect.top - parent_rect.top + this.element_legend_childs.perfect_scroller.firstChild.clientHeight + 18; // 15 = toolbox + 3 space
  5975. // console.log(parent_rect);
  5976. // console.log(content_rect);
  5977. // console.log(wanted);
  5978. // this.log('resize to firstChild, current = ' + this.event_resize.chart_last_h.toString() + 'px, original = ' + this.event_resize.chart_original_h.toString() + 'px, optimal = ' + optimal.toString() + 'px, internal = ' + this.height_original.toString() + 'px, firstChild = ' + wanted.toString() + 'px' );
  5979. if (this.event_resize.chart_last_h !== wanted) {
  5980. resizeChartToHeight(wanted.toString() + 'px');
  5981. }
  5982. }
  5983. } else {
  5984. this.event_resize.last = now;
  5985. // process movement event
  5986. document.onmousemove =
  5987. document.ontouchmove =
  5988. this.element_legend_childs.resize_handler.onmousemove =
  5989. this.element_legend_childs.resize_handler.ontouchmove =
  5990. function (e) {
  5991. let y = null;
  5992. switch (e.type) {
  5993. case 'mousemove':
  5994. y = e.clientY;
  5995. break;
  5996. case 'touchmove':
  5997. y = e.touches.item(e.touches - 1).pageY;
  5998. break;
  5999. }
  6000. if (y !== null) {
  6001. let newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
  6002. if (newH >= 70 && newH !== that.event_resize.chart_last_h) {
  6003. resizeChartToHeight(newH.toString() + 'px');
  6004. that.event_resize.chart_last_h = newH;
  6005. }
  6006. }
  6007. };
  6008. // process end event
  6009. document.onmouseup =
  6010. document.ontouchend =
  6011. this.element_legend_childs.resize_handler.onmouseup =
  6012. this.element_legend_childs.resize_handler.ontouchend =
  6013. function (e) {
  6014. void(e);
  6015. // remove all the hooks
  6016. document.onmouseup =
  6017. document.onmousemove =
  6018. document.ontouchmove =
  6019. document.ontouchend =
  6020. that.element_legend_childs.resize_handler.onmousemove =
  6021. that.element_legend_childs.resize_handler.ontouchmove =
  6022. that.element_legend_childs.resize_handler.onmouseout =
  6023. that.element_legend_childs.resize_handler.onmouseup =
  6024. that.element_legend_childs.resize_handler.ontouchend =
  6025. null;
  6026. // allow auto-refreshes
  6027. NETDATA.options.auto_refresher_stop_until = 0;
  6028. };
  6029. }
  6030. };
  6031. const noDataToShow = () => {
  6032. showMessageIcon(NETDATA.icons.noData + ' empty');
  6033. this.legendUpdateDOM();
  6034. this.tm.last_autorefreshed = Date.now();
  6035. // this.data_update_every = 30 * 1000;
  6036. //this.element_chart.style.display = 'none';
  6037. //if (this.element_legend !== null) this.element_legend.style.display = 'none';
  6038. //this.tmp.___chartIsHidden___ = true;
  6039. };
  6040. // ============================================================================================================
  6041. // PUBLIC FUNCTIONS
  6042. this.error = function (msg) {
  6043. error(msg);
  6044. };
  6045. this.setMode = function (m) {
  6046. if (this.current !== null && this.current.name === m) {
  6047. return;
  6048. }
  6049. if (m === 'auto') {
  6050. this.current = this.auto;
  6051. } else if (m === 'pan') {
  6052. this.current = this.pan;
  6053. } else if (m === 'zoom') {
  6054. this.current = this.zoom;
  6055. } else {
  6056. this.current = this.auto;
  6057. }
  6058. this.current.force_update_at = 0;
  6059. this.current.force_before_ms = null;
  6060. this.current.force_after_ms = null;
  6061. this.tm.last_mode_switch = Date.now();
  6062. };
  6063. // ----------------------------------------------------------------------------------------------------------------
  6064. // global selection sync for slaves
  6065. // can the chart participate to the global selection sync as a slave?
  6066. this.globalSelectionSyncIsEligible = function () {
  6067. return (
  6068. this.enabled &&
  6069. this.library !== null &&
  6070. typeof this.library.setSelection === 'function' &&
  6071. this.isVisible() &&
  6072. this.chart_created
  6073. );
  6074. };
  6075. this.setSelection = function (t) {
  6076. if (typeof this.library.setSelection === 'function') {
  6077. // this.selected = this.library.setSelection(this, t) === true;
  6078. this.selected = this.library.setSelection(this, t);
  6079. } else {
  6080. this.selected = true;
  6081. }
  6082. if (this.selected && this.debug) {
  6083. this.log('selection set to ' + t.toString());
  6084. }
  6085. if (this.foreignElementSelection !== null) {
  6086. this.foreignElementSelection.innerText = NETDATA.dateTime.localeDateString(t) + ' ' + NETDATA.dateTime.localeTimeString(t);
  6087. }
  6088. return this.selected;
  6089. };
  6090. this.clearSelection = function () {
  6091. if (this.selected) {
  6092. if (typeof this.library.clearSelection === 'function') {
  6093. this.selected = (this.library.clearSelection(this) !== true);
  6094. } else {
  6095. this.selected = false;
  6096. }
  6097. if (this.selected === false && this.debug) {
  6098. this.log('selection cleared');
  6099. }
  6100. if (this.foreignElementSelection !== null) {
  6101. this.foreignElementSelection.innerText = '';
  6102. }
  6103. this.legendReset();
  6104. }
  6105. return this.selected;
  6106. };
  6107. // ----------------------------------------------------------------------------------------------------------------
  6108. // find if a timestamp (ms) is shown in the current chart
  6109. this.timeIsVisible = function (t) {
  6110. return (t >= this.data_after && t <= this.data_before);
  6111. };
  6112. this.calculateRowForTime = function (t) {
  6113. if (!this.timeIsVisible(t)) {
  6114. return -1;
  6115. }
  6116. return Math.floor((t - this.data_after) / this.data_update_every);
  6117. };
  6118. // ----------------------------------------------------------------------------------------------------------------
  6119. this.pauseChart = function () {
  6120. if (!this.paused) {
  6121. if (this.debug) {
  6122. this.log('pauseChart()');
  6123. }
  6124. this.paused = true;
  6125. }
  6126. };
  6127. this.unpauseChart = function () {
  6128. if (this.paused) {
  6129. if (this.debug) {
  6130. this.log('unpauseChart()');
  6131. }
  6132. this.paused = false;
  6133. }
  6134. };
  6135. this.resetChart = function (dontClearMaster, dontUpdate) {
  6136. if (this.debug) {
  6137. this.log('resetChart(' + dontClearMaster + ', ' + dontUpdate + ') called');
  6138. }
  6139. if (typeof dontClearMaster === 'undefined') {
  6140. dontClearMaster = false;
  6141. }
  6142. if (typeof dontUpdate === 'undefined') {
  6143. dontUpdate = false;
  6144. }
  6145. if (dontClearMaster !== true && NETDATA.globalPanAndZoom.isMaster(this)) {
  6146. if (this.debug) {
  6147. this.log('resetChart() diverting to clearMaster().');
  6148. }
  6149. // this will call us back with master === true
  6150. NETDATA.globalPanAndZoom.clearMaster();
  6151. return;
  6152. }
  6153. this.clearSelection();
  6154. this.tm.pan_and_zoom_seq = 0;
  6155. this.setMode('auto');
  6156. this.current.force_update_at = 0;
  6157. this.current.force_before_ms = null;
  6158. this.current.force_after_ms = null;
  6159. this.tm.last_autorefreshed = 0;
  6160. this.paused = false;
  6161. this.selected = false;
  6162. this.enabled = true;
  6163. // this.debug = false;
  6164. // do not update the chart here
  6165. // or the chart will flip-flop when it is the master
  6166. // of a selection sync and another chart becomes
  6167. // the new master
  6168. if (dontUpdate !== true && this.isVisible()) {
  6169. this.updateChart();
  6170. }
  6171. };
  6172. this.updateChartPanOrZoom = function (after, before, callback) {
  6173. let logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
  6174. let ret = true;
  6175. NETDATA.globalPanAndZoom.delay();
  6176. NETDATA.globalSelectionSync.delay();
  6177. if (this.debug) {
  6178. this.log(logme);
  6179. }
  6180. if (before < after) {
  6181. if (this.debug) {
  6182. this.log(logme + 'flipped parameters, rejecting it.');
  6183. }
  6184. return false;
  6185. }
  6186. if (typeof this.fixed_min_duration === 'undefined') {
  6187. this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
  6188. }
  6189. let min_duration = this.fixed_min_duration;
  6190. let current_duration = Math.round(this.view_before - this.view_after);
  6191. // round the numbers
  6192. after = Math.round(after);
  6193. before = Math.round(before);
  6194. // align them to update_every
  6195. // stretching them further away
  6196. after -= after % this.data_update_every;
  6197. before += this.data_update_every - (before % this.data_update_every);
  6198. // the final wanted duration
  6199. let wanted_duration = before - after;
  6200. // to allow panning, accept just a point below our minimum
  6201. if ((current_duration - this.data_update_every) < min_duration) {
  6202. min_duration = current_duration - this.data_update_every;
  6203. }
  6204. // we do it, but we adjust to minimum size and return false
  6205. // when the wanted size is below the current and the minimum
  6206. // and we zoom
  6207. if (wanted_duration < current_duration && wanted_duration < min_duration) {
  6208. if (this.debug) {
  6209. this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
  6210. }
  6211. min_duration = this.fixed_min_duration;
  6212. let dt = (min_duration - wanted_duration) / 2;
  6213. before += dt;
  6214. after -= dt;
  6215. wanted_duration = before - after;
  6216. ret = false;
  6217. }
  6218. let tolerance = this.data_update_every * 2;
  6219. let movement = Math.abs(before - this.view_before);
  6220. if (Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance && ret) {
  6221. if (this.debug) {
  6222. this.log(logme + 'REJECTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false);
  6223. }
  6224. return false;
  6225. }
  6226. if (this.current.name === 'auto') {
  6227. this.log(logme + 'caller called me with mode: ' + this.current.name);
  6228. this.setMode('pan');
  6229. }
  6230. if (this.debug) {
  6231. this.log(logme + 'ACCEPTING UPDATE: current/min duration: ' + (current_duration / 1000).toString() + '/' + (this.fixed_min_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret);
  6232. }
  6233. this.current.force_update_at = Date.now() + NETDATA.options.current.pan_and_zoom_delay;
  6234. this.current.force_after_ms = after;
  6235. this.current.force_before_ms = before;
  6236. NETDATA.globalPanAndZoom.setMaster(this, after, before);
  6237. if (ret && typeof callback === 'function') {
  6238. callback();
  6239. }
  6240. return ret;
  6241. };
  6242. this.updateChartPanOrZoomAsyncTimeOutId = undefined;
  6243. this.updateChartPanOrZoomAsync = function (after, before, callback) {
  6244. NETDATA.globalPanAndZoom.delay();
  6245. NETDATA.globalSelectionSync.delay();
  6246. if (!NETDATA.globalPanAndZoom.isMaster(this)) {
  6247. this.pauseChart();
  6248. NETDATA.globalPanAndZoom.setMaster(this, after, before);
  6249. // NETDATA.globalSelectionSync.stop();
  6250. NETDATA.globalSelectionSync.setMaster(this);
  6251. }
  6252. if (this.updateChartPanOrZoomAsyncTimeOutId) {
  6253. NETDATA.timeout.clear(this.updateChartPanOrZoomAsyncTimeOutId);
  6254. }
  6255. NETDATA.timeout.set(function () {
  6256. that.updateChartPanOrZoomAsyncTimeOutId = undefined;
  6257. that.updateChartPanOrZoom(after, before, callback);
  6258. }, 0);
  6259. };
  6260. let _unitsConversionLastUnits = undefined;
  6261. let _unitsConversionLastUnitsDesired = undefined;
  6262. let _unitsConversionLastMin = undefined;
  6263. let _unitsConversionLastMax = undefined;
  6264. let _unitsConversion = function (value) {
  6265. return value;
  6266. };
  6267. this.unitsConversionSetup = function (min, max) {
  6268. if (this.units !== _unitsConversionLastUnits
  6269. || this.units_desired !== _unitsConversionLastUnitsDesired
  6270. || min !== _unitsConversionLastMin
  6271. || max !== _unitsConversionLastMax) {
  6272. _unitsConversionLastUnits = this.units;
  6273. _unitsConversionLastUnitsDesired = this.units_desired;
  6274. _unitsConversionLastMin = min;
  6275. _unitsConversionLastMax = max;
  6276. _unitsConversion = NETDATA.unitsConversion.get(this.uuid, min, max, this.units, this.units_desired, this.units_common, function (units) {
  6277. // console.log('switching units from ' + that.units.toString() + ' to ' + units.toString());
  6278. that.units_current = units;
  6279. that.legendSetUnitsString(that.units_current);
  6280. });
  6281. }
  6282. };
  6283. let _legendFormatValueChartDecimalsLastMin = undefined;
  6284. let _legendFormatValueChartDecimalsLastMax = undefined;
  6285. let _legendFormatValueChartDecimals = -1;
  6286. let _intlNumberFormat = null;
  6287. this.legendFormatValueDecimalsFromMinMax = function (min, max) {
  6288. if (min === _legendFormatValueChartDecimalsLastMin && max === _legendFormatValueChartDecimalsLastMax) {
  6289. return;
  6290. }
  6291. this.unitsConversionSetup(min, max);
  6292. if (_unitsConversion !== null) {
  6293. min = _unitsConversion(min);
  6294. max = _unitsConversion(max);
  6295. if (typeof min !== 'number' || typeof max !== 'number') {
  6296. return;
  6297. }
  6298. }
  6299. _legendFormatValueChartDecimalsLastMin = min;
  6300. _legendFormatValueChartDecimalsLastMax = max;
  6301. let old = _legendFormatValueChartDecimals;
  6302. if (this.data !== null && this.data.min === this.data.max)
  6303. // it is a fixed number, let the visualizer decide based on the value
  6304. {
  6305. _legendFormatValueChartDecimals = -1;
  6306. } else if (this.value_decimal_detail !== -1)
  6307. // there is an override
  6308. {
  6309. _legendFormatValueChartDecimals = this.value_decimal_detail;
  6310. } else {
  6311. // ok, let's calculate the proper number of decimal points
  6312. let delta;
  6313. if (min === max) {
  6314. delta = Math.abs(min);
  6315. } else {
  6316. delta = Math.abs(max - min);
  6317. }
  6318. if (delta > 1000) {
  6319. _legendFormatValueChartDecimals = 0;
  6320. } else if (delta > 10) {
  6321. _legendFormatValueChartDecimals = 1;
  6322. } else if (delta > 1) {
  6323. _legendFormatValueChartDecimals = 2;
  6324. } else if (delta > 0.1) {
  6325. _legendFormatValueChartDecimals = 2;
  6326. } else if (delta > 0.01) {
  6327. _legendFormatValueChartDecimals = 4;
  6328. } else if (delta > 0.001) {
  6329. _legendFormatValueChartDecimals = 5;
  6330. } else if (delta > 0.0001) {
  6331. _legendFormatValueChartDecimals = 6;
  6332. } else {
  6333. _legendFormatValueChartDecimals = 7;
  6334. }
  6335. }
  6336. if (_legendFormatValueChartDecimals !== old) {
  6337. if (_legendFormatValueChartDecimals < 0) {
  6338. _intlNumberFormat = null;
  6339. } else {
  6340. _intlNumberFormat = NETDATA.fastNumberFormat.get(
  6341. _legendFormatValueChartDecimals,
  6342. _legendFormatValueChartDecimals
  6343. );
  6344. }
  6345. }
  6346. };
  6347. this.legendFormatValue = function (value) {
  6348. if (typeof value !== 'number') {
  6349. return '-';
  6350. }
  6351. value = _unitsConversion(value);
  6352. if (typeof value !== 'number') {
  6353. return value;
  6354. }
  6355. if (_intlNumberFormat !== null) {
  6356. return _intlNumberFormat.format(value);
  6357. }
  6358. let dmin, dmax;
  6359. if (this.value_decimal_detail !== -1) {
  6360. dmin = dmax = this.value_decimal_detail;
  6361. } else {
  6362. dmin = 0;
  6363. let abs = (value < 0) ? -value : value;
  6364. if (abs > 1000) {
  6365. dmax = 0;
  6366. } else if (abs > 10) {
  6367. dmax = 1;
  6368. } else if (abs > 1) {
  6369. dmax = 2;
  6370. } else if (abs > 0.1) {
  6371. dmax = 2;
  6372. } else if (abs > 0.01) {
  6373. dmax = 4;
  6374. } else if (abs > 0.001) {
  6375. dmax = 5;
  6376. } else if (abs > 0.0001) {
  6377. dmax = 6;
  6378. } else {
  6379. dmax = 7;
  6380. }
  6381. }
  6382. return NETDATA.fastNumberFormat.get(dmin, dmax).format(value);
  6383. };
  6384. this.legendSetLabelValue = function (label, value) {
  6385. let series = this.element_legend_childs.series[label];
  6386. if (typeof series === 'undefined') {
  6387. return;
  6388. }
  6389. if (series.value === null && series.user === null) {
  6390. return;
  6391. }
  6392. /*
  6393. // this slows down firefox and edge significantly
  6394. // since it requires to use innerHTML(), instead of innerText()
  6395. // if the value has not changed, skip DOM update
  6396. //if (series.last === value) return;
  6397. let s, r;
  6398. if (typeof value === 'number') {
  6399. let v = Math.abs(value);
  6400. s = r = this.legendFormatValue(value);
  6401. if (typeof series.last === 'number') {
  6402. if (v > series.last) s += '<i class="fas fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
  6403. else if (v < series.last) s += '<i class="fas fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
  6404. else s += '<i class="fas fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
  6405. }
  6406. else s += '<i class="fas fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
  6407. series.last = v;
  6408. }
  6409. else {
  6410. if (value === null)
  6411. s = r = '';
  6412. else
  6413. s = r = value;
  6414. series.last = value;
  6415. }
  6416. */
  6417. let s = this.legendFormatValue(value);
  6418. // caching: do not update the update to show the same value again
  6419. if (s === series.last_shown_value) {
  6420. return;
  6421. }
  6422. series.last_shown_value = s;
  6423. if (series.value !== null) {
  6424. series.value.innerText = s;
  6425. }
  6426. if (series.user !== null) {
  6427. series.user.innerText = s;
  6428. }
  6429. };
  6430. this.legendSetDateString = function (date) {
  6431. if (this.element_legend_childs.title_date !== null && date !== this.tmp.__last_shown_legend_date) {
  6432. this.element_legend_childs.title_date.innerText = date;
  6433. this.tmp.__last_shown_legend_date = date;
  6434. }
  6435. };
  6436. this.legendSetTimeString = function (time) {
  6437. if (this.element_legend_childs.title_time !== null && time !== this.tmp.__last_shown_legend_time) {
  6438. this.element_legend_childs.title_time.innerText = time;
  6439. this.tmp.__last_shown_legend_time = time;
  6440. }
  6441. };
  6442. this.legendSetUnitsString = function (units) {
  6443. if (this.element_legend_childs.title_units !== null && units !== this.tmp.__last_shown_legend_units) {
  6444. this.element_legend_childs.title_units.innerText = units;
  6445. this.tmp.__last_shown_legend_units = units;
  6446. }
  6447. };
  6448. this.legendSetDateLast = {
  6449. ms: 0,
  6450. date: undefined,
  6451. time: undefined
  6452. };
  6453. this.legendSetDate = function (ms) {
  6454. if (typeof ms !== 'number') {
  6455. this.legendShowUndefined();
  6456. return;
  6457. }
  6458. if (this.legendSetDateLast.ms !== ms) {
  6459. let d = new Date(ms);
  6460. this.legendSetDateLast.ms = ms;
  6461. this.legendSetDateLast.date = NETDATA.dateTime.localeDateString(d);
  6462. this.legendSetDateLast.time = NETDATA.dateTime.localeTimeString(d);
  6463. }
  6464. this.legendSetDateString(this.legendSetDateLast.date);
  6465. this.legendSetTimeString(this.legendSetDateLast.time);
  6466. this.legendSetUnitsString(this.units_current)
  6467. };
  6468. this.legendShowUndefined = function () {
  6469. this.legendSetDateString(this.legendPluginModuleString(false));
  6470. this.legendSetTimeString(this.chart.context.toString());
  6471. // this.legendSetUnitsString(' ');
  6472. if (this.data && this.element_legend_childs.series !== null) {
  6473. let labels = this.data.dimension_names;
  6474. let i = labels.length;
  6475. while (i--) {
  6476. let label = labels[i];
  6477. if (typeof label === 'undefined' || typeof this.element_legend_childs.series[label] === 'undefined') {
  6478. continue;
  6479. }
  6480. this.legendSetLabelValue(label, null);
  6481. }
  6482. }
  6483. };
  6484. this.legendShowLatestValues = function () {
  6485. if (this.chart === null) {
  6486. return;
  6487. }
  6488. if (this.selected) {
  6489. return;
  6490. }
  6491. if (this.data === null || this.element_legend_childs.series === null) {
  6492. this.legendShowUndefined();
  6493. return;
  6494. }
  6495. let show_undefined = true;
  6496. if (Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
  6497. show_undefined = false;
  6498. }
  6499. if (show_undefined) {
  6500. this.legendShowUndefined();
  6501. return;
  6502. }
  6503. this.legendSetDate(this.view_before);
  6504. let labels = this.data.dimension_names;
  6505. let i = labels.length;
  6506. while (i--) {
  6507. let label = labels[i];
  6508. if (typeof label === 'undefined') {
  6509. continue;
  6510. }
  6511. if (typeof this.element_legend_childs.series[label] === 'undefined') {
  6512. continue;
  6513. }
  6514. this.legendSetLabelValue(label, this.data.view_latest_values[i]);
  6515. }
  6516. };
  6517. this.legendReset = function () {
  6518. this.legendShowLatestValues();
  6519. };
  6520. // this should be called just ONCE per dimension per chart
  6521. this.__chartDimensionColor = function (label) {
  6522. let c = NETDATA.commonColors.get(this, label);
  6523. // it is important to maintain a list of colors
  6524. // for this chart only, since the chart library
  6525. // uses this to assign colors to dimensions in the same
  6526. // order the dimension are given to it
  6527. this.colors.push(c);
  6528. return c;
  6529. };
  6530. this.chartPrepareColorPalette = function () {
  6531. NETDATA.commonColors.refill(this);
  6532. };
  6533. // get the ordered list of chart colors
  6534. // this includes user defined colors
  6535. this.chartCustomColors = function () {
  6536. this.chartPrepareColorPalette();
  6537. let colors;
  6538. if (this.colors_custom.length) {
  6539. colors = this.colors_custom;
  6540. } else {
  6541. colors = this.colors;
  6542. }
  6543. if (this.debug) {
  6544. this.log("chartCustomColors() returns:");
  6545. this.log(colors);
  6546. }
  6547. return colors;
  6548. };
  6549. // get the ordered list of chart ASSIGNED colors
  6550. // (this returns only the colors that have been
  6551. // assigned to dimensions, prepended with any
  6552. // custom colors defined)
  6553. this.chartColors = function () {
  6554. this.chartPrepareColorPalette();
  6555. if (this.debug) {
  6556. this.log("chartColors() returns:");
  6557. this.log(this.colors);
  6558. }
  6559. return this.colors;
  6560. };
  6561. this.legendPluginModuleString = function (withContext) {
  6562. let str = ' ';
  6563. let context = '';
  6564. if (typeof this.chart !== 'undefined') {
  6565. if (withContext && typeof this.chart.context === 'string') {
  6566. context = this.chart.context;
  6567. }
  6568. if (typeof this.chart.plugin === 'string' && this.chart.plugin !== '') {
  6569. str = this.chart.plugin;
  6570. if (str.endsWith(".plugin")) {
  6571. str = str.substring(0, str.length - 7);
  6572. }
  6573. if (typeof this.chart.module === 'string' && this.chart.module !== '') {
  6574. str += ':' + this.chart.module;
  6575. }
  6576. if (withContext && context !== '') {
  6577. str += ', ' + context;
  6578. }
  6579. }
  6580. else if (withContext && context !== '') {
  6581. str = context;
  6582. }
  6583. }
  6584. return str;
  6585. };
  6586. this.legendResolutionTooltip = function () {
  6587. if (!this.chart) {
  6588. return '';
  6589. }
  6590. let collected = this.chart.update_every;
  6591. let viewed = (this.data) ? this.data.view_update_every : collected;
  6592. if (collected === viewed) {
  6593. return "resolution " + NETDATA.seconds4human(collected);
  6594. }
  6595. return "resolution " + NETDATA.seconds4human(viewed) + ", collected every " + NETDATA.seconds4human(collected);
  6596. };
  6597. this.legendUpdateDOM = function () {
  6598. let needed = false, dim, keys, len;
  6599. // check that the legend DOM is up to date for the downloaded dimensions
  6600. if (typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
  6601. // this.log('the legend does not have any series - requesting legend update');
  6602. needed = true;
  6603. } else if (this.data === null) {
  6604. // this.log('the chart does not have any data - requesting legend update');
  6605. needed = true;
  6606. } else if (typeof this.element_legend_childs.series.labels_key === 'undefined') {
  6607. needed = true;
  6608. } else {
  6609. let labels = this.data.dimension_names.toString();
  6610. if (labels !== this.element_legend_childs.series.labels_key) {
  6611. needed = true;
  6612. if (this.debug) {
  6613. this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
  6614. }
  6615. }
  6616. }
  6617. if (!needed) {
  6618. // make sure colors available
  6619. this.chartPrepareColorPalette();
  6620. // do we have to update the current values?
  6621. // we do this, only when the visible chart is current
  6622. if (Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
  6623. if (this.debug) {
  6624. this.log('chart is in latest position... updating values on legend...');
  6625. }
  6626. //let labels = this.data.dimension_names;
  6627. //let i = labels.length;
  6628. //while (i--)
  6629. // this.legendSetLabelValue(labels[i], this.data.view_latest_values[i]);
  6630. }
  6631. return;
  6632. }
  6633. if (this.colors === null) {
  6634. // this is the first time we update the chart
  6635. // let's assign colors to all dimensions
  6636. if (this.library.track_colors()) {
  6637. this.colors = [];
  6638. keys = Object.keys(this.chart.dimensions);
  6639. len = keys.length;
  6640. for (let i = 0; i < len; i++) {
  6641. NETDATA.commonColors.get(this, this.chart.dimensions[keys[i]].name);
  6642. }
  6643. }
  6644. }
  6645. // we will re-generate the colors for the chart
  6646. // based on the dimensions this result has data for
  6647. this.colors = [];
  6648. if (this.debug) {
  6649. this.log('updating Legend DOM');
  6650. }
  6651. // mark all dimensions as invalid
  6652. this.dimensions_visibility.invalidateAll();
  6653. const genLabel = function (state, parent, dim, name, count) {
  6654. let color = state.__chartDimensionColor(name);
  6655. let user_element = null;
  6656. let user_id = NETDATA.dataAttribute(state.element, 'show-value-of-' + name.toLowerCase() + '-at', null);
  6657. if (user_id === null) {
  6658. user_id = NETDATA.dataAttribute(state.element, 'show-value-of-' + dim.toLowerCase() + '-at', null);
  6659. }
  6660. if (user_id !== null) {
  6661. user_element = document.getElementById(user_id) || null;
  6662. if (user_element === null) {
  6663. state.log('Cannot find element with id: ' + user_id);
  6664. }
  6665. }
  6666. state.element_legend_childs.series[name] = {
  6667. name: document.createElement('span'),
  6668. value: document.createElement('span'),
  6669. user: user_element,
  6670. last: null,
  6671. last_shown_value: null
  6672. };
  6673. let label = state.element_legend_childs.series[name];
  6674. // create the dimension visibility tracking for this label
  6675. state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
  6676. let rgb = NETDATA.colorHex2Rgb(color);
  6677. label.name.innerHTML = '<table class="netdata-legend-name-table-'
  6678. + state.chart.chart_type
  6679. + '" style="background-color: '
  6680. + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ') !important'
  6681. + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>';
  6682. let text = document.createTextNode(' ' + name);
  6683. label.name.appendChild(text);
  6684. if (count > 0) {
  6685. parent.appendChild(document.createElement('br'));
  6686. }
  6687. parent.appendChild(label.name);
  6688. parent.appendChild(label.value);
  6689. };
  6690. let content = document.createElement('div');
  6691. if (this.element_chart === null) {
  6692. this.element_chart = document.createElement('div');
  6693. this.element_chart.id = this.library_name + '-' + this.uuid + '-chart';
  6694. this.element.appendChild(this.element_chart);
  6695. if (this.hasLegend()) {
  6696. this.element_chart.className = 'netdata-chart-with-legend-right netdata-' + this.library_name + '-chart-with-legend-right';
  6697. } else {
  6698. this.element_chart.className = ' netdata-chart netdata-' + this.library_name + '-chart';
  6699. }
  6700. }
  6701. if (this.hasLegend()) {
  6702. if (this.element_legend === null) {
  6703. this.element_legend = document.createElement('div');
  6704. this.element_legend.className = 'netdata-chart-legend netdata-' + this.library_name + '-legend';
  6705. this.element.appendChild(this.element_legend);
  6706. } else {
  6707. this.element_legend.innerHTML = '';
  6708. }
  6709. this.element_legend_childs = {
  6710. content: content,
  6711. resize_handler: null,
  6712. toolbox: null,
  6713. toolbox_left: null,
  6714. toolbox_right: null,
  6715. toolbox_reset: null,
  6716. toolbox_zoomin: null,
  6717. toolbox_zoomout: null,
  6718. toolbox_volume: null,
  6719. title_date: document.createElement('span'),
  6720. title_time: document.createElement('span'),
  6721. title_units: document.createElement('span'),
  6722. perfect_scroller: document.createElement('div'),
  6723. series: {}
  6724. };
  6725. if (NETDATA.options.current.legend_toolbox && this.library.toolboxPanAndZoom !== null) {
  6726. this.element_legend_childs.toolbox = document.createElement('div');
  6727. this.element_legend_childs.toolbox_left = document.createElement('div');
  6728. this.element_legend_childs.toolbox_right = document.createElement('div');
  6729. this.element_legend_childs.toolbox_reset = document.createElement('div');
  6730. this.element_legend_childs.toolbox_zoomin = document.createElement('div');
  6731. this.element_legend_childs.toolbox_zoomout = document.createElement('div');
  6732. this.element_legend_childs.toolbox_volume = document.createElement('div');
  6733. const getPanAndZoomStep = function (event) {
  6734. if (event.ctrlKey) {
  6735. return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_control;
  6736. } else if (event.shiftKey) {
  6737. return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_shift;
  6738. } else if (event.altKey) {
  6739. return NETDATA.options.current.pan_and_zoom_factor * NETDATA.options.current.pan_and_zoom_factor_multiplier_alt;
  6740. } else {
  6741. return NETDATA.options.current.pan_and_zoom_factor;
  6742. }
  6743. };
  6744. this.element_legend_childs.toolbox.className += ' netdata-legend-toolbox';
  6745. this.element.appendChild(this.element_legend_childs.toolbox);
  6746. this.element_legend_childs.toolbox_left.className += ' netdata-legend-toolbox-button';
  6747. this.element_legend_childs.toolbox_left.innerHTML = NETDATA.icons.left;
  6748. this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_left);
  6749. this.element_legend_childs.toolbox_left.onclick = function (e) {
  6750. e.preventDefault();
  6751. let step = (that.view_before - that.view_after) * getPanAndZoomStep(e);
  6752. let before = that.view_before - step;
  6753. let after = that.view_after - step;
  6754. if (after >= that.netdata_first) {
  6755. that.library.toolboxPanAndZoom(that, after, before);
  6756. }
  6757. };
  6758. if (NETDATA.options.current.show_help) {
  6759. $(this.element_legend_childs.toolbox_left).popover({
  6760. container: "body",
  6761. animation: false,
  6762. html: true,
  6763. trigger: 'hover',
  6764. placement: 'bottom',
  6765. delay: {
  6766. show: NETDATA.options.current.show_help_delay_show_ms,
  6767. hide: NETDATA.options.current.show_help_delay_hide_ms
  6768. },
  6769. title: 'Pan Left',
  6770. content: 'Pan the chart to the left. You can also <b>drag it</b> with your mouse or your finger (on touch devices).<br/><small>Help can be disabled from the settings.</small>'
  6771. });
  6772. }
  6773. this.element_legend_childs.toolbox_reset.className += ' netdata-legend-toolbox-button';
  6774. this.element_legend_childs.toolbox_reset.innerHTML = NETDATA.icons.reset;
  6775. this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_reset);
  6776. this.element_legend_childs.toolbox_reset.onclick = function (e) {
  6777. e.preventDefault();
  6778. NETDATA.resetAllCharts(that);
  6779. };
  6780. if (NETDATA.options.current.show_help) {
  6781. $(this.element_legend_childs.toolbox_reset).popover({
  6782. container: "body",
  6783. animation: false,
  6784. html: true,
  6785. trigger: 'hover',
  6786. placement: 'bottom',
  6787. delay: {
  6788. show: NETDATA.options.current.show_help_delay_show_ms,
  6789. hide: NETDATA.options.current.show_help_delay_hide_ms
  6790. },
  6791. title: 'Chart Reset',
  6792. content: 'Reset all the charts to their default auto-refreshing state. You can also <b>double click</b> the chart contents with your mouse or your finger (on touch devices).<br/><small>Help can be disabled from the settings.</small>'
  6793. });
  6794. }
  6795. this.element_legend_childs.toolbox_right.className += ' netdata-legend-toolbox-button';
  6796. this.element_legend_childs.toolbox_right.innerHTML = NETDATA.icons.right;
  6797. this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_right);
  6798. this.element_legend_childs.toolbox_right.onclick = function (e) {
  6799. e.preventDefault();
  6800. let step = (that.view_before - that.view_after) * getPanAndZoomStep(e);
  6801. let before = that.view_before + step;
  6802. let after = that.view_after + step;
  6803. if (before <= that.netdata_last) {
  6804. that.library.toolboxPanAndZoom(that, after, before);
  6805. }
  6806. };
  6807. if (NETDATA.options.current.show_help) {
  6808. $(this.element_legend_childs.toolbox_right).popover({
  6809. container: "body",
  6810. animation: false,
  6811. html: true,
  6812. trigger: 'hover',
  6813. placement: 'bottom',
  6814. delay: {
  6815. show: NETDATA.options.current.show_help_delay_show_ms,
  6816. hide: NETDATA.options.current.show_help_delay_hide_ms
  6817. },
  6818. title: 'Pan Right',
  6819. content: 'Pan the chart to the right. You can also <b>drag it</b> with your mouse or your finger (on touch devices).<br/><small>Help can be disabled from the settings.</small>'
  6820. });
  6821. }
  6822. this.element_legend_childs.toolbox_zoomin.className += ' netdata-legend-toolbox-button';
  6823. this.element_legend_childs.toolbox_zoomin.innerHTML = NETDATA.icons.zoomIn;
  6824. this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_zoomin);
  6825. this.element_legend_childs.toolbox_zoomin.onclick = function (e) {
  6826. e.preventDefault();
  6827. let dt = ((that.view_before - that.view_after) * (getPanAndZoomStep(e) * 0.8) / 2);
  6828. let before = that.view_before - dt;
  6829. let after = that.view_after + dt;
  6830. that.library.toolboxPanAndZoom(that, after, before);
  6831. };
  6832. if (NETDATA.options.current.show_help) {
  6833. $(this.element_legend_childs.toolbox_zoomin).popover({
  6834. container: "body",
  6835. animation: false,
  6836. html: true,
  6837. trigger: 'hover',
  6838. placement: 'bottom',
  6839. delay: {
  6840. show: NETDATA.options.current.show_help_delay_show_ms,
  6841. hide: NETDATA.options.current.show_help_delay_hide_ms
  6842. },
  6843. title: 'Chart Zoom In',
  6844. content: 'Zoom in the chart. You can also press SHIFT and select an area of the chart, or press SHIFT or ALT and use the mouse wheel or 2-finger touchpad scroll to zoom in or out.<br/><small>Help can be disabled from the settings.</small>'
  6845. });
  6846. }
  6847. this.element_legend_childs.toolbox_zoomout.className += ' netdata-legend-toolbox-button';
  6848. this.element_legend_childs.toolbox_zoomout.innerHTML = NETDATA.icons.zoomOut;
  6849. this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_zoomout);
  6850. this.element_legend_childs.toolbox_zoomout.onclick = function (e) {
  6851. e.preventDefault();
  6852. let dt = (((that.view_before - that.view_after) / (1.0 - (getPanAndZoomStep(e) * 0.8)) - (that.view_before - that.view_after)) / 2);
  6853. let before = that.view_before + dt;
  6854. let after = that.view_after - dt;
  6855. that.library.toolboxPanAndZoom(that, after, before);
  6856. };
  6857. if (NETDATA.options.current.show_help) {
  6858. $(this.element_legend_childs.toolbox_zoomout).popover({
  6859. container: "body",
  6860. animation: false,
  6861. html: true,
  6862. trigger: 'hover',
  6863. placement: 'bottom',
  6864. delay: {
  6865. show: NETDATA.options.current.show_help_delay_show_ms,
  6866. hide: NETDATA.options.current.show_help_delay_hide_ms
  6867. },
  6868. title: 'Chart Zoom Out',
  6869. content: 'Zoom out the chart. You can also press SHIFT or ALT and use the mouse wheel, or 2-finger touchpad scroll to zoom in or out.<br/><small>Help can be disabled from the settings.</small>'
  6870. });
  6871. }
  6872. //this.element_legend_childs.toolbox_volume.className += ' netdata-legend-toolbox-button';
  6873. //this.element_legend_childs.toolbox_volume.innerHTML = '<i class="fas fa-sort-amount-down"></i>';
  6874. //this.element_legend_childs.toolbox_volume.title = 'Visible Volume';
  6875. //this.element_legend_childs.toolbox.appendChild(this.element_legend_childs.toolbox_volume);
  6876. //this.element_legend_childs.toolbox_volume.onclick = function(e) {
  6877. //e.preventDefault();
  6878. //alert('clicked toolbox_volume on ' + that.id);
  6879. //}
  6880. }
  6881. if (NETDATA.options.current.resize_charts) {
  6882. this.element_legend_childs.resize_handler = document.createElement('div');
  6883. this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
  6884. this.element_legend_childs.resize_handler.innerHTML = NETDATA.icons.resize;
  6885. this.element.appendChild(this.element_legend_childs.resize_handler);
  6886. if (NETDATA.options.current.show_help) {
  6887. $(this.element_legend_childs.resize_handler).popover({
  6888. container: "body",
  6889. animation: false,
  6890. html: true,
  6891. trigger: 'hover',
  6892. placement: 'bottom',
  6893. delay: {
  6894. show: NETDATA.options.current.show_help_delay_show_ms,
  6895. hide: NETDATA.options.current.show_help_delay_hide_ms
  6896. },
  6897. title: 'Chart Resize',
  6898. content: 'Drag this point with your mouse or your finger (on touch devices), to resize the chart vertically. You can also <b>double click it</b> or <b>double tap it</b> to reset between 2 states: the default and the one that fits all the values.<br/><small>Help can be disabled from the settings.</small>'
  6899. });
  6900. }
  6901. // mousedown event
  6902. this.element_legend_childs.resize_handler.onmousedown =
  6903. function (e) {
  6904. that.resizeHandler(e);
  6905. };
  6906. // touchstart event
  6907. this.element_legend_childs.resize_handler.addEventListener('touchstart', function (e) {
  6908. that.resizeHandler(e);
  6909. }, false);
  6910. }
  6911. if (this.chart) {
  6912. this.element_legend_childs.title_date.title = this.legendPluginModuleString(true);
  6913. this.element_legend_childs.title_time.title = this.legendResolutionTooltip();
  6914. }
  6915. this.element_legend_childs.title_date.className += " netdata-legend-title-date";
  6916. this.element_legend.appendChild(this.element_legend_childs.title_date);
  6917. this.tmp.__last_shown_legend_date = undefined;
  6918. this.element_legend.appendChild(document.createElement('br'));
  6919. this.element_legend_childs.title_time.className += " netdata-legend-title-time";
  6920. this.element_legend.appendChild(this.element_legend_childs.title_time);
  6921. this.tmp.__last_shown_legend_time = undefined;
  6922. this.element_legend.appendChild(document.createElement('br'));
  6923. this.element_legend_childs.title_units.className += " netdata-legend-title-units";
  6924. this.element_legend_childs.title_units.innerText = this.units_current;
  6925. this.element_legend.appendChild(this.element_legend_childs.title_units);
  6926. this.tmp.__last_shown_legend_units = undefined;
  6927. this.element_legend.appendChild(document.createElement('br'));
  6928. this.element_legend_childs.perfect_scroller.className = 'netdata-legend-series';
  6929. this.element_legend.appendChild(this.element_legend_childs.perfect_scroller);
  6930. content.className = 'netdata-legend-series-content';
  6931. this.element_legend_childs.perfect_scroller.appendChild(content);
  6932. this.element_legend_childs.content = content;
  6933. if (NETDATA.options.current.show_help) {
  6934. $(content).popover({
  6935. container: "body",
  6936. animation: false,
  6937. html: true,
  6938. trigger: 'hover',
  6939. placement: 'bottom',
  6940. title: 'Chart Legend',
  6941. delay: {
  6942. show: NETDATA.options.current.show_help_delay_show_ms,
  6943. hide: NETDATA.options.current.show_help_delay_hide_ms
  6944. },
  6945. content: 'You can click or tap on the values or the labels to select dimensions. By pressing SHIFT or CONTROL, you can enable or disable multiple dimensions.<br/><small>Help can be disabled from the settings.</small>'
  6946. });
  6947. }
  6948. } else {
  6949. this.element_legend_childs = {
  6950. content: content,
  6951. resize_handler: null,
  6952. toolbox: null,
  6953. toolbox_left: null,
  6954. toolbox_right: null,
  6955. toolbox_reset: null,
  6956. toolbox_zoomin: null,
  6957. toolbox_zoomout: null,
  6958. toolbox_volume: null,
  6959. title_date: null,
  6960. title_time: null,
  6961. title_units: null,
  6962. perfect_scroller: null,
  6963. series: {}
  6964. };
  6965. }
  6966. if (this.data) {
  6967. this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
  6968. if (this.debug) {
  6969. this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
  6970. }
  6971. for (let i = 0, len = this.data.dimension_names.length; i < len; i++) {
  6972. genLabel(this, content, this.data.dimension_ids[i], this.data.dimension_names[i], i);
  6973. }
  6974. } else {
  6975. let tmp = [];
  6976. keys = Object.keys(this.chart.dimensions);
  6977. for (let i = 0, len = keys.length; i < len; i++) {
  6978. dim = keys[i];
  6979. tmp.push(this.chart.dimensions[dim].name);
  6980. genLabel(this, content, dim, this.chart.dimensions[dim].name, i);
  6981. }
  6982. this.element_legend_childs.series.labels_key = tmp.toString();
  6983. if (this.debug) {
  6984. this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
  6985. }
  6986. }
  6987. // create a hidden div to be used for hiding
  6988. // the original legend of the chart library
  6989. let el = document.createElement('div');
  6990. if (this.element_legend !== null) {
  6991. this.element_legend.appendChild(el);
  6992. }
  6993. el.style.display = 'none';
  6994. this.element_legend_childs.hidden = document.createElement('div');
  6995. el.appendChild(this.element_legend_childs.hidden);
  6996. if (this.element_legend_childs.perfect_scroller !== null) {
  6997. Ps.initialize(this.element_legend_childs.perfect_scroller, {
  6998. wheelSpeed: 0.2,
  6999. wheelPropagation: true,
  7000. swipePropagation: true,
  7001. minScrollbarLength: null,
  7002. maxScrollbarLength: null,
  7003. useBothWheelAxes: false,
  7004. suppressScrollX: true,
  7005. suppressScrollY: false,
  7006. scrollXMarginOffset: 0,
  7007. scrollYMarginOffset: 0,
  7008. theme: 'default'
  7009. });
  7010. Ps.update(this.element_legend_childs.perfect_scroller);
  7011. }
  7012. this.legendShowLatestValues();
  7013. };
  7014. this.hasLegend = function () {
  7015. if (typeof this.tmp.___hasLegendCache___ !== 'undefined') {
  7016. return this.tmp.___hasLegendCache___;
  7017. }
  7018. let leg = false;
  7019. if (this.library && this.library.legend(this) === 'right-side') {
  7020. leg = true;
  7021. }
  7022. this.tmp.___hasLegendCache___ = leg;
  7023. return leg;
  7024. };
  7025. this.legendWidth = function () {
  7026. return (this.hasLegend()) ? 140 : 0;
  7027. };
  7028. this.legendHeight = function () {
  7029. return $(this.element).height();
  7030. };
  7031. this.chartWidth = function () {
  7032. return $(this.element).width() - this.legendWidth();
  7033. };
  7034. this.chartHeight = function () {
  7035. return $(this.element).height();
  7036. };
  7037. this.chartPixelsPerPoint = function () {
  7038. // force an options provided detail
  7039. let px = this.pixels_per_point;
  7040. if (this.library && px < this.library.pixels_per_point(this)) {
  7041. px = this.library.pixels_per_point(this);
  7042. }
  7043. if (px < NETDATA.options.current.pixels_per_point) {
  7044. px = NETDATA.options.current.pixels_per_point;
  7045. }
  7046. return px;
  7047. };
  7048. this.needsRecreation = function () {
  7049. let ret = (
  7050. this.chart_created &&
  7051. this.library &&
  7052. this.library.autoresize() === false &&
  7053. this.tm.last_resized < NETDATA.options.last_page_resize
  7054. );
  7055. if (this.debug) {
  7056. this.log('needsRecreation(): ' + ret.toString() + ', chart_created = ' + this.chart_created.toString());
  7057. }
  7058. return ret;
  7059. };
  7060. this.chartDataUniqueID = function () {
  7061. return this.id + ',' + this.library_name + ',' + this.dimensions + ',' + this.chartURLOptions(true);
  7062. };
  7063. this.chartURLOptions = function (isForUniqueId) {
  7064. let ret = '';
  7065. if (this.override_options !== null) {
  7066. ret = this.override_options.toString();
  7067. } else {
  7068. ret = this.library.options(this);
  7069. }
  7070. if (this.append_options !== null) {
  7071. ret += '%7C' + this.append_options.toString();
  7072. }
  7073. ret += '%7C' + 'jsonwrap';
  7074. // always add `nonzero` when it's used to create a chartDataUniqueID
  7075. // we cannot just remove `nonzero` because of backwards compatibility with old snapshots
  7076. if (isForUniqueId || NETDATA.options.current.eliminate_zero_dimensions) {
  7077. ret += '%7C' + 'nonzero';
  7078. }
  7079. return ret;
  7080. };
  7081. this.chartURL = function () {
  7082. let after, before, points_multiplier = 1;
  7083. if (NETDATA.globalPanAndZoom.isActive()) {
  7084. if (this.current.force_before_ms !== null && this.current.force_after_ms !== null) {
  7085. this.tm.pan_and_zoom_seq = 0;
  7086. before = Math.round(this.current.force_before_ms / 1000);
  7087. after = Math.round(this.current.force_after_ms / 1000);
  7088. this.view_after = after * 1000;
  7089. this.view_before = before * 1000;
  7090. if (NETDATA.options.current.pan_and_zoom_data_padding) {
  7091. this.requested_padding = Math.round((before - after) / 2);
  7092. after -= this.requested_padding;
  7093. before += this.requested_padding;
  7094. this.requested_padding *= 1000;
  7095. points_multiplier = 2;
  7096. }
  7097. this.current.force_before_ms = null;
  7098. this.current.force_after_ms = null;
  7099. } else {
  7100. this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
  7101. after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
  7102. before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
  7103. this.view_after = after * 1000;
  7104. this.view_before = before * 1000;
  7105. this.requested_padding = null;
  7106. points_multiplier = 1;
  7107. }
  7108. } else {
  7109. this.tm.pan_and_zoom_seq = 0;
  7110. before = this.before;
  7111. after = this.after;
  7112. this.view_after = after * 1000;
  7113. this.view_before = before * 1000;
  7114. this.requested_padding = null;
  7115. points_multiplier = 1;
  7116. }
  7117. this.requested_after = after * 1000;
  7118. this.requested_before = before * 1000;
  7119. let data_points;
  7120. if (NETDATA.options.force_data_points !== 0) {
  7121. data_points = NETDATA.options.force_data_points;
  7122. this.data_points = data_points;
  7123. } else {
  7124. this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
  7125. data_points = this.data_points * points_multiplier;
  7126. }
  7127. // build the data URL
  7128. this.data_url = this.host + this.chart.data_url;
  7129. this.data_url += "&format=" + this.library.format();
  7130. this.data_url += "&points=" + (data_points).toString();
  7131. this.data_url += "&group=" + this.method;
  7132. this.data_url += "&gtime=" + this.gtime;
  7133. this.data_url += "&options=" + this.chartURLOptions();
  7134. if (after) {
  7135. this.data_url += "&after=" + after.toString();
  7136. }
  7137. if (before) {
  7138. this.data_url += "&before=" + before.toString();
  7139. }
  7140. if (this.dimensions) {
  7141. this.data_url += "&dimensions=" + this.dimensions;
  7142. }
  7143. if (NETDATA.options.debug.chart_data_url || this.debug) {
  7144. this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + data_points.toString() + ' library: ' + this.library_name);
  7145. }
  7146. };
  7147. this.redrawChart = function () {
  7148. if (this.data !== null) {
  7149. this.updateChartWithData(this.data);
  7150. }
  7151. };
  7152. this.updateChartWithData = function (data) {
  7153. if (this.debug) {
  7154. this.log('updateChartWithData() called.');
  7155. }
  7156. // this may force the chart to be re-created
  7157. resizeChart();
  7158. this.data = data;
  7159. let started = Date.now();
  7160. let view_update_every = data.view_update_every * 1000;
  7161. if (this.data_update_every !== view_update_every) {
  7162. if (this.element_legend_childs.title_time) {
  7163. this.element_legend_childs.title_time.title = this.legendResolutionTooltip();
  7164. }
  7165. }
  7166. // if the result is JSON, find the latest update-every
  7167. this.data_update_every = view_update_every;
  7168. this.data_after = data.after * 1000;
  7169. this.data_before = data.before * 1000;
  7170. this.netdata_first = data.first_entry * 1000;
  7171. this.netdata_last = data.last_entry * 1000;
  7172. this.data_points = data.points;
  7173. data.state = this;
  7174. if (NETDATA.options.current.pan_and_zoom_data_padding && this.requested_padding !== null) {
  7175. if (this.view_after < this.data_after) {
  7176. // console.log('adjusting view_after from ' + this.view_after + ' to ' + this.data_after);
  7177. this.view_after = this.data_after;
  7178. }
  7179. if (this.view_before > this.data_before) {
  7180. // console.log('adjusting view_before from ' + this.view_before + ' to ' + this.data_before);
  7181. this.view_before = this.data_before;
  7182. }
  7183. } else {
  7184. this.view_after = this.data_after;
  7185. this.view_before = this.data_before;
  7186. }
  7187. if (this.debug) {
  7188. this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
  7189. if (this.current.force_after_ms) {
  7190. this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
  7191. } else {
  7192. this.log('STATUS: forced : unset');
  7193. }
  7194. this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
  7195. this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
  7196. this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString());
  7197. this.log('STATUS: points : ' + (this.data_points).toString());
  7198. }
  7199. if (this.data_points === 0) {
  7200. noDataToShow();
  7201. return;
  7202. }
  7203. if (this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
  7204. if (this.debug) {
  7205. this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
  7206. }
  7207. init('force');
  7208. return;
  7209. }
  7210. // check and update the legend
  7211. this.legendUpdateDOM();
  7212. if (this.chart_created && typeof this.library.update === 'function') {
  7213. if (this.debug) {
  7214. this.log('updating chart...');
  7215. }
  7216. if (!callChartLibraryUpdateSafely(data)) {
  7217. return;
  7218. }
  7219. } else {
  7220. if (this.debug) {
  7221. this.log('creating chart...');
  7222. }
  7223. if (!callChartLibraryCreateSafely(data)) {
  7224. return;
  7225. }
  7226. }
  7227. if (this.isVisible()) {
  7228. hideMessage();
  7229. this.legendShowLatestValues();
  7230. } else {
  7231. this.__redraw_on_unhide = true;
  7232. if (this.debug) {
  7233. this.log("drawn while not visible");
  7234. }
  7235. }
  7236. if (this.selected) {
  7237. NETDATA.globalSelectionSync.stop();
  7238. }
  7239. // update the performance counters
  7240. let now = Date.now();
  7241. this.tm.last_updated = now;
  7242. // don't update last_autorefreshed if this chart is
  7243. // forced to be updated with global PanAndZoom
  7244. if (NETDATA.globalPanAndZoom.isActive()) {
  7245. this.tm.last_autorefreshed = 0;
  7246. } else {
  7247. if (NETDATA.options.current.parallel_refresher && NETDATA.options.current.concurrent_refreshes && typeof this.force_update_every !== 'number') {
  7248. this.tm.last_autorefreshed = now - (now % this.data_update_every);
  7249. } else {
  7250. this.tm.last_autorefreshed = now;
  7251. }
  7252. }
  7253. this.refresh_dt_ms = now - started;
  7254. NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
  7255. if (this.refresh_dt_element !== null) {
  7256. this.refresh_dt_element.innerText = this.refresh_dt_ms.toString();
  7257. }
  7258. if (this.foreignElementBefore !== null) {
  7259. this.foreignElementBefore.innerText = NETDATA.dateTime.localeDateString(this.view_before) + ' ' + NETDATA.dateTime.localeTimeString(this.view_before);
  7260. }
  7261. if (this.foreignElementAfter !== null) {
  7262. this.foreignElementAfter.innerText = NETDATA.dateTime.localeDateString(this.view_after) + ' ' + NETDATA.dateTime.localeTimeString(this.view_after);
  7263. }
  7264. if (this.foreignElementDuration !== null) {
  7265. this.foreignElementDuration.innerText = NETDATA.seconds4human(Math.floor((this.view_before - this.view_after) / 1000) + 1);
  7266. }
  7267. if (this.foreignElementUpdateEvery !== null) {
  7268. this.foreignElementUpdateEvery.innerText = NETDATA.seconds4human(Math.floor(this.data_update_every / 1000));
  7269. }
  7270. };
  7271. this.getSnapshotData = function (key) {
  7272. if (this.debug) {
  7273. this.log('updating from snapshot: ' + key);
  7274. }
  7275. if (typeof netdataSnapshotData.data[key] === 'undefined') {
  7276. this.log('snapshot does not include data for key "' + key + '"');
  7277. return null;
  7278. }
  7279. if (typeof netdataSnapshotData.data[key] !== 'string') {
  7280. this.log('snapshot data for key "' + key + '" is not string');
  7281. return null;
  7282. }
  7283. let uncompressed;
  7284. try {
  7285. uncompressed = netdataSnapshotData.uncompress(netdataSnapshotData.data[key]);
  7286. if (uncompressed === null) {
  7287. this.log('uncompressed snapshot data for key ' + key + ' is null');
  7288. return null;
  7289. }
  7290. if (typeof uncompressed === 'undefined') {
  7291. this.log('uncompressed snapshot data for key ' + key + ' is undefined');
  7292. return null;
  7293. }
  7294. } catch (e) {
  7295. this.log('decompression of snapshot data for key ' + key + ' failed');
  7296. console.log(e);
  7297. uncompressed = null;
  7298. }
  7299. if (typeof uncompressed !== 'string') {
  7300. this.log('uncompressed snapshot data for key ' + key + ' is not string');
  7301. return null;
  7302. }
  7303. let data;
  7304. try {
  7305. data = JSON.parse(uncompressed);
  7306. } catch (e) {
  7307. this.log('parsing snapshot data for key ' + key + ' failed');
  7308. console.log(e);
  7309. data = null;
  7310. }
  7311. return data;
  7312. };
  7313. this.updateChart = function (callback) {
  7314. if (this.debug) {
  7315. this.log('updateChart()');
  7316. }
  7317. if (this.fetching_data) {
  7318. if (this.debug) {
  7319. this.log('updateChart(): I am already updating...');
  7320. }
  7321. if (typeof callback === 'function') {
  7322. return callback(false, 'already running');
  7323. }
  7324. return;
  7325. }
  7326. // due to late initialization of charts and libraries
  7327. // we need to check this too
  7328. if (!this.enabled) {
  7329. if (this.debug) {
  7330. this.log('updateChart(): I am not enabled');
  7331. }
  7332. if (typeof callback === 'function') {
  7333. return callback(false, 'not enabled');
  7334. }
  7335. return;
  7336. }
  7337. if (!canBeRendered()) {
  7338. if (this.debug) {
  7339. this.log('updateChart(): cannot be rendered');
  7340. }
  7341. if (typeof callback === 'function') {
  7342. return callback(false, 'cannot be rendered');
  7343. }
  7344. return;
  7345. }
  7346. if (that.dom_created !== true) {
  7347. if (this.debug) {
  7348. this.log('updateChart(): creating DOM');
  7349. }
  7350. createDOM();
  7351. }
  7352. if (this.chart === null) {
  7353. if (this.debug) {
  7354. this.log('updateChart(): getting chart');
  7355. }
  7356. return this.getChart(function () {
  7357. return that.updateChart(callback);
  7358. });
  7359. }
  7360. if (!this.library.initialized) {
  7361. if (this.library.enabled) {
  7362. if (this.debug) {
  7363. this.log('updateChart(): initializing chart library');
  7364. }
  7365. return this.library.initialize(function () {
  7366. return that.updateChart(callback);
  7367. });
  7368. } else {
  7369. error('chart library "' + this.library_name + '" is not available.');
  7370. if (typeof callback === 'function') {
  7371. return callback(false, 'library not available');
  7372. }
  7373. return;
  7374. }
  7375. }
  7376. this.clearSelection();
  7377. this.chartURL();
  7378. NETDATA.statistics.refreshes_total++;
  7379. NETDATA.statistics.refreshes_active++;
  7380. if (NETDATA.statistics.refreshes_active > NETDATA.statistics.refreshes_active_max) {
  7381. NETDATA.statistics.refreshes_active_max = NETDATA.statistics.refreshes_active;
  7382. }
  7383. let ok = false;
  7384. this.fetching_data = true;
  7385. if (netdataSnapshotData !== null) {
  7386. let key = this.chartDataUniqueID();
  7387. let data = this.getSnapshotData(key);
  7388. if (data !== null) {
  7389. ok = true;
  7390. data = NETDATA.xss.checkData('/api/v1/data', data, this.library.xssRegexIgnore);
  7391. this.updateChartWithData(data);
  7392. } else {
  7393. ok = false;
  7394. error('cannot get data from snapshot for key: "' + key + '"');
  7395. that.tm.last_autorefreshed = Date.now();
  7396. }
  7397. NETDATA.statistics.refreshes_active--;
  7398. this.fetching_data = false;
  7399. if (typeof callback === 'function') {
  7400. callback(ok, 'snapshot');
  7401. }
  7402. return;
  7403. }
  7404. if (this.debug) {
  7405. this.log('updating from ' + this.data_url);
  7406. }
  7407. this.xhr = $.ajax({
  7408. url: this.data_url,
  7409. cache: false,
  7410. async: true,
  7411. headers: {
  7412. 'Cache-Control': 'no-cache, no-store',
  7413. 'Pragma': 'no-cache'
  7414. },
  7415. xhrFields: {withCredentials: true} // required for the cookie
  7416. })
  7417. .done(function (data) {
  7418. data = NETDATA.xss.checkData('/api/v1/data', data, that.library.xssRegexIgnore);
  7419. that.xhr = undefined;
  7420. that.retries_on_data_failures = 0;
  7421. ok = true;
  7422. if (that.debug) {
  7423. that.log('data received. updating chart.');
  7424. }
  7425. that.updateChartWithData(data);
  7426. })
  7427. .fail(function (msg) {
  7428. that.xhr = undefined;
  7429. if (msg.statusText !== 'abort') {
  7430. that.retries_on_data_failures++;
  7431. if (that.retries_on_data_failures > NETDATA.options.current.retries_on_data_failures) {
  7432. // that.log('failed ' + that.retries_on_data_failures.toString() + ' times - giving up');
  7433. that.retries_on_data_failures = 0;
  7434. error('data download failed for url: ' + that.data_url);
  7435. }
  7436. else {
  7437. that.tm.last_autorefreshed = Date.now();
  7438. // that.log('failed ' + that.retries_on_data_failures.toString() + ' times, but I will retry');
  7439. }
  7440. }
  7441. })
  7442. .always(function () {
  7443. that.xhr = undefined;
  7444. NETDATA.statistics.refreshes_active--;
  7445. that.fetching_data = false;
  7446. if (typeof callback === 'function') {
  7447. return callback(ok, 'download');
  7448. }
  7449. });
  7450. };
  7451. const __isVisible = function () {
  7452. let ret = true;
  7453. if (NETDATA.options.current.update_only_visible !== false) {
  7454. // tolerance is the number of pixels a chart can be off-screen
  7455. // to consider it as visible and refresh it as if was visible
  7456. let tolerance = 0;
  7457. that.tm.last_visible_check = Date.now();
  7458. let rect = that.element.getBoundingClientRect();
  7459. let screenTop = window.scrollY;
  7460. let screenBottom = screenTop + window.innerHeight;
  7461. let chartTop = rect.top + screenTop;
  7462. let chartBottom = chartTop + rect.height;
  7463. ret = !(rect.width === 0 || rect.height === 0 || chartBottom + tolerance < screenTop || chartTop - tolerance > screenBottom);
  7464. }
  7465. if (that.debug) {
  7466. that.log('__isVisible(): ' + ret);
  7467. }
  7468. return ret;
  7469. };
  7470. this.isVisible = function (nocache) {
  7471. // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
  7472. // caching - we do not evaluate the charts visibility
  7473. // if the page has not been scrolled since the last check
  7474. if ((typeof nocache !== 'undefined' && nocache)
  7475. || typeof this.tmp.___isVisible___ === 'undefined'
  7476. || this.tm.last_visible_check <= NETDATA.options.last_page_scroll) {
  7477. this.tmp.___isVisible___ = __isVisible();
  7478. if (this.tmp.___isVisible___) {
  7479. this.unhideChart();
  7480. } else {
  7481. this.hideChart();
  7482. }
  7483. }
  7484. if (this.debug) {
  7485. this.log('isVisible(' + nocache + '): ' + this.tmp.___isVisible___);
  7486. }
  7487. return this.tmp.___isVisible___;
  7488. };
  7489. this.isAutoRefreshable = function () {
  7490. return (this.current.autorefresh);
  7491. };
  7492. this.canBeAutoRefreshed = function () {
  7493. if (!this.enabled) {
  7494. if (this.debug) {
  7495. this.log('canBeAutoRefreshed() -> not enabled');
  7496. }
  7497. return false;
  7498. }
  7499. if (this.running) {
  7500. if (this.debug) {
  7501. this.log('canBeAutoRefreshed() -> already running');
  7502. }
  7503. return false;
  7504. }
  7505. if (this.library === null || this.library.enabled === false) {
  7506. error('charting library "' + this.library_name + '" is not available');
  7507. if (this.debug) {
  7508. this.log('canBeAutoRefreshed() -> chart library ' + this.library_name + ' is not available');
  7509. }
  7510. return false;
  7511. }
  7512. if (!this.isVisible()) {
  7513. if (NETDATA.options.debug.visibility || this.debug) {
  7514. this.log('canBeAutoRefreshed() -> not visible');
  7515. }
  7516. return false;
  7517. }
  7518. let now = Date.now();
  7519. if (this.current.force_update_at !== 0 && this.current.force_update_at < now) {
  7520. if (this.debug) {
  7521. this.log('canBeAutoRefreshed() -> timed force update - allowing this update');
  7522. }
  7523. this.current.force_update_at = 0;
  7524. return true;
  7525. }
  7526. if (!this.isAutoRefreshable()) {
  7527. if (this.debug) {
  7528. this.log('canBeAutoRefreshed() -> not auto-refreshable');
  7529. }
  7530. return false;
  7531. }
  7532. // allow the first update, even if the page is not visible
  7533. if (NETDATA.options.page_is_visible === false && this.updates_counter && this.updates_since_last_unhide) {
  7534. if (NETDATA.options.debug.focus || this.debug) {
  7535. this.log('canBeAutoRefreshed() -> not the first update, and page does not have focus');
  7536. }
  7537. return false;
  7538. }
  7539. if (this.needsRecreation()) {
  7540. if (this.debug) {
  7541. this.log('canBeAutoRefreshed() -> needs re-creation.');
  7542. }
  7543. return true;
  7544. }
  7545. if (NETDATA.options.auto_refresher_stop_until >= now) {
  7546. if (this.debug) {
  7547. this.log('canBeAutoRefreshed() -> stopped until is in future.');
  7548. }
  7549. return false;
  7550. }
  7551. // options valid only for autoRefresh()
  7552. if (NETDATA.globalPanAndZoom.isActive()) {
  7553. if (NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
  7554. if (this.debug) {
  7555. this.log('canBeAutoRefreshed(): global panning: I need an update.');
  7556. }
  7557. return true;
  7558. }
  7559. else {
  7560. if (this.debug) {
  7561. this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
  7562. }
  7563. return false;
  7564. }
  7565. }
  7566. if (this.selected) {
  7567. if (this.debug) {
  7568. this.log('canBeAutoRefreshed(): I have a selection in place.');
  7569. }
  7570. return false;
  7571. }
  7572. if (this.paused) {
  7573. if (this.debug) {
  7574. this.log('canBeAutoRefreshed(): I am paused.');
  7575. }
  7576. return false;
  7577. }
  7578. let data_update_every = this.data_update_every;
  7579. if (typeof this.force_update_every === 'number') {
  7580. data_update_every = this.force_update_every;
  7581. }
  7582. if (now - this.tm.last_autorefreshed >= data_update_every) {
  7583. if (this.debug) {
  7584. this.log('canBeAutoRefreshed(): It is time to update me. Now: ' + now.toString() + ', last_autorefreshed: ' + this.tm.last_autorefreshed + ', data_update_every: ' + data_update_every + ', delta: ' + (now - this.tm.last_autorefreshed).toString());
  7585. }
  7586. return true;
  7587. }
  7588. return false;
  7589. };
  7590. this.autoRefresh = function (callback) {
  7591. let state = that;
  7592. if (state.canBeAutoRefreshed() && state.running === false) {
  7593. state.running = true;
  7594. state.updateChart(function () {
  7595. state.running = false;
  7596. if (typeof callback === 'function') {
  7597. return callback();
  7598. }
  7599. });
  7600. } else {
  7601. if (typeof callback === 'function') {
  7602. return callback();
  7603. }
  7604. }
  7605. };
  7606. this.__defaultsFromDownloadedChart = function (chart) {
  7607. this.chart = chart;
  7608. this.chart_url = chart.url;
  7609. this.data_update_every = chart.update_every * 1000;
  7610. this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
  7611. this.tm.last_info_downloaded = Date.now();
  7612. if (this.title === null) {
  7613. this.title = chart.title;
  7614. }
  7615. if (this.units === null) {
  7616. this.units = chart.units;
  7617. this.units_current = this.units;
  7618. }
  7619. };
  7620. // fetch the chart description from the netdata server
  7621. this.getChart = function (callback) {
  7622. this.chart = NETDATA.chartRegistry.get(this.host, this.id);
  7623. if (this.chart) {
  7624. this.__defaultsFromDownloadedChart(this.chart);
  7625. if (typeof callback === 'function') {
  7626. return callback();
  7627. }
  7628. } else if (netdataSnapshotData !== null) {
  7629. // console.log(this);
  7630. // console.log(NETDATA.chartRegistry);
  7631. NETDATA.error(404, 'host: ' + this.host + ', chart: ' + this.id);
  7632. error('chart not found in snapshot');
  7633. if (typeof callback === 'function') {
  7634. return callback();
  7635. }
  7636. } else {
  7637. this.chart_url = "/api/v1/chart?chart=" + this.id;
  7638. if (this.debug) {
  7639. this.log('downloading ' + this.chart_url);
  7640. }
  7641. $.ajax({
  7642. url: this.host + this.chart_url,
  7643. cache: false,
  7644. async: true,
  7645. xhrFields: {withCredentials: true} // required for the cookie
  7646. })
  7647. .done(function (chart) {
  7648. chart = NETDATA.xss.checkOptional('/api/v1/chart', chart);
  7649. chart.url = that.chart_url;
  7650. that.__defaultsFromDownloadedChart(chart);
  7651. NETDATA.chartRegistry.add(that.host, that.id, chart);
  7652. })
  7653. .fail(function () {
  7654. NETDATA.error(404, that.chart_url);
  7655. error('chart not found on url "' + that.chart_url + '"');
  7656. })
  7657. .always(function () {
  7658. if (typeof callback === 'function') {
  7659. return callback();
  7660. }
  7661. });
  7662. }
  7663. };
  7664. // ============================================================================================================
  7665. // INITIALIZATION
  7666. initDOM();
  7667. init('fast');
  7668. };
  7669. NETDATA.resetAllCharts = function (state) {
  7670. // first clear the global selection sync
  7671. // to make sure no chart is in selected state
  7672. NETDATA.globalSelectionSync.stop();
  7673. // there are 2 possibilities here
  7674. // a. state is the global Pan and Zoom master
  7675. // b. state is not the global Pan and Zoom master
  7676. // let master = true;
  7677. // if (NETDATA.globalPanAndZoom.isMaster(state) === false) {
  7678. // master = false;
  7679. // }
  7680. const master = NETDATA.globalPanAndZoom.isMaster(state);
  7681. // clear the global Pan and Zoom
  7682. // this will also refresh the master
  7683. // and unblock any charts currently mirroring the master
  7684. NETDATA.globalPanAndZoom.clearMaster();
  7685. // if we were not the master, reset our status too
  7686. // this is required because most probably the mouse
  7687. // is over this chart, blocking it from auto-refreshing
  7688. if (master === false && (state.paused || state.selected)) {
  7689. state.resetChart();
  7690. }
  7691. };
  7692. // get or create a chart state, given a DOM element
  7693. NETDATA.chartState = function (element) {
  7694. let self = $(element);
  7695. let state = self.data('netdata-state-object') || null;
  7696. if (state === null) {
  7697. state = new chartState(element);
  7698. self.data('netdata-state-object', state);
  7699. }
  7700. return state;
  7701. };
  7702. // ----------------------------------------------------------------------------------------------------------------
  7703. // Library functions
  7704. // Load a script without jquery
  7705. // This is used to load jquery - after it is loaded, we use jquery
  7706. NETDATA._loadjQuery = function (callback) {
  7707. if (typeof jQuery === 'undefined') {
  7708. if (NETDATA.options.debug.main_loop) {
  7709. console.log('loading ' + NETDATA.jQuery);
  7710. }
  7711. let script = document.createElement('script');
  7712. script.type = 'text/javascript';
  7713. script.async = true;
  7714. script.src = NETDATA.jQuery;
  7715. // script.onabort = onError;
  7716. script.onerror = function () {
  7717. NETDATA.error(101, NETDATA.jQuery);
  7718. };
  7719. if (typeof callback === "function") {
  7720. script.onload = function () {
  7721. $ = jQuery;
  7722. return callback();
  7723. };
  7724. }
  7725. let s = document.getElementsByTagName('script')[0];
  7726. s.parentNode.insertBefore(script, s);
  7727. }
  7728. else if (typeof callback === "function") {
  7729. $ = jQuery;
  7730. return callback();
  7731. }
  7732. };
  7733. NETDATA._loadCSS = function (filename) {
  7734. // don't use jQuery here
  7735. // styles are loaded before jQuery
  7736. // to eliminate showing an unstyled page to the user
  7737. let fileref = document.createElement("link");
  7738. fileref.setAttribute("rel", "stylesheet");
  7739. fileref.setAttribute("type", "text/css");
  7740. fileref.setAttribute("href", filename);
  7741. if (typeof fileref !== 'undefined') {
  7742. document.getElementsByTagName("head")[0].appendChild(fileref);
  7743. }
  7744. };
  7745. // user function to signal us the DOM has been
  7746. // updated.
  7747. NETDATA.updatedDom = function () {
  7748. NETDATA.options.updated_dom = true;
  7749. };
  7750. NETDATA.ready = function (callback) {
  7751. NETDATA.options.pauseCallback = callback;
  7752. };
  7753. NETDATA.pause = function (callback) {
  7754. if (typeof callback === 'function') {
  7755. if (NETDATA.options.pause) {
  7756. return callback();
  7757. } else {
  7758. NETDATA.options.pauseCallback = callback;
  7759. }
  7760. }
  7761. };
  7762. NETDATA.unpause = function () {
  7763. NETDATA.options.pauseCallback = null;
  7764. NETDATA.options.updated_dom = true;
  7765. NETDATA.options.pause = false;
  7766. };
  7767. // ----------------------------------------------------------------------------------------------------------------
  7768. // this is purely sequential charts refresher
  7769. // it is meant to be autonomous
  7770. NETDATA.chartRefresherNoParallel = function (index, callback) {
  7771. let targets = NETDATA.intersectionObserver.targets();
  7772. if (NETDATA.options.debug.main_loop) {
  7773. console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
  7774. }
  7775. if (NETDATA.options.updated_dom) {
  7776. // the dom has been updated
  7777. // get the dom parts again
  7778. NETDATA.parseDom(callback);
  7779. return;
  7780. }
  7781. if (index >= targets.length) {
  7782. if (NETDATA.options.debug.main_loop) {
  7783. console.log('waiting to restart main loop...');
  7784. }
  7785. NETDATA.options.auto_refresher_fast_weight = 0;
  7786. callback();
  7787. } else {
  7788. let state = targets[index];
  7789. if (NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
  7790. if (NETDATA.options.debug.main_loop) {
  7791. console.log('fast rendering...');
  7792. }
  7793. if (state.isVisible()) {
  7794. NETDATA.timeout.set(function () {
  7795. state.autoRefresh(function () {
  7796. NETDATA.chartRefresherNoParallel(++index, callback);
  7797. });
  7798. }, 0);
  7799. } else {
  7800. NETDATA.chartRefresherNoParallel(++index, callback);
  7801. }
  7802. } else {
  7803. if (NETDATA.options.debug.main_loop) {
  7804. console.log('waiting for next refresh...');
  7805. }
  7806. NETDATA.options.auto_refresher_fast_weight = 0;
  7807. NETDATA.timeout.set(function () {
  7808. state.autoRefresh(function () {
  7809. NETDATA.chartRefresherNoParallel(++index, callback);
  7810. });
  7811. }, NETDATA.options.current.idle_between_charts);
  7812. }
  7813. }
  7814. };
  7815. NETDATA.chartRefresherWaitTime = function () {
  7816. return NETDATA.options.current.idle_parallel_loops;
  7817. };
  7818. // the default refresher
  7819. NETDATA.chartRefresherLastRun = 0;
  7820. NETDATA.chartRefresherRunsAfterParseDom = 0;
  7821. NETDATA.chartRefresherTimeoutId = undefined;
  7822. NETDATA.chartRefresherReschedule = function () {
  7823. if (NETDATA.options.current.async_on_scroll) {
  7824. if (NETDATA.chartRefresherTimeoutId) {
  7825. NETDATA.timeout.clear(NETDATA.chartRefresherTimeoutId);
  7826. }
  7827. NETDATA.chartRefresherTimeoutId = NETDATA.timeout.set(NETDATA.chartRefresher, NETDATA.options.current.onscroll_worker_duration_threshold);
  7828. //console.log('chartRefresherReschedule()');
  7829. }
  7830. };
  7831. NETDATA.chartRefresher = function () {
  7832. // console.log('chartRefresher() begin ' + (Date.now() - NETDATA.chartRefresherLastRun).toString() + ' ms since last run');
  7833. if (NETDATA.options.page_is_visible === false
  7834. && NETDATA.options.current.stop_updates_when_focus_is_lost
  7835. && NETDATA.chartRefresherLastRun > NETDATA.options.last_page_resize
  7836. && NETDATA.chartRefresherLastRun > NETDATA.options.last_page_scroll
  7837. && NETDATA.chartRefresherRunsAfterParseDom > 10
  7838. ) {
  7839. setTimeout(
  7840. NETDATA.chartRefresher,
  7841. NETDATA.options.current.idle_lost_focus
  7842. );
  7843. // console.log('chartRefresher() page without focus, will run in ' + NETDATA.options.current.idle_lost_focus.toString() + ' ms, ' + NETDATA.chartRefresherRunsAfterParseDom.toString());
  7844. return;
  7845. }
  7846. NETDATA.chartRefresherRunsAfterParseDom++;
  7847. let now = Date.now();
  7848. NETDATA.chartRefresherLastRun = now;
  7849. if (now < NETDATA.options.on_scroll_refresher_stop_until) {
  7850. NETDATA.chartRefresherTimeoutId = NETDATA.timeout.set(
  7851. NETDATA.chartRefresher,
  7852. NETDATA.chartRefresherWaitTime()
  7853. );
  7854. // console.log('chartRefresher() end1 will run in ' + NETDATA.chartRefresherWaitTime().toString() + ' ms');
  7855. return;
  7856. }
  7857. if (now < NETDATA.options.auto_refresher_stop_until) {
  7858. NETDATA.chartRefresherTimeoutId = NETDATA.timeout.set(
  7859. NETDATA.chartRefresher,
  7860. NETDATA.chartRefresherWaitTime()
  7861. );
  7862. // console.log('chartRefresher() end2 will run in ' + NETDATA.chartRefresherWaitTime().toString() + ' ms');
  7863. return;
  7864. }
  7865. if (NETDATA.options.pause) {
  7866. // console.log('auto-refresher is paused');
  7867. NETDATA.chartRefresherTimeoutId = NETDATA.timeout.set(
  7868. NETDATA.chartRefresher,
  7869. NETDATA.chartRefresherWaitTime()
  7870. );
  7871. // console.log('chartRefresher() end3 will run in ' + NETDATA.chartRefresherWaitTime().toString() + ' ms');
  7872. return;
  7873. }
  7874. if (typeof NETDATA.options.pauseCallback === 'function') {
  7875. // console.log('auto-refresher is calling pauseCallback');
  7876. NETDATA.options.pause = true;
  7877. NETDATA.options.pauseCallback();
  7878. NETDATA.chartRefresher();
  7879. // console.log('chartRefresher() end4 (nested)');
  7880. return;
  7881. }
  7882. if (!NETDATA.options.current.parallel_refresher) {
  7883. // console.log('auto-refresher is calling chartRefresherNoParallel(0)');
  7884. NETDATA.chartRefresherNoParallel(0, function () {
  7885. NETDATA.chartRefresherTimeoutId = NETDATA.timeout.set(
  7886. NETDATA.chartRefresher,
  7887. NETDATA.options.current.idle_between_loops
  7888. );
  7889. });
  7890. // console.log('chartRefresher() end5 (no parallel, nested)');
  7891. return;
  7892. }
  7893. if (NETDATA.options.updated_dom) {
  7894. // the dom has been updated
  7895. // get the dom parts again
  7896. // console.log('auto-refresher is calling parseDom()');
  7897. NETDATA.parseDom(NETDATA.chartRefresher);
  7898. // console.log('chartRefresher() end6 (parseDom)');
  7899. return;
  7900. }
  7901. if (!NETDATA.globalSelectionSync.active()) {
  7902. let parallel = [];
  7903. let targets = NETDATA.intersectionObserver.targets();
  7904. let len = targets.length;
  7905. let state;
  7906. while (len--) {
  7907. state = targets[len];
  7908. if (state.running || state.isVisible() === false) {
  7909. continue;
  7910. }
  7911. if (!state.library.initialized) {
  7912. if (state.library.enabled) {
  7913. state.library.initialize(NETDATA.chartRefresher);
  7914. //console.log('chartRefresher() end6 (library init)');
  7915. return;
  7916. }
  7917. else {
  7918. state.error('chart library "' + state.library_name + '" is not enabled.');
  7919. }
  7920. }
  7921. if (NETDATA.scrollUp) {
  7922. parallel.unshift(state);
  7923. } else {
  7924. parallel.push(state);
  7925. }
  7926. }
  7927. len = parallel.length;
  7928. while (len--) {
  7929. state = parallel[len];
  7930. // console.log('auto-refresher executing in parallel for ' + parallel.length.toString() + ' charts');
  7931. // this will execute the jobs in parallel
  7932. if (!state.running) {
  7933. NETDATA.timeout.set(state.autoRefresh, 0);
  7934. }
  7935. }
  7936. //else {
  7937. // console.log('auto-refresher nothing to do');
  7938. //}
  7939. }
  7940. // run the next refresh iteration
  7941. NETDATA.chartRefresherTimeoutId = NETDATA.timeout.set(
  7942. NETDATA.chartRefresher,
  7943. NETDATA.chartRefresherWaitTime()
  7944. );
  7945. //console.log('chartRefresher() completed in ' + (Date.now() - now).toString() + ' ms');
  7946. };
  7947. NETDATA.parseDom = function (callback) {
  7948. //console.log('parseDom()');
  7949. NETDATA.options.last_page_scroll = Date.now();
  7950. NETDATA.options.updated_dom = false;
  7951. NETDATA.chartRefresherRunsAfterParseDom = 0;
  7952. let targets = $('div[data-netdata]'); //.filter(':visible');
  7953. if (NETDATA.options.debug.main_loop) {
  7954. console.log('DOM updated - there are ' + targets.length + ' charts on page.');
  7955. }
  7956. NETDATA.intersectionObserver.globalReset();
  7957. NETDATA.options.targets = [];
  7958. let len = targets.length;
  7959. while (len--) {
  7960. // the initialization will take care of sizing
  7961. // and the "loading..." message
  7962. let state = NETDATA.chartState(targets[len]);
  7963. NETDATA.options.targets.push(state);
  7964. NETDATA.intersectionObserver.observe(state);
  7965. }
  7966. if (NETDATA.globalChartUnderlay.isActive()) {
  7967. NETDATA.globalChartUnderlay.setup();
  7968. } else {
  7969. NETDATA.globalChartUnderlay.clear();
  7970. }
  7971. if (typeof callback === 'function') {
  7972. return callback();
  7973. }
  7974. };
  7975. // this is the main function - where everything starts
  7976. NETDATA.started = false;
  7977. NETDATA.start = function () {
  7978. // this should be called only once
  7979. if (NETDATA.started) {
  7980. console.log('netdata is already started');
  7981. return;
  7982. }
  7983. NETDATA.started = true;
  7984. NETDATA.options.page_is_visible = true;
  7985. $(window).blur(function () {
  7986. if (NETDATA.options.current.stop_updates_when_focus_is_lost) {
  7987. NETDATA.options.page_is_visible = false;
  7988. if (NETDATA.options.debug.focus) {
  7989. console.log('Lost Focus!');
  7990. }
  7991. }
  7992. });
  7993. $(window).focus(function () {
  7994. if (NETDATA.options.current.stop_updates_when_focus_is_lost) {
  7995. NETDATA.options.page_is_visible = true;
  7996. if (NETDATA.options.debug.focus) {
  7997. console.log('Focus restored!');
  7998. }
  7999. }
  8000. });
  8001. if (typeof document.hasFocus === 'function' && !document.hasFocus()) {
  8002. if (NETDATA.options.current.stop_updates_when_focus_is_lost) {
  8003. NETDATA.options.page_is_visible = false;
  8004. if (NETDATA.options.debug.focus) {
  8005. console.log('Document has no focus!');
  8006. }
  8007. }
  8008. }
  8009. // bootstrap tab switching
  8010. $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
  8011. // bootstrap modal switching
  8012. let $modal = $('.modal');
  8013. $modal.on('hidden.bs.modal', NETDATA.onscroll);
  8014. $modal.on('shown.bs.modal', NETDATA.onscroll);
  8015. // bootstrap collapse switching
  8016. let $collapse = $('.collapse');
  8017. $collapse.on('hidden.bs.collapse', NETDATA.onscroll);
  8018. $collapse.on('shown.bs.collapse', NETDATA.onscroll);
  8019. NETDATA.parseDom(NETDATA.chartRefresher);
  8020. // Alarms initialization
  8021. setTimeout(NETDATA.alarms.init, 1000);
  8022. // Registry initialization
  8023. setTimeout(NETDATA.registry.init, netdataRegistryAfterMs);
  8024. if (typeof netdataCallback === 'function') {
  8025. netdataCallback();
  8026. }
  8027. };
  8028. NETDATA.globalReset = function () {
  8029. NETDATA.intersectionObserver.globalReset();
  8030. NETDATA.globalSelectionSync.globalReset();
  8031. NETDATA.globalPanAndZoom.globalReset();
  8032. NETDATA.chartRegistry.globalReset();
  8033. NETDATA.commonMin.globalReset();
  8034. NETDATA.commonMax.globalReset();
  8035. NETDATA.commonColors.globalReset();
  8036. NETDATA.unitsConversion.globalReset();
  8037. NETDATA.options.targets = [];
  8038. NETDATA.parseDom();
  8039. NETDATA.unpause();
  8040. };
  8041. // Registry of netdata hosts
  8042. NETDATA.alarms = {
  8043. onclick: null, // the callback to handle the click - it will be called with the alarm log entry
  8044. chart_div_offset: -50, // give that space above the chart when scrolling to it
  8045. chart_div_id_prefix: 'chart_', // the chart DIV IDs have this prefix (they should be NETDATA.name2id(chart.id))
  8046. chart_div_animation_duration: 0,// the duration of the animation while scrolling to a chart
  8047. ms_penalty: 0, // the time penalty of the next alarm
  8048. ms_between_notifications: 500, // firefox moves the alarms off-screen (above, outside the top of the screen)
  8049. // if alarms are shown faster than: one per 500ms
  8050. update_every: 10000, // the time in ms between alarm checks
  8051. notifications: false, // when true, the browser supports notifications (may not be granted though)
  8052. last_notification_id: 0, // the id of the last alarm_log we have raised an alarm for
  8053. first_notification_id: 0, // the id of the first alarm_log entry for this session
  8054. // this is used to prevent CLEAR notifications for past events
  8055. // notifications_shown: [],
  8056. server: null, // the server to connect to for fetching alarms
  8057. current: null, // the list of raised alarms - updated in the background
  8058. // a callback function to call every time the list of raised alarms is refreshed
  8059. callback: (typeof netdataAlarmsActiveCallback === 'function') ? netdataAlarmsActiveCallback : null,
  8060. // a callback function to call every time a notification is shown
  8061. // the return value is used to decide if the notification will be shown
  8062. notificationCallback: (typeof netdataAlarmsNotifCallback === 'function') ? netdataAlarmsNotifCallback : null,
  8063. recipients: null, // the list (array) of recipients to show alarms for, or null
  8064. recipientMatches: function (to_string, wanted_array) {
  8065. if (typeof wanted_array === 'undefined' || wanted_array === null || Array.isArray(wanted_array) === false) {
  8066. return true;
  8067. }
  8068. let r = ' ' + to_string.toString() + ' ';
  8069. let len = wanted_array.length;
  8070. while (len--) {
  8071. if (r.indexOf(' ' + wanted_array[len] + ' ') >= 0) {
  8072. return true;
  8073. }
  8074. }
  8075. return false;
  8076. },
  8077. activeForRecipients: function () {
  8078. let active = {};
  8079. let data = NETDATA.alarms.current;
  8080. if (typeof data === 'undefined' || data === null) {
  8081. return active;
  8082. }
  8083. for (let x in data.alarms) {
  8084. if (!data.alarms.hasOwnProperty(x)) {
  8085. continue;
  8086. }
  8087. let alarm = data.alarms[x];
  8088. if ((alarm.status === 'WARNING' || alarm.status === 'CRITICAL') && NETDATA.alarms.recipientMatches(alarm.recipient, NETDATA.alarms.recipients)) {
  8089. active[x] = alarm;
  8090. }
  8091. }
  8092. return active;
  8093. },
  8094. notify: function (entry) {
  8095. // console.log('alarm ' + entry.unique_id);
  8096. if (entry.updated) {
  8097. // console.log('alarm ' + entry.unique_id + ' has been updated by another alarm');
  8098. return;
  8099. }
  8100. let value_string = entry.value_string;
  8101. if (NETDATA.alarms.current !== null) {
  8102. // get the current value_string
  8103. let t = NETDATA.alarms.current.alarms[entry.chart + '.' + entry.name];
  8104. if (typeof t !== 'undefined' && entry.status === t.status && typeof t.value_string !== 'undefined') {
  8105. value_string = t.value_string;
  8106. }
  8107. }
  8108. let name = entry.name.replace(/_/g, ' ');
  8109. let status = entry.status.toLowerCase();
  8110. let title = name + ' = ' + value_string.toString();
  8111. let tag = entry.alarm_id;
  8112. let icon = 'images/banner-icon-144x144.png';
  8113. let interaction = false;
  8114. let data = entry;
  8115. let show = true;
  8116. // console.log('alarm ' + entry.unique_id + ' ' + entry.chart + '.' + entry.name + ' is ' + entry.status);
  8117. switch (entry.status) {
  8118. case 'REMOVED':
  8119. show = false;
  8120. break;
  8121. case 'UNDEFINED':
  8122. return;
  8123. case 'UNINITIALIZED':
  8124. return;
  8125. case 'CLEAR':
  8126. if (entry.unique_id < NETDATA.alarms.first_notification_id) {
  8127. // console.log('alarm ' + entry.unique_id + ' is not current');
  8128. return;
  8129. }
  8130. if (entry.old_status === 'UNINITIALIZED' || entry.old_status === 'UNDEFINED') {
  8131. // console.log('alarm' + entry.unique_id + ' switch to CLEAR from ' + entry.old_status);
  8132. return;
  8133. }
  8134. if (entry.no_clear_notification) {
  8135. // console.log('alarm' + entry.unique_id + ' is CLEAR but has no_clear_notification flag');
  8136. return;
  8137. }
  8138. title = name + ' back to normal (' + value_string.toString() + ')';
  8139. icon = 'images/check-mark-2-128-green.png';
  8140. interaction = false;
  8141. break;
  8142. case 'WARNING':
  8143. if (entry.old_status === 'CRITICAL') {
  8144. status = 'demoted to ' + entry.status.toLowerCase();
  8145. }
  8146. icon = 'images/alert-128-orange.png';
  8147. interaction = false;
  8148. break;
  8149. case 'CRITICAL':
  8150. if (entry.old_status === 'WARNING') {
  8151. status = 'escalated to ' + entry.status.toLowerCase();
  8152. }
  8153. icon = 'images/alert-128-red.png';
  8154. interaction = true;
  8155. break;
  8156. default:
  8157. console.log('invalid alarm status ' + entry.status);
  8158. return;
  8159. }
  8160. // filter recipients
  8161. if (show) {
  8162. show = NETDATA.alarms.recipientMatches(entry.recipient, NETDATA.alarms.recipients);
  8163. }
  8164. /*
  8165. // cleanup old notifications with the same alarm_id as this one
  8166. // it does not seem to work on any web browser - so notifications cannot be removed
  8167. let len = NETDATA.alarms.notifications_shown.length;
  8168. while (len--) {
  8169. let n = NETDATA.alarms.notifications_shown[len];
  8170. if (n.data.alarm_id === entry.alarm_id) {
  8171. console.log('removing old alarm ' + n.data.unique_id);
  8172. // close the notification
  8173. n.close.bind(n);
  8174. // remove it from the array
  8175. NETDATA.alarms.notifications_shown.splice(len, 1);
  8176. len = NETDATA.alarms.notifications_shown.length;
  8177. }
  8178. }
  8179. */
  8180. if (show) {
  8181. if (typeof NETDATA.alarms.notificationCallback === 'function') {
  8182. show = NETDATA.alarms.notificationCallback(entry);
  8183. }
  8184. if (show) {
  8185. setTimeout(function () {
  8186. // show this notification
  8187. // console.log('new notification: ' + title);
  8188. let n = new Notification(title, {
  8189. body: entry.hostname + ' - ' + entry.chart + ' (' + entry.family + ') - ' + status + ': ' + entry.info,
  8190. tag: tag,
  8191. requireInteraction: interaction,
  8192. icon: NETDATA.serverStatic + icon,
  8193. data: data
  8194. });
  8195. n.onclick = function (event) {
  8196. event.preventDefault();
  8197. NETDATA.alarms.onclick(event.target.data);
  8198. };
  8199. // console.log(n);
  8200. // NETDATA.alarms.notifications_shown.push(n);
  8201. // console.log(entry);
  8202. }, NETDATA.alarms.ms_penalty);
  8203. NETDATA.alarms.ms_penalty += NETDATA.alarms.ms_between_notifications;
  8204. }
  8205. }
  8206. },
  8207. scrollToChart: function (chart_id) {
  8208. if (typeof chart_id === 'string') {
  8209. let offset = $('#' + NETDATA.alarms.chart_div_id_prefix + NETDATA.name2id(chart_id)).offset();
  8210. if (typeof offset !== 'undefined') {
  8211. $('html, body').animate({scrollTop: offset.top + NETDATA.alarms.chart_div_offset}, NETDATA.alarms.chart_div_animation_duration);
  8212. return true;
  8213. }
  8214. }
  8215. return false;
  8216. },
  8217. scrollToAlarm: function (alarm) {
  8218. if (typeof alarm === 'object') {
  8219. let ret = NETDATA.alarms.scrollToChart(alarm.chart);
  8220. if (ret && NETDATA.options.page_is_visible === false) {
  8221. window.focus();
  8222. }
  8223. // alert('netdata dashboard will now scroll to chart: ' + alarm.chart + '\n\nThis alarm opened to bring the browser window in front of the screen. Click on the dashboard to prevent it from appearing again.');
  8224. }
  8225. },
  8226. notifyAll: function () {
  8227. // console.log('FETCHING ALARM LOG');
  8228. NETDATA.alarms.get_log(NETDATA.alarms.last_notification_id, function (data) {
  8229. // console.log('ALARM LOG FETCHED');
  8230. if (data === null || typeof data !== 'object') {
  8231. console.log('invalid alarms log response');
  8232. return;
  8233. }
  8234. if (data.length === 0) {
  8235. console.log('received empty alarm log');
  8236. return;
  8237. }
  8238. // console.log('received alarm log of ' + data.length + ' entries, from ' + data[data.length - 1].unique_id.toString() + ' to ' + data[0].unique_id.toString());
  8239. data.sort(function (a, b) {
  8240. if (a.unique_id > b.unique_id) {
  8241. return -1;
  8242. }
  8243. if (a.unique_id < b.unique_id) {
  8244. return 1;
  8245. }
  8246. return 0;
  8247. });
  8248. NETDATA.alarms.ms_penalty = 0;
  8249. let len = data.length;
  8250. while (len--) {
  8251. if (data[len].unique_id > NETDATA.alarms.last_notification_id) {
  8252. NETDATA.alarms.notify(data[len]);
  8253. }
  8254. //else
  8255. // console.log('ignoring alarm (older) with id ' + data[len].unique_id.toString());
  8256. }
  8257. NETDATA.alarms.last_notification_id = data[0].unique_id;
  8258. if (typeof netdataAlarmsRemember === 'undefined' || netdataAlarmsRemember) {
  8259. NETDATA.localStorageSet('last_notification_id', NETDATA.alarms.last_notification_id, null);
  8260. }
  8261. // console.log('last notification id = ' + NETDATA.alarms.last_notification_id);
  8262. })
  8263. },
  8264. check_notifications: function () {
  8265. // returns true if we should fire 1+ notifications
  8266. if (NETDATA.alarms.notifications !== true) {
  8267. // console.log('web notifications are not available');
  8268. return false;
  8269. }
  8270. if (Notification.permission !== 'granted') {
  8271. // console.log('web notifications are not granted');
  8272. return false;
  8273. }
  8274. if (typeof NETDATA.alarms.current !== 'undefined' && typeof NETDATA.alarms.current.alarms === 'object') {
  8275. // console.log('can do alarms: old id = ' + NETDATA.alarms.last_notification_id + ' new id = ' + NETDATA.alarms.current.latest_alarm_log_unique_id);
  8276. if (NETDATA.alarms.current.latest_alarm_log_unique_id > NETDATA.alarms.last_notification_id) {
  8277. // console.log('new alarms detected');
  8278. return true;
  8279. }
  8280. //else console.log('no new alarms');
  8281. }
  8282. // else console.log('cannot process alarms');
  8283. return false;
  8284. },
  8285. get: function (what, callback) {
  8286. $.ajax({
  8287. url: NETDATA.alarms.server + '/api/v1/alarms?' + what.toString(),
  8288. async: true,
  8289. cache: false,
  8290. headers: {
  8291. 'Cache-Control': 'no-cache, no-store',
  8292. 'Pragma': 'no-cache'
  8293. },
  8294. xhrFields: {withCredentials: true} // required for the cookie
  8295. })
  8296. .done(function (data) {
  8297. data = NETDATA.xss.checkOptional('/api/v1/alarms', data /*, '.*\.(calc|calc_parsed|warn|warn_parsed|crit|crit_parsed)$' */);
  8298. if (NETDATA.alarms.first_notification_id === 0 && typeof data.latest_alarm_log_unique_id === 'number') {
  8299. NETDATA.alarms.first_notification_id = data.latest_alarm_log_unique_id;
  8300. }
  8301. if (typeof callback === 'function') {
  8302. return callback(data);
  8303. }
  8304. })
  8305. .fail(function () {
  8306. NETDATA.error(415, NETDATA.alarms.server);
  8307. if (typeof callback === 'function') {
  8308. return callback(null);
  8309. }
  8310. });
  8311. },
  8312. update_forever: function () {
  8313. if (netdataShowAlarms !== true || netdataSnapshotData !== null) {
  8314. return;
  8315. }
  8316. NETDATA.alarms.get('active', function (data) {
  8317. if (data !== null) {
  8318. NETDATA.alarms.current = data;
  8319. if (NETDATA.alarms.check_notifications()) {
  8320. NETDATA.alarms.notifyAll();
  8321. }
  8322. if (typeof NETDATA.alarms.callback === 'function') {
  8323. NETDATA.alarms.callback(data);
  8324. }
  8325. // Health monitoring is disabled on this netdata
  8326. if (data.status === false) {
  8327. return;
  8328. }
  8329. }
  8330. setTimeout(NETDATA.alarms.update_forever, NETDATA.alarms.update_every);
  8331. });
  8332. },
  8333. get_log: function (last_id, callback) {
  8334. // console.log('fetching all log after ' + last_id.toString());
  8335. $.ajax({
  8336. url: NETDATA.alarms.server + '/api/v1/alarm_log?after=' + last_id.toString(),
  8337. async: true,
  8338. cache: false,
  8339. headers: {
  8340. 'Cache-Control': 'no-cache, no-store',
  8341. 'Pragma': 'no-cache'
  8342. },
  8343. xhrFields: {withCredentials: true} // required for the cookie
  8344. })
  8345. .done(function (data) {
  8346. data = NETDATA.xss.checkOptional('/api/v1/alarm_log', data);
  8347. if (typeof callback === 'function') {
  8348. return callback(data);
  8349. }
  8350. })
  8351. .fail(function () {
  8352. NETDATA.error(416, NETDATA.alarms.server);
  8353. if (typeof callback === 'function') {
  8354. return callback(null);
  8355. }
  8356. });
  8357. },
  8358. init: function () {
  8359. NETDATA.alarms.server = NETDATA.fixHost(NETDATA.serverDefault);
  8360. if (typeof netdataAlarmsRemember === 'undefined' || netdataAlarmsRemember) {
  8361. NETDATA.alarms.last_notification_id =
  8362. NETDATA.localStorageGet('last_notification_id', NETDATA.alarms.last_notification_id, null);
  8363. }
  8364. if (NETDATA.alarms.onclick === null) {
  8365. NETDATA.alarms.onclick = NETDATA.alarms.scrollToAlarm;
  8366. }
  8367. if (typeof netdataAlarmsRecipients !== 'undefined' && Array.isArray(netdataAlarmsRecipients)) {
  8368. NETDATA.alarms.recipients = netdataAlarmsRecipients;
  8369. }
  8370. if (netdataShowAlarms) {
  8371. NETDATA.alarms.update_forever();
  8372. if ('Notification' in window) {
  8373. // console.log('notifications available');
  8374. NETDATA.alarms.notifications = true;
  8375. if (Notification.permission === 'default') {
  8376. Notification.requestPermission();
  8377. }
  8378. }
  8379. }
  8380. }
  8381. };
  8382. // Registry of netdata hosts
  8383. NETDATA.registry = {
  8384. server: null, // the netdata registry server
  8385. isCloudEnabled: false,// is netdata.cloud functionality enabled?
  8386. cloudBaseURL: null, // the netdata cloud base url
  8387. person_guid: null, // the unique ID of this browser / user
  8388. machine_guid: null, // the unique ID the netdata server that served dashboard.js
  8389. hostname: 'unknown', // the hostname of the netdata server that served dashboard.js
  8390. machines: null, // the user's other URLs
  8391. machines_array: null, // the user's other URLs in an array
  8392. person_urls: null,
  8393. anonymous_statistics_checked: false,
  8394. MASKED_DATA: "***",
  8395. isUsingGlobalRegistry: function() {
  8396. return NETDATA.registry.server == "https://registry.my-netdata.io";
  8397. },
  8398. isRegistryEnabled: function() {
  8399. return !(NETDATA.registry.isUsingGlobalRegistry() || isSignedIn())
  8400. },
  8401. parsePersonUrls: function (person_urls) {
  8402. NETDATA.registry.person_urls = person_urls;
  8403. if (person_urls) {
  8404. NETDATA.registry.machines = {};
  8405. NETDATA.registry.machines_array = [];
  8406. let apu = person_urls;
  8407. let i = apu.length;
  8408. while (i--) {
  8409. if (typeof NETDATA.registry.machines[apu[i][0]] === 'undefined') {
  8410. // console.log('adding: ' + apu[i][4] + ', ' + ((now - apu[i][2]) / 1000).toString());
  8411. let obj = {
  8412. guid: apu[i][0],
  8413. url: apu[i][1],
  8414. last_t: apu[i][2],
  8415. accesses: apu[i][3],
  8416. name: apu[i][4],
  8417. alternate_urls: []
  8418. };
  8419. obj.alternate_urls.push(apu[i][1]);
  8420. NETDATA.registry.machines[apu[i][0]] = obj;
  8421. NETDATA.registry.machines_array.push(obj);
  8422. } else {
  8423. // console.log('appending: ' + apu[i][4] + ', ' + ((now - apu[i][2]) / 1000).toString());
  8424. let pu = NETDATA.registry.machines[apu[i][0]];
  8425. if (pu.last_t < apu[i][2]) {
  8426. pu.url = apu[i][1];
  8427. pu.last_t = apu[i][2];
  8428. pu.name = apu[i][4];
  8429. }
  8430. pu.accesses += apu[i][3];
  8431. pu.alternate_urls.push(apu[i][1]);
  8432. }
  8433. }
  8434. }
  8435. if (typeof netdataRegistryCallback === 'function') {
  8436. netdataRegistryCallback(NETDATA.registry.machines_array);
  8437. }
  8438. },
  8439. init: function () {
  8440. if (netdataRegistry !== true) {
  8441. return;
  8442. }
  8443. NETDATA.registry.hello(NETDATA.serverDefault, function (data) {
  8444. if (data) {
  8445. NETDATA.registry.server = data.registry;
  8446. if (data.cloud_base_url !== "") {
  8447. NETDATA.registry.isCloudEnabled = true;
  8448. NETDATA.registry.cloudBaseURL = data.cloud_base_url;
  8449. } else {
  8450. NETDATA.registry.isCloudEnabled = false;
  8451. NETDATA.registry.cloudBaseURL = "";
  8452. }
  8453. NETDATA.registry.machine_guid = data.machine_guid;
  8454. NETDATA.registry.hostname = data.hostname;
  8455. if (!NETDATA.registry.anonymous_statistics_checked) {
  8456. NETDATA.registry.anonymous_statistics_checked=true;
  8457. if (data.anonymous_statistics) {
  8458. (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  8459. new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  8460. j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=false;j.src=
  8461. 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  8462. })(window,document,'script','dataLayer','GTM-N6CBMJD');
  8463. dataLayer.push({"anonymous_statistics" : "true", "machine_guid" : data.machine_guid});
  8464. }
  8465. }
  8466. NETDATA.registry.access(2, function (person_urls) {
  8467. NETDATA.registry.parsePersonUrls(person_urls);
  8468. });
  8469. }
  8470. });
  8471. },
  8472. hello: function (host, callback) {
  8473. host = NETDATA.fixHost(host);
  8474. // send HELLO to a netdata server:
  8475. // 1. verifies the server is reachable
  8476. // 2. responds with the registry URL, the machine GUID of this netdata server and its hostname
  8477. $.ajax({
  8478. url: host + '/api/v1/registry?action=hello',
  8479. async: true,
  8480. cache: false,
  8481. headers: {
  8482. 'Cache-Control': 'no-cache, no-store',
  8483. 'Pragma': 'no-cache'
  8484. },
  8485. xhrFields: {withCredentials: true} // required for the cookie
  8486. })
  8487. .done(function (data) {
  8488. data = NETDATA.xss.checkOptional('/api/v1/registry?action=hello', data);
  8489. if (typeof data.status !== 'string' || data.status !== 'ok') {
  8490. NETDATA.error(408, host + ' response: ' + JSON.stringify(data));
  8491. data = null;
  8492. }
  8493. if (typeof callback === 'function') {
  8494. return callback(data);
  8495. }
  8496. })
  8497. .fail(function () {
  8498. NETDATA.error(407, host);
  8499. if (typeof callback === 'function') {
  8500. return callback(null);
  8501. }
  8502. });
  8503. },
  8504. access: function (max_redirects, callback) {
  8505. let name = NETDATA.registry.hostname;
  8506. let url = NETDATA.serverDefault;
  8507. console.log("ACCESS", name, url);
  8508. // send ACCESS to a netdata registry:
  8509. // 1. it lets it know we are accessing a netdata server (its machine GUID and its URL)
  8510. // 2. it responds with a list of netdata servers we know
  8511. // the registry identifies us using a cookie it sets the first time we access it
  8512. // the registry may respond with a redirect URL to send us to another registry
  8513. $.ajax({
  8514. url: NETDATA.registry.server + '/api/v1/registry?action=access&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(name) + '&url=' + encodeURIComponent(url), // + '&visible_url=' + encodeURIComponent(document.location),
  8515. async: true,
  8516. cache: false,
  8517. headers: {
  8518. 'Cache-Control': 'no-cache, no-store',
  8519. 'Pragma': 'no-cache'
  8520. },
  8521. xhrFields: {withCredentials: true} // required for the cookie
  8522. })
  8523. .done(function (data) {
  8524. data = NETDATA.xss.checkAlways('/api/v1/registry?action=access', data);
  8525. let redirect = null;
  8526. if (typeof data.registry === 'string') {
  8527. redirect = data.registry;
  8528. }
  8529. if (typeof data.status !== 'string' || data.status !== 'ok') {
  8530. NETDATA.error(409, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data));
  8531. data = null;
  8532. }
  8533. if (data === null) {
  8534. if (redirect !== null && max_redirects > 0) {
  8535. NETDATA.registry.server = redirect;
  8536. NETDATA.registry.access(max_redirects - 1, callback);
  8537. }
  8538. else {
  8539. if (typeof callback === 'function') {
  8540. return callback(null);
  8541. }
  8542. }
  8543. } else {
  8544. if (typeof data.person_guid === 'string') {
  8545. NETDATA.registry.person_guid = data.person_guid;
  8546. }
  8547. if (typeof callback === 'function') {
  8548. const urls = data.urls.filter((u) => u[1] !== NETDATA.registry.MASKED_DATA);
  8549. return callback(urls);
  8550. }
  8551. }
  8552. })
  8553. .fail(function () {
  8554. NETDATA.error(410, NETDATA.registry.server);
  8555. if (typeof callback === 'function') {
  8556. return callback(null);
  8557. }
  8558. });
  8559. },
  8560. delete: function (delete_url, callback) {
  8561. // send DELETE to a netdata registry:
  8562. $.ajax({
  8563. url: NETDATA.registry.server + '/api/v1/registry?action=delete&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&delete_url=' + encodeURIComponent(delete_url),
  8564. async: true,
  8565. cache: false,
  8566. headers: {
  8567. 'Cache-Control': 'no-cache, no-store',
  8568. 'Pragma': 'no-cache'
  8569. },
  8570. xhrFields: {withCredentials: true} // required for the cookie
  8571. })
  8572. .done(function (data) {
  8573. data = NETDATA.xss.checkAlways('/api/v1/registry?action=delete', data);
  8574. if (typeof data.status !== 'string' || data.status !== 'ok') {
  8575. NETDATA.error(411, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data));
  8576. data = null;
  8577. }
  8578. if (typeof callback === 'function') {
  8579. return callback(data);
  8580. }
  8581. })
  8582. .fail(function () {
  8583. NETDATA.error(412, NETDATA.registry.server);
  8584. if (typeof callback === 'function') {
  8585. return callback(null);
  8586. }
  8587. });
  8588. },
  8589. search: function (machine_guid, callback) {
  8590. // SEARCH for the URLs of a machine:
  8591. $.ajax({
  8592. url: NETDATA.registry.server + '/api/v1/registry?action=search&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&for=' + machine_guid,
  8593. async: true,
  8594. cache: false,
  8595. headers: {
  8596. 'Cache-Control': 'no-cache, no-store',
  8597. 'Pragma': 'no-cache'
  8598. },
  8599. xhrFields: {withCredentials: true} // required for the cookie
  8600. })
  8601. .done(function (data) {
  8602. data = NETDATA.xss.checkAlways('/api/v1/registry?action=search', data);
  8603. if (typeof data.status !== 'string' || data.status !== 'ok') {
  8604. NETDATA.error(417, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data));
  8605. data = null;
  8606. }
  8607. if (typeof callback === 'function') {
  8608. return callback(data);
  8609. }
  8610. })
  8611. .fail(function () {
  8612. NETDATA.error(418, NETDATA.registry.server);
  8613. if (typeof callback === 'function') {
  8614. return callback(null);
  8615. }
  8616. });
  8617. },
  8618. switch: function (new_person_guid, callback) {
  8619. // impersonate
  8620. $.ajax({
  8621. url: NETDATA.registry.server + '/api/v1/registry?action=switch&machine=' + NETDATA.registry.machine_guid + '&name=' + encodeURIComponent(NETDATA.registry.hostname) + '&url=' + encodeURIComponent(NETDATA.serverDefault) + '&to=' + new_person_guid,
  8622. async: true,
  8623. cache: false,
  8624. headers: {
  8625. 'Cache-Control': 'no-cache, no-store',
  8626. 'Pragma': 'no-cache'
  8627. },
  8628. xhrFields: {withCredentials: true} // required for the cookie
  8629. })
  8630. .done(function (data) {
  8631. data = NETDATA.xss.checkAlways('/api/v1/registry?action=switch', data);
  8632. if (typeof data.status !== 'string' || data.status !== 'ok') {
  8633. NETDATA.error(413, NETDATA.registry.server + ' responded with: ' + JSON.stringify(data));
  8634. data = null;
  8635. }
  8636. if (typeof callback === 'function') {
  8637. return callback(data);
  8638. }
  8639. })
  8640. .fail(function () {
  8641. NETDATA.error(414, NETDATA.registry.server);
  8642. if (typeof callback === 'function') {
  8643. return callback(null);
  8644. }
  8645. });
  8646. }
  8647. };
  8648. // Load required JS libraries and CSS
  8649. NETDATA.requiredJs = [
  8650. {
  8651. url: NETDATA.serverStatic + 'lib/bootstrap-3.3.7.min.js',
  8652. async: false,
  8653. isAlreadyLoaded: function () {
  8654. // check if bootstrap is loaded
  8655. if (typeof $().emulateTransitionEnd === 'function') {
  8656. return true;
  8657. } else {
  8658. return typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap;
  8659. }
  8660. }
  8661. },
  8662. {
  8663. url: NETDATA.serverStatic + 'lib/fontawesome-all-5.0.1.min.js',
  8664. async: true,
  8665. isAlreadyLoaded: function () {
  8666. return typeof netdataNoFontAwesome !== 'undefined' && netdataNoFontAwesome;
  8667. }
  8668. },
  8669. {
  8670. url: NETDATA.serverStatic + 'lib/perfect-scrollbar-0.6.15.min.js',
  8671. isAlreadyLoaded: function () {
  8672. return false;
  8673. }
  8674. }
  8675. ];
  8676. NETDATA.requiredCSS = [
  8677. {
  8678. url: NETDATA.themes.current.bootstrap_css,
  8679. isAlreadyLoaded: function () {
  8680. return typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap;
  8681. }
  8682. },
  8683. {
  8684. url: NETDATA.themes.current.dashboard_css,
  8685. isAlreadyLoaded: function () {
  8686. return false;
  8687. }
  8688. }
  8689. ];
  8690. NETDATA.loadedRequiredJs = 0;
  8691. NETDATA.loadRequiredJs = function (index, callback) {
  8692. if (index >= NETDATA.requiredJs.length) {
  8693. if (typeof callback === 'function') {
  8694. return callback();
  8695. }
  8696. return;
  8697. }
  8698. if (NETDATA.requiredJs[index].isAlreadyLoaded()) {
  8699. NETDATA.loadedRequiredJs++;
  8700. NETDATA.loadRequiredJs(++index, callback);
  8701. return;
  8702. }
  8703. if (NETDATA.options.debug.main_loop) {
  8704. console.log('loading ' + NETDATA.requiredJs[index].url);
  8705. }
  8706. let async = true;
  8707. if (typeof NETDATA.requiredJs[index].async !== 'undefined' && NETDATA.requiredJs[index].async === false) {
  8708. async = false;
  8709. }
  8710. $.ajax({
  8711. url: NETDATA.requiredJs[index].url,
  8712. cache: true,
  8713. dataType: "script",
  8714. xhrFields: {withCredentials: true} // required for the cookie
  8715. })
  8716. .done(function () {
  8717. if (NETDATA.options.debug.main_loop) {
  8718. console.log('loaded ' + NETDATA.requiredJs[index].url);
  8719. }
  8720. })
  8721. .fail(function () {
  8722. alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
  8723. })
  8724. .always(function () {
  8725. NETDATA.loadedRequiredJs++;
  8726. // if (async === false)
  8727. if (!async) {
  8728. NETDATA.loadRequiredJs(++index, callback);
  8729. }
  8730. });
  8731. // if (async === true)
  8732. if (async) {
  8733. NETDATA.loadRequiredJs(++index, callback);
  8734. }
  8735. };
  8736. NETDATA.loadRequiredCSS = function (index) {
  8737. if (index >= NETDATA.requiredCSS.length) {
  8738. return;
  8739. }
  8740. if (NETDATA.requiredCSS[index].isAlreadyLoaded()) {
  8741. NETDATA.loadRequiredCSS(++index);
  8742. return;
  8743. }
  8744. if (NETDATA.options.debug.main_loop) {
  8745. console.log('loading ' + NETDATA.requiredCSS[index].url);
  8746. }
  8747. NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
  8748. NETDATA.loadRequiredCSS(++index);
  8749. };
  8750. // Boot it!
  8751. if (typeof netdataPrepCallback === 'function') {
  8752. netdataPrepCallback();
  8753. }
  8754. NETDATA.errorReset();
  8755. NETDATA.loadRequiredCSS(0);
  8756. NETDATA._loadjQuery(function () {
  8757. NETDATA.loadRequiredJs(0, function () {
  8758. if (typeof $().emulateTransitionEnd !== 'function') {
  8759. // bootstrap is not available
  8760. NETDATA.options.current.show_help = false;
  8761. }
  8762. if (typeof netdataDontStart === 'undefined' || !netdataDontStart) {
  8763. if (NETDATA.options.debug.main_loop) {
  8764. console.log('starting chart refresh thread');
  8765. }
  8766. NETDATA.start();
  8767. }
  8768. });
  8769. });
  8770. })(window, document, (typeof jQuery === 'function')?jQuery:undefined);