main.js 186 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162
  1. // Main JavaScript file for the Netdata GUI.
  2. // Codacy declarations
  3. /* global NETDATA */
  4. // netdata snapshot data
  5. var netdataSnapshotData = null;
  6. // enable alarms checking and notifications
  7. var netdataShowAlarms = true;
  8. // enable registry updates
  9. var netdataRegistry = true;
  10. // forward definition only - not used here
  11. var netdataServer = undefined;
  12. var netdataServerStatic = undefined;
  13. var netdataCheckXSS = undefined;
  14. // control the welcome modal and analytics
  15. var this_is_demo = null;
  16. function escapeUserInputHTML(s) {
  17. return s.toString()
  18. .replace(/&/g, '&')
  19. .replace(/</g, '&lt;')
  20. .replace(/>/g, '&gt;')
  21. .replace(/"/g, '&quot;')
  22. .replace(/#/g, '&#35;')
  23. .replace(/'/g, '&#39;')
  24. .replace(/\(/g, '&#40;')
  25. .replace(/\)/g, '&#41;')
  26. .replace(/\//g, '&#47;');
  27. }
  28. function verifyURL(s) {
  29. if (typeof (s) === 'string' && (s.startsWith('http://') || s.startsWith('https://'))) {
  30. return s
  31. .replace(/'/g, '%22')
  32. .replace(/"/g, '%27')
  33. .replace(/\)/g, '%28')
  34. .replace(/\(/g, '%29');
  35. }
  36. console.log('invalid URL detected:');
  37. console.log(s);
  38. return 'javascript:alert("invalid url");';
  39. }
  40. // --------------------------------------------------------------------
  41. // urlOptions
  42. var urlOptions = {
  43. hash: '#',
  44. theme: null,
  45. help: null,
  46. mode: 'live', // 'live', 'print'
  47. update_always: false,
  48. pan_and_zoom: false,
  49. server: null,
  50. after: 0,
  51. before: 0,
  52. highlight: false,
  53. highlight_after: 0,
  54. highlight_before: 0,
  55. nowelcome: false,
  56. show_alarms: false,
  57. chart: null,
  58. family: null,
  59. alarm: null,
  60. alarm_unique_id: 0,
  61. alarm_id: 0,
  62. alarm_event_id: 0,
  63. alarm_when: 0,
  64. hasProperty: function (property) {
  65. // console.log('checking property ' + property + ' of type ' + typeof(this[property]));
  66. return typeof this[property] !== 'undefined';
  67. },
  68. genHash: function (forReload) {
  69. var hash = urlOptions.hash;
  70. if (urlOptions.pan_and_zoom === true) {
  71. hash += ';after=' + urlOptions.after.toString() +
  72. ';before=' + urlOptions.before.toString();
  73. }
  74. if (urlOptions.highlight === true) {
  75. hash += ';highlight_after=' + urlOptions.highlight_after.toString() +
  76. ';highlight_before=' + urlOptions.highlight_before.toString();
  77. }
  78. if (urlOptions.theme !== null) {
  79. hash += ';theme=' + urlOptions.theme.toString();
  80. }
  81. if (urlOptions.help !== null) {
  82. hash += ';help=' + urlOptions.help.toString();
  83. }
  84. if (urlOptions.update_always === true) {
  85. hash += ';update_always=true';
  86. }
  87. if (forReload === true && urlOptions.server !== null) {
  88. hash += ';server=' + urlOptions.server.toString();
  89. }
  90. if (urlOptions.mode !== 'live') {
  91. hash += ';mode=' + urlOptions.mode;
  92. }
  93. return hash;
  94. },
  95. parseHash: function () {
  96. var variables = document.location.hash.split(';');
  97. var len = variables.length;
  98. while (len--) {
  99. if (len !== 0) {
  100. var p = variables[len].split('=');
  101. if (urlOptions.hasProperty(p[0]) && typeof p[1] !== 'undefined') {
  102. urlOptions[p[0]] = decodeURIComponent(p[1]);
  103. }
  104. } else {
  105. if (variables[len].length > 0) {
  106. urlOptions.hash = variables[len];
  107. }
  108. }
  109. }
  110. var booleans = ['nowelcome', 'show_alarms', 'update_always'];
  111. len = booleans.length;
  112. while (len--) {
  113. if (urlOptions[booleans[len]] === 'true' || urlOptions[booleans[len]] === true || urlOptions[booleans[len]] === '1' || urlOptions[booleans[len]] === 1) {
  114. urlOptions[booleans[len]] = true;
  115. } else {
  116. urlOptions[booleans[len]] = false;
  117. }
  118. }
  119. var numeric = ['after', 'before', 'highlight_after', 'highlight_before', 'alarm_when'];
  120. len = numeric.length;
  121. while (len--) {
  122. if (typeof urlOptions[numeric[len]] === 'string') {
  123. try {
  124. urlOptions[numeric[len]] = parseInt(urlOptions[numeric[len]]);
  125. }
  126. catch (e) {
  127. console.log('failed to parse URL hash parameter ' + numeric[len]);
  128. urlOptions[numeric[len]] = 0;
  129. }
  130. }
  131. }
  132. if (urlOptions.alarm_when) {
  133. // if alarm_when exists, create after/before params
  134. // -/+ 2 minutes from the alarm, and reload the page
  135. const alarmTime = new Date(urlOptions.alarm_when * 1000).valueOf();
  136. const timeMarginMs = 120000; // 2 mins
  137. const after = alarmTime - timeMarginMs;
  138. const before = alarmTime + timeMarginMs;
  139. const newHash = document.location.hash.replace(
  140. /;alarm_when=[0-9]*/i,
  141. ";after=" + after + ";before=" + before,
  142. );
  143. history.replaceState(null, '', newHash);
  144. location.reload();
  145. }
  146. if (urlOptions.server !== null && urlOptions.server !== '') {
  147. netdataServerStatic = document.location.origin.toString() + document.location.pathname.toString();
  148. netdataServer = urlOptions.server;
  149. netdataCheckXSS = true;
  150. } else {
  151. urlOptions.server = null;
  152. }
  153. if (urlOptions.before > 0 && urlOptions.after > 0) {
  154. urlOptions.pan_and_zoom = true;
  155. urlOptions.nowelcome = true;
  156. } else {
  157. urlOptions.pan_and_zoom = false;
  158. }
  159. if (urlOptions.highlight_before > 0 && urlOptions.highlight_after > 0) {
  160. urlOptions.highlight = true;
  161. } else {
  162. urlOptions.highlight = false;
  163. }
  164. switch (urlOptions.mode) {
  165. case 'print':
  166. urlOptions.theme = 'white';
  167. urlOptions.welcome = false;
  168. urlOptions.help = false;
  169. urlOptions.show_alarms = false;
  170. if (urlOptions.pan_and_zoom === false) {
  171. urlOptions.pan_and_zoom = true;
  172. urlOptions.before = Date.now();
  173. urlOptions.after = urlOptions.before - 600000;
  174. }
  175. netdataShowAlarms = false;
  176. netdataRegistry = false;
  177. this_is_demo = false;
  178. break;
  179. case 'live':
  180. default:
  181. urlOptions.mode = 'live';
  182. break;
  183. }
  184. // console.log(urlOptions);
  185. },
  186. hashUpdate: function () {
  187. history.replaceState(null, '', urlOptions.genHash(true));
  188. },
  189. netdataPanAndZoomCallback: function (status, after, before) {
  190. //console.log(1);
  191. //console.log(new Error().stack);
  192. if (netdataSnapshotData === null) {
  193. urlOptions.pan_and_zoom = status;
  194. urlOptions.after = after;
  195. urlOptions.before = before;
  196. urlOptions.hashUpdate();
  197. }
  198. },
  199. netdataHighlightCallback: function (status, after, before) {
  200. //console.log(2);
  201. //console.log(new Error().stack);
  202. if (status === true && (after === null || before === null || after <= 0 || before <= 0 || after >= before)) {
  203. status = false;
  204. after = 0;
  205. before = 0;
  206. }
  207. if (netdataSnapshotData === null) {
  208. urlOptions.highlight = status;
  209. } else {
  210. urlOptions.highlight = false;
  211. }
  212. urlOptions.highlight_after = Math.round(after);
  213. urlOptions.highlight_before = Math.round(before);
  214. urlOptions.hashUpdate();
  215. var show_eye = NETDATA.globalChartUnderlay.hasViewport();
  216. if (status === true && after > 0 && before > 0 && after < before) {
  217. var d1 = NETDATA.dateTime.localeDateString(after);
  218. var d2 = NETDATA.dateTime.localeDateString(before);
  219. if (d1 === d2) {
  220. d2 = '';
  221. }
  222. document.getElementById('navbar-highlight-content').innerHTML =
  223. ((show_eye === true) ? '<span class="navbar-highlight-bar highlight-tooltip" onclick="urlOptions.showHighlight();" title="restore the highlighted view" data-toggle="tooltip" data-placement="bottom">' : '<span>').toString()
  224. + 'highlighted time-frame'
  225. + ' <b>' + d1 + ' <code>' + NETDATA.dateTime.localeTimeString(after) + '</code></b> to '
  226. + ' <b>' + d2 + ' <code>' + NETDATA.dateTime.localeTimeString(before) + '</code></b>, '
  227. + 'duration <b>' + NETDATA.seconds4human(Math.round((before - after) / 1000)) + '</b>'
  228. + '</span>'
  229. + '<span class="navbar-highlight-button-right highlight-tooltip" onclick="urlOptions.clearHighlight();" title="clear the highlighted time-frame" data-toggle="tooltip" data-placement="bottom"><i class="fas fa-times"></i></span>';
  230. $('.navbar-highlight').show();
  231. $('.highlight-tooltip').tooltip({
  232. html: true,
  233. delay: { show: 500, hide: 0 },
  234. container: 'body'
  235. });
  236. } else {
  237. $('.navbar-highlight').hide();
  238. }
  239. },
  240. clearHighlight: function () {
  241. NETDATA.globalChartUnderlay.clear();
  242. if (NETDATA.globalPanAndZoom.isActive() === true) {
  243. NETDATA.globalPanAndZoom.clearMaster();
  244. }
  245. },
  246. showHighlight: function () {
  247. NETDATA.globalChartUnderlay.focus();
  248. }
  249. };
  250. urlOptions.parseHash();
  251. // --------------------------------------------------------------------
  252. // check options that should be processed before loading netdata.js
  253. var localStorageTested = -1;
  254. function localStorageTest() {
  255. if (localStorageTested !== -1) {
  256. return localStorageTested;
  257. }
  258. if (typeof Storage !== "undefined" && typeof localStorage === 'object') {
  259. var test = 'test';
  260. try {
  261. localStorage.setItem(test, test);
  262. localStorage.removeItem(test);
  263. localStorageTested = true;
  264. }
  265. catch (e) {
  266. console.log(e);
  267. localStorageTested = false;
  268. }
  269. } else {
  270. localStorageTested = false;
  271. }
  272. return localStorageTested;
  273. }
  274. function loadLocalStorage(name) {
  275. var ret = null;
  276. try {
  277. if (localStorageTest() === true) {
  278. ret = localStorage.getItem(name);
  279. } else {
  280. console.log('localStorage is not available');
  281. }
  282. }
  283. catch (error) {
  284. console.log(error);
  285. return null;
  286. }
  287. if (typeof ret === 'undefined' || ret === null) {
  288. return null;
  289. }
  290. // console.log('loaded: ' + name.toString() + ' = ' + ret.toString());
  291. return ret;
  292. }
  293. function saveLocalStorage(name, value) {
  294. // console.log('saving: ' + name.toString() + ' = ' + value.toString());
  295. try {
  296. if (localStorageTest() === true) {
  297. localStorage.setItem(name, value.toString());
  298. return true;
  299. }
  300. }
  301. catch (error) {
  302. console.log(error);
  303. }
  304. return false;
  305. }
  306. function getTheme(def) {
  307. if (urlOptions.mode === 'print') {
  308. return 'white';
  309. }
  310. var ret = loadLocalStorage('netdataTheme');
  311. if (typeof ret === 'undefined' || ret === null || ret === 'undefined') {
  312. return def;
  313. } else {
  314. return ret;
  315. }
  316. }
  317. function setTheme(theme) {
  318. if (urlOptions.mode === 'print') {
  319. return false;
  320. }
  321. if (theme === netdataTheme) {
  322. return false;
  323. }
  324. return saveLocalStorage('netdataTheme', theme);
  325. }
  326. var netdataTheme = getTheme('slate');
  327. var netdataShowHelp = true;
  328. if (urlOptions.theme !== null) {
  329. setTheme(urlOptions.theme);
  330. netdataTheme = urlOptions.theme;
  331. } else {
  332. urlOptions.theme = netdataTheme;
  333. }
  334. if (urlOptions.help !== null) {
  335. saveLocalStorage('options.show_help', urlOptions.help);
  336. netdataShowHelp = urlOptions.help;
  337. } else {
  338. urlOptions.help = loadLocalStorage('options.show_help');
  339. }
  340. // --------------------------------------------------------------------
  341. // natural sorting
  342. // http://www.davekoelle.com/files/alphanum.js - LGPL
  343. function naturalSortChunkify(t) {
  344. var tz = [];
  345. var x = 0, y = -1, n = 0, i, j;
  346. while (i = (j = t.charAt(x++)).charCodeAt(0)) {
  347. var m = (i >= 48 && i <= 57);
  348. if (m !== n) {
  349. tz[++y] = "";
  350. n = m;
  351. }
  352. tz[y] += j;
  353. }
  354. return tz;
  355. }
  356. function naturalSortCompare(a, b) {
  357. var aa = naturalSortChunkify(a.toLowerCase());
  358. var bb = naturalSortChunkify(b.toLowerCase());
  359. for (var x = 0; aa[x] && bb[x]; x++) {
  360. if (aa[x] !== bb[x]) {
  361. var c = Number(aa[x]), d = Number(bb[x]);
  362. if (c.toString() === aa[x] && d.toString() === bb[x]) {
  363. return c - d;
  364. } else {
  365. return (aa[x] > bb[x]) ? 1 : -1;
  366. }
  367. }
  368. }
  369. return aa.length - bb.length;
  370. }
  371. // --------------------------------------------------------------------
  372. // saving files to client
  373. function saveTextToClient(data, filename) {
  374. var blob = new Blob([data], {
  375. type: 'application/octet-stream'
  376. });
  377. var url = URL.createObjectURL(blob);
  378. var link = document.createElement('a');
  379. link.setAttribute('href', url);
  380. link.setAttribute('download', filename);
  381. var el = document.getElementById('hiddenDownloadLinks');
  382. el.innerHTML = '';
  383. el.appendChild(link);
  384. setTimeout(function () {
  385. el.removeChild(link);
  386. URL.revokeObjectURL(url);
  387. }, 60);
  388. link.click();
  389. }
  390. function saveObjectToClient(data, filename) {
  391. saveTextToClient(JSON.stringify(data), filename);
  392. }
  393. // -----------------------------------------------------------------------------
  394. // registry call back to render my-netdata menu
  395. function toggleExpandIcon(svgEl) {
  396. if (svgEl.getAttribute('data-icon') === 'caret-down') {
  397. svgEl.setAttribute('data-icon', 'caret-up');
  398. } else {
  399. svgEl.setAttribute('data-icon', 'caret-down');
  400. }
  401. }
  402. function toggleAgentItem(e, guid) {
  403. e.stopPropagation();
  404. e.preventDefault();
  405. toggleExpandIcon(e.currentTarget.children[0]);
  406. const el = document.querySelector(`.agent-alternate-urls.agent-${guid}`);
  407. if (el) {
  408. el.classList.toggle('collapsed');
  409. }
  410. }
  411. // When you stream metrics from netdata to netdata, the receiving netdata now
  412. // has multiple host databases. It's own, and multiple mirrored. Mirrored databases
  413. // can be accessed with <http://localhost:19999/host/NAME/>
  414. const OLD_DASHBOARD_SUFFIX = "old"
  415. let isOldSuffix = true
  416. try {
  417. const currentScriptMainJs = document.currentScript;
  418. const mainJsSrc = currentScriptMainJs.getAttribute("src")
  419. isOldSuffix = mainJsSrc.startsWith("../main.js")
  420. } catch {
  421. console.warn("current script not detecting, assuming the dashboard is running with /old suffix")
  422. }
  423. function transformWithOldSuffix(url) {
  424. return isOldSuffix ? `../${url}` : url
  425. }
  426. function renderStreamedHosts(options) {
  427. let html = `<div class="info-item">Databases streamed to this agent</div>`;
  428. var base = document.location.origin.toString() +
  429. document.location.pathname.toString()
  430. .replace(isOldSuffix ? `/${OLD_DASHBOARD_SUFFIX}` : "", "");
  431. if (base.endsWith("/host/" + options.hostname + "/")) {
  432. base = base.substring(0, base.length - ("/host/" + options.hostname + "/").toString().length);
  433. }
  434. if (base.endsWith("/")) {
  435. base = base.substring(0, base.length - 1);
  436. }
  437. var master = options.hosts[0].hostname;
  438. // We sort a clone of options.hosts, to keep the master as the first element
  439. // for future calls.
  440. var sorted = options.hosts.slice(0).sort(function (a, b) {
  441. if (a.hostname === master) {
  442. return -1;
  443. }
  444. return naturalSortCompare(a.hostname, b.hostname);
  445. });
  446. let displayedDatabases = false;
  447. for (var s of sorted) {
  448. let url, icon;
  449. const hostname = s.hostname;
  450. if (myNetdataMenuFilterValue !== "") {
  451. if (!hostname.includes(myNetdataMenuFilterValue)) {
  452. continue;
  453. }
  454. }
  455. displayedDatabases = true;
  456. if (hostname === master) {
  457. url = isOldSuffix ? `${base}/${OLD_DASHBOARD_SUFFIX}/` : `${base}/`;
  458. icon = 'home';
  459. } else {
  460. url = isOldSuffix ? `${base}/host/${hostname}/${OLD_DASHBOARD_SUFFIX}/` : `${base}/host/${hostname}/`;
  461. icon = 'window-restore';
  462. }
  463. html += (
  464. `<div class="agent-item">
  465. <a class="registry_link" href="${url}#" onClick="return gotoHostedModalHandler('${url}');">
  466. <i class="fas fa-${icon}" style="color: #999;"></i>
  467. </a>
  468. <span class="__title" onClick="return gotoHostedModalHandler('${url}');">
  469. <a class="registry_link" href="${url}#">${hostname}</a>
  470. </span>
  471. <div></div>
  472. </div>`
  473. )
  474. }
  475. if (!displayedDatabases) {
  476. html += (
  477. `<div class="info-item">
  478. <i class="fas fa-filter"></i>
  479. <span style="margin-left: 8px">no databases match the filter criteria.<span>
  480. </div>`
  481. )
  482. }
  483. return html;
  484. }
  485. function renderMachines(machinesArray) {
  486. let html = `<div class="info-item">My nodes</div>`;
  487. if (machinesArray === null) {
  488. let ret = loadLocalStorage("registryCallback");
  489. if (ret) {
  490. machinesArray = JSON.parse(ret);
  491. console.log("failed to contact the registry - loaded registry data from browser local storage");
  492. }
  493. }
  494. let found = false;
  495. let displayedAgents = false;
  496. const maskedURL = NETDATA.registry.MASKED_DATA;
  497. if (machinesArray) {
  498. saveLocalStorage("registryCallback", JSON.stringify(machinesArray));
  499. var machines = machinesArray.sort(function (a, b) {
  500. return naturalSortCompare(a.name, b.name);
  501. });
  502. for (var machine of machines) {
  503. found = true;
  504. if (myNetdataMenuFilterValue !== "") {
  505. if (!machine.name.includes(myNetdataMenuFilterValue)) {
  506. continue;
  507. }
  508. }
  509. displayedAgents = true;
  510. const alternateUrlItems = (
  511. `<div class="agent-alternate-urls agent-${machine.guid} collapsed">
  512. ${machine.alternate_urls.reduce((str, url) => {
  513. if (url === maskedURL) {
  514. return str
  515. }
  516. return str + (
  517. `<div class="agent-item agent-item--alternate">
  518. <div></div>
  519. <a href="${url}" title="${url}">${truncateString(url, 64)}</a>
  520. <a href="#" onclick="deleteRegistryModalHandler('${machine.guid}', '${machine.name}', '${url}'); return false;">
  521. <i class="fas fa-trash" style="color: #777;"></i>
  522. </a>
  523. </div>`
  524. )
  525. },
  526. ''
  527. )}
  528. </div>`
  529. )
  530. html += (
  531. `<div class="agent-item agent-${machine.guid}">
  532. <i class="fas fa-chart-bar" color: #fff"></i>
  533. <span class="__title" onClick="return gotoServerModalHandler('${machine.guid}');">
  534. <a class="registry_link" href="${machine.url}#">${machine.name}</a>
  535. </span>
  536. <a href="#" onClick="toggleAgentItem(event, '${machine.guid}');">
  537. <i class="fas fa-caret-down" style="color: #999"></i>
  538. </a>
  539. </div>
  540. ${alternateUrlItems}`
  541. )
  542. }
  543. if (found && (!displayedAgents)) {
  544. html += (
  545. `<div class="info-item">
  546. <i class="fas fa-filter"></i>
  547. <span style="margin-left: 8px">zero nodes are matching the filter value.<span>
  548. </div>`
  549. )
  550. }
  551. }
  552. if (!found) {
  553. if (machines) {
  554. html += (
  555. `<div class="info-item">
  556. <a href="https://github.com/netdata/netdata/tree/master/registry#registry" target="_blank">Your nodes list is empty</a>
  557. </div>`
  558. )
  559. } else {
  560. html += (
  561. `<div class="info-item">
  562. <a href="https://github.com/netdata/netdata/tree/master/registry#registry" target="_blank">Failed to contact the registry</a>
  563. </div>`
  564. )
  565. }
  566. html += `<hr />`;
  567. html += `<div class="info-item">Demo netdata nodes</div>`;
  568. const demoServers = [
  569. { url: "//london.netdata.rocks/default.html", title: "UK - London (DigitalOcean.com)" },
  570. { url: "//newyork.netdata.rocks/default.html", title: "US - New York (DigitalOcean.com)" },
  571. { url: "//sanfrancisco.netdata.rocks/default.html", title: "US - San Francisco (DigitalOcean.com)" },
  572. { url: "//atlanta.netdata.rocks/default.html", title: "US - Atlanta (CDN77.com)" },
  573. { url: "//frankfurt.netdata.rocks/default.html", title: "Germany - Frankfurt (DigitalOcean.com)" },
  574. { url: "//toronto.netdata.rocks/default.html", title: "Canada - Toronto (DigitalOcean.com)" },
  575. { url: "//singapore.netdata.rocks/default.html", title: "Japan - Singapore (DigitalOcean.com)" },
  576. { url: "//bangalore.netdata.rocks/default.html", title: "India - Bangalore (DigitalOcean.com)" },
  577. ]
  578. for (var server of demoServers) {
  579. html += (
  580. `<div class="agent-item">
  581. <i class="fas fa-chart-bar" style="color: #fff"></i>
  582. <a href="${server.url}">${server.title}</a>
  583. <div></div>
  584. </div>
  585. `
  586. );
  587. }
  588. }
  589. return html;
  590. }
  591. function setMyNetdataMenu(html) {
  592. const el = document.getElementById('my-netdata-dropdown-content')
  593. el.innerHTML = html;
  594. }
  595. function clearMyNetdataMenu() {
  596. setMyNetdataMenu(`<div class="agent-item" style="white-space: nowrap">
  597. <i class="fas fa-hourglass-half"></i>
  598. Loading, please wait...
  599. <div></div>
  600. </div>`);
  601. }
  602. function errorMyNetdataMenu() {
  603. setMyNetdataMenu(`<div class="agent-item" style="padding: 0 8px">
  604. <i class="fas fa-exclamation-triangle" style="color: red"></i>
  605. Cannot load known Netdata agents from Netdata Cloud! Please make sure you have the latest version of Netdata.
  606. </div>`);
  607. }
  608. function restrictMyNetdataMenu() {
  609. setMyNetdataMenu(`<div class="info-item" style="white-space: nowrap">
  610. <span>Please <a href="#" onclick="signInDidClick(event); return false">sign in to netdata.cloud</a> to view your nodes!</span>
  611. <div></div>
  612. </div>`);
  613. }
  614. function openAuthenticatedUrl(url) {
  615. if (isSignedIn()) {
  616. window.open(url);
  617. } else {
  618. window.open(`${NETDATA.registry.cloudBaseURL}/account/sign-in-agent?id=${NETDATA.registry.machine_guid}&name=${encodeURIComponent(NETDATA.registry.hostname)}&origin=${encodeURIComponent(window.location.origin + "/")}&redirect_uri=${encodeURIComponent(window.location.origin + "/" + url)}`);
  619. }
  620. }
  621. function renderMyNetdataMenu(machinesArray) {
  622. const el = document.getElementById('my-netdata-dropdown-content');
  623. el.classList.add(`theme-${netdataTheme}`);
  624. if (machinesArray == registryAgents) {
  625. console.log("Rendering my-netdata menu from registry");
  626. } else {
  627. console.log("Rendering my-netdata menu from netdata.cloud", machinesArray);
  628. }
  629. let html = '';
  630. if (!isSignedIn()) {
  631. if (!NETDATA.registry.isRegistryEnabled()) {
  632. html += (
  633. `<div class="info-item" style="white-space: nowrap">
  634. <span>Please <a href="#" onclick="signInDidClick(event); return false">sign in to netdata.cloud</a> to view your nodes!</span>
  635. <div></div>
  636. </div>
  637. <hr />`
  638. );
  639. }
  640. }
  641. if (isSignedIn()) {
  642. html += (
  643. `<div class="filter-control">
  644. <input
  645. id="my-netdata-menu-filter-input"
  646. type="text"
  647. placeholder="filter nodes..."
  648. autofocus
  649. autocomplete="off"
  650. value="${myNetdataMenuFilterValue}"
  651. onkeydown="myNetdataFilterDidChange(event)"
  652. />
  653. <span class="filter-control__clear" onclick="myNetdataFilterClearDidClick(event)"><i class="fas fa-times"></i><span>
  654. </div>
  655. <hr />`
  656. );
  657. }
  658. // options.hosts = [
  659. // {
  660. // hostname: "streamed1",
  661. // },
  662. // {
  663. // hostname: "streamed2",
  664. // },
  665. // ]
  666. if (options.hosts.length > 1) {
  667. html += `<div id="my-netdata-menu-streamed">${renderStreamedHosts(options)}</div><hr />`;
  668. }
  669. if (isSignedIn() || NETDATA.registry.isRegistryEnabled()) {
  670. html += `<div id="my-netdata-menu-machines">${renderMachines(machinesArray)}</div><hr />`;
  671. }
  672. if (!isSignedIn()) {
  673. html += (
  674. `<div class="agent-item">
  675. <i class="fas fa-cog""></i>
  676. <a href="#" onclick="switchRegistryModalHandler(); return false;">Switch Identity</a>
  677. <div></div>
  678. </div>
  679. <div class="agent-item">
  680. <i class="fas fa-question-circle""></i>
  681. <a href="https://github.com/netdata/netdata/tree/master/registry#registry" target="_blank">What is this?</a>
  682. <div></div>
  683. </div>`
  684. )
  685. } else {
  686. html += (
  687. `<div class="agent-item">
  688. <i class="fas fa-tv"></i>
  689. <a onclick="openAuthenticatedUrl('console.html');" target="_blank">Nodes<sup class="beta"> beta</sup></a>
  690. <div></div>
  691. </div>
  692. <div class="agent-item">
  693. <i class="fas fa-sync"></i>
  694. <a href="#" onclick="showSyncModal(); return false">Synchronize with netdata.cloud</a>
  695. <div></div>
  696. </div>
  697. <div class="agent-item">
  698. <i class="fas fa-question-circle""></i>
  699. <a href="https://netdata.cloud/about" target="_blank">What is this?</a>
  700. <div></div>
  701. </div>`
  702. )
  703. }
  704. el.innerHTML = html;
  705. gotoServerInit();
  706. }
  707. function isdemo() {
  708. if (this_is_demo !== null) {
  709. return this_is_demo;
  710. }
  711. this_is_demo = false;
  712. try {
  713. if (typeof document.location.hostname === 'string') {
  714. if (document.location.hostname.endsWith('.my-netdata.io') ||
  715. document.location.hostname.endsWith('.mynetdata.io') ||
  716. document.location.hostname.endsWith('.netdata.rocks') ||
  717. document.location.hostname.endsWith('.netdata.ai') ||
  718. document.location.hostname.endsWith('.netdata.live') ||
  719. document.location.hostname.endsWith('.firehol.org') ||
  720. document.location.hostname.endsWith('.netdata.online') ||
  721. document.location.hostname.endsWith('.netdata.cloud')) {
  722. this_is_demo = true;
  723. }
  724. }
  725. }
  726. catch (error) {
  727. }
  728. return this_is_demo;
  729. }
  730. function netdataURL(url, forReload) {
  731. if (typeof url === 'undefined')
  732. // url = document.location.toString();
  733. {
  734. url = '';
  735. }
  736. if (url.indexOf('#') !== -1) {
  737. url = url.substring(0, url.indexOf('#'));
  738. }
  739. var hash = urlOptions.genHash(forReload);
  740. // console.log('netdataURL: ' + url + hash);
  741. return url + hash;
  742. }
  743. function netdataReload(url) {
  744. document.location = verifyURL(netdataURL(url, true));
  745. // since we play with hash
  746. // this is needed to reload the page
  747. location.reload();
  748. }
  749. function gotoHostedModalHandler(url) {
  750. document.location = verifyURL(url + urlOptions.genHash());
  751. return false;
  752. }
  753. var gotoServerValidateRemaining = 0;
  754. var gotoServerMiddleClick = false;
  755. var gotoServerStop = false;
  756. function gotoServerValidateUrl(id, guid, url) {
  757. var penalty = 0;
  758. var error = 'failed';
  759. if (document.location.toString().startsWith('http://') && url.toString().startsWith('https://'))
  760. // we penalize https only if the current url is http
  761. // to allow the user walk through all its servers.
  762. {
  763. penalty = 500;
  764. } else if (document.location.toString().startsWith('https://') && url.toString().startsWith('http://')) {
  765. error = 'can\'t check';
  766. }
  767. var finalURL = netdataURL(url);
  768. setTimeout(function () {
  769. document.getElementById('gotoServerList').innerHTML += '<tr><td style="padding-left: 20px;"><a href="' + verifyURL(finalURL) + '" target="_blank">' + escapeUserInputHTML(url) + '</a></td><td style="padding-left: 30px;"><code id="' + guid + '-' + id + '-status">checking...</code></td></tr>';
  770. NETDATA.registry.hello(url, function (data) {
  771. if (typeof data !== 'undefined' && data !== null && typeof data.machine_guid === 'string' && data.machine_guid === guid) {
  772. // console.log('OK ' + id + ' URL: ' + url);
  773. document.getElementById(guid + '-' + id + '-status').innerHTML = "OK";
  774. if (!gotoServerStop) {
  775. gotoServerStop = true;
  776. if (gotoServerMiddleClick) {
  777. window.open(verifyURL(finalURL), '_blank');
  778. gotoServerMiddleClick = false;
  779. document.getElementById('gotoServerResponse').innerHTML = '<b>Opening new window to ' + NETDATA.registry.machines[guid].name + '<br/><a href="' + verifyURL(finalURL) + '">' + escapeUserInputHTML(url) + '</a></b><br/>(check your pop-up blocker if it fails)';
  780. } else {
  781. document.getElementById('gotoServerResponse').innerHTML += 'found it! It is at:<br/><small>' + escapeUserInputHTML(url) + '</small>';
  782. document.location = verifyURL(finalURL);
  783. $('#gotoServerModal').modal('hide');
  784. }
  785. }
  786. } else {
  787. if (typeof data !== 'undefined' && data !== null && typeof data.machine_guid === 'string' && data.machine_guid !== guid) {
  788. error = 'wrong machine';
  789. }
  790. document.getElementById(guid + '-' + id + '-status').innerHTML = error;
  791. gotoServerValidateRemaining--;
  792. if (gotoServerValidateRemaining <= 0) {
  793. gotoServerMiddleClick = false;
  794. document.getElementById('gotoServerResponse').innerHTML = '<b>Sorry! I cannot find any operational URL for this server</b>';
  795. }
  796. }
  797. });
  798. }, (id * 50) + penalty);
  799. }
  800. function gotoServerModalHandler(guid) {
  801. // console.log('goto server: ' + guid);
  802. gotoServerStop = false;
  803. var checked = {};
  804. var len = NETDATA.registry.machines[guid].alternate_urls.length;
  805. var count = 0;
  806. document.getElementById('gotoServerResponse').innerHTML = '';
  807. document.getElementById('gotoServerList').innerHTML = '';
  808. document.getElementById('gotoServerName').innerHTML = NETDATA.registry.machines[guid].name;
  809. $('#gotoServerModal').modal('show');
  810. gotoServerValidateRemaining = len;
  811. while (len--) {
  812. var url = NETDATA.registry.machines[guid].alternate_urls[len];
  813. checked[url] = true;
  814. gotoServerValidateUrl(count++, guid, url);
  815. }
  816. if (!isSignedIn()) {
  817. // When the registry is enabled, if the user's known URLs are not working
  818. // we consult the registry to get additional URLs.
  819. setTimeout(function () {
  820. if (gotoServerStop === false) {
  821. document.getElementById('gotoServerResponse').innerHTML = '<b>Added all the known URLs for this machine.</b>';
  822. NETDATA.registry.search(guid, function (data) {
  823. // console.log(data);
  824. len = data.urls.length;
  825. while (len--) {
  826. var url = data.urls[len][1];
  827. // console.log(url);
  828. if (typeof checked[url] === 'undefined') {
  829. gotoServerValidateRemaining++;
  830. checked[url] = true;
  831. gotoServerValidateUrl(count++, guid, url);
  832. }
  833. }
  834. });
  835. }
  836. }, 2000);
  837. }
  838. return false;
  839. }
  840. function gotoServerInit() {
  841. $(".registry_link").on('click', function (e) {
  842. if (e.which === 2) {
  843. e.preventDefault();
  844. gotoServerMiddleClick = true;
  845. } else {
  846. gotoServerMiddleClick = false;
  847. }
  848. return true;
  849. });
  850. }
  851. function switchRegistryModalHandler() {
  852. document.getElementById('switchRegistryPersonGUID').value = NETDATA.registry.person_guid;
  853. document.getElementById('switchRegistryURL').innerHTML = NETDATA.registry.server;
  854. document.getElementById('switchRegistryResponse').innerHTML = '';
  855. $('#switchRegistryModal').modal('show');
  856. }
  857. function notifyForSwitchRegistry() {
  858. var n = document.getElementById('switchRegistryPersonGUID').value;
  859. if (n !== '' && n.length === 36) {
  860. NETDATA.registry.switch(n, function (result) {
  861. if (result !== null) {
  862. $('#switchRegistryModal').modal('hide');
  863. NETDATA.registry.init();
  864. } else {
  865. document.getElementById('switchRegistryResponse').innerHTML = "<b>Sorry! The registry rejected your request.</b>";
  866. }
  867. });
  868. } else {
  869. document.getElementById('switchRegistryResponse').innerHTML = "<b>The ID you have entered is not a GUID.</b>";
  870. }
  871. }
  872. var deleteRegistryGuid = null;
  873. var deleteRegistryUrl = null;
  874. function deleteRegistryModalHandler(guid, name, url) {
  875. // void (guid);
  876. deleteRegistryGuid = guid;
  877. deleteRegistryUrl = url;
  878. document.getElementById('deleteRegistryServerName').innerHTML = name;
  879. document.getElementById('deleteRegistryServerName2').innerHTML = name;
  880. document.getElementById('deleteRegistryServerURL').innerHTML = url;
  881. document.getElementById('deleteRegistryResponse').innerHTML = '';
  882. $('#deleteRegistryModal').modal('show');
  883. }
  884. function notifyForDeleteRegistry() {
  885. const responseEl = document.getElementById('deleteRegistryResponse');
  886. if (deleteRegistryUrl) {
  887. if (isSignedIn()) {
  888. deleteCloudAgentURL(deleteRegistryGuid, deleteRegistryUrl)
  889. .then((count) => {
  890. if (!count) {
  891. responseEl.innerHTML = "<b>Sorry, this command was rejected by netdata.cloud!</b>";
  892. return;
  893. }
  894. NETDATA.registry.delete(deleteRegistryUrl, function (result) {
  895. if (result === null) {
  896. console.log("Received error from registry", result);
  897. }
  898. deleteRegistryUrl = null;
  899. $('#deleteRegistryModal').modal('hide');
  900. NETDATA.registry.init();
  901. });
  902. });
  903. } else {
  904. NETDATA.registry.delete(deleteRegistryUrl, function (result) {
  905. if (result !== null) {
  906. deleteRegistryUrl = null;
  907. $('#deleteRegistryModal').modal('hide');
  908. NETDATA.registry.init();
  909. } else {
  910. responseEl.innerHTML = "<b>Sorry, this command was rejected by the registry server!</b>";
  911. }
  912. });
  913. }
  914. }
  915. }
  916. var options = {
  917. menus: {},
  918. submenu_names: {},
  919. data: null,
  920. hostname: 'netdata_server', // will be overwritten by the netdata server
  921. version: 'unknown',
  922. release_channel: 'unknown',
  923. hosts: [],
  924. duration: 0, // the default duration of the charts
  925. update_every: 1,
  926. chartsPerRow: 0,
  927. // chartsMinWidth: 1450,
  928. chartsHeight: 180,
  929. };
  930. function chartsPerRow(total) {
  931. void (total);
  932. if (options.chartsPerRow === 0) {
  933. return 1;
  934. //var width = Math.floor(total / options.chartsMinWidth);
  935. //if(width === 0) width = 1;
  936. //return width;
  937. } else {
  938. return options.chartsPerRow;
  939. }
  940. }
  941. function prioritySort(a, b) {
  942. if (a.priority < b.priority) {
  943. return -1;
  944. }
  945. if (a.priority > b.priority) {
  946. return 1;
  947. }
  948. return naturalSortCompare(a.name, b.name);
  949. }
  950. function sortObjectByPriority(object) {
  951. var idx = {};
  952. var sorted = [];
  953. for (var i in object) {
  954. if (!object.hasOwnProperty(i)) {
  955. continue;
  956. }
  957. if (typeof idx[i] === 'undefined') {
  958. idx[i] = object[i];
  959. sorted.push(i);
  960. }
  961. }
  962. sorted.sort(function (a, b) {
  963. if (idx[a].priority < idx[b].priority) {
  964. return -1;
  965. }
  966. if (idx[a].priority > idx[b].priority) {
  967. return 1;
  968. }
  969. return naturalSortCompare(a, b);
  970. });
  971. return sorted;
  972. }
  973. // ----------------------------------------------------------------------------
  974. // scroll to a section, without changing the browser history
  975. function scrollToId(hash) {
  976. if (hash && hash !== '' && document.getElementById(hash) !== null) {
  977. var offset = $('#' + hash).offset();
  978. if (typeof offset !== 'undefined') {
  979. //console.log('scrolling to ' + hash + ' at ' + offset.top.toString());
  980. $('html, body').animate({ scrollTop: offset.top - 30 }, 0);
  981. }
  982. }
  983. // we must return false to prevent the default action
  984. return false;
  985. }
  986. // ----------------------------------------------------------------------------
  987. // user editable information
  988. var customDashboard = {
  989. menu: {},
  990. submenu: {},
  991. context: {}
  992. };
  993. // netdata standard information
  994. var netdataDashboard = {
  995. sparklines_registry: {},
  996. os: 'unknown',
  997. menu: {},
  998. submenu: {},
  999. context: {},
  1000. // generate a sparkline
  1001. // used in the documentation
  1002. sparkline: function (prefix, chart, dimension, units, suffix) {
  1003. if (options.data === null || typeof options.data.charts === 'undefined') {
  1004. return '';
  1005. }
  1006. if (typeof options.data.charts[chart] === 'undefined') {
  1007. return '';
  1008. }
  1009. if (typeof options.data.charts[chart].dimensions === 'undefined') {
  1010. return '';
  1011. }
  1012. if (typeof options.data.charts[chart].dimensions[dimension] === 'undefined') {
  1013. return '';
  1014. }
  1015. var key = chart + '.' + dimension;
  1016. if (typeof units === 'undefined') {
  1017. units = '';
  1018. }
  1019. if (typeof this.sparklines_registry[key] === 'undefined') {
  1020. this.sparklines_registry[key] = { count: 1 };
  1021. } else {
  1022. this.sparklines_registry[key].count++;
  1023. }
  1024. key = key + '.' + this.sparklines_registry[key].count;
  1025. return prefix + '<div class="netdata-container" data-netdata="' + chart + '" data-after="-120" data-width="25%" data-height="15px" data-chart-library="dygraph" data-dygraph-theme="sparkline" data-dimensions="' + dimension + '" data-show-value-of-' + dimension + '-at="' + key + '"></div> (<span id="' + key + '" style="display: inline-block; min-width: 50px; text-align: right;">X</span>' + units + ')' + suffix;
  1026. },
  1027. gaugeChart: function (title, width, dimensions, colors) {
  1028. if (typeof colors === 'undefined') {
  1029. colors = '';
  1030. }
  1031. if (typeof dimensions === 'undefined') {
  1032. dimensions = '';
  1033. }
  1034. return '<div class="netdata-container" data-netdata="CHART_UNIQUE_ID"'
  1035. + ' data-dimensions="' + dimensions + '"'
  1036. + ' data-chart-library="gauge"'
  1037. + ' data-gauge-adjust="width"'
  1038. + ' data-title="' + title + '"'
  1039. + ' data-width="' + width + '"'
  1040. + ' data-before="0"'
  1041. + ' data-after="-CHART_DURATION"'
  1042. + ' data-points="CHART_DURATION"'
  1043. + ' data-colors="' + colors + '"'
  1044. + ' role="application"></div>';
  1045. },
  1046. anyAttribute: function (obj, attr, key, def) {
  1047. if (typeof (obj[key]) !== 'undefined') {
  1048. var x = obj[key][attr];
  1049. if (typeof (x) === 'undefined') {
  1050. return def;
  1051. }
  1052. if (typeof (x) === 'function') {
  1053. return x(netdataDashboard.os);
  1054. }
  1055. return x;
  1056. }
  1057. return def;
  1058. },
  1059. menuTitle: function (chart) {
  1060. if (typeof chart.menu_pattern !== 'undefined') {
  1061. return (this.anyAttribute(this.menu, 'title', chart.menu_pattern, chart.menu_pattern).toString()
  1062. + '&nbsp;' + chart.type.slice(-(chart.type.length - chart.menu_pattern.length - 1)).toString()).replace(/_/g, ' ');
  1063. }
  1064. return (this.anyAttribute(this.menu, 'title', chart.menu, chart.menu)).toString().replace(/_/g, ' ');
  1065. },
  1066. menuIcon: function (chart) {
  1067. if (typeof chart.menu_pattern !== 'undefined') {
  1068. return this.anyAttribute(this.menu, 'icon', chart.menu_pattern, '<i class="fas fa-puzzle-piece"></i>').toString();
  1069. }
  1070. return this.anyAttribute(this.menu, 'icon', chart.menu, '<i class="fas fa-puzzle-piece"></i>');
  1071. },
  1072. menuInfo: function (chart) {
  1073. if (typeof chart.menu_pattern !== 'undefined') {
  1074. return this.anyAttribute(this.menu, 'info', chart.menu_pattern, null);
  1075. }
  1076. return this.anyAttribute(this.menu, 'info', chart.menu, null);
  1077. },
  1078. menuHeight: function (chart) {
  1079. if (typeof chart.menu_pattern !== 'undefined') {
  1080. return this.anyAttribute(this.menu, 'height', chart.menu_pattern, 1.0);
  1081. }
  1082. return this.anyAttribute(this.menu, 'height', chart.menu, 1.0);
  1083. },
  1084. submenuTitle: function (menu, submenu) {
  1085. var key = menu + '.' + submenu;
  1086. // console.log(key);
  1087. var title = this.anyAttribute(this.submenu, 'title', key, submenu).toString().replace(/_/g, ' ');
  1088. if (title.length > 28) {
  1089. var a = title.substring(0, 13);
  1090. var b = title.substring(title.length - 12, title.length);
  1091. return a + '...' + b;
  1092. }
  1093. return title;
  1094. },
  1095. submenuInfo: function (menu, submenu) {
  1096. var key = menu + '.' + submenu;
  1097. return this.anyAttribute(this.submenu, 'info', key, null);
  1098. },
  1099. submenuHeight: function (menu, submenu, relative) {
  1100. var key = menu + '.' + submenu;
  1101. return this.anyAttribute(this.submenu, 'height', key, 1.0) * relative;
  1102. },
  1103. contextInfo: function (id) {
  1104. var x = this.anyAttribute(this.context, 'info', id, null);
  1105. if (x !== null) {
  1106. return '<div class="shorten dashboard-context-info netdata-chart-alignment" role="document">' + x + '</div>';
  1107. } else {
  1108. return '';
  1109. }
  1110. },
  1111. contextValueRange: function (id) {
  1112. if (typeof this.context[id] !== 'undefined' && typeof this.context[id].valueRange !== 'undefined') {
  1113. return this.context[id].valueRange;
  1114. } else {
  1115. return '[null, null]';
  1116. }
  1117. },
  1118. contextHeight: function (id, def) {
  1119. if (typeof this.context[id] !== 'undefined' && typeof this.context[id].height !== 'undefined') {
  1120. return def * this.context[id].height;
  1121. } else {
  1122. return def;
  1123. }
  1124. },
  1125. contextDecimalDigits: function (id, def) {
  1126. if (typeof this.context[id] !== 'undefined' && typeof this.context[id].decimalDigits !== 'undefined') {
  1127. return this.context[id].decimalDigits;
  1128. } else {
  1129. return def;
  1130. }
  1131. }
  1132. };
  1133. // ----------------------------------------------------------------------------
  1134. // enrich the data structure returned by netdata
  1135. // to reflect our menu system and content
  1136. // TODO: this is a shame - we should fix charts naming (issue #807)
  1137. function enrichChartData(chart) {
  1138. var parts = chart.type.split('_');
  1139. var tmp = parts[0];
  1140. switch (tmp) {
  1141. case 'ap':
  1142. case 'net':
  1143. case 'disk':
  1144. case 'powersupply':
  1145. chart.menu = tmp;
  1146. break;
  1147. case 'apache':
  1148. chart.menu = chart.type;
  1149. if (parts.length > 2 && parts[1] === 'cache') {
  1150. chart.menu_pattern = tmp + '_' + parts[1];
  1151. } else if (parts.length > 1) {
  1152. chart.menu_pattern = tmp;
  1153. }
  1154. break;
  1155. case 'bind':
  1156. chart.menu = chart.type;
  1157. if (parts.length > 2 && parts[1] === 'rndc') {
  1158. chart.menu_pattern = tmp + '_' + parts[1];
  1159. } else if (parts.length > 1) {
  1160. chart.menu_pattern = tmp;
  1161. }
  1162. break;
  1163. case 'cgroup':
  1164. chart.menu = chart.type;
  1165. if (chart.id.match(/.*[\._\/-:]qemu[\._\/-:]*/) || chart.id.match(/.*[\._\/-:]kvm[\._\/-:]*/)) {
  1166. chart.menu_pattern = 'cgqemu';
  1167. } else {
  1168. chart.menu_pattern = 'cgroup';
  1169. }
  1170. break;
  1171. case 'go':
  1172. chart.menu = chart.type;
  1173. if (parts.length > 2 && parts[1] === 'expvar') {
  1174. chart.menu_pattern = tmp + '_' + parts[1];
  1175. } else if (parts.length > 1) {
  1176. chart.menu_pattern = tmp;
  1177. }
  1178. break;
  1179. case 'mount':
  1180. if (parts.length > 2) {
  1181. chart.menu = tmp + '_' + parts[1];
  1182. } else {
  1183. chart.menu = tmp;
  1184. }
  1185. break;
  1186. case 'isc':
  1187. chart.menu = chart.type;
  1188. if (parts.length > 2 && parts[1] === 'dhcpd') {
  1189. chart.menu_pattern = tmp + '_' + parts[1];
  1190. } else if (parts.length > 1) {
  1191. chart.menu_pattern = tmp;
  1192. }
  1193. break;
  1194. case 'ovpn':
  1195. chart.menu = chart.type;
  1196. if (parts.length > 3 && parts[1] === 'status' && parts[2] === 'log') {
  1197. chart.menu_pattern = tmp + '_' + parts[1];
  1198. } else if (parts.length > 1) {
  1199. chart.menu_pattern = tmp;
  1200. }
  1201. break;
  1202. case 'smartd':
  1203. case 'web':
  1204. chart.menu = chart.type;
  1205. if (parts.length > 2 && parts[1] === 'log') {
  1206. chart.menu_pattern = tmp + '_' + parts[1];
  1207. } else if (parts.length > 1) {
  1208. chart.menu_pattern = tmp;
  1209. }
  1210. break;
  1211. case 'tc':
  1212. chart.menu = tmp;
  1213. // find a name for this device from fireqos info
  1214. // we strip '_(in|out)' or '(in|out)_'
  1215. if (chart.context === 'tc.qos' && (typeof options.submenu_names[chart.family] === 'undefined' || options.submenu_names[chart.family] === chart.family)) {
  1216. var n = chart.name.split('.')[1];
  1217. if (n.endsWith('_in')) {
  1218. options.submenu_names[chart.family] = n.slice(0, n.lastIndexOf('_in'));
  1219. } else if (n.endsWith('_out')) {
  1220. options.submenu_names[chart.family] = n.slice(0, n.lastIndexOf('_out'));
  1221. } else if (n.startsWith('in_')) {
  1222. options.submenu_names[chart.family] = n.slice(3, n.length);
  1223. } else if (n.startsWith('out_')) {
  1224. options.submenu_names[chart.family] = n.slice(4, n.length);
  1225. } else {
  1226. options.submenu_names[chart.family] = n;
  1227. }
  1228. }
  1229. // increase the priority of IFB devices
  1230. // to have inbound appear before outbound
  1231. if (chart.id.match(/.*-ifb$/)) {
  1232. chart.priority--;
  1233. }
  1234. break;
  1235. default:
  1236. chart.menu = chart.type;
  1237. if (parts.length > 1) {
  1238. chart.menu_pattern = tmp;
  1239. }
  1240. break;
  1241. }
  1242. chart.submenu = chart.family;
  1243. }
  1244. // ----------------------------------------------------------------------------
  1245. function headMain(os, charts, duration) {
  1246. void (os);
  1247. if (urlOptions.mode === 'print') {
  1248. return '';
  1249. }
  1250. var head = '';
  1251. if (typeof charts['system.swap'] !== 'undefined') {
  1252. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.swap"'
  1253. + ' data-dimensions="used"'
  1254. + ' data-append-options="percentage"'
  1255. + ' data-chart-library="easypiechart"'
  1256. + ' data-title="Used Swap"'
  1257. + ' data-units="%"'
  1258. + ' data-easypiechart-max-value="100"'
  1259. + ' data-width="9%"'
  1260. + ' data-before="0"'
  1261. + ' data-after="-' + duration.toString() + '"'
  1262. + ' data-points="' + duration.toString() + '"'
  1263. + ' data-colors="#DD4400"'
  1264. + ' role="application"></div>';
  1265. }
  1266. if (typeof charts['system.io'] !== 'undefined') {
  1267. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.io"'
  1268. + ' data-dimensions="in"'
  1269. + ' data-chart-library="easypiechart"'
  1270. + ' data-title="Disk Read"'
  1271. + ' data-width="11%"'
  1272. + ' data-before="0"'
  1273. + ' data-after="-' + duration.toString() + '"'
  1274. + ' data-points="' + duration.toString() + '"'
  1275. + ' data-common-units="system.io.mainhead"'
  1276. + ' role="application"></div>';
  1277. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.io"'
  1278. + ' data-dimensions="out"'
  1279. + ' data-chart-library="easypiechart"'
  1280. + ' data-title="Disk Write"'
  1281. + ' data-width="11%"'
  1282. + ' data-before="0"'
  1283. + ' data-after="-' + duration.toString() + '"'
  1284. + ' data-points="' + duration.toString() + '"'
  1285. + ' data-common-units="system.io.mainhead"'
  1286. + ' role="application"></div>';
  1287. }
  1288. else if (typeof charts['system.pgpgio'] !== 'undefined') {
  1289. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.pgpgio"'
  1290. + ' data-dimensions="in"'
  1291. + ' data-chart-library="easypiechart"'
  1292. + ' data-title="Disk Read"'
  1293. + ' data-width="11%"'
  1294. + ' data-before="0"'
  1295. + ' data-after="-' + duration.toString() + '"'
  1296. + ' data-points="' + duration.toString() + '"'
  1297. + ' data-common-units="system.pgpgio.mainhead"'
  1298. + ' role="application"></div>';
  1299. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.pgpgio"'
  1300. + ' data-dimensions="out"'
  1301. + ' data-chart-library="easypiechart"'
  1302. + ' data-title="Disk Write"'
  1303. + ' data-width="11%"'
  1304. + ' data-before="0"'
  1305. + ' data-after="-' + duration.toString() + '"'
  1306. + ' data-points="' + duration.toString() + '"'
  1307. + ' data-common-units="system.pgpgio.mainhead"'
  1308. + ' role="application"></div>';
  1309. }
  1310. if (typeof charts['system.cpu'] !== 'undefined') {
  1311. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.cpu"'
  1312. + ' data-chart-library="gauge"'
  1313. + ' data-title="CPU"'
  1314. + ' data-units="%"'
  1315. + ' data-gauge-max-value="100"'
  1316. + ' data-width="20%"'
  1317. + ' data-after="-' + duration.toString() + '"'
  1318. + ' data-points="' + duration.toString() + '"'
  1319. + ' data-colors="' + NETDATA.colors[12] + '"'
  1320. + ' role="application"></div>';
  1321. }
  1322. if (typeof charts['system.net'] !== 'undefined') {
  1323. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.net"'
  1324. + ' data-dimensions="received"'
  1325. + ' data-chart-library="easypiechart"'
  1326. + ' data-title="Net Inbound"'
  1327. + ' data-width="11%"'
  1328. + ' data-before="0"'
  1329. + ' data-after="-' + duration.toString() + '"'
  1330. + ' data-points="' + duration.toString() + '"'
  1331. + ' data-common-units="system.net.mainhead"'
  1332. + ' role="application"></div>';
  1333. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.net"'
  1334. + ' data-dimensions="sent"'
  1335. + ' data-chart-library="easypiechart"'
  1336. + ' data-title="Net Outbound"'
  1337. + ' data-width="11%"'
  1338. + ' data-before="0"'
  1339. + ' data-after="-' + duration.toString() + '"'
  1340. + ' data-points="' + duration.toString() + '"'
  1341. + ' data-common-units="system.net.mainhead"'
  1342. + ' role="application"></div>';
  1343. }
  1344. else if (typeof charts['system.ip'] !== 'undefined') {
  1345. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ip"'
  1346. + ' data-dimensions="received"'
  1347. + ' data-chart-library="easypiechart"'
  1348. + ' data-title="IP Inbound"'
  1349. + ' data-width="11%"'
  1350. + ' data-before="0"'
  1351. + ' data-after="-' + duration.toString() + '"'
  1352. + ' data-points="' + duration.toString() + '"'
  1353. + ' data-common-units="system.ip.mainhead"'
  1354. + ' role="application"></div>';
  1355. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ip"'
  1356. + ' data-dimensions="sent"'
  1357. + ' data-chart-library="easypiechart"'
  1358. + ' data-title="IP Outbound"'
  1359. + ' data-width="11%"'
  1360. + ' data-before="0"'
  1361. + ' data-after="-' + duration.toString() + '"'
  1362. + ' data-points="' + duration.toString() + '"'
  1363. + ' data-common-units="system.ip.mainhead"'
  1364. + ' role="application"></div>';
  1365. }
  1366. else if (typeof charts['system.ipv4'] !== 'undefined') {
  1367. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv4"'
  1368. + ' data-dimensions="received"'
  1369. + ' data-chart-library="easypiechart"'
  1370. + ' data-title="IPv4 Inbound"'
  1371. + ' data-width="11%"'
  1372. + ' data-before="0"'
  1373. + ' data-after="-' + duration.toString() + '"'
  1374. + ' data-points="' + duration.toString() + '"'
  1375. + ' data-common-units="system.ipv4.mainhead"'
  1376. + ' role="application"></div>';
  1377. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv4"'
  1378. + ' data-dimensions="sent"'
  1379. + ' data-chart-library="easypiechart"'
  1380. + ' data-title="IPv4 Outbound"'
  1381. + ' data-width="11%"'
  1382. + ' data-before="0"'
  1383. + ' data-after="-' + duration.toString() + '"'
  1384. + ' data-points="' + duration.toString() + '"'
  1385. + ' data-common-units="system.ipv4.mainhead"'
  1386. + ' role="application"></div>';
  1387. }
  1388. else if (typeof charts['system.ipv6'] !== 'undefined') {
  1389. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv6"'
  1390. + ' data-dimensions="received"'
  1391. + ' data-chart-library="easypiechart"'
  1392. + ' data-title="IPv6 Inbound"'
  1393. + ' data-units="kbps"'
  1394. + ' data-width="11%"'
  1395. + ' data-before="0"'
  1396. + ' data-after="-' + duration.toString() + '"'
  1397. + ' data-points="' + duration.toString() + '"'
  1398. + ' data-common-units="system.ipv6.mainhead"'
  1399. + ' role="application"></div>';
  1400. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv6"'
  1401. + ' data-dimensions="sent"'
  1402. + ' data-chart-library="easypiechart"'
  1403. + ' data-title="IPv6 Outbound"'
  1404. + ' data-units="kbps"'
  1405. + ' data-width="11%"'
  1406. + ' data-before="0"'
  1407. + ' data-after="-' + duration.toString() + '"'
  1408. + ' data-points="' + duration.toString() + '"'
  1409. + ' data-common-units="system.ipv6.mainhead"'
  1410. + ' role="application"></div>';
  1411. }
  1412. if (typeof charts['system.ram'] !== 'undefined') {
  1413. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ram"'
  1414. + ' data-dimensions="used|buffers|active|wired"' // active and wired are FreeBSD stats
  1415. + ' data-append-options="percentage"'
  1416. + ' data-chart-library="easypiechart"'
  1417. + ' data-title="Used RAM"'
  1418. + ' data-units="%"'
  1419. + ' data-easypiechart-max-value="100"'
  1420. + ' data-width="9%"'
  1421. + ' data-after="-' + duration.toString() + '"'
  1422. + ' data-points="' + duration.toString() + '"'
  1423. + ' data-colors="' + NETDATA.colors[7] + '"'
  1424. + ' role="application"></div>';
  1425. }
  1426. return head;
  1427. }
  1428. function generateHeadCharts(type, chart, duration) {
  1429. if (urlOptions.mode === 'print') {
  1430. return '';
  1431. }
  1432. var head = '';
  1433. var hcharts = netdataDashboard.anyAttribute(netdataDashboard.context, type, chart.context, []);
  1434. if (hcharts.length > 0) {
  1435. var hi = 0, hlen = hcharts.length;
  1436. while (hi < hlen) {
  1437. if (typeof hcharts[hi] === 'function') {
  1438. head += hcharts[hi](netdataDashboard.os, chart.id).replace(/CHART_DURATION/g, duration.toString()).replace(/CHART_UNIQUE_ID/g, chart.id);
  1439. } else {
  1440. head += hcharts[hi].replace(/CHART_DURATION/g, duration.toString()).replace(/CHART_UNIQUE_ID/g, chart.id);
  1441. }
  1442. hi++;
  1443. }
  1444. }
  1445. return head;
  1446. }
  1447. function renderPage(menus, data) {
  1448. var div = document.getElementById('charts_div');
  1449. var pcent_width = Math.floor(100 / chartsPerRow($(div).width()));
  1450. // find the proper duration for per-second updates
  1451. var duration = Math.round(($(div).width() * pcent_width / 100 * data.update_every / 3) / 60) * 60;
  1452. options.duration = duration;
  1453. options.update_every = data.update_every;
  1454. var html = '';
  1455. var sidebar = '<ul class="nav dashboard-sidenav" data-spy="affix" id="sidebar_ul">';
  1456. var mainhead = headMain(netdataDashboard.os, data.charts, duration);
  1457. // sort the menus
  1458. var main = sortObjectByPriority(menus);
  1459. var i = 0, len = main.length;
  1460. while (i < len) {
  1461. var menu = main[i++];
  1462. // generate an entry at the main menu
  1463. var menuid = NETDATA.name2id('menu_' + menu);
  1464. sidebar += '<li class=""><a href="#' + menuid + '" onClick="return scrollToId(\'' + menuid + '\');">' + menus[menu].icon + ' ' + menus[menu].title + '</a><ul class="nav">';
  1465. html += '<div role="section" class="dashboard-section"><div role="sectionhead"><h1 id="' + menuid + '" role="heading">' + menus[menu].icon + ' ' + menus[menu].title + '</h1></div><div role="section" class="dashboard-subsection">';
  1466. if (menus[menu].info !== null) {
  1467. html += menus[menu].info;
  1468. }
  1469. // console.log(' >> ' + menu + ' (' + menus[menu].priority + '): ' + menus[menu].title);
  1470. var shtml = '';
  1471. var mhead = '<div class="netdata-chart-row">' + mainhead;
  1472. mainhead = '';
  1473. // sort the submenus of this menu
  1474. var sub = sortObjectByPriority(menus[menu].submenus);
  1475. var si = 0, slen = sub.length;
  1476. while (si < slen) {
  1477. var submenu = sub[si++];
  1478. // generate an entry at the submenu
  1479. var submenuid = NETDATA.name2id('menu_' + menu + '_submenu_' + submenu);
  1480. sidebar += '<li class><a href="#' + submenuid + '" onClick="return scrollToId(\'' + submenuid + '\');">' + menus[menu].submenus[submenu].title + '</a></li>';
  1481. shtml += '<div role="section" class="dashboard-section-container" id="' + submenuid + '"><h2 id="' + submenuid + '" class="netdata-chart-alignment" role="heading">' + menus[menu].submenus[submenu].title + '</h2>';
  1482. if (menus[menu].submenus[submenu].info !== null) {
  1483. shtml += '<div class="dashboard-submenu-info netdata-chart-alignment" role="document">' + menus[menu].submenus[submenu].info + '</div>';
  1484. }
  1485. var head = '<div class="netdata-chart-row">';
  1486. var chtml = '';
  1487. // console.log(' \------- ' + submenu + ' (' + menus[menu].submenus[submenu].priority + '): ' + menus[menu].submenus[submenu].title);
  1488. // sort the charts in this submenu of this menu
  1489. menus[menu].submenus[submenu].charts.sort(prioritySort);
  1490. var ci = 0, clen = menus[menu].submenus[submenu].charts.length;
  1491. while (ci < clen) {
  1492. var chart = menus[menu].submenus[submenu].charts[ci++];
  1493. // generate the submenu heading charts
  1494. mhead += generateHeadCharts('mainheads', chart, duration);
  1495. head += generateHeadCharts('heads', chart, duration);
  1496. function chartCommonMin(family, context, units) {
  1497. var x = netdataDashboard.anyAttribute(netdataDashboard.context, 'commonMin', context, undefined);
  1498. if (typeof x !== 'undefined') {
  1499. return ' data-common-min="' + family + '/' + context + '/' + units + '"';
  1500. } else {
  1501. return '';
  1502. }
  1503. }
  1504. function chartCommonMax(family, context, units) {
  1505. var x = netdataDashboard.anyAttribute(netdataDashboard.context, 'commonMax', context, undefined);
  1506. if (typeof x !== 'undefined') {
  1507. return ' data-common-max="' + family + '/' + context + '/' + units + '"';
  1508. } else {
  1509. return '';
  1510. }
  1511. }
  1512. // generate the chart
  1513. if (urlOptions.mode === 'print') {
  1514. chtml += '<div role="row" class="dashboard-print-row">';
  1515. }
  1516. chtml += '<div class="netdata-chartblock-container" style="width: ' + pcent_width.toString() + '%;">' + netdataDashboard.contextInfo(chart.context) + '<div class="netdata-container" id="chart_' + NETDATA.name2id(chart.id) + '" data-netdata="' + chart.id + '"'
  1517. + ' data-width="100%"'
  1518. + ' data-height="' + netdataDashboard.contextHeight(chart.context, options.chartsHeight).toString() + 'px"'
  1519. + ' data-dygraph-valuerange="' + netdataDashboard.contextValueRange(chart.context) + '"'
  1520. + ' data-before="0"'
  1521. + ' data-after="-' + duration.toString() + '"'
  1522. + ' data-id="' + NETDATA.name2id(options.hostname + '/' + chart.id) + '"'
  1523. + ' data-colors="' + netdataDashboard.anyAttribute(netdataDashboard.context, 'colors', chart.context, '') + '"'
  1524. + ' data-decimal-digits="' + netdataDashboard.contextDecimalDigits(chart.context, -1) + '"'
  1525. + chartCommonMin(chart.family, chart.context, chart.units)
  1526. + chartCommonMax(chart.family, chart.context, chart.units)
  1527. + ' role="application"></div></div>';
  1528. if (urlOptions.mode === 'print') {
  1529. chtml += '</div>';
  1530. }
  1531. }
  1532. head += '</div>';
  1533. shtml += head + chtml + '</div>';
  1534. }
  1535. mhead += '</div>';
  1536. sidebar += '</ul></li>';
  1537. html += mhead + shtml + '</div></div><hr role="separator"/>';
  1538. }
  1539. const isMemoryModeDbEngine = data.memory_mode === "dbengine";
  1540. sidebar += '<li class="" style="padding-top:15px;"><a href="https://learn.netdata.cloud/docs/agent/collectors/quickstart/" target="_blank"><i class="fas fa-plus"></i> Add more charts</a></li>';
  1541. sidebar += '<li class=""><a href="https://learn.netdata.cloud/docs/agent/health/quickstart/" target="_blank"><i class="fas fa-plus"></i> Add more alarms</a></li>';
  1542. sidebar += '<li class="" style="margin:20px;color:#666;"><small>Every ' +
  1543. ((data.update_every === 1) ? 'second' : data.update_every.toString() + ' seconds') + ', ' +
  1544. 'Netdata collects <strong>' + data.dimensions_count.toLocaleString() + '</strong> metrics on ' +
  1545. data.hostname.toString() + ', presents them in <strong>' +
  1546. data.charts_count.toLocaleString() + '</strong> charts' +
  1547. (isMemoryModeDbEngine ? '' : ',') + // oxford comma
  1548. ' and monitors them with <strong>' +
  1549. data.alarms_count.toLocaleString() + '</strong> alarms.';
  1550. if (!isMemoryModeDbEngine) {
  1551. sidebar += '<br />&nbsp;<br />Get more history by ' +
  1552. '<a href="https://learn.netdata.cloud/guides/longer-metrics-storage#using-the-round-robin-database" target=_blank>configuring Netdata\'s <strong>history</strong></a> or using the <a href="https://learn.netdata.cloud/docs/agent/database/engine/" target=_blank>DB engine.</a>';
  1553. }
  1554. sidebar += '<br/>&nbsp;<br/><strong>netdata</strong><br/>' + data.version.toString() + '</small></li>';
  1555. sidebar += '</ul>';
  1556. div.innerHTML = html;
  1557. document.getElementById('sidebar').innerHTML = sidebar;
  1558. if (urlOptions.highlight === true) {
  1559. NETDATA.globalChartUnderlay.init(null
  1560. , urlOptions.highlight_after
  1561. , urlOptions.highlight_before
  1562. , (urlOptions.after > 0) ? urlOptions.after : null
  1563. , (urlOptions.before > 0) ? urlOptions.before : null
  1564. );
  1565. } else {
  1566. NETDATA.globalChartUnderlay.clear();
  1567. }
  1568. if (urlOptions.mode === 'print') {
  1569. printPage();
  1570. } else {
  1571. finalizePage();
  1572. }
  1573. }
  1574. function renderChartsAndMenu(data) {
  1575. options.menus = {};
  1576. options.submenu_names = {};
  1577. var menus = options.menus;
  1578. var charts = data.charts;
  1579. var m, menu_key;
  1580. for (var c in charts) {
  1581. if (!charts.hasOwnProperty(c)) {
  1582. continue;
  1583. }
  1584. var chart = charts[c];
  1585. enrichChartData(chart);
  1586. m = chart.menu;
  1587. // create the menu
  1588. if (typeof menus[m] === 'undefined') {
  1589. menus[m] = {
  1590. menu_pattern: chart.menu_pattern,
  1591. priority: chart.priority,
  1592. submenus: {},
  1593. title: netdataDashboard.menuTitle(chart),
  1594. icon: netdataDashboard.menuIcon(chart),
  1595. info: netdataDashboard.menuInfo(chart),
  1596. height: netdataDashboard.menuHeight(chart) * options.chartsHeight
  1597. };
  1598. } else {
  1599. if (typeof (menus[m].menu_pattern) === 'undefined') {
  1600. menus[m].menu_pattern = chart.menu_pattern;
  1601. }
  1602. if (chart.priority < menus[m].priority) {
  1603. menus[m].priority = chart.priority;
  1604. }
  1605. }
  1606. menu_key = (typeof (menus[m].menu_pattern) !== 'undefined') ? menus[m].menu_pattern : m;
  1607. // create the submenu
  1608. if (typeof menus[m].submenus[chart.submenu] === 'undefined') {
  1609. menus[m].submenus[chart.submenu] = {
  1610. priority: chart.priority,
  1611. charts: [],
  1612. title: null,
  1613. info: netdataDashboard.submenuInfo(menu_key, chart.submenu),
  1614. height: netdataDashboard.submenuHeight(menu_key, chart.submenu, menus[m].height)
  1615. };
  1616. } else {
  1617. if (chart.priority < menus[m].submenus[chart.submenu].priority) {
  1618. menus[m].submenus[chart.submenu].priority = chart.priority;
  1619. }
  1620. }
  1621. // index the chart in the menu/submenu
  1622. menus[m].submenus[chart.submenu].charts.push(chart);
  1623. }
  1624. // propagate the descriptive subname given to QoS
  1625. // to all the other submenus with the same name
  1626. for (var m in menus) {
  1627. if (!menus.hasOwnProperty(m)) {
  1628. continue;
  1629. }
  1630. for (var s in menus[m].submenus) {
  1631. if (!menus[m].submenus.hasOwnProperty(s)) {
  1632. continue;
  1633. }
  1634. // set the family using a name
  1635. if (typeof options.submenu_names[s] !== 'undefined') {
  1636. menus[m].submenus[s].title = s + ' (' + options.submenu_names[s] + ')';
  1637. } else {
  1638. menu_key = (typeof (menus[m].menu_pattern) !== 'undefined') ? menus[m].menu_pattern : m;
  1639. menus[m].submenus[s].title = netdataDashboard.submenuTitle(menu_key, s);
  1640. }
  1641. }
  1642. }
  1643. renderPage(menus, data);
  1644. }
  1645. // ----------------------------------------------------------------------------
  1646. function loadJs(url, callback) {
  1647. $.ajax({
  1648. url: url.startsWith("http") ? url : transformWithOldSuffix(url),
  1649. cache: true,
  1650. dataType: "script",
  1651. xhrFields: { withCredentials: true } // required for the cookie
  1652. })
  1653. .fail(function () {
  1654. alert('Cannot load required JS library: ' + url);
  1655. })
  1656. .always(function () {
  1657. if (typeof callback === 'function') {
  1658. callback();
  1659. }
  1660. })
  1661. }
  1662. var clipboardLoaded = false;
  1663. function loadClipboard(callback) {
  1664. if (clipboardLoaded === false) {
  1665. clipboardLoaded = true;
  1666. loadJs('lib/clipboard-polyfill-be05dad.js', callback);
  1667. } else {
  1668. callback();
  1669. }
  1670. }
  1671. var bootstrapTableLoaded = false;
  1672. function loadBootstrapTable(callback) {
  1673. if (bootstrapTableLoaded === false) {
  1674. bootstrapTableLoaded = true;
  1675. loadJs('lib/bootstrap-table-1.11.0.min.js', function () {
  1676. loadJs('lib/bootstrap-table-export-1.11.0.min.js', function () {
  1677. loadJs('lib/tableExport-1.6.0.min.js', callback);
  1678. })
  1679. });
  1680. } else {
  1681. callback();
  1682. }
  1683. }
  1684. var bootstrapSliderLoaded = false;
  1685. function loadBootstrapSlider(callback) {
  1686. if (bootstrapSliderLoaded === false) {
  1687. bootstrapSliderLoaded = true;
  1688. loadJs('lib/bootstrap-slider-10.0.0.min.js', function () {
  1689. NETDATA._loadCSS(transformWithOldSuffix("css/bootstrap-slider-10.0.0.min.css"));
  1690. callback();
  1691. });
  1692. } else {
  1693. callback();
  1694. }
  1695. }
  1696. var lzStringLoaded = false;
  1697. function loadLzString(callback) {
  1698. if (lzStringLoaded === false) {
  1699. lzStringLoaded = true;
  1700. loadJs('lib/lz-string-1.4.4.min.js', callback);
  1701. } else {
  1702. callback();
  1703. }
  1704. }
  1705. var pakoLoaded = false;
  1706. function loadPako(callback) {
  1707. if (pakoLoaded === false) {
  1708. pakoLoaded = true;
  1709. loadJs('lib/pako-1.0.6.min.js', callback);
  1710. } else {
  1711. callback();
  1712. }
  1713. }
  1714. // ----------------------------------------------------------------------------
  1715. function clipboardCopy(text) {
  1716. clipboard.writeText(text);
  1717. }
  1718. function clipboardCopyBadgeEmbed(url) {
  1719. clipboard.writeText('<embed src="' + url + '" type="image/svg+xml" height="20"/>');
  1720. }
  1721. // ----------------------------------------------------------------------------
  1722. function alarmsUpdateModal() {
  1723. var active = '<h3>Raised Alarms</h3><table class="table">';
  1724. var all = '<h3>All Running Alarms</h3><div class="panel-group" id="alarms_all_accordion" role="tablist" aria-multiselectable="true">';
  1725. var footer = '<hr/><a href="https://github.com/netdata/netdata/tree/master/web/api/badges#netdata-badges" target="_blank">netdata badges</a> refresh automatically. Their color indicates the state of the alarm: <span style="color: #e05d44"><b>&nbsp;red&nbsp;</b></span> is critical, <span style="color:#fe7d37"><b>&nbsp;orange&nbsp;</b></span> is warning, <span style="color: #4c1"><b>&nbsp;bright green&nbsp;</b></span> is ok, <span style="color: #9f9f9f"><b>&nbsp;light grey&nbsp;</b></span> is undefined (i.e. no data or no status), <span style="color: #000"><b>&nbsp;black&nbsp;</b></span> is not initialized. You can copy and paste their URLs to embed them in any web page.<br/>netdata can send notifications for these alarms. Check <a href="https://github.com/netdata/netdata/blob/master/health/notifications/health_alarm_notify.conf" target="_blank">this configuration file</a> for more information.';
  1726. loadClipboard(function () {
  1727. });
  1728. NETDATA.alarms.get('all', function (data) {
  1729. options.alarm_families = [];
  1730. alarmsCallback(data);
  1731. if (data === null) {
  1732. document.getElementById('alarms_active').innerHTML =
  1733. document.getElementById('alarms_all').innerHTML =
  1734. document.getElementById('alarms_log').innerHTML =
  1735. 'failed to load alarm data!';
  1736. return;
  1737. }
  1738. function alarmid4human(id) {
  1739. if (id === 0) {
  1740. return '-';
  1741. }
  1742. return id.toString();
  1743. }
  1744. function timestamp4human(timestamp, space) {
  1745. if (timestamp === 0) {
  1746. return '-';
  1747. }
  1748. if (typeof space === 'undefined') {
  1749. space = '&nbsp;';
  1750. }
  1751. var t = new Date(timestamp * 1000);
  1752. var now = new Date();
  1753. if (t.toDateString() === now.toDateString()) {
  1754. return t.toLocaleTimeString();
  1755. }
  1756. return t.toLocaleDateString() + space + t.toLocaleTimeString();
  1757. }
  1758. function alarm_lookup_explain(alarm, chart) {
  1759. var dimensions = ' of all values ';
  1760. if (chart.dimensions.length > 1) {
  1761. dimensions = ' of the sum of all dimensions ';
  1762. }
  1763. if (typeof alarm.lookup_dimensions !== 'undefined') {
  1764. var d = alarm.lookup_dimensions.replace(/|/g, ',');
  1765. var x = d.split(',');
  1766. if (x.length > 1) {
  1767. dimensions = 'of the sum of dimensions <code>' + alarm.lookup_dimensions + '</code> ';
  1768. } else {
  1769. dimensions = 'of all values of dimension <code>' + alarm.lookup_dimensions + '</code> ';
  1770. }
  1771. }
  1772. return '<code>' + alarm.lookup_method + '</code> '
  1773. + dimensions + ', of chart <code>' + alarm.chart + '</code>'
  1774. + ', starting <code>' + NETDATA.seconds4human(alarm.lookup_after + alarm.lookup_before, { space: '&nbsp;' }) + '</code> and up to <code>' + NETDATA.seconds4human(alarm.lookup_before, { space: '&nbsp;' }) + '</code>'
  1775. + ((alarm.lookup_options) ? (', with options <code>' + alarm.lookup_options.replace(/ /g, ',&nbsp;') + '</code>') : '')
  1776. + '.';
  1777. }
  1778. function alarm_to_html(alarm, full) {
  1779. var chart = options.data.charts[alarm.chart];
  1780. if (typeof (chart) === 'undefined') {
  1781. chart = options.data.charts_by_name[alarm.chart];
  1782. if (typeof (chart) === 'undefined') {
  1783. // this means the charts loaded are incomplete
  1784. // probably netdata was restarted and more alarms
  1785. // are now available.
  1786. console.log('Cannot find chart ' + alarm.chart + ', you probably need to refresh the page.');
  1787. return '';
  1788. }
  1789. }
  1790. var has_alarm = (typeof alarm.warn !== 'undefined' || typeof alarm.crit !== 'undefined');
  1791. var badge_url = NETDATA.alarms.server + '/api/v1/badge.svg?chart=' + alarm.chart + '&alarm=' + alarm.name + '&refresh=auto';
  1792. var action_buttons = '<br/>&nbsp;<br/>role: <b>' + alarm.recipient + '</b><br/>&nbsp;<br/>'
  1793. + '<div class="action-button ripple" title="click to scroll the dashboard to the chart of this alarm" data-toggle="tooltip" data-placement="bottom" onClick="scrollToChartAfterHidingModal(\'' + alarm.chart + '\', ' + alarm.last_status_change * 1000 + ', \'' + alarm.status + '\'); $(\'#alarmsModal\').modal(\'hide\'); return false;"><i class="fab fa-periscope"></i></div>'
  1794. + '<div class="action-button ripple" title="click to copy to the clipboard the URL of this badge" data-toggle="tooltip" data-placement="bottom" onClick="clipboardCopy(\'' + badge_url + '\'); return false;"><i class="far fa-copy"></i></div>'
  1795. + '<div class="action-button ripple" title="click to copy to the clipboard an auto-refreshing <code>embed</code> html element for this badge" data-toggle="tooltip" data-placement="bottom" onClick="clipboardCopyBadgeEmbed(\'' + badge_url + '\'); return false;"><i class="fas fa-copy"></i></div>';
  1796. var html = '<tr><td class="text-center" style="vertical-align:middle" width="40%"><b>' + alarm.chart + '</b><br/>&nbsp;<br/><embed src="' + badge_url + '" type="image/svg+xml" height="20"/><br/>&nbsp;<br/><span style="font-size: 18px">' + alarm.info + '</span>' + action_buttons + '</td>'
  1797. + '<td><table class="table">'
  1798. + ((typeof alarm.warn !== 'undefined') ? ('<tr><td width="10%" style="text-align:right">warning&nbsp;when</td><td><span style="font-family: monospace; color:#fe7d37; font-weight: bold;">' + alarm.warn + '</span></td></tr>') : '')
  1799. + ((typeof alarm.crit !== 'undefined') ? ('<tr><td width="10%" style="text-align:right">critical&nbsp;when</td><td><span style="font-family: monospace; color: #e05d44; font-weight: bold;">' + alarm.crit + '</span></td></tr>') : '');
  1800. if (full === true) {
  1801. var units = chart.units;
  1802. if (units === '%') {
  1803. units = '&#37;';
  1804. }
  1805. html += ((typeof alarm.lookup_after !== 'undefined') ? ('<tr><td width="10%" style="text-align:right">db&nbsp;lookup</td><td>' + alarm_lookup_explain(alarm, chart) + '</td></tr>') : '')
  1806. + ((typeof alarm.calc !== 'undefined') ? ('<tr><td width="10%" style="text-align:right">calculation</td><td><span style="font-family: monospace;">' + alarm.calc + '</span></td></tr>') : '')
  1807. + ((chart.green !== null) ? ('<tr><td width="10%" style="text-align:right">green&nbsp;threshold</td><td><code>' + chart.green + ' ' + units + '</code></td></tr>') : '')
  1808. + ((chart.red !== null) ? ('<tr><td width="10%" style="text-align:right">red&nbsp;threshold</td><td><code>' + chart.red + ' ' + units + '</code></td></tr>') : '');
  1809. }
  1810. if (alarm.warn_repeat_every > 0) {
  1811. html += '<tr><td width="10%" style="text-align:right">repeat&nbsp;warning</td><td>' + NETDATA.seconds4human(alarm.warn_repeat_every) + '</td></tr>';
  1812. }
  1813. if (alarm.crit_repeat_every > 0) {
  1814. html += '<tr><td width="10%" style="text-align:right">repeat&nbsp;critical</td><td>' + NETDATA.seconds4human(alarm.crit_repeat_every) + '</td></tr>';
  1815. }
  1816. var delay = '';
  1817. if ((alarm.delay_up_duration > 0 || alarm.delay_down_duration > 0) && alarm.delay_multiplier !== 0 && alarm.delay_max_duration > 0) {
  1818. if (alarm.delay_up_duration === alarm.delay_down_duration) {
  1819. delay += '<small><br/>hysteresis ' + NETDATA.seconds4human(alarm.delay_up_duration, {
  1820. space: '&nbsp;',
  1821. negative_suffix: ''
  1822. });
  1823. } else {
  1824. delay = '<small><br/>hysteresis ';
  1825. if (alarm.delay_up_duration > 0) {
  1826. delay += 'on&nbsp;escalation&nbsp;<code>' + NETDATA.seconds4human(alarm.delay_up_duration, {
  1827. space: '&nbsp;',
  1828. negative_suffix: ''
  1829. }) + '</code>, ';
  1830. }
  1831. if (alarm.delay_down_duration > 0) {
  1832. delay += 'on&nbsp;recovery&nbsp;<code>' + NETDATA.seconds4human(alarm.delay_down_duration, {
  1833. space: '&nbsp;',
  1834. negative_suffix: ''
  1835. }) + '</code>, ';
  1836. }
  1837. }
  1838. if (alarm.delay_multiplier !== 1.0) {
  1839. delay += 'multiplied&nbsp;by&nbsp;<code>' + alarm.delay_multiplier.toString() + '</code>';
  1840. delay += ',&nbsp;up&nbsp;to&nbsp;<code>' + NETDATA.seconds4human(alarm.delay_max_duration, {
  1841. space: '&nbsp;',
  1842. negative_suffix: ''
  1843. }) + '</code>';
  1844. }
  1845. delay += '</small>';
  1846. }
  1847. html += '<tr><td width="10%" style="text-align:right">check&nbsp;every</td><td>' + NETDATA.seconds4human(alarm.update_every, {
  1848. space: '&nbsp;',
  1849. negative_suffix: ''
  1850. }) + '</td></tr>'
  1851. + ((has_alarm === true) ? ('<tr><td width="10%" style="text-align:right">execute</td><td><span style="font-family: monospace;">' + alarm.exec + '</span>' + delay + '</td></tr>') : '')
  1852. + '<tr><td width="10%" style="text-align:right">source</td><td><span style="font-family: monospace;">' + alarm.source + '</span></td></tr>'
  1853. + '</table></td></tr>';
  1854. return html;
  1855. }
  1856. function alarm_family_show(id) {
  1857. var html = '<table class="table">';
  1858. var family = options.alarm_families[id];
  1859. var len = family.arr.length;
  1860. while (len--) {
  1861. var alarm = family.arr[len];
  1862. html += alarm_to_html(alarm, true);
  1863. }
  1864. html += '</table>';
  1865. $('#alarm_all_' + id.toString()).html(html);
  1866. enableTooltipsAndPopovers();
  1867. }
  1868. // find the proper family of each alarm
  1869. var x, family, alarm;
  1870. var count_active = 0;
  1871. var count_all = 0;
  1872. var families = {};
  1873. var families_sort = [];
  1874. for (x in data.alarms) {
  1875. if (!data.alarms.hasOwnProperty(x)) {
  1876. continue;
  1877. }
  1878. alarm = data.alarms[x];
  1879. family = alarm.family;
  1880. // find the chart
  1881. var chart = options.data.charts[alarm.chart];
  1882. if (typeof chart === 'undefined') {
  1883. chart = options.data.charts_by_name[alarm.chart];
  1884. }
  1885. // not found - this should never happen!
  1886. if (typeof chart === 'undefined') {
  1887. console.log('WARNING: alarm ' + x + ' is linked to chart ' + alarm.chart + ', which is not found in the list of chart got from the server.');
  1888. chart = { priority: 9999999 };
  1889. }
  1890. else if (typeof chart.menu !== 'undefined' && typeof chart.submenu !== 'undefined')
  1891. // the family based on the chart
  1892. {
  1893. family = chart.menu + ' - ' + chart.submenu;
  1894. }
  1895. if (typeof families[family] === 'undefined') {
  1896. families[family] = {
  1897. name: family,
  1898. arr: [],
  1899. priority: chart.priority
  1900. };
  1901. families_sort.push(families[family]);
  1902. }
  1903. if (chart.priority < families[family].priority) {
  1904. families[family].priority = chart.priority;
  1905. }
  1906. families[family].arr.unshift(alarm);
  1907. }
  1908. // sort the families, like the dashboard menu does
  1909. var families_sorted = families_sort.sort(function (a, b) {
  1910. if (a.priority < b.priority) {
  1911. return -1;
  1912. }
  1913. if (a.priority > b.priority) {
  1914. return 1;
  1915. }
  1916. return naturalSortCompare(a.name, b.name);
  1917. });
  1918. var i = 0;
  1919. var fc = 0;
  1920. var len = families_sorted.length;
  1921. while (len--) {
  1922. family = families_sorted[i++].name;
  1923. var active_family_added = false;
  1924. var expanded = 'true';
  1925. var collapsed = '';
  1926. var cin = 'in';
  1927. if (fc !== 0) {
  1928. all += "</table></div></div></div>";
  1929. expanded = 'false';
  1930. collapsed = 'class="collapsed"';
  1931. cin = '';
  1932. }
  1933. all += '<div class="panel panel-default"><div class="panel-heading" role="tab" id="alarm_all_heading_' + fc.toString() + '"><h4 class="panel-title"><a ' + collapsed + ' role="button" data-toggle="collapse" data-parent="#alarms_all_accordion" href="#alarm_all_' + fc.toString() + '" aria-expanded="' + expanded + '" aria-controls="alarm_all_' + fc.toString() + '">' + family.toString() + '</a></h4></div><div id="alarm_all_' + fc.toString() + '" class="panel-collapse collapse ' + cin + '" role="tabpanel" aria-labelledby="alarm_all_heading_' + fc.toString() + '" data-alarm-id="' + fc.toString() + '"><div class="panel-body" id="alarm_all_body_' + fc.toString() + '">';
  1934. options.alarm_families[fc] = families[family];
  1935. fc++;
  1936. var arr = families[family].arr;
  1937. var c = arr.length;
  1938. while (c--) {
  1939. alarm = arr[c];
  1940. if (alarm.status === 'WARNING' || alarm.status === 'CRITICAL') {
  1941. if (!active_family_added) {
  1942. active_family_added = true;
  1943. active += '<tr><th class="text-center" colspan="2"><h4>' + family + '</h4></th></tr>';
  1944. }
  1945. count_active++;
  1946. active += alarm_to_html(alarm, true);
  1947. }
  1948. count_all++;
  1949. }
  1950. }
  1951. active += "</table>";
  1952. if (families_sorted.length > 0) {
  1953. all += "</div></div></div>";
  1954. }
  1955. all += "</div>";
  1956. if (!count_active) {
  1957. active += '<div style="width:100%; height: 100px; text-align: center;"><span style="font-size: 50px;"><i class="fas fa-thumbs-up"></i></span><br/>Everything is normal. No raised alarms.</div>';
  1958. } else {
  1959. active += footer;
  1960. }
  1961. if (!count_all) {
  1962. all += "<h4>No alarms are running in this system.</h4>";
  1963. } else {
  1964. all += footer;
  1965. }
  1966. document.getElementById('alarms_active').innerHTML = active;
  1967. document.getElementById('alarms_all').innerHTML = all;
  1968. enableTooltipsAndPopovers();
  1969. if (families_sorted.length > 0) {
  1970. alarm_family_show(0);
  1971. }
  1972. // register bootstrap events
  1973. var $accordion = $('#alarms_all_accordion');
  1974. $accordion.on('show.bs.collapse', function (d) {
  1975. var target = $(d.target);
  1976. var id = $(target).data('alarm-id');
  1977. alarm_family_show(id);
  1978. });
  1979. $accordion.on('hidden.bs.collapse', function (d) {
  1980. var target = $(d.target);
  1981. var id = $(target).data('alarm-id');
  1982. $('#alarm_all_' + id.toString()).html('');
  1983. });
  1984. document.getElementById('alarms_log').innerHTML = '<h3>Alarm Log</h3><table id="alarms_log_table"></table>';
  1985. loadBootstrapTable(function () {
  1986. $('#alarms_log_table').bootstrapTable({
  1987. url: NETDATA.alarms.server + '/api/v1/alarm_log?all',
  1988. cache: false,
  1989. pagination: true,
  1990. pageSize: 10,
  1991. showPaginationSwitch: false,
  1992. search: true,
  1993. searchTimeOut: 300,
  1994. searchAlign: 'left',
  1995. showColumns: true,
  1996. showExport: true,
  1997. exportDataType: 'basic',
  1998. exportOptions: {
  1999. fileName: 'netdata_alarm_log'
  2000. },
  2001. onClickRow: function (row, $element,field) {
  2002. void (field);
  2003. void ($element);
  2004. let main_url;
  2005. let common_url = "&host=" + encodeURIComponent(row['hostname']) + "&chart=" + encodeURIComponent(row['chart']) + "&family=" + encodeURIComponent(row['family']) + "&alarm=" + encodeURIComponent(row['name']) + "&alarm_unique_id=" + row['unique_id'] + "&alarm_id=" + row['alarm_id'] + "&alarm_event_id=" + row['alarm_event_id'] + "&alarm_when=" + row['when'];
  2006. if (NETDATA.registry.isUsingGlobalRegistry() && NETDATA.registry.machine_guid != null) {
  2007. main_url = "https://netdata.cloud/alarms/redirect?agentID=" + NETDATA.registry.machine_guid + common_url;
  2008. } else {
  2009. main_url = NETDATA.registry.server + "/goto-host-from-alarm.html?" + common_url ;
  2010. }
  2011. window.open(main_url,"_blank");
  2012. },
  2013. rowStyle: function (row, index) {
  2014. void (index);
  2015. switch (row.status) {
  2016. case 'CRITICAL':
  2017. return { classes: 'danger' };
  2018. break;
  2019. case 'WARNING':
  2020. return { classes: 'warning' };
  2021. break;
  2022. case 'UNDEFINED':
  2023. return { classes: 'info' };
  2024. break;
  2025. case 'CLEAR':
  2026. return { classes: 'success' };
  2027. break;
  2028. }
  2029. return {};
  2030. },
  2031. showFooter: false,
  2032. showHeader: true,
  2033. showRefresh: true,
  2034. showToggle: false,
  2035. sortable: true,
  2036. silentSort: false,
  2037. columns: [
  2038. {
  2039. field: 'when',
  2040. title: 'Event Date',
  2041. valign: 'middle',
  2042. titleTooltip: 'The date and time the even took place',
  2043. formatter: function (value, row, index) {
  2044. void (row);
  2045. void (index);
  2046. return timestamp4human(value, ' ');
  2047. },
  2048. align: 'center',
  2049. switchable: false,
  2050. sortable: true
  2051. },
  2052. {
  2053. field: 'hostname',
  2054. title: 'Host',
  2055. valign: 'middle',
  2056. titleTooltip: 'The host that generated this event',
  2057. align: 'center',
  2058. visible: false,
  2059. sortable: true
  2060. },
  2061. {
  2062. field: 'unique_id',
  2063. title: 'Unique ID',
  2064. titleTooltip: 'The host unique ID for this event',
  2065. formatter: function (value, row, index) {
  2066. void (row);
  2067. void (index);
  2068. return alarmid4human(value);
  2069. },
  2070. align: 'center',
  2071. valign: 'middle',
  2072. visible: false,
  2073. sortable: true
  2074. },
  2075. {
  2076. field: 'alarm_id',
  2077. title: 'Alarm ID',
  2078. titleTooltip: 'The ID of the alarm that generated this event',
  2079. formatter: function (value, row, index) {
  2080. void (row);
  2081. void (index);
  2082. return alarmid4human(value);
  2083. },
  2084. align: 'center',
  2085. valign: 'middle',
  2086. visible: false,
  2087. sortable: true
  2088. },
  2089. {
  2090. field: 'alarm_event_id',
  2091. title: 'Alarm Event ID',
  2092. titleTooltip: 'The incremental ID of this event for the given alarm',
  2093. formatter: function (value, row, index) {
  2094. void (row);
  2095. void (index);
  2096. return alarmid4human(value);
  2097. },
  2098. align: 'center',
  2099. valign: 'middle',
  2100. visible: false,
  2101. sortable: true
  2102. },
  2103. {
  2104. field: 'chart',
  2105. title: 'Chart',
  2106. titleTooltip: 'The chart the alarm is attached to',
  2107. align: 'center',
  2108. valign: 'middle',
  2109. switchable: false,
  2110. sortable: true
  2111. },
  2112. {
  2113. field: 'family',
  2114. title: 'Family',
  2115. titleTooltip: 'The family of the chart the alarm is attached to',
  2116. align: 'center',
  2117. valign: 'middle',
  2118. visible: false,
  2119. sortable: true
  2120. },
  2121. {
  2122. field: 'name',
  2123. title: 'Alarm',
  2124. titleTooltip: 'The alarm name that generated this event',
  2125. formatter: function (value, row, index) {
  2126. void (row);
  2127. void (index);
  2128. return value.toString().replace(/_/g, ' ');
  2129. },
  2130. align: 'center',
  2131. valign: 'middle',
  2132. switchable: false,
  2133. sortable: true
  2134. },
  2135. {
  2136. field: 'value_string',
  2137. title: 'Friendly Value',
  2138. titleTooltip: 'The value of the alarm, that triggered this event',
  2139. align: 'right',
  2140. valign: 'middle',
  2141. sortable: true
  2142. },
  2143. {
  2144. field: 'old_value_string',
  2145. title: 'Friendly Old Value',
  2146. titleTooltip: 'The value of the alarm, just before this event',
  2147. align: 'right',
  2148. valign: 'middle',
  2149. visible: false,
  2150. sortable: true
  2151. },
  2152. {
  2153. field: 'old_value',
  2154. title: 'Old Value',
  2155. titleTooltip: 'The value of the alarm, just before this event',
  2156. formatter: function (value, row, index) {
  2157. void (row);
  2158. void (index);
  2159. return ((value !== null) ? Math.round(value * 100) / 100 : 'NaN').toString();
  2160. },
  2161. align: 'center',
  2162. valign: 'middle',
  2163. visible: false,
  2164. sortable: true
  2165. },
  2166. {
  2167. field: 'value',
  2168. title: 'Value',
  2169. titleTooltip: 'The value of the alarm, that triggered this event',
  2170. formatter: function (value, row, index) {
  2171. void (row);
  2172. void (index);
  2173. return ((value !== null) ? Math.round(value * 100) / 100 : 'NaN').toString();
  2174. },
  2175. align: 'right',
  2176. valign: 'middle',
  2177. visible: false,
  2178. sortable: true
  2179. },
  2180. {
  2181. field: 'units',
  2182. title: 'Units',
  2183. titleTooltip: 'The units of the value of the alarm',
  2184. align: 'left',
  2185. valign: 'middle',
  2186. visible: false,
  2187. sortable: true
  2188. },
  2189. {
  2190. field: 'old_status',
  2191. title: 'Old Status',
  2192. titleTooltip: 'The status of the alarm, just before this event',
  2193. align: 'center',
  2194. valign: 'middle',
  2195. visible: false,
  2196. sortable: true
  2197. },
  2198. {
  2199. field: 'status',
  2200. title: 'Status',
  2201. titleTooltip: 'The status of the alarm, that was set due to this event',
  2202. align: 'center',
  2203. valign: 'middle',
  2204. switchable: false,
  2205. sortable: true
  2206. },
  2207. {
  2208. field: 'duration',
  2209. title: 'Last Duration',
  2210. titleTooltip: 'The duration the alarm was at its previous state, just before this event',
  2211. formatter: function (value, row, index) {
  2212. void (row);
  2213. void (index);
  2214. return NETDATA.seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
  2215. },
  2216. align: 'center',
  2217. valign: 'middle',
  2218. visible: false,
  2219. sortable: true
  2220. },
  2221. {
  2222. field: 'non_clear_duration',
  2223. title: 'Raised Duration',
  2224. titleTooltip: 'The duration the alarm was raised, just before this event',
  2225. formatter: function (value, row, index) {
  2226. void (row);
  2227. void (index);
  2228. return NETDATA.seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
  2229. },
  2230. align: 'center',
  2231. valign: 'middle',
  2232. visible: false,
  2233. sortable: true
  2234. },
  2235. {
  2236. field: 'recipient',
  2237. title: 'Recipient',
  2238. titleTooltip: 'The recipient of this event',
  2239. align: 'center',
  2240. valign: 'middle',
  2241. visible: false,
  2242. sortable: true
  2243. },
  2244. {
  2245. field: 'processed',
  2246. title: 'Processed Status',
  2247. titleTooltip: 'True when this event is processed',
  2248. formatter: function (value, row, index) {
  2249. void (row);
  2250. void (index);
  2251. if (value === true) {
  2252. return 'DONE';
  2253. } else {
  2254. return 'PENDING';
  2255. }
  2256. },
  2257. align: 'center',
  2258. valign: 'middle',
  2259. visible: false,
  2260. sortable: true
  2261. },
  2262. {
  2263. field: 'updated',
  2264. title: 'Updated Status',
  2265. titleTooltip: 'True when this event has been updated by another event',
  2266. formatter: function (value, row, index) {
  2267. void (row);
  2268. void (index);
  2269. if (value === true) {
  2270. return 'UPDATED';
  2271. } else {
  2272. return 'CURRENT';
  2273. }
  2274. },
  2275. align: 'center',
  2276. valign: 'middle',
  2277. visible: false,
  2278. sortable: true
  2279. },
  2280. {
  2281. field: 'updated_by_id',
  2282. title: 'Updated By ID',
  2283. titleTooltip: 'The unique ID of the event that obsoleted this one',
  2284. formatter: function (value, row, index) {
  2285. void (row);
  2286. void (index);
  2287. return alarmid4human(value);
  2288. },
  2289. align: 'center',
  2290. valign: 'middle',
  2291. visible: false,
  2292. sortable: true
  2293. },
  2294. {
  2295. field: 'updates_id',
  2296. title: 'Updates ID',
  2297. titleTooltip: 'The unique ID of the event obsoleted because of this event',
  2298. formatter: function (value, row, index) {
  2299. void (row);
  2300. void (index);
  2301. return alarmid4human(value);
  2302. },
  2303. align: 'center',
  2304. valign: 'middle',
  2305. visible: false,
  2306. sortable: true
  2307. },
  2308. {
  2309. field: 'exec',
  2310. title: 'Script',
  2311. titleTooltip: 'The script to handle the event notification',
  2312. align: 'center',
  2313. valign: 'middle',
  2314. visible: false,
  2315. sortable: true
  2316. },
  2317. {
  2318. field: 'exec_run',
  2319. title: 'Script Run At',
  2320. titleTooltip: 'The date and time the script has been ran',
  2321. formatter: function (value, row, index) {
  2322. void (row);
  2323. void (index);
  2324. return timestamp4human(value, ' ');
  2325. },
  2326. align: 'center',
  2327. valign: 'middle',
  2328. visible: false,
  2329. sortable: true
  2330. },
  2331. {
  2332. field: 'exec_code',
  2333. title: 'Script Return Value',
  2334. titleTooltip: 'The return code of the script',
  2335. formatter: function (value, row, index) {
  2336. void (row);
  2337. void (index);
  2338. if (value === 0) {
  2339. return 'OK (returned 0)';
  2340. } else {
  2341. return 'FAILED (with code ' + value.toString() + ')';
  2342. }
  2343. },
  2344. align: 'center',
  2345. valign: 'middle',
  2346. visible: false,
  2347. sortable: true
  2348. },
  2349. {
  2350. field: 'delay',
  2351. title: 'Script Delay',
  2352. titleTooltip: 'The hysteresis of the notification',
  2353. formatter: function (value, row, index) {
  2354. void (row);
  2355. void (index);
  2356. return NETDATA.seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
  2357. },
  2358. align: 'center',
  2359. valign: 'middle',
  2360. visible: false,
  2361. sortable: true
  2362. },
  2363. {
  2364. field: 'delay_up_to_timestamp',
  2365. title: 'Script Delay Run At',
  2366. titleTooltip: 'The date and time the script should be run, after hysteresis',
  2367. formatter: function (value, row, index) {
  2368. void (row);
  2369. void (index);
  2370. return timestamp4human(value, ' ');
  2371. },
  2372. align: 'center',
  2373. valign: 'middle',
  2374. visible: false,
  2375. sortable: true
  2376. },
  2377. {
  2378. field: 'info',
  2379. title: 'Description',
  2380. titleTooltip: 'A short description of the alarm',
  2381. align: 'center',
  2382. valign: 'middle',
  2383. visible: false,
  2384. sortable: true
  2385. },
  2386. {
  2387. field: 'source',
  2388. title: 'Alarm Source',
  2389. titleTooltip: 'The source of configuration of the alarm',
  2390. align: 'center',
  2391. valign: 'middle',
  2392. visible: false,
  2393. sortable: true
  2394. }
  2395. ]
  2396. });
  2397. // console.log($('#alarms_log_table').bootstrapTable('getOptions'));
  2398. });
  2399. });
  2400. }
  2401. function alarmsCallback(data) {
  2402. var count = 0, x;
  2403. for (x in data.alarms) {
  2404. if (!data.alarms.hasOwnProperty(x)) {
  2405. continue;
  2406. }
  2407. var alarm = data.alarms[x];
  2408. if (alarm.status === 'WARNING' || alarm.status === 'CRITICAL') {
  2409. count++;
  2410. }
  2411. }
  2412. if (count > 0) {
  2413. document.getElementById('alarms_count_badge').innerHTML = count.toString();
  2414. } else {
  2415. document.getElementById('alarms_count_badge').innerHTML = '';
  2416. }
  2417. }
  2418. function initializeDynamicDashboardWithData(data) {
  2419. if (data !== null) {
  2420. options.hostname = data.hostname;
  2421. options.data = data;
  2422. options.version = data.version;
  2423. options.release_channel = data.release_channel;
  2424. netdataDashboard.os = data.os;
  2425. if (typeof data.hosts !== 'undefined') {
  2426. options.hosts = data.hosts;
  2427. }
  2428. // update the dashboard hostname
  2429. document.getElementById('hostname').innerHTML = '<span id="hostnametext">' + options.hostname + ((netdataSnapshotData !== null) ? ' (snap)' : '').toString() + '</span>&nbsp;&nbsp;<strong class="caret">';
  2430. document.getElementById('hostname').href = NETDATA.serverDefault;
  2431. document.getElementById('netdataVersion').innerHTML = options.version;
  2432. if (netdataSnapshotData !== null) {
  2433. $('#alarmsButton').hide();
  2434. $('#updateButton').hide();
  2435. // $('#loadButton').hide();
  2436. $('#saveButton').hide();
  2437. $('#printButton').hide();
  2438. }
  2439. // update the dashboard title
  2440. document.title = options.hostname + ' netdata dashboard';
  2441. // close the splash screen
  2442. $("#loadOverlay").css("display", "none");
  2443. // create a chart_by_name index
  2444. data.charts_by_name = {};
  2445. var charts = data.charts;
  2446. var x;
  2447. for (x in charts) {
  2448. if (!charts.hasOwnProperty(x)) {
  2449. continue;
  2450. }
  2451. var chart = charts[x];
  2452. data.charts_by_name[chart.name] = chart;
  2453. }
  2454. // render all charts
  2455. renderChartsAndMenu(data);
  2456. // Ensure MyNetdata menu is rendered with latest host info #5370
  2457. renderMyNetdataMenu(isSignedIn() ? cloudAgents : registryAgents);
  2458. }
  2459. }
  2460. // an object to keep initialization configuration
  2461. // needed due to the async nature of the XSS modal
  2462. var initializeConfig = {
  2463. url: null,
  2464. custom_info: true,
  2465. };
  2466. function loadCustomDashboardInfo(url, callback) {
  2467. loadJs(url, function () {
  2468. $.extend(true, netdataDashboard, customDashboard);
  2469. callback();
  2470. });
  2471. }
  2472. function initializeChartsAndCustomInfo() {
  2473. NETDATA.alarms.callback = alarmsCallback;
  2474. // download all the charts the server knows
  2475. NETDATA.chartRegistry.downloadAll(initializeConfig.url, function (data) {
  2476. if (data !== null) {
  2477. if (initializeConfig.custom_info === true && typeof data.custom_info !== 'undefined' && data.custom_info !== "" && netdataSnapshotData === null) {
  2478. //console.log('loading custom dashboard decorations from server ' + initializeConfig.url);
  2479. loadCustomDashboardInfo(NETDATA.serverDefault + data.custom_info, function () {
  2480. initializeDynamicDashboardWithData(data);
  2481. });
  2482. } else {
  2483. //console.log('not loading custom dashboard decorations from server ' + initializeConfig.url);
  2484. initializeDynamicDashboardWithData(data);
  2485. }
  2486. }
  2487. });
  2488. }
  2489. function xssModalDisableXss() {
  2490. //console.log('disabling xss checks');
  2491. NETDATA.xss.enabled = false;
  2492. NETDATA.xss.enabled_for_data = false;
  2493. initializeConfig.custom_info = true;
  2494. initializeChartsAndCustomInfo();
  2495. return false;
  2496. }
  2497. function xssModalKeepXss() {
  2498. //console.log('keeping xss checks');
  2499. NETDATA.xss.enabled = true;
  2500. NETDATA.xss.enabled_for_data = true;
  2501. initializeConfig.custom_info = false;
  2502. initializeChartsAndCustomInfo();
  2503. return false;
  2504. }
  2505. function initializeDynamicDashboard(netdata_url) {
  2506. if (typeof netdata_url === 'undefined' || netdata_url === null) {
  2507. netdata_url = NETDATA.serverDefault;
  2508. }
  2509. initializeConfig.url = netdata_url;
  2510. // initialize clickable alarms
  2511. NETDATA.alarms.chart_div_offset = -50;
  2512. NETDATA.alarms.chart_div_id_prefix = 'chart_';
  2513. NETDATA.alarms.chart_div_animation_duration = 0;
  2514. NETDATA.pause(function () {
  2515. if (typeof netdataCheckXSS !== 'undefined' && netdataCheckXSS === true) {
  2516. //$("#loadOverlay").css("display","none");
  2517. document.getElementById('netdataXssModalServer').innerText = initializeConfig.url;
  2518. $('#xssModal').modal('show');
  2519. } else {
  2520. initializeChartsAndCustomInfo();
  2521. }
  2522. });
  2523. }
  2524. // ----------------------------------------------------------------------------
  2525. function versionLog(msg) {
  2526. document.getElementById('versionCheckLog').innerHTML = msg;
  2527. }
  2528. // New way of checking for updates, based only on versions
  2529. function versionsMatch(v1, v2) {
  2530. if (v1 == v2) {
  2531. return true;
  2532. } else {
  2533. let s1 = v1.split('.');
  2534. let s2 = v2.split('.');
  2535. // Check major version
  2536. let n1 = parseInt(s1[0].substring(1, 2), 10);
  2537. let n2 = parseInt(s2[0].substring(1, 2), 10);
  2538. if (n1 < n2) return false;
  2539. else if (n1 > n2) return true;
  2540. // Check minor version
  2541. n1 = parseInt(s1[1], 10);
  2542. n2 = parseInt(s2[1], 10);
  2543. if (n1 < n2) return false;
  2544. else if (n1 > n2) return true;
  2545. // Split patch: format could be e.g. 0-22-nightly
  2546. s1 = s1[2].split('-');
  2547. s2 = s2[2].split('-');
  2548. n1 = parseInt(s1[0], 10);
  2549. n2 = parseInt(s2[0], 10);
  2550. if (n1 < n2) return false;
  2551. else if (n1 > n2) return true;
  2552. n1 = (s1.length > 1) ? parseInt(s1[1], 10) : 0;
  2553. n2 = (s2.length > 1) ? parseInt(s2[1], 10) : 0;
  2554. if (n1 < n2) return false;
  2555. else return true;
  2556. }
  2557. }
  2558. function getGithubLatestVersion(callback) {
  2559. versionLog('Downloading latest version id from github...');
  2560. $.ajax({
  2561. url: 'https://api.github.com/repos/netdata/netdata/releases/latest',
  2562. async: true,
  2563. cache: false
  2564. })
  2565. .done(function (data) {
  2566. data = data.tag_name.replace(/(\r\n|\n|\r| |\t)/gm, "");
  2567. versionLog('Latest stable version from github is ' + data);
  2568. callback(data);
  2569. })
  2570. .fail(function () {
  2571. versionLog('Failed to download the latest stable version id from github!');
  2572. callback(null);
  2573. });
  2574. }
  2575. function getGCSLatestVersion(callback) {
  2576. versionLog('Downloading latest version id from GCS...');
  2577. $.ajax({
  2578. url: "https://www.googleapis.com/storage/v1/b/netdata-nightlies/o/latest-version.txt",
  2579. async: true,
  2580. cache: false
  2581. })
  2582. .done(function (response) {
  2583. $.ajax({
  2584. url: response.mediaLink,
  2585. async: true,
  2586. cache: false
  2587. })
  2588. .done(function (data) {
  2589. data = data.replace(/(\r\n|\n|\r| |\t)/gm, "");
  2590. versionLog('Latest nightly version from GCS is ' + data);
  2591. callback(data);
  2592. })
  2593. .fail(function (xhr, textStatus, errorThrown) {
  2594. versionLog('Failed to download the latest nightly version id from GCS!');
  2595. callback(null);
  2596. });
  2597. })
  2598. .fail(function (xhr, textStatus, errorThrown) {
  2599. versionLog('Failed to download the latest nightly version from GCS!');
  2600. callback(null);
  2601. });
  2602. }
  2603. function checkForUpdateByVersion(force, callback) {
  2604. if (options.release_channel === 'stable') {
  2605. getGithubLatestVersion(function (sha2) {
  2606. callback(options.version, sha2);
  2607. });
  2608. } else {
  2609. getGCSLatestVersion(function (sha2) {
  2610. callback(options.version, sha2);
  2611. });
  2612. }
  2613. return null;
  2614. }
  2615. function notifyForUpdate(force) {
  2616. versionLog('<p>checking for updates...</p>');
  2617. var now = Date.now();
  2618. if (typeof force === 'undefined' || force !== true) {
  2619. var last = loadLocalStorage('last_update_check');
  2620. if (typeof last === 'string') {
  2621. last = parseInt(last);
  2622. } else {
  2623. last = 0;
  2624. }
  2625. if (now - last < 3600000 * 8) {
  2626. // no need to check it - too soon
  2627. return;
  2628. }
  2629. }
  2630. checkForUpdateByVersion(force, function (sha1, sha2) {
  2631. var save = false;
  2632. if (sha1 === null) {
  2633. save = false;
  2634. versionLog('<p><big>Failed to get your netdata version!</big></p><p>You can always get the latest netdata from <a href="https://github.com/netdata/netdata" target="_blank">its github page</a>.</p>');
  2635. } else if (sha2 === null) {
  2636. save = false;
  2637. versionLog('<p><big>Failed to get the latest netdata version.</big></p><p>You can always get the latest netdata from <a href="https://github.com/netdata/netdata" target="_blank">its github page</a>.</p>');
  2638. } else if (versionsMatch(sha1, sha2)) {
  2639. save = true;
  2640. versionLog('<p><big>You already have the latest netdata!</big></p><p>No update yet?<br/>We probably need some motivation to keep going on!</p><p>If you haven\'t already, <a href="https://github.com/netdata/netdata" target="_blank">give netdata a <b><i class="fas fa-star"></i></b> at its github page</a>.</p>');
  2641. } else {
  2642. save = true;
  2643. var compare = 'https://learn.netdata.cloud/docs/agent/changelog/';
  2644. versionLog('<p><big><strong>New version of netdata available!</strong></big></p><p>Latest version: <b><code>' + sha2 + '</code></b></p><p><a href="' + compare + '" target="_blank">Click here for the changes log</a> and<br/><a href="https://github.com/netdata/netdata/tree/master/packaging/installer/UPDATE.md" target="_blank">click here for directions on updating</a> your netdata installation.</p><p>We suggest to review the changes log for new features you may be interested, or important bug fixes you may need.<br/>Keeping your netdata updated is generally a good idea.</p>');
  2645. document.getElementById('update_badge').innerHTML = '!';
  2646. }
  2647. if (save) {
  2648. saveLocalStorage('last_update_check', now.toString());
  2649. }
  2650. });
  2651. }
  2652. // ----------------------------------------------------------------------------
  2653. // printing dashboards
  2654. function showPageFooter() {
  2655. document.getElementById('footer').style.display = 'block';
  2656. }
  2657. function printPreflight() {
  2658. var url = document.location.origin.toString() + document.location.pathname.toString() + document.location.search.toString() + urlOptions.genHash() + ';mode=print';
  2659. var width = 990;
  2660. var height = screen.height * 90 / 100;
  2661. //console.log(url);
  2662. //console.log(document.location);
  2663. window.open(url, '', 'width=' + width.toString() + ',height=' + height.toString() + ',menubar=no,toolbar=no,personalbar=no,location=no,resizable=no,scrollbars=yes,status=no,chrome=yes,centerscreen=yes,attention=yes,dialog=yes');
  2664. $('#printPreflightModal').modal('hide');
  2665. }
  2666. function printPage() {
  2667. var print_is_rendering = true;
  2668. $('#printModal').on('hide.bs.modal', function (e) {
  2669. if (print_is_rendering === true) {
  2670. e.preventDefault();
  2671. return false;
  2672. }
  2673. return true;
  2674. });
  2675. $('#printModal').on('show.bs.modal', function () {
  2676. var print_options = {
  2677. stop_updates_when_focus_is_lost: false,
  2678. update_only_visible: false,
  2679. sync_selection: false,
  2680. eliminate_zero_dimensions: false,
  2681. pan_and_zoom_data_padding: false,
  2682. show_help: false,
  2683. legend_toolbox: false,
  2684. resize_charts: false,
  2685. pixels_per_point: 1
  2686. };
  2687. var x;
  2688. for (x in print_options) {
  2689. if (print_options.hasOwnProperty(x)) {
  2690. NETDATA.options.current[x] = print_options[x];
  2691. }
  2692. }
  2693. NETDATA.parseDom();
  2694. showPageFooter();
  2695. NETDATA.globalSelectionSync.stop();
  2696. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], urlOptions.after, urlOptions.before);
  2697. // NETDATA.onresize();
  2698. var el = document.getElementById('printModalProgressBar');
  2699. var eltxt = document.getElementById('printModalProgressBarText');
  2700. function update_chart(idx) {
  2701. var state = NETDATA.options.targets[--idx];
  2702. var pcent = (NETDATA.options.targets.length - idx) * 100 / NETDATA.options.targets.length;
  2703. $(el).css('width', pcent + '%').attr('aria-valuenow', pcent);
  2704. eltxt.innerText = Math.round(pcent).toString() + '%, ' + state.id;
  2705. setTimeout(function () {
  2706. state.updateChart(function () {
  2707. NETDATA.options.targets[idx].resizeForPrint();
  2708. if (idx > 0) {
  2709. update_chart(idx);
  2710. } else {
  2711. print_is_rendering = false;
  2712. $('#printModal').modal('hide');
  2713. window.print();
  2714. window.close();
  2715. }
  2716. })
  2717. }, 0);
  2718. }
  2719. print_is_rendering = true;
  2720. update_chart(NETDATA.options.targets.length);
  2721. });
  2722. $('#printModal').modal('show');
  2723. }
  2724. // --------------------------------------------------------------------
  2725. function jsonStringifyFn(obj) {
  2726. return JSON.stringify(obj, function (key, value) {
  2727. return (typeof value === 'function') ? value.toString() : value;
  2728. });
  2729. }
  2730. function jsonParseFn(str) {
  2731. return JSON.parse(str, function (key, value) {
  2732. if (typeof value != 'string') {
  2733. return value;
  2734. }
  2735. return (value.substring(0, 8) == 'function') ? eval('(' + value + ')') : value;
  2736. });
  2737. }
  2738. // --------------------------------------------------------------------
  2739. var snapshotOptions = {
  2740. bytes_per_chart: 2048,
  2741. compressionDefault: 'pako.deflate.base64',
  2742. compressions: {
  2743. 'none': {
  2744. bytes_per_point_memory: 5.2,
  2745. bytes_per_point_disk: 5.6,
  2746. compress: function (s) {
  2747. return s;
  2748. },
  2749. compressed_length: function (s) {
  2750. return s.length;
  2751. },
  2752. uncompress: function (s) {
  2753. return s;
  2754. }
  2755. },
  2756. 'pako.deflate.base64': {
  2757. bytes_per_point_memory: 1.8,
  2758. bytes_per_point_disk: 1.9,
  2759. compress: function (s) {
  2760. return btoa(pako.deflate(s, { to: 'string' }));
  2761. },
  2762. compressed_length: function (s) {
  2763. return s.length;
  2764. },
  2765. uncompress: function (s) {
  2766. return pako.inflate(atob(s), { to: 'string' });
  2767. }
  2768. },
  2769. 'pako.deflate': {
  2770. bytes_per_point_memory: 1.4,
  2771. bytes_per_point_disk: 3.2,
  2772. compress: function (s) {
  2773. return pako.deflate(s, { to: 'string' });
  2774. },
  2775. compressed_length: function (s) {
  2776. return s.length;
  2777. },
  2778. uncompress: function (s) {
  2779. return pako.inflate(s, { to: 'string' });
  2780. }
  2781. },
  2782. 'lzstring.utf16': {
  2783. bytes_per_point_memory: 1.7,
  2784. bytes_per_point_disk: 2.6,
  2785. compress: function (s) {
  2786. return LZString.compressToUTF16(s);
  2787. },
  2788. compressed_length: function (s) {
  2789. return s.length * 2;
  2790. },
  2791. uncompress: function (s) {
  2792. return LZString.decompressFromUTF16(s);
  2793. }
  2794. },
  2795. 'lzstring.base64': {
  2796. bytes_per_point_memory: 2.1,
  2797. bytes_per_point_disk: 2.3,
  2798. compress: function (s) {
  2799. return LZString.compressToBase64(s);
  2800. },
  2801. compressed_length: function (s) {
  2802. return s.length;
  2803. },
  2804. uncompress: function (s) {
  2805. return LZString.decompressFromBase64(s);
  2806. }
  2807. },
  2808. 'lzstring.uri': {
  2809. bytes_per_point_memory: 2.1,
  2810. bytes_per_point_disk: 2.3,
  2811. compress: function (s) {
  2812. return LZString.compressToEncodedURIComponent(s);
  2813. },
  2814. compressed_length: function (s) {
  2815. return s.length;
  2816. },
  2817. uncompress: function (s) {
  2818. return LZString.decompressFromEncodedURIComponent(s);
  2819. }
  2820. }
  2821. }
  2822. };
  2823. // --------------------------------------------------------------------
  2824. // loading snapshots
  2825. function loadSnapshotModalLog(priority, msg) {
  2826. document.getElementById('loadSnapshotStatus').className = "alert alert-" + priority;
  2827. document.getElementById('loadSnapshotStatus').innerHTML = msg;
  2828. }
  2829. var tmpSnapshotData = null;
  2830. function loadSnapshot() {
  2831. $('#loadSnapshotImport').addClass('disabled');
  2832. if (tmpSnapshotData === null) {
  2833. loadSnapshotPreflightEmpty();
  2834. loadSnapshotModalLog('danger', 'no data have been loaded');
  2835. return;
  2836. }
  2837. loadPako(function () {
  2838. loadLzString(function () {
  2839. loadSnapshotModalLog('info', 'Please wait, activating snapshot...');
  2840. $('#loadSnapshotModal').modal('hide');
  2841. netdataShowAlarms = false;
  2842. netdataRegistry = false;
  2843. netdataServer = tmpSnapshotData.server;
  2844. NETDATA.serverDefault = netdataServer;
  2845. document.getElementById('charts_div').innerHTML = '';
  2846. document.getElementById('sidebar').innerHTML = '';
  2847. NETDATA.globalReset();
  2848. if (typeof tmpSnapshotData.hash !== 'undefined') {
  2849. urlOptions.hash = tmpSnapshotData.hash;
  2850. } else {
  2851. urlOptions.hash = '#';
  2852. }
  2853. if (typeof tmpSnapshotData.info !== 'undefined') {
  2854. var info = jsonParseFn(tmpSnapshotData.info);
  2855. if (typeof info.menu !== 'undefined') {
  2856. netdataDashboard.menu = info.menu;
  2857. }
  2858. if (typeof info.submenu !== 'undefined') {
  2859. netdataDashboard.submenu = info.submenu;
  2860. }
  2861. if (typeof info.context !== 'undefined') {
  2862. netdataDashboard.context = info.context;
  2863. }
  2864. }
  2865. if (typeof tmpSnapshotData.compression !== 'string') {
  2866. tmpSnapshotData.compression = 'none';
  2867. }
  2868. if (typeof snapshotOptions.compressions[tmpSnapshotData.compression] === 'undefined') {
  2869. alert('unknown compression method: ' + tmpSnapshotData.compression);
  2870. tmpSnapshotData.compression = 'none';
  2871. }
  2872. tmpSnapshotData.uncompress = snapshotOptions.compressions[tmpSnapshotData.compression].uncompress;
  2873. netdataSnapshotData = tmpSnapshotData;
  2874. urlOptions.after = tmpSnapshotData.after_ms;
  2875. urlOptions.before = tmpSnapshotData.before_ms;
  2876. if (typeof tmpSnapshotData.highlight_after_ms !== 'undefined'
  2877. && tmpSnapshotData.highlight_after_ms !== null
  2878. && tmpSnapshotData.highlight_after_ms > 0
  2879. && typeof tmpSnapshotData.highlight_before_ms !== 'undefined'
  2880. && tmpSnapshotData.highlight_before_ms !== null
  2881. && tmpSnapshotData.highlight_before_ms > 0
  2882. ) {
  2883. urlOptions.highlight_after = tmpSnapshotData.highlight_after_ms;
  2884. urlOptions.highlight_before = tmpSnapshotData.highlight_before_ms;
  2885. urlOptions.highlight = true;
  2886. } else {
  2887. urlOptions.highlight_after = 0;
  2888. urlOptions.highlight_before = 0;
  2889. urlOptions.highlight = false;
  2890. }
  2891. netdataCheckXSS = false; // disable the modal - this does not affect XSS checks, since dashboard.js is already loaded
  2892. NETDATA.xss.enabled = true; // we should not do any remote requests, but if we do, check them
  2893. NETDATA.xss.enabled_for_data = true; // check also snapshot data - that have been excluded from the initial check, due to compression
  2894. loadSnapshotPreflightEmpty();
  2895. initializeDynamicDashboard();
  2896. });
  2897. });
  2898. };
  2899. function loadSnapshotPreflightFile(file) {
  2900. var filename = NETDATA.xss.string(file.name);
  2901. var fr = new FileReader();
  2902. fr.onload = function (e) {
  2903. document.getElementById('loadSnapshotFilename').innerHTML = filename;
  2904. var result = null;
  2905. try {
  2906. result = NETDATA.xss.checkAlways('snapshot', JSON.parse(e.target.result), /^(snapshot\.info|snapshot\.data)$/);
  2907. //console.log(result);
  2908. var date_after = new Date(result.after_ms);
  2909. var date_before = new Date(result.before_ms);
  2910. if (typeof result.charts_ok === 'undefined') {
  2911. result.charts_ok = 'unknown';
  2912. }
  2913. if (typeof result.charts_failed === 'undefined') {
  2914. result.charts_failed = 0;
  2915. }
  2916. if (typeof result.compression === 'undefined') {
  2917. result.compression = 'none';
  2918. }
  2919. if (typeof result.data_size === 'undefined') {
  2920. result.data_size = 0;
  2921. }
  2922. document.getElementById('loadSnapshotFilename').innerHTML = '<code>' + filename + '</code>';
  2923. document.getElementById('loadSnapshotHostname').innerHTML = '<b>' + result.hostname + '</b>, netdata version: <b>' + result.netdata_version.toString() + '</b>';
  2924. document.getElementById('loadSnapshotURL').innerHTML = result.url;
  2925. document.getElementById('loadSnapshotCharts').innerHTML = result.charts.charts_count.toString() + ' charts, ' + result.charts.dimensions_count.toString() + ' dimensions, ' + result.data_points.toString() + ' points per dimension, ' + Math.round(result.duration_ms / result.data_points).toString() + ' ms per point';
  2926. document.getElementById('loadSnapshotInfo').innerHTML = 'version: <b>' + result.snapshot_version.toString() + '</b>, includes <b>' + result.charts_ok.toString() + '</b> unique chart data queries ' + ((result.charts_failed > 0) ? ('<b>' + result.charts_failed.toString() + '</b> failed') : '').toString() + ', compressed with <code>' + result.compression.toString() + '</code>, data size ' + (Math.round(result.data_size * 100 / 1024 / 1024) / 100).toString() + ' MB';
  2927. document.getElementById('loadSnapshotTimeRange').innerHTML = '<b>' + NETDATA.dateTime.localeDateString(date_after) + ' ' + NETDATA.dateTime.localeTimeString(date_after) + '</b> to <b>' + NETDATA.dateTime.localeDateString(date_before) + ' ' + NETDATA.dateTime.localeTimeString(date_before) + '</b>';
  2928. document.getElementById('loadSnapshotComments').innerHTML = ((result.comments) ? result.comments : '').toString();
  2929. loadSnapshotModalLog('success', 'File loaded, click <b>Import</b> to render it!');
  2930. $('#loadSnapshotImport').removeClass('disabled');
  2931. tmpSnapshotData = result;
  2932. }
  2933. catch (e) {
  2934. console.log(e);
  2935. document.getElementById('loadSnapshotStatus').className = "alert alert-danger";
  2936. document.getElementById('loadSnapshotStatus').innerHTML = "Failed to parse this file!";
  2937. $('#loadSnapshotImport').addClass('disabled');
  2938. }
  2939. }
  2940. //console.log(file);
  2941. fr.readAsText(file);
  2942. };
  2943. function loadSnapshotPreflightEmpty() {
  2944. document.getElementById('loadSnapshotFilename').innerHTML = '';
  2945. document.getElementById('loadSnapshotHostname').innerHTML = '';
  2946. document.getElementById('loadSnapshotURL').innerHTML = '';
  2947. document.getElementById('loadSnapshotCharts').innerHTML = '';
  2948. document.getElementById('loadSnapshotInfo').innerHTML = '';
  2949. document.getElementById('loadSnapshotTimeRange').innerHTML = '';
  2950. document.getElementById('loadSnapshotComments').innerHTML = '';
  2951. loadSnapshotModalLog('success', 'Browse for a snapshot file (or drag it and drop it here), then click <b>Import</b> to render it.');
  2952. $('#loadSnapshotImport').addClass('disabled');
  2953. };
  2954. var loadSnapshotDragAndDropInitialized = false;
  2955. function loadSnapshotDragAndDropSetup() {
  2956. if (loadSnapshotDragAndDropInitialized === false) {
  2957. loadSnapshotDragAndDropInitialized = true;
  2958. $('#loadSnapshotDragAndDrop')
  2959. .on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  2960. e.preventDefault();
  2961. e.stopPropagation();
  2962. })
  2963. .on('drop', function (e) {
  2964. if (e.originalEvent.dataTransfer.files.length) {
  2965. loadSnapshotPreflightFile(e.originalEvent.dataTransfer.files.item(0));
  2966. } else {
  2967. loadSnapshotPreflightEmpty();
  2968. loadSnapshotModalLog('danger', 'No file selected');
  2969. }
  2970. });
  2971. }
  2972. };
  2973. function loadSnapshotPreflight() {
  2974. var files = document.getElementById('loadSnapshotSelectFiles').files;
  2975. if (files.length <= 0) {
  2976. loadSnapshotPreflightEmpty();
  2977. loadSnapshotModalLog('danger', 'No file selected');
  2978. return;
  2979. }
  2980. loadSnapshotModalLog('info', 'Loading file...');
  2981. loadSnapshotPreflightFile(files.item(0));
  2982. }
  2983. // --------------------------------------------------------------------
  2984. // saving snapshots
  2985. var saveSnapshotStop = false;
  2986. function saveSnapshotCancel() {
  2987. saveSnapshotStop = true;
  2988. }
  2989. var saveSnapshotModalInitialized = false;
  2990. function saveSnapshotModalSetup() {
  2991. if (saveSnapshotModalInitialized === false) {
  2992. saveSnapshotModalInitialized = true;
  2993. $('#saveSnapshotModal')
  2994. .on('hide.bs.modal', saveSnapshotCancel)
  2995. .on('show.bs.modal', saveSnapshotModalInit)
  2996. .on('shown.bs.modal', function () {
  2997. $('#saveSnapshotResolutionSlider').find(".slider-handle:first").attr("tabindex", 1);
  2998. document.getElementById('saveSnapshotComments').focus();
  2999. });
  3000. }
  3001. };
  3002. function saveSnapshotModalLog(priority, msg) {
  3003. document.getElementById('saveSnapshotStatus').className = "alert alert-" + priority;
  3004. document.getElementById('saveSnapshotStatus').innerHTML = msg;
  3005. }
  3006. function saveSnapshotModalShowExpectedSize() {
  3007. var points = Math.round(saveSnapshotViewDuration / saveSnapshotSelectedSecondsPerPoint);
  3008. var priority = 'info';
  3009. var msg = 'A moderate snapshot.';
  3010. var sizemb = Math.round(
  3011. (options.data.charts_count * snapshotOptions.bytes_per_chart
  3012. + options.data.dimensions_count * points * snapshotOptions.compressions[saveSnapshotCompression].bytes_per_point_disk)
  3013. * 10 / 1024 / 1024) / 10;
  3014. var memmb = Math.round(
  3015. (options.data.charts_count * snapshotOptions.bytes_per_chart
  3016. + options.data.dimensions_count * points * snapshotOptions.compressions[saveSnapshotCompression].bytes_per_point_memory)
  3017. * 10 / 1024 / 1024) / 10;
  3018. if (sizemb < 10) {
  3019. priority = 'success';
  3020. msg = 'A nice small snapshot!';
  3021. }
  3022. if (sizemb > 50) {
  3023. priority = 'warning';
  3024. msg = 'Will stress your browser...';
  3025. }
  3026. if (sizemb > 100) {
  3027. priority = 'danger';
  3028. msg = 'Hm... good luck...';
  3029. }
  3030. saveSnapshotModalLog(priority, 'The snapshot will have ' + points.toString() + ' points per dimension. Expected size on disk ' + sizemb + ' MB, at browser memory ' + memmb + ' MB.<br/>' + msg);
  3031. }
  3032. var saveSnapshotCompression = snapshotOptions.compressionDefault;
  3033. function saveSnapshotSetCompression(name) {
  3034. saveSnapshotCompression = name;
  3035. document.getElementById('saveSnapshotCompressionName').innerHTML = saveSnapshotCompression;
  3036. saveSnapshotModalShowExpectedSize();
  3037. }
  3038. var saveSnapshotSlider = null;
  3039. var saveSnapshotSelectedSecondsPerPoint = 1;
  3040. var saveSnapshotViewDuration = 1;
  3041. function saveSnapshotModalInit() {
  3042. $('#saveSnapshotModalProgressSection').hide();
  3043. $('#saveSnapshotResolutionRadio').show();
  3044. saveSnapshotModalLog('info', 'Select resolution and click <b>Save</b>');
  3045. $('#saveSnapshotExport').removeClass('disabled');
  3046. loadBootstrapSlider(function () {
  3047. saveSnapshotViewDuration = options.duration;
  3048. var start_ms = Math.round(Date.now() - saveSnapshotViewDuration * 1000);
  3049. if (NETDATA.globalPanAndZoom.isActive() === true) {
  3050. saveSnapshotViewDuration = Math.round((NETDATA.globalPanAndZoom.force_before_ms - NETDATA.globalPanAndZoom.force_after_ms) / 1000);
  3051. start_ms = NETDATA.globalPanAndZoom.force_after_ms;
  3052. }
  3053. var start_date = new Date(start_ms);
  3054. var yyyymmddhhssmm = start_date.getFullYear() + NETDATA.zeropad(start_date.getMonth() + 1) + NETDATA.zeropad(start_date.getDate()) + '-' + NETDATA.zeropad(start_date.getHours()) + NETDATA.zeropad(start_date.getMinutes()) + NETDATA.zeropad(start_date.getSeconds());
  3055. document.getElementById('saveSnapshotFilename').value = 'netdata-' + options.hostname.toString() + '-' + yyyymmddhhssmm.toString() + '-' + saveSnapshotViewDuration.toString() + '.snapshot';
  3056. saveSnapshotSetCompression(saveSnapshotCompression);
  3057. var min = options.update_every;
  3058. var max = Math.round(saveSnapshotViewDuration / 100);
  3059. if (NETDATA.globalPanAndZoom.isActive() === false) {
  3060. max = Math.round(saveSnapshotViewDuration / 50);
  3061. }
  3062. var view = Math.round(saveSnapshotViewDuration / Math.round($(document.getElementById('charts_div')).width() / 2));
  3063. // console.log('view duration: ' + saveSnapshotViewDuration + ', min: ' + min + ', max: ' + max + ', view: ' + view);
  3064. if (max < 10) {
  3065. max = 10;
  3066. }
  3067. if (max < min) {
  3068. max = min;
  3069. }
  3070. if (view < min) {
  3071. view = min;
  3072. }
  3073. if (view > max) {
  3074. view = max;
  3075. }
  3076. if (saveSnapshotSlider !== null) {
  3077. saveSnapshotSlider.destroy();
  3078. }
  3079. saveSnapshotSlider = new Slider('#saveSnapshotResolutionSlider', {
  3080. ticks: [min, view, max],
  3081. min: min,
  3082. max: max,
  3083. step: options.update_every,
  3084. value: view,
  3085. scale: (max > 100) ? 'logarithmic' : 'linear',
  3086. tooltip: 'always',
  3087. formatter: function (value) {
  3088. if (value < 1) {
  3089. value = 1;
  3090. }
  3091. if (value < options.data.update_every) {
  3092. value = options.data.update_every;
  3093. }
  3094. saveSnapshotSelectedSecondsPerPoint = value;
  3095. saveSnapshotModalShowExpectedSize();
  3096. var seconds = ' seconds ';
  3097. if (value === 1) {
  3098. seconds = ' second ';
  3099. }
  3100. return value + seconds + 'per point' + ((value === options.data.update_every) ? ', server default' : '').toString();
  3101. }
  3102. });
  3103. });
  3104. }
  3105. function saveSnapshot() {
  3106. loadPako(function () {
  3107. loadLzString(function () {
  3108. saveSnapshotStop = false;
  3109. $('#saveSnapshotModalProgressSection').show();
  3110. $('#saveSnapshotResolutionRadio').hide();
  3111. $('#saveSnapshotExport').addClass('disabled');
  3112. var filename = document.getElementById('saveSnapshotFilename').value;
  3113. // console.log(filename);
  3114. saveSnapshotModalLog('info', 'Generating snapshot as <code>' + filename.toString() + '</code>');
  3115. var save_options = {
  3116. stop_updates_when_focus_is_lost: false,
  3117. update_only_visible: false,
  3118. sync_selection: false,
  3119. eliminate_zero_dimensions: true,
  3120. pan_and_zoom_data_padding: false,
  3121. show_help: false,
  3122. legend_toolbox: false,
  3123. resize_charts: false,
  3124. pixels_per_point: 1
  3125. };
  3126. var backedup_options = {};
  3127. var x;
  3128. for (x in save_options) {
  3129. if (save_options.hasOwnProperty(x)) {
  3130. backedup_options[x] = NETDATA.options.current[x];
  3131. NETDATA.options.current[x] = save_options[x];
  3132. }
  3133. }
  3134. var el = document.getElementById('saveSnapshotModalProgressBar');
  3135. var eltxt = document.getElementById('saveSnapshotModalProgressBarText');
  3136. options.data.charts_by_name = null;
  3137. var saveData = {
  3138. hostname: options.hostname,
  3139. server: NETDATA.serverDefault,
  3140. netdata_version: options.data.version,
  3141. snapshot_version: 1,
  3142. after_ms: Date.now() - options.duration * 1000,
  3143. before_ms: Date.now(),
  3144. highlight_after_ms: urlOptions.highlight_after,
  3145. highlight_before_ms: urlOptions.highlight_before,
  3146. duration_ms: options.duration * 1000,
  3147. update_every_ms: options.update_every * 1000,
  3148. data_points: 0,
  3149. url: ((urlOptions.server !== null) ? urlOptions.server : document.location.origin.toString() + document.location.pathname.toString() + document.location.search.toString()).toString(),
  3150. comments: document.getElementById('saveSnapshotComments').value.toString(),
  3151. hash: urlOptions.hash,
  3152. charts: options.data,
  3153. info: jsonStringifyFn({
  3154. menu: netdataDashboard.menu,
  3155. submenu: netdataDashboard.submenu,
  3156. context: netdataDashboard.context
  3157. }),
  3158. charts_ok: 0,
  3159. charts_failed: 0,
  3160. compression: saveSnapshotCompression,
  3161. data_size: 0,
  3162. data: {}
  3163. };
  3164. if (typeof snapshotOptions.compressions[saveData.compression] === 'undefined') {
  3165. alert('unknown compression method: ' + saveData.compression);
  3166. saveData.compression = 'none';
  3167. }
  3168. var compress = snapshotOptions.compressions[saveData.compression].compress;
  3169. var compressed_length = snapshotOptions.compressions[saveData.compression].compressed_length;
  3170. function pack_api1_v1_chart_data(state) {
  3171. if (state.library_name === null || state.data === null) {
  3172. return;
  3173. }
  3174. var data = state.data;
  3175. state.data = null;
  3176. data.state = null;
  3177. var str = JSON.stringify(data);
  3178. if (typeof str === 'string') {
  3179. var cstr = compress(str);
  3180. saveData.data[state.chartDataUniqueID()] = cstr;
  3181. return compressed_length(cstr);
  3182. } else {
  3183. return 0;
  3184. }
  3185. }
  3186. var clearPanAndZoom = false;
  3187. if (NETDATA.globalPanAndZoom.isActive() === false) {
  3188. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], saveData.after_ms, saveData.before_ms);
  3189. clearPanAndZoom = true;
  3190. }
  3191. saveData.after_ms = NETDATA.globalPanAndZoom.force_after_ms;
  3192. saveData.before_ms = NETDATA.globalPanAndZoom.force_before_ms;
  3193. saveData.duration_ms = saveData.before_ms - saveData.after_ms;
  3194. saveData.data_points = Math.round((saveData.before_ms - saveData.after_ms) / (saveSnapshotSelectedSecondsPerPoint * 1000));
  3195. saveSnapshotModalLog('info', 'Generating snapshot with ' + saveData.data_points.toString() + ' data points per dimension...');
  3196. var charts_count = 0;
  3197. var charts_ok = 0;
  3198. var charts_failed = 0;
  3199. function saveSnapshotRestore() {
  3200. $('#saveSnapshotModal').modal('hide');
  3201. // restore the options
  3202. var x;
  3203. for (x in backedup_options) {
  3204. if (backedup_options.hasOwnProperty(x)) {
  3205. NETDATA.options.current[x] = backedup_options[x];
  3206. }
  3207. }
  3208. $(el).css('width', '0%').attr('aria-valuenow', 0);
  3209. eltxt.innerText = '0%';
  3210. if (clearPanAndZoom) {
  3211. NETDATA.globalPanAndZoom.clearMaster();
  3212. }
  3213. NETDATA.options.force_data_points = 0;
  3214. NETDATA.options.fake_chart_rendering = false;
  3215. NETDATA.onscroll_updater_enabled = true;
  3216. NETDATA.onresize();
  3217. NETDATA.unpause();
  3218. $('#saveSnapshotExport').removeClass('disabled');
  3219. }
  3220. NETDATA.globalSelectionSync.stop();
  3221. NETDATA.options.force_data_points = saveData.data_points;
  3222. NETDATA.options.fake_chart_rendering = true;
  3223. NETDATA.onscroll_updater_enabled = false;
  3224. NETDATA.abortAllRefreshes();
  3225. var size = 0;
  3226. var info = ' Resolution: <b>' + saveSnapshotSelectedSecondsPerPoint.toString() + ((saveSnapshotSelectedSecondsPerPoint === 1) ? ' second ' : ' seconds ').toString() + 'per point</b>.';
  3227. function update_chart(idx) {
  3228. if (saveSnapshotStop === true) {
  3229. saveSnapshotModalLog('info', 'Cancelled!');
  3230. saveSnapshotRestore();
  3231. return;
  3232. }
  3233. var state = NETDATA.options.targets[--idx];
  3234. var pcent = (NETDATA.options.targets.length - idx) * 100 / NETDATA.options.targets.length;
  3235. $(el).css('width', pcent + '%').attr('aria-valuenow', pcent);
  3236. eltxt.innerText = Math.round(pcent).toString() + '%, ' + state.id;
  3237. setTimeout(function () {
  3238. charts_count++;
  3239. state.isVisible(true);
  3240. state.current.force_after_ms = saveData.after_ms;
  3241. state.current.force_before_ms = saveData.before_ms;
  3242. state.updateChart(function (status, reason) {
  3243. state.current.force_after_ms = null;
  3244. state.current.force_before_ms = null;
  3245. if (status === true) {
  3246. charts_ok++;
  3247. // state.log('ok');
  3248. size += pack_api1_v1_chart_data(state);
  3249. } else {
  3250. charts_failed++;
  3251. state.log('failed to be updated: ' + reason);
  3252. }
  3253. saveSnapshotModalLog((charts_failed) ? 'danger' : 'info', 'Generated snapshot data size <b>' + (Math.round(size * 100 / 1024 / 1024) / 100).toString() + ' MB</b>. ' + ((charts_failed) ? (charts_failed.toString() + ' charts have failed to be downloaded') : '').toString() + info);
  3254. if (idx > 0) {
  3255. update_chart(idx);
  3256. } else {
  3257. saveData.charts_ok = charts_ok;
  3258. saveData.charts_failed = charts_failed;
  3259. saveData.data_size = size;
  3260. // console.log(saveData.compression + ': ' + (size / (options.data.dimensions_count * Math.round(saveSnapshotViewDuration / saveSnapshotSelectedSecondsPerPoint))).toString());
  3261. // save it
  3262. // console.log(saveData);
  3263. saveObjectToClient(saveData, filename);
  3264. if (charts_failed > 0) {
  3265. alert(charts_failed.toString() + ' failed to be downloaded');
  3266. }
  3267. saveSnapshotRestore();
  3268. saveData = null;
  3269. }
  3270. })
  3271. }, 0);
  3272. }
  3273. update_chart(NETDATA.options.targets.length);
  3274. });
  3275. });
  3276. }
  3277. // --------------------------------------------------------------------
  3278. // activate netdata on the page
  3279. function dashboardSettingsSetup() {
  3280. var update_options_modal = function () {
  3281. // console.log('update_options_modal');
  3282. var sync_option = function (option) {
  3283. var self = $('#' + option);
  3284. if (self.prop('checked') !== NETDATA.getOption(option)) {
  3285. // console.log('switching ' + option.toString());
  3286. self.bootstrapToggle(NETDATA.getOption(option) ? 'on' : 'off');
  3287. }
  3288. };
  3289. var theme_sync_option = function (option) {
  3290. var self = $('#' + option);
  3291. self.bootstrapToggle(netdataTheme === 'slate' ? 'on' : 'off');
  3292. };
  3293. var units_sync_option = function (option) {
  3294. var self = $('#' + option);
  3295. if (self.prop('checked') !== (NETDATA.getOption('units') === 'auto')) {
  3296. self.bootstrapToggle(NETDATA.getOption('units') === 'auto' ? 'on' : 'off');
  3297. }
  3298. if (self.prop('checked') === true) {
  3299. $('#settingsLocaleTempRow').show();
  3300. $('#settingsLocaleTimeRow').show();
  3301. } else {
  3302. $('#settingsLocaleTempRow').hide();
  3303. $('#settingsLocaleTimeRow').hide();
  3304. }
  3305. };
  3306. var temp_sync_option = function (option) {
  3307. var self = $('#' + option);
  3308. if (self.prop('checked') !== (NETDATA.getOption('temperature') === 'celsius')) {
  3309. self.bootstrapToggle(NETDATA.getOption('temperature') === 'celsius' ? 'on' : 'off');
  3310. }
  3311. };
  3312. var timezone_sync_option = function (option) {
  3313. var self = $('#' + option);
  3314. document.getElementById('browser_timezone').innerText = NETDATA.options.browser_timezone;
  3315. document.getElementById('server_timezone').innerText = NETDATA.options.server_timezone;
  3316. document.getElementById('current_timezone').innerText = (NETDATA.options.current.timezone === 'default') ? 'unset, using browser default' : NETDATA.options.current.timezone;
  3317. if (self.prop('checked') === NETDATA.dateTime.using_timezone) {
  3318. self.bootstrapToggle(NETDATA.dateTime.using_timezone ? 'off' : 'on');
  3319. }
  3320. };
  3321. sync_option('eliminate_zero_dimensions');
  3322. sync_option('destroy_on_hide');
  3323. sync_option('async_on_scroll');
  3324. sync_option('parallel_refresher');
  3325. sync_option('concurrent_refreshes');
  3326. sync_option('sync_selection');
  3327. sync_option('sync_pan_and_zoom');
  3328. sync_option('stop_updates_when_focus_is_lost');
  3329. sync_option('smooth_plot');
  3330. sync_option('pan_and_zoom_data_padding');
  3331. sync_option('show_help');
  3332. sync_option('seconds_as_time');
  3333. theme_sync_option('netdata_theme_control');
  3334. units_sync_option('units_conversion');
  3335. temp_sync_option('units_temp');
  3336. timezone_sync_option('local_timezone');
  3337. if (NETDATA.getOption('parallel_refresher') === false) {
  3338. $('#concurrent_refreshes_row').hide();
  3339. } else {
  3340. $('#concurrent_refreshes_row').show();
  3341. }
  3342. };
  3343. NETDATA.setOption('setOptionCallback', update_options_modal);
  3344. // handle options changes
  3345. $('#eliminate_zero_dimensions').change(function () {
  3346. NETDATA.setOption('eliminate_zero_dimensions', $(this).prop('checked'));
  3347. });
  3348. $('#destroy_on_hide').change(function () {
  3349. NETDATA.setOption('destroy_on_hide', $(this).prop('checked'));
  3350. });
  3351. $('#async_on_scroll').change(function () {
  3352. NETDATA.setOption('async_on_scroll', $(this).prop('checked'));
  3353. });
  3354. $('#parallel_refresher').change(function () {
  3355. NETDATA.setOption('parallel_refresher', $(this).prop('checked'));
  3356. });
  3357. $('#concurrent_refreshes').change(function () {
  3358. NETDATA.setOption('concurrent_refreshes', $(this).prop('checked'));
  3359. });
  3360. $('#sync_selection').change(function () {
  3361. NETDATA.setOption('sync_selection', $(this).prop('checked'));
  3362. });
  3363. $('#sync_pan_and_zoom').change(function () {
  3364. NETDATA.setOption('sync_pan_and_zoom', $(this).prop('checked'));
  3365. });
  3366. $('#stop_updates_when_focus_is_lost').change(function () {
  3367. urlOptions.update_always = !$(this).prop('checked');
  3368. urlOptions.hashUpdate();
  3369. NETDATA.setOption('stop_updates_when_focus_is_lost', !urlOptions.update_always);
  3370. });
  3371. $('#smooth_plot').change(function () {
  3372. NETDATA.setOption('smooth_plot', $(this).prop('checked'));
  3373. });
  3374. $('#pan_and_zoom_data_padding').change(function () {
  3375. NETDATA.setOption('pan_and_zoom_data_padding', $(this).prop('checked'));
  3376. });
  3377. $('#seconds_as_time').change(function () {
  3378. NETDATA.setOption('seconds_as_time', $(this).prop('checked'));
  3379. });
  3380. $('#local_timezone').change(function () {
  3381. if ($(this).prop('checked')) {
  3382. selected_server_timezone('default', true);
  3383. } else {
  3384. selected_server_timezone('default', false);
  3385. }
  3386. });
  3387. $('#units_conversion').change(function () {
  3388. NETDATA.setOption('units', $(this).prop('checked') ? 'auto' : 'original');
  3389. });
  3390. $('#units_temp').change(function () {
  3391. NETDATA.setOption('temperature', $(this).prop('checked') ? 'celsius' : 'fahrenheit');
  3392. });
  3393. $('#show_help').change(function () {
  3394. urlOptions.help = $(this).prop('checked');
  3395. urlOptions.hashUpdate();
  3396. NETDATA.setOption('show_help', urlOptions.help);
  3397. netdataReload();
  3398. });
  3399. // this has to be the last
  3400. // it reloads the page
  3401. $('#netdata_theme_control').change(function () {
  3402. urlOptions.theme = $(this).prop('checked') ? 'slate' : 'white';
  3403. urlOptions.hashUpdate();
  3404. if (setTheme(urlOptions.theme)) {
  3405. netdataReload();
  3406. }
  3407. });
  3408. }
  3409. function scrollDashboardTo() {
  3410. if (netdataSnapshotData !== null && typeof netdataSnapshotData.hash !== 'undefined') {
  3411. //console.log(netdataSnapshotData.hash);
  3412. scrollToId(netdataSnapshotData.hash.replace('#', ''));
  3413. } else {
  3414. // check if we have to jump to a specific section
  3415. scrollToId(urlOptions.hash.replace('#', ''));
  3416. if (urlOptions.chart !== null) {
  3417. NETDATA.alarms.scrollToChart(urlOptions.chart);
  3418. //urlOptions.hash = '#' + NETDATA.name2id('menu_' + charts[c].menu + '_submenu_' + charts[c].submenu);
  3419. //urlOptions.hash = '#chart_' + NETDATA.name2id(urlOptions.chart);
  3420. //console.log('hash = ' + urlOptions.hash);
  3421. }
  3422. }
  3423. }
  3424. var modalHiddenCallback = null;
  3425. function scrollToChartAfterHidingModal(chart, alarmDate, alarmStatus) {
  3426. modalHiddenCallback = function () {
  3427. NETDATA.alarms.scrollToChart(chart, alarmDate);
  3428. if (['WARNING', 'CRITICAL'].includes(alarmStatus)) {
  3429. const currentChartState = NETDATA.options.targets.find(
  3430. (chartState) => chartState.id === chart,
  3431. )
  3432. const twoMinutes = 2 * 60 * 1000
  3433. NETDATA.globalPanAndZoom.setMaster(
  3434. currentChartState,
  3435. alarmDate - twoMinutes,
  3436. alarmDate + twoMinutes,
  3437. )
  3438. }
  3439. };
  3440. }
  3441. // ----------------------------------------------------------------------------
  3442. function enableTooltipsAndPopovers() {
  3443. $('[data-toggle="tooltip"]').tooltip({
  3444. animated: 'fade',
  3445. trigger: 'hover',
  3446. html: true,
  3447. delay: { show: 500, hide: 0 },
  3448. container: 'body'
  3449. });
  3450. $('[data-toggle="popover"]').popover();
  3451. }
  3452. // ----------------------------------------------------------------------------
  3453. var runOnceOnDashboardLastRun = 0;
  3454. function runOnceOnDashboardWithjQuery() {
  3455. if (runOnceOnDashboardLastRun !== 0) {
  3456. scrollDashboardTo();
  3457. // restore the scrollspy at the proper position
  3458. $(document.body).scrollspy('refresh');
  3459. $(document.body).scrollspy('process');
  3460. return;
  3461. }
  3462. runOnceOnDashboardLastRun = Date.now();
  3463. // ------------------------------------------------------------------------
  3464. // bootstrap modals
  3465. // prevent bootstrap modals from scrolling the page
  3466. // maintains the current scroll position
  3467. // https://stackoverflow.com/a/34754029/4525767
  3468. var scrollPos = 0;
  3469. var modal_depth = 0; // how many modals are currently open
  3470. var modal_shown = false; // set to true, if a modal is shown
  3471. var netdata_paused_on_modal = false; // set to true, if the modal paused netdata
  3472. var scrollspyOffset = $(window).height() / 3; // will be updated below - the offset of scrollspy to select an item
  3473. $('.modal')
  3474. .on('show.bs.modal', function () {
  3475. if (modal_depth === 0) {
  3476. scrollPos = window.scrollY;
  3477. $('body').css({
  3478. overflow: 'hidden',
  3479. position: 'fixed',
  3480. top: -scrollPos
  3481. });
  3482. modal_shown = true;
  3483. if (NETDATA.options.pauseCallback === null) {
  3484. NETDATA.pause(function () {
  3485. });
  3486. netdata_paused_on_modal = true;
  3487. } else {
  3488. netdata_paused_on_modal = false;
  3489. }
  3490. }
  3491. modal_depth++;
  3492. //console.log(urlOptions.after);
  3493. })
  3494. .on('hide.bs.modal', function () {
  3495. modal_depth--;
  3496. if (modal_depth <= 0) {
  3497. modal_depth = 0;
  3498. $('body')
  3499. .css({
  3500. overflow: '',
  3501. position: '',
  3502. top: ''
  3503. });
  3504. // scroll to the position we had open before the modal
  3505. $('html, body')
  3506. .animate({ scrollTop: scrollPos }, 0);
  3507. // unpause netdata, if we paused it
  3508. if (netdata_paused_on_modal === true) {
  3509. NETDATA.unpause();
  3510. netdata_paused_on_modal = false;
  3511. }
  3512. // restore the scrollspy at the proper position
  3513. $(document.body).scrollspy('process');
  3514. }
  3515. //console.log(urlOptions.after);
  3516. })
  3517. .on('hidden.bs.modal', function () {
  3518. if (modal_depth === 0) {
  3519. modal_shown = false;
  3520. }
  3521. if (typeof modalHiddenCallback === 'function') {
  3522. modalHiddenCallback();
  3523. }
  3524. modalHiddenCallback = null;
  3525. //console.log(urlOptions.after);
  3526. });
  3527. // ------------------------------------------------------------------------
  3528. // sidebar / affix
  3529. if (shouldShowSignInBanner()) {
  3530. const el = document.getElementById("sign-in-banner");
  3531. if (el) {
  3532. el.style.display = "initial";
  3533. el.classList.add(`theme-${netdataTheme}`);
  3534. }
  3535. }
  3536. $('#sidebar')
  3537. .affix({
  3538. offset: {
  3539. top: (isdemo()) ? 150 : 0,
  3540. bottom: 0
  3541. }
  3542. })
  3543. .on('affixed.bs.affix', function () {
  3544. // fix scrolling of very long affix lists
  3545. // http://stackoverflow.com/questions/21691585/bootstrap-3-1-0-affix-too-long
  3546. $(this).removeAttr('style');
  3547. })
  3548. .on('affix-top.bs.affix', function () {
  3549. // fix bootstrap affix click bug
  3550. // https://stackoverflow.com/a/37847981/4525767
  3551. if (modal_shown) {
  3552. return false;
  3553. }
  3554. })
  3555. .on('activate.bs.scrollspy', function (e) {
  3556. // change the URL based on the current position of the screen
  3557. if (modal_shown === false) {
  3558. var el = $(e.target);
  3559. var hash = el.find('a').attr('href');
  3560. if (typeof hash === 'string' && hash.substring(0, 1) === '#' && urlOptions.hash.startsWith(hash + '_submenu_') === false) {
  3561. urlOptions.hash = hash;
  3562. urlOptions.hashUpdate();
  3563. }
  3564. }
  3565. });
  3566. Ps.initialize(document.getElementById('sidebar'), {
  3567. wheelSpeed: 0.5,
  3568. wheelPropagation: true,
  3569. swipePropagation: true,
  3570. minScrollbarLength: null,
  3571. maxScrollbarLength: null,
  3572. useBothWheelAxes: false,
  3573. suppressScrollX: true,
  3574. suppressScrollY: false,
  3575. scrollXMarginOffset: 0,
  3576. scrollYMarginOffset: 0,
  3577. theme: 'default'
  3578. });
  3579. // ------------------------------------------------------------------------
  3580. // scrollspy
  3581. if (scrollspyOffset > 250) {
  3582. scrollspyOffset = 250;
  3583. }
  3584. if (scrollspyOffset < 75) {
  3585. scrollspyOffset = 75;
  3586. }
  3587. document.body.setAttribute('data-offset', scrollspyOffset);
  3588. // scroll the dashboard, before activating the scrollspy, so that our
  3589. // hash will not be updated before we got the chance to scroll to it
  3590. scrollDashboardTo();
  3591. $(document.body).scrollspy({
  3592. target: '#sidebar',
  3593. offset: scrollspyOffset // controls the diff of the <hX> element to the top, to select it
  3594. });
  3595. // ------------------------------------------------------------------------
  3596. // my-netdata menu
  3597. Ps.initialize(document.getElementById('my-netdata-dropdown-content'), {
  3598. wheelSpeed: 1,
  3599. wheelPropagation: false,
  3600. swipePropagation: false,
  3601. minScrollbarLength: null,
  3602. maxScrollbarLength: null,
  3603. useBothWheelAxes: false,
  3604. suppressScrollX: true,
  3605. suppressScrollY: false,
  3606. scrollXMarginOffset: 0,
  3607. scrollYMarginOffset: 0,
  3608. theme: 'default'
  3609. });
  3610. $('#myNetdataDropdownParent')
  3611. .on('show.bs.dropdown', function () {
  3612. var hash = urlOptions.genHash();
  3613. $('.registry_link').each(function (idx) {
  3614. this.setAttribute('href', this.getAttribute("href").replace(/#.*$/, hash));
  3615. });
  3616. NETDATA.pause(function () {
  3617. });
  3618. })
  3619. .on('shown.bs.dropdown', function () {
  3620. Ps.update(document.getElementById('my-netdata-dropdown-content'));
  3621. myNetdataMenuDidShow();
  3622. })
  3623. .on('hidden.bs.dropdown', function () {
  3624. NETDATA.unpause();
  3625. });
  3626. $('#deleteRegistryModal')
  3627. .on('hidden.bs.modal', function () {
  3628. deleteRegistryGuid = null;
  3629. });
  3630. // ------------------------------------------------------------------------
  3631. // update modal
  3632. $('#updateModal')
  3633. .on('show.bs.modal', function () {
  3634. versionLog('checking, please wait...');
  3635. })
  3636. .on('shown.bs.modal', function () {
  3637. notifyForUpdate(true);
  3638. });
  3639. // ------------------------------------------------------------------------
  3640. // alarms modal
  3641. $('#alarmsModal')
  3642. .on('shown.bs.modal', function () {
  3643. alarmsUpdateModal();
  3644. })
  3645. .on('hidden.bs.modal', function () {
  3646. document.getElementById('alarms_active').innerHTML =
  3647. document.getElementById('alarms_all').innerHTML =
  3648. document.getElementById('alarms_log').innerHTML =
  3649. 'loading...';
  3650. });
  3651. // ------------------------------------------------------------------------
  3652. dashboardSettingsSetup();
  3653. loadSnapshotDragAndDropSetup();
  3654. saveSnapshotModalSetup();
  3655. showPageFooter();
  3656. // ------------------------------------------------------------------------
  3657. // https://github.com/viralpatel/jquery.shorten/blob/master/src/jquery.shorten.js
  3658. $.fn.shorten = function (settings) {
  3659. "use strict";
  3660. var config = {
  3661. showChars: 750,
  3662. minHideChars: 10,
  3663. ellipsesText: "...",
  3664. moreText: '<i class="fas fa-expand"></i> show more information',
  3665. lessText: '<i class="fas fa-compress"></i> show less information',
  3666. onLess: function () {
  3667. NETDATA.onscroll();
  3668. },
  3669. onMore: function () {
  3670. NETDATA.onscroll();
  3671. },
  3672. errMsg: null,
  3673. force: false
  3674. };
  3675. if (settings) {
  3676. $.extend(config, settings);
  3677. }
  3678. if ($(this).data('jquery.shorten') && !config.force) {
  3679. return false;
  3680. }
  3681. $(this).data('jquery.shorten', true);
  3682. $(document).off("click", '.morelink');
  3683. $(document).on({
  3684. click: function () {
  3685. var $this = $(this);
  3686. if ($this.hasClass('less')) {
  3687. $this.removeClass('less');
  3688. $this.html(config.moreText);
  3689. $this.parent().prev().animate({ 'height': '0' + '%' }, 0, function () {
  3690. $this.parent().prev().prev().show();
  3691. }).hide(0, function () {
  3692. config.onLess();
  3693. });
  3694. } else {
  3695. $this.addClass('less');
  3696. $this.html(config.lessText);
  3697. $this.parent().prev().animate({ 'height': '100' + '%' }, 0, function () {
  3698. $this.parent().prev().prev().hide();
  3699. }).show(0, function () {
  3700. config.onMore();
  3701. });
  3702. }
  3703. return false;
  3704. }
  3705. }, '.morelink');
  3706. return this.each(function () {
  3707. var $this = $(this);
  3708. var content = $this.html();
  3709. var contentlen = $this.text().length;
  3710. if (contentlen > config.showChars + config.minHideChars) {
  3711. var c = content.substr(0, config.showChars);
  3712. if (c.indexOf('<') >= 0) // If there's HTML don't want to cut it
  3713. {
  3714. var inTag = false; // I'm in a tag?
  3715. var bag = ''; // Put the characters to be shown here
  3716. var countChars = 0; // Current bag size
  3717. var openTags = []; // Stack for opened tags, so I can close them later
  3718. var tagName = null;
  3719. for (var i = 0, r = 0; r <= config.showChars; i++) {
  3720. if (content[i] === '<' && !inTag) {
  3721. inTag = true;
  3722. // This could be "tag" or "/tag"
  3723. tagName = content.substring(i + 1, content.indexOf('>', i));
  3724. // If its a closing tag
  3725. if (tagName[0] === '/') {
  3726. if (tagName !== ('/' + openTags[0])) {
  3727. config.errMsg = 'ERROR en HTML: the top of the stack should be the tag that closes';
  3728. } else {
  3729. openTags.shift(); // Pops the last tag from the open tag stack (the tag is closed in the retult HTML!)
  3730. }
  3731. } else {
  3732. // There are some nasty tags that don't have a close tag like <br/>
  3733. if (tagName.toLowerCase() !== 'br') {
  3734. openTags.unshift(tagName); // Add to start the name of the tag that opens
  3735. }
  3736. }
  3737. }
  3738. if (inTag && content[i] === '>') {
  3739. inTag = false;
  3740. }
  3741. if (inTag) {
  3742. bag += content.charAt(i);
  3743. } else {
  3744. // Add tag name chars to the result
  3745. r++;
  3746. if (countChars <= config.showChars) {
  3747. bag += content.charAt(i); // Fix to ie 7 not allowing you to reference string characters using the []
  3748. countChars++;
  3749. } else {
  3750. // Now I have the characters needed
  3751. if (openTags.length > 0) {
  3752. // I have unclosed tags
  3753. //console.log('They were open tags');
  3754. //console.log(openTags);
  3755. for (var j = 0; j < openTags.length; j++) {
  3756. //console.log('Cierro tag ' + openTags[j]);
  3757. bag += '</' + openTags[j] + '>'; // Close all tags that were opened
  3758. // You could shift the tag from the stack to check if you end with an empty stack, that means you have closed all open tags
  3759. }
  3760. break;
  3761. }
  3762. }
  3763. }
  3764. }
  3765. c = $('<div/>').html(bag + '<span class="ellip">' + config.ellipsesText + '</span>').html();
  3766. } else {
  3767. c += config.ellipsesText;
  3768. }
  3769. var html = '<div class="shortcontent">' + c +
  3770. '</div><div class="allcontent">' + content +
  3771. '</div><span><a href="javascript://nop/" class="morelink">' + config.moreText + '</a></span>';
  3772. $this.html(html);
  3773. $this.find(".allcontent").hide(); // Hide all text
  3774. $('.shortcontent p:last', $this).css('margin-bottom', 0); //Remove bottom margin on last paragraph as it's likely shortened
  3775. }
  3776. });
  3777. };
  3778. }
  3779. function finalizePage() {
  3780. // resize all charts - without starting the background thread
  3781. // this has to be done while NETDATA is paused
  3782. // if we omit this, the affix menu will be wrong, since all
  3783. // the Dom elements are initially zero-sized
  3784. NETDATA.parseDom();
  3785. // ------------------------------------------------------------------------
  3786. NETDATA.globalPanAndZoom.callback = null;
  3787. NETDATA.globalChartUnderlay.callback = null;
  3788. if (urlOptions.pan_and_zoom === true && NETDATA.options.targets.length > 0) {
  3789. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], urlOptions.after, urlOptions.before);
  3790. }
  3791. // callback for us to track PanAndZoom operations
  3792. NETDATA.globalPanAndZoom.callback = urlOptions.netdataPanAndZoomCallback;
  3793. NETDATA.globalChartUnderlay.callback = urlOptions.netdataHighlightCallback;
  3794. // ------------------------------------------------------------------------
  3795. // let it run (update the charts)
  3796. NETDATA.unpause();
  3797. runOnceOnDashboardWithjQuery();
  3798. $(".shorten").shorten();
  3799. enableTooltipsAndPopovers();
  3800. if (isdemo()) {
  3801. // do not to give errors on netdata demo servers for 60 seconds
  3802. NETDATA.options.current.retries_on_data_failures = 60;
  3803. // google analytics when this is used for the home page of the demo sites
  3804. // this does not run on user's installations
  3805. setTimeout(function () {
  3806. (function (i, s, o, g, r, a, m) {
  3807. i['GoogleAnalyticsObject'] = r;
  3808. i[r] = i[r] || function () {
  3809. (i[r].q = i[r].q || []).push(arguments)
  3810. }, i[r].l = 1 * new Date();
  3811. a = s.createElement(o),
  3812. m = s.getElementsByTagName(o)[0];
  3813. a.async = 1;
  3814. a.src = g;
  3815. m.parentNode.insertBefore(a, m)
  3816. })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
  3817. ga('create', 'UA-64295674-3', 'auto');
  3818. ga('send', 'pageview', '/demosite/' + window.location.host);
  3819. }, 2000);
  3820. } else {
  3821. notifyForUpdate();
  3822. }
  3823. if (urlOptions.show_alarms === true) {
  3824. setTimeout(function () {
  3825. $('#alarmsModal').modal('show');
  3826. }, 1000);
  3827. }
  3828. NETDATA.onresizeCallback = function () {
  3829. Ps.update(document.getElementById('sidebar'));
  3830. Ps.update(document.getElementById('my-netdata-dropdown-content'));
  3831. };
  3832. NETDATA.onresizeCallback();
  3833. if (netdataSnapshotData !== null) {
  3834. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], netdataSnapshotData.after_ms, netdataSnapshotData.before_ms);
  3835. }
  3836. //if (urlOptions.nowelcome !== true) {
  3837. // setTimeout(function () {
  3838. // $('#welcomeModal').modal();
  3839. // }, 2000);
  3840. //}
  3841. // var netdataEnded = performance.now();
  3842. // console.log('start up time: ' + (netdataEnded - netdataStarted).toString() + ' ms');
  3843. }
  3844. function resetDashboardOptions() {
  3845. var help = NETDATA.options.current.show_help;
  3846. NETDATA.resetOptions();
  3847. if (setTheme('slate')) {
  3848. netdataReload();
  3849. }
  3850. if (help !== NETDATA.options.current.show_help) {
  3851. netdataReload();
  3852. }
  3853. }
  3854. // callback to add the dashboard info to the
  3855. // parallel javascript downloader in netdata
  3856. var netdataPrepCallback = function () {
  3857. NETDATA.requiredCSS.push({
  3858. url: NETDATA.serverStatic + 'css/bootstrap-toggle-2.2.2.min.css',
  3859. isAlreadyLoaded: function () {
  3860. return false;
  3861. }
  3862. });
  3863. NETDATA.requiredJs.push({
  3864. url: NETDATA.serverStatic + 'lib/bootstrap-toggle-2.2.2.min.js',
  3865. isAlreadyLoaded: function () {
  3866. return false;
  3867. }
  3868. });
  3869. NETDATA.requiredJs.push({
  3870. url: NETDATA.serverStatic + 'dashboard_info.js?v20181019-1',
  3871. async: false,
  3872. isAlreadyLoaded: function () {
  3873. return false;
  3874. }
  3875. });
  3876. if (isdemo()) {
  3877. document.getElementById('masthead').style.display = 'block';
  3878. } else {
  3879. if (urlOptions.update_always === true) {
  3880. NETDATA.setOption('stop_updates_when_focus_is_lost', !urlOptions.update_always);
  3881. }
  3882. }
  3883. };
  3884. var selected_server_timezone = function (timezone, status) {
  3885. //console.log('called with timezone: ' + timezone + ", status: " + ((typeof status === 'undefined')?'undefined':status).toString());
  3886. // clear the error
  3887. document.getElementById('timezone_error_message').innerHTML = '';
  3888. if (typeof status === 'undefined') {
  3889. // the user selected a timezone from the menu
  3890. NETDATA.setOption('user_set_server_timezone', timezone);
  3891. if (NETDATA.dateTime.init(timezone) === false) {
  3892. NETDATA.dateTime.init();
  3893. if (!$('#local_timezone').prop('checked')) {
  3894. $('#local_timezone').bootstrapToggle('on');
  3895. }
  3896. document.getElementById('timezone_error_message').innerHTML = 'Ooops! That timezone was not accepted by your browser. Please open a github issue to help us fix it.';
  3897. NETDATA.setOption('user_set_server_timezone', NETDATA.options.server_timezone);
  3898. } else {
  3899. if ($('#local_timezone').prop('checked')) {
  3900. $('#local_timezone').bootstrapToggle('off');
  3901. }
  3902. }
  3903. } else if (status === true) {
  3904. // the user wants the browser default timezone to be activated
  3905. NETDATA.dateTime.init();
  3906. } else {
  3907. // the user wants the server default timezone to be activated
  3908. //console.log('found ' + NETDATA.options.current.user_set_server_timezone);
  3909. if (NETDATA.options.current.user_set_server_timezone === 'default') {
  3910. NETDATA.options.current.user_set_server_timezone = NETDATA.options.server_timezone;
  3911. }
  3912. timezone = NETDATA.options.current.user_set_server_timezone;
  3913. if (NETDATA.dateTime.init(timezone) === false) {
  3914. NETDATA.dateTime.init();
  3915. if (!$('#local_timezone').prop('checked')) {
  3916. $('#local_timezone').bootstrapToggle('on');
  3917. }
  3918. document.getElementById('timezone_error_message').innerHTML = 'Sorry. The timezone "' + timezone.toString() + '" is not accepted by your browser. Please select one from the list.';
  3919. NETDATA.setOption('user_set_server_timezone', NETDATA.options.server_timezone);
  3920. }
  3921. }
  3922. document.getElementById('current_timezone').innerText = (NETDATA.options.current.timezone === 'default') ? 'unset, using browser default' : NETDATA.options.current.timezone;
  3923. return false;
  3924. };
  3925. // our entry point
  3926. // var netdataStarted = performance.now();
  3927. var netdataCallback = initializeDynamicDashboard;
  3928. // =================================================================================================
  3929. // netdata.cloud
  3930. let registryAgents = [];
  3931. let cloudAgents = [];
  3932. let myNetdataMenuFilterValue = "";
  3933. let cloudAccountID = null;
  3934. let cloudAccountName = null;
  3935. let cloudToken = null;
  3936. /// Enforces a maximum string length while retaining the prefix and the postfix of
  3937. /// the string.
  3938. function truncateString(str, maxLength) {
  3939. if (str.length <= maxLength) {
  3940. return str;
  3941. }
  3942. const spanLength = Math.floor((maxLength - 3) / 2);
  3943. return `${str.substring(0, spanLength)}...${str.substring(str.length - spanLength)}`;
  3944. }
  3945. // -------------------------------------------------------------------------------------------------
  3946. // netdata.cloud API Client
  3947. // -------------------------------------------------------------------------------------------------
  3948. function isValidAgent(a) {
  3949. return a.urls != null && a.urls.length > 0;
  3950. }
  3951. // https://github.com/netdata/hub/issues/146
  3952. function getCloudAccountAgents() {
  3953. if (!isSignedIn()) {
  3954. return [];
  3955. }
  3956. return fetch(
  3957. `${NETDATA.registry.cloudBaseURL}/api/v1/accounts/${cloudAccountID}/agents`,
  3958. {
  3959. method: "GET",
  3960. mode: "cors",
  3961. headers: {
  3962. "Authorization": `Bearer ${cloudToken}`
  3963. }
  3964. }
  3965. ).then((response) => {
  3966. if (!response.ok) {
  3967. throw Error("Cannot fetch known accounts");
  3968. }
  3969. return response.json();
  3970. }).then((payload) => {
  3971. const agents = payload.result ? payload.result.agents : null;
  3972. if (!agents) {
  3973. return [];
  3974. }
  3975. return agents.filter((a) => isValidAgent(a)).map((a) => {
  3976. return {
  3977. "guid": a.id,
  3978. "name": a.name,
  3979. "url": a.urls[0],
  3980. "alternate_urls": a.urls
  3981. }
  3982. })
  3983. }).catch(function (error) {
  3984. console.log(error);
  3985. return null;
  3986. });
  3987. }
  3988. /** Updates the lastAccessTime and accessCount properties of the agent for the account. */
  3989. function touchAgent() {
  3990. if (!isSignedIn()) {
  3991. return [];
  3992. }
  3993. const touchUrl = `${NETDATA.registry.cloudBaseURL}/api/v1/agents/${NETDATA.registry.machine_guid}/touch?account_id=${cloudAccountID}`;
  3994. return fetch(
  3995. touchUrl,
  3996. {
  3997. method: "post",
  3998. body: "",
  3999. mode: "cors",
  4000. headers: {
  4001. "Authorization": `Bearer ${cloudToken}`
  4002. }
  4003. }
  4004. ).then((response) => {
  4005. if (!response.ok) {
  4006. throw Error("Cannot touch agent" + JSON.stringify(response));
  4007. }
  4008. return response.json();
  4009. }).then((payload) => {
  4010. }).catch(function (error) {
  4011. console.log(error);
  4012. return null;
  4013. });
  4014. }
  4015. // https://github.com/netdata/hub/issues/128
  4016. function postCloudAccountAgents(agentsToSync) {
  4017. if (!isSignedIn()) {
  4018. return [];
  4019. }
  4020. const maskedURL = NETDATA.registry.MASKED_DATA;
  4021. const agents = agentsToSync.map((a) => {
  4022. const urls = a.alternate_urls.filter((url) => url != maskedURL);
  4023. return {
  4024. "id": a.guid,
  4025. "name": a.name,
  4026. "urls": urls
  4027. }
  4028. }).filter((a) => isValidAgent(a))
  4029. const payload = {
  4030. "accountID": cloudAccountID,
  4031. "agents": agents,
  4032. "merge": false,
  4033. };
  4034. return fetch(
  4035. `${NETDATA.registry.cloudBaseURL}/api/v1/accounts/${cloudAccountID}/agents`,
  4036. {
  4037. method: "POST",
  4038. mode: "cors",
  4039. headers: {
  4040. "Content-Type": "application/json; charset=utf-8",
  4041. "Authorization": `Bearer ${cloudToken}`
  4042. },
  4043. body: JSON.stringify(payload)
  4044. }
  4045. ).then((response) => {
  4046. return response.json();
  4047. }).then((payload) => {
  4048. const agents = payload.result ? payload.result.agents : null;
  4049. if (!agents) {
  4050. return [];
  4051. }
  4052. return agents.filter((a) => isValidAgent(a)).map((a) => {
  4053. return {
  4054. "guid": a.id,
  4055. "name": a.name,
  4056. "url": a.urls[0],
  4057. "alternate_urls": a.urls
  4058. }
  4059. })
  4060. });
  4061. }
  4062. function deleteCloudAgentURL(agentID, url) {
  4063. if (!isSignedIn()) {
  4064. return [];
  4065. }
  4066. return fetch(
  4067. `${NETDATA.registry.cloudBaseURL}/api/v1/accounts/${cloudAccountID}/agents/${agentID}/url?value=${encodeURIComponent(url)}`,
  4068. {
  4069. method: "DELETE",
  4070. mode: "cors",
  4071. headers: {
  4072. "Content-Type": "application/json; charset=utf-8",
  4073. "Authorization": `Bearer ${cloudToken}`
  4074. },
  4075. }
  4076. ).then((response) => {
  4077. return response.json();
  4078. }).then((payload) => {
  4079. const count = payload.result ? payload.result.count : 0;
  4080. return count;
  4081. });
  4082. }
  4083. // -------------------------------------------------------------------------------------------------
  4084. function signInDidClick(e) {
  4085. e.preventDefault();
  4086. e.stopPropagation();
  4087. if (!NETDATA.registry.isUsingGlobalRegistry()) {
  4088. // If user is using a private registry, request his consent for
  4089. // synchronizing with cloud.
  4090. showSignInModal();
  4091. return;
  4092. }
  4093. signIn();
  4094. }
  4095. function shouldShowSignInBanner() {
  4096. return false;
  4097. }
  4098. function closeSignInBanner() {
  4099. localStorage.setItem("signInBannerClosed", "true");
  4100. const el = document.getElementById("sign-in-banner");
  4101. if (el) {
  4102. el.style.display = "none";
  4103. }
  4104. }
  4105. function closeSignInBannerDidClick(e) {
  4106. closeSignInBanner();
  4107. }
  4108. function signOutDidClick(e) {
  4109. e.preventDefault();
  4110. e.stopPropagation();
  4111. signOut();
  4112. }
  4113. // -------------------------------------------------------------------------------------------------
  4114. function updateMyNetdataAfterFilterChange() {
  4115. const machinesEl = document.getElementById("my-netdata-menu-machines")
  4116. machinesEl.innerHTML = renderMachines(cloudAgents);
  4117. if (options.hosts.length > 1) {
  4118. const streamedEl = document.getElementById("my-netdata-menu-streamed")
  4119. streamedEl.innerHTML = renderStreamedHosts(options);
  4120. }
  4121. }
  4122. function myNetdataMenuDidShow() {
  4123. const filterEl = document.getElementById("my-netdata-menu-filter-input");
  4124. if (filterEl) {
  4125. filterEl.focus();
  4126. }
  4127. }
  4128. function myNetdataFilterDidChange(e) {
  4129. const inputEl = e.target;
  4130. setTimeout(() => {
  4131. myNetdataMenuFilterValue = inputEl.value;
  4132. updateMyNetdataAfterFilterChange();
  4133. }, 1);
  4134. }
  4135. function myNetdataFilterClearDidClick(e) {
  4136. e.preventDefault();
  4137. e.stopPropagation();
  4138. const inputEl = document.getElementById("my-netdata-menu-filter-input");
  4139. inputEl.value = "";
  4140. myNetdataMenuFilterValue = "";
  4141. updateMyNetdataAfterFilterChange();
  4142. inputEl.focus();
  4143. }
  4144. // -------------------------------------------------------------------------------------------------
  4145. function clearCloudVariables() {
  4146. cloudAccountID = null;
  4147. cloudAccountName = null;
  4148. cloudToken = null;
  4149. }
  4150. function clearCloudLocalStorageItems() {
  4151. localStorage.removeItem("cloud.baseURL");
  4152. localStorage.removeItem("cloud.agentID");
  4153. localStorage.removeItem("cloud.sync");
  4154. }
  4155. function signIn() {
  4156. const url = `${NETDATA.registry.cloudBaseURL}/account/sign-in-agent?id=${NETDATA.registry.machine_guid}&name=${encodeURIComponent(NETDATA.registry.hostname)}&origin=${encodeURIComponent(window.location.origin + "/")}`;
  4157. window.open(url);
  4158. }
  4159. function signOut() {
  4160. cloudSSOSignOut();
  4161. }
  4162. function handleMessage(e) {
  4163. switch (e.data.type) {
  4164. case "sign-in":
  4165. handleSignInMessage(e);
  4166. break;
  4167. case "sign-out":
  4168. handleSignOutMessage(e);
  4169. break;
  4170. default:
  4171. return;
  4172. }
  4173. }
  4174. function handleSignInMessage(e) {
  4175. closeSignInBanner();
  4176. localStorage.setItem("cloud.baseURL", NETDATA.registry.cloudBaseURL);
  4177. cloudAccountID = e.data.accountID;
  4178. cloudAccountName = e.data.accountName;
  4179. cloudToken = e.data.token;
  4180. netdataRegistryCallback(registryAgents);
  4181. if (e.data.redirectURI && !window.location.href.includes(e.data.redirectURI)) {
  4182. // lgtm false-positive - redirectURI does not come from user input, but from iframe callback
  4183. window.location.replace(e.data.redirectURI); // lgtm[js/client-side-unvalidated-url-redirection]
  4184. }
  4185. }
  4186. function handleSignOutMessage(e) {
  4187. clearCloudVariables();
  4188. renderMyNetdataMenu(registryAgents);
  4189. }
  4190. function isSignedIn() {
  4191. return cloudToken != null && cloudAccountID != null;
  4192. }
  4193. function sortedArraysEqual(a, b) {
  4194. if (a.length != b.length) return false;
  4195. for (var i = 0; i < a.length; ++i) {
  4196. if (a[i] !== b[i]) return false;
  4197. }
  4198. return true;
  4199. }
  4200. // If merging is needed returns the merged agents set, otherwise returns null.
  4201. function mergeAgents(cloud, local) {
  4202. let dirty = false;
  4203. const union = new Map();
  4204. for (const cagent of cloud) {
  4205. union.set(cagent.guid, cagent);
  4206. }
  4207. for (const lagent of local) {
  4208. const cagent = union.get(lagent.guid);
  4209. if (cagent) {
  4210. for (const u of lagent.alternate_urls) {
  4211. if (u === NETDATA.registry.MASKED_DATA) { // TODO: temp until registry is updated.
  4212. continue;
  4213. }
  4214. if (!cagent.alternate_urls.includes(u)) {
  4215. dirty = true;
  4216. cagent.alternate_urls.push(u);
  4217. }
  4218. }
  4219. } else {
  4220. dirty = true;
  4221. union.set(lagent.guid, lagent);
  4222. }
  4223. }
  4224. if (dirty) {
  4225. return Array.from(union.values());
  4226. }
  4227. return null;
  4228. }
  4229. function showSignInModal() {
  4230. document.getElementById("sim-registry").innerHTML = NETDATA.registry.server;
  4231. $("#signInModal").modal("show");
  4232. }
  4233. function explicitlySignIn() {
  4234. $("#signInModal").modal("hide");
  4235. signIn();
  4236. }
  4237. function showSyncModal() {
  4238. document.getElementById("sync-registry-modal-registry").innerHTML = NETDATA.registry.server;
  4239. $("#syncRegistryModal").modal("show");
  4240. }
  4241. function explicitlySyncAgents() {
  4242. $("#syncRegistryModal").modal("hide");
  4243. const json = localStorage.getItem("cloud.sync");
  4244. const sync = json ? JSON.parse(json) : {};
  4245. delete sync[cloudAccountID];
  4246. localStorage.setItem("cloud.sync", JSON.stringify(sync));
  4247. NETDATA.registry.init();
  4248. }
  4249. function syncAgents(callback) {
  4250. const json = localStorage.getItem("cloud.sync");
  4251. const sync = json ? JSON.parse(json) : {};
  4252. const currentAgent = {
  4253. guid: NETDATA.registry.machine_guid,
  4254. name: NETDATA.registry.hostname,
  4255. url: NETDATA.serverDefault,
  4256. alternate_urls: [NETDATA.serverDefault],
  4257. }
  4258. const localAgents = sync[cloudAccountID]
  4259. ? [currentAgent]
  4260. : registryAgents.concat([currentAgent]);
  4261. console.log("Checking if sync is needed.", localAgents);
  4262. const agentsToSync = mergeAgents(cloudAgents, localAgents);
  4263. if ((!sync[cloudAccountID]) || agentsToSync) {
  4264. sync[cloudAccountID] = new Date().getTime();
  4265. localStorage.setItem("cloud.sync", JSON.stringify(sync));
  4266. }
  4267. if (agentsToSync) {
  4268. console.log("Synchronizing with netdata.cloud.");
  4269. postCloudAccountAgents(agentsToSync).then((agents) => {
  4270. // TODO: clear syncTime on error!
  4271. cloudAgents = agents;
  4272. callback(cloudAgents);
  4273. });
  4274. return
  4275. }
  4276. callback(cloudAgents);
  4277. }
  4278. let isCloudSSOInitialized = false;
  4279. function cloudSSOInit() {
  4280. const iframeEl = document.getElementById("ssoifrm");
  4281. const url = `${NETDATA.registry.cloudBaseURL}/account/sso-agent?id=${NETDATA.registry.machine_guid}`;
  4282. iframeEl.src = url;
  4283. isCloudSSOInitialized = true;
  4284. }
  4285. function cloudSSOSignOut() {
  4286. const iframe = document.getElementById("ssoifrm");
  4287. const url = `${NETDATA.registry.cloudBaseURL}/account/sign-out-agent`;
  4288. iframe.src = url;
  4289. }
  4290. function initCloud() {
  4291. if (!NETDATA.registry.isCloudEnabled) {
  4292. clearCloudVariables();
  4293. clearCloudLocalStorageItems();
  4294. return;
  4295. }
  4296. if (NETDATA.registry.cloudBaseURL != localStorage.getItem("cloud.baseURL")) {
  4297. clearCloudVariables();
  4298. clearCloudLocalStorageItems();
  4299. if (NETDATA.registry.cloudBaseURL) {
  4300. localStorage.setItem("cloud.baseURL", NETDATA.registry.cloudBaseURL);
  4301. }
  4302. }
  4303. if (!isCloudSSOInitialized) {
  4304. cloudSSOInit();
  4305. }
  4306. touchAgent();
  4307. }
  4308. // This callback is called after NETDATA.registry is initialized.
  4309. function netdataRegistryCallback(machinesArray) {
  4310. localStorage.setItem("cloud.agentID", NETDATA.registry.machine_guid);
  4311. initCloud();
  4312. registryAgents = machinesArray;
  4313. if (isSignedIn()) {
  4314. // We call getCloudAccountAgents() here because it requires that
  4315. // NETDATA.registry is initialized.
  4316. clearMyNetdataMenu();
  4317. getCloudAccountAgents().then((agents) => {
  4318. if (!agents) {
  4319. errorMyNetdataMenu();
  4320. return;
  4321. }
  4322. cloudAgents = agents;
  4323. syncAgents((agents) => {
  4324. const agentsMap = {}
  4325. for (const agent of agents) {
  4326. agentsMap[agent.guid] = agent;
  4327. }
  4328. NETDATA.registry.machines = agentsMap;
  4329. NETDATA.registry.machines_array = agents;
  4330. renderMyNetdataMenu(agents);
  4331. });
  4332. });
  4333. } else {
  4334. renderMyNetdataMenu(machinesArray)
  4335. }
  4336. };
  4337. // If we know the cloudBaseURL and agentID from local storage render (eagerly)
  4338. // the account ui before receiving the definitive response from the web server.
  4339. // This improves the perceived performance.
  4340. function tryFastInitCloud() {
  4341. const baseURL = localStorage.getItem("cloud.baseURL");
  4342. const agentID = localStorage.getItem("cloud.agentID");
  4343. if (baseURL && agentID) {
  4344. NETDATA.registry.cloudBaseURL = baseURL;
  4345. NETDATA.registry.machine_guid = agentID;
  4346. NETDATA.registry.isCloudEnabled = true;
  4347. initCloud();
  4348. }
  4349. }
  4350. function initializeApp() {
  4351. window.addEventListener("message", handleMessage, false);
  4352. // tryFastInitCloud();
  4353. }
  4354. if (document.readyState === "complete") {
  4355. initializeApp();
  4356. } else {
  4357. document.addEventListener("readystatechange", () => {
  4358. if (document.readyState === "complete") {
  4359. initializeApp();
  4360. }
  4361. });
  4362. }