main.js 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161
  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. window.location.replace(e.data.redirectURI);
  4183. }
  4184. }
  4185. function handleSignOutMessage(e) {
  4186. clearCloudVariables();
  4187. renderMyNetdataMenu(registryAgents);
  4188. }
  4189. function isSignedIn() {
  4190. return cloudToken != null && cloudAccountID != null;
  4191. }
  4192. function sortedArraysEqual(a, b) {
  4193. if (a.length != b.length) return false;
  4194. for (var i = 0; i < a.length; ++i) {
  4195. if (a[i] !== b[i]) return false;
  4196. }
  4197. return true;
  4198. }
  4199. // If merging is needed returns the merged agents set, otherwise returns null.
  4200. function mergeAgents(cloud, local) {
  4201. let dirty = false;
  4202. const union = new Map();
  4203. for (const cagent of cloud) {
  4204. union.set(cagent.guid, cagent);
  4205. }
  4206. for (const lagent of local) {
  4207. const cagent = union.get(lagent.guid);
  4208. if (cagent) {
  4209. for (const u of lagent.alternate_urls) {
  4210. if (u === NETDATA.registry.MASKED_DATA) { // TODO: temp until registry is updated.
  4211. continue;
  4212. }
  4213. if (!cagent.alternate_urls.includes(u)) {
  4214. dirty = true;
  4215. cagent.alternate_urls.push(u);
  4216. }
  4217. }
  4218. } else {
  4219. dirty = true;
  4220. union.set(lagent.guid, lagent);
  4221. }
  4222. }
  4223. if (dirty) {
  4224. return Array.from(union.values());
  4225. }
  4226. return null;
  4227. }
  4228. function showSignInModal() {
  4229. document.getElementById("sim-registry").innerHTML = NETDATA.registry.server;
  4230. $("#signInModal").modal("show");
  4231. }
  4232. function explicitlySignIn() {
  4233. $("#signInModal").modal("hide");
  4234. signIn();
  4235. }
  4236. function showSyncModal() {
  4237. document.getElementById("sync-registry-modal-registry").innerHTML = NETDATA.registry.server;
  4238. $("#syncRegistryModal").modal("show");
  4239. }
  4240. function explicitlySyncAgents() {
  4241. $("#syncRegistryModal").modal("hide");
  4242. const json = localStorage.getItem("cloud.sync");
  4243. const sync = json ? JSON.parse(json) : {};
  4244. delete sync[cloudAccountID];
  4245. localStorage.setItem("cloud.sync", JSON.stringify(sync));
  4246. NETDATA.registry.init();
  4247. }
  4248. function syncAgents(callback) {
  4249. const json = localStorage.getItem("cloud.sync");
  4250. const sync = json ? JSON.parse(json) : {};
  4251. const currentAgent = {
  4252. guid: NETDATA.registry.machine_guid,
  4253. name: NETDATA.registry.hostname,
  4254. url: NETDATA.serverDefault,
  4255. alternate_urls: [NETDATA.serverDefault],
  4256. }
  4257. const localAgents = sync[cloudAccountID]
  4258. ? [currentAgent]
  4259. : registryAgents.concat([currentAgent]);
  4260. console.log("Checking if sync is needed.", localAgents);
  4261. const agentsToSync = mergeAgents(cloudAgents, localAgents);
  4262. if ((!sync[cloudAccountID]) || agentsToSync) {
  4263. sync[cloudAccountID] = new Date().getTime();
  4264. localStorage.setItem("cloud.sync", JSON.stringify(sync));
  4265. }
  4266. if (agentsToSync) {
  4267. console.log("Synchronizing with netdata.cloud.");
  4268. postCloudAccountAgents(agentsToSync).then((agents) => {
  4269. // TODO: clear syncTime on error!
  4270. cloudAgents = agents;
  4271. callback(cloudAgents);
  4272. });
  4273. return
  4274. }
  4275. callback(cloudAgents);
  4276. }
  4277. let isCloudSSOInitialized = false;
  4278. function cloudSSOInit() {
  4279. const iframeEl = document.getElementById("ssoifrm");
  4280. const url = `${NETDATA.registry.cloudBaseURL}/account/sso-agent?id=${NETDATA.registry.machine_guid}`;
  4281. iframeEl.src = url;
  4282. isCloudSSOInitialized = true;
  4283. }
  4284. function cloudSSOSignOut() {
  4285. const iframe = document.getElementById("ssoifrm");
  4286. const url = `${NETDATA.registry.cloudBaseURL}/account/sign-out-agent`;
  4287. iframe.src = url;
  4288. }
  4289. function initCloud() {
  4290. if (!NETDATA.registry.isCloudEnabled) {
  4291. clearCloudVariables();
  4292. clearCloudLocalStorageItems();
  4293. return;
  4294. }
  4295. if (NETDATA.registry.cloudBaseURL != localStorage.getItem("cloud.baseURL")) {
  4296. clearCloudVariables();
  4297. clearCloudLocalStorageItems();
  4298. if (NETDATA.registry.cloudBaseURL) {
  4299. localStorage.setItem("cloud.baseURL", NETDATA.registry.cloudBaseURL);
  4300. }
  4301. }
  4302. if (!isCloudSSOInitialized) {
  4303. cloudSSOInit();
  4304. }
  4305. touchAgent();
  4306. }
  4307. // This callback is called after NETDATA.registry is initialized.
  4308. function netdataRegistryCallback(machinesArray) {
  4309. localStorage.setItem("cloud.agentID", NETDATA.registry.machine_guid);
  4310. initCloud();
  4311. registryAgents = machinesArray;
  4312. if (isSignedIn()) {
  4313. // We call getCloudAccountAgents() here because it requires that
  4314. // NETDATA.registry is initialized.
  4315. clearMyNetdataMenu();
  4316. getCloudAccountAgents().then((agents) => {
  4317. if (!agents) {
  4318. errorMyNetdataMenu();
  4319. return;
  4320. }
  4321. cloudAgents = agents;
  4322. syncAgents((agents) => {
  4323. const agentsMap = {}
  4324. for (const agent of agents) {
  4325. agentsMap[agent.guid] = agent;
  4326. }
  4327. NETDATA.registry.machines = agentsMap;
  4328. NETDATA.registry.machines_array = agents;
  4329. renderMyNetdataMenu(agents);
  4330. });
  4331. });
  4332. } else {
  4333. renderMyNetdataMenu(machinesArray)
  4334. }
  4335. };
  4336. // If we know the cloudBaseURL and agentID from local storage render (eagerly)
  4337. // the account ui before receiving the definitive response from the web server.
  4338. // This improves the perceived performance.
  4339. function tryFastInitCloud() {
  4340. const baseURL = localStorage.getItem("cloud.baseURL");
  4341. const agentID = localStorage.getItem("cloud.agentID");
  4342. if (baseURL && agentID) {
  4343. NETDATA.registry.cloudBaseURL = baseURL;
  4344. NETDATA.registry.machine_guid = agentID;
  4345. NETDATA.registry.isCloudEnabled = true;
  4346. initCloud();
  4347. }
  4348. }
  4349. function initializeApp() {
  4350. window.addEventListener("message", handleMessage, false);
  4351. // tryFastInitCloud();
  4352. }
  4353. if (document.readyState === "complete") {
  4354. initializeApp();
  4355. } else {
  4356. document.addEventListener("readystatechange", () => {
  4357. if (document.readyState === "complete") {
  4358. initializeApp();
  4359. }
  4360. });
  4361. }