main.js 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155
  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. case 'statsd':
  1146. chart.menu = tmp;
  1147. break;
  1148. case 'apache':
  1149. chart.menu = chart.type;
  1150. if (parts.length > 2 && parts[1] === 'cache') {
  1151. chart.menu_pattern = tmp + '_' + parts[1];
  1152. } else if (parts.length > 1) {
  1153. chart.menu_pattern = tmp;
  1154. }
  1155. break;
  1156. case 'bind':
  1157. chart.menu = chart.type;
  1158. if (parts.length > 2 && parts[1] === 'rndc') {
  1159. chart.menu_pattern = tmp + '_' + parts[1];
  1160. } else if (parts.length > 1) {
  1161. chart.menu_pattern = tmp;
  1162. }
  1163. break;
  1164. case 'cgroup':
  1165. chart.menu = chart.type;
  1166. if (chart.id.match(/.*[\._\/-:]qemu[\._\/-:]*/) || chart.id.match(/.*[\._\/-:]kvm[\._\/-:]*/)) {
  1167. chart.menu_pattern = 'cgqemu';
  1168. } else {
  1169. chart.menu_pattern = 'cgroup';
  1170. }
  1171. break;
  1172. case 'go':
  1173. chart.menu = chart.type;
  1174. if (parts.length > 2 && parts[1] === 'expvar') {
  1175. chart.menu_pattern = tmp + '_' + parts[1];
  1176. } else if (parts.length > 1) {
  1177. chart.menu_pattern = tmp;
  1178. }
  1179. break;
  1180. case 'isc':
  1181. chart.menu = chart.type;
  1182. if (parts.length > 2 && parts[1] === 'dhcpd') {
  1183. chart.menu_pattern = tmp + '_' + parts[1];
  1184. } else if (parts.length > 1) {
  1185. chart.menu_pattern = tmp;
  1186. }
  1187. break;
  1188. case 'ovpn':
  1189. chart.menu = chart.type;
  1190. if (parts.length > 3 && parts[1] === 'status' && parts[2] === 'log') {
  1191. chart.menu_pattern = tmp + '_' + parts[1];
  1192. } else if (parts.length > 1) {
  1193. chart.menu_pattern = tmp;
  1194. }
  1195. break;
  1196. case 'smartd':
  1197. case 'web':
  1198. chart.menu = chart.type;
  1199. if (parts.length > 2 && parts[1] === 'log') {
  1200. chart.menu_pattern = tmp + '_' + parts[1];
  1201. } else if (parts.length > 1) {
  1202. chart.menu_pattern = tmp;
  1203. }
  1204. break;
  1205. case 'tc':
  1206. chart.menu = tmp;
  1207. // find a name for this device from fireqos info
  1208. // we strip '_(in|out)' or '(in|out)_'
  1209. if (chart.context === 'tc.qos' && (typeof options.submenu_names[chart.family] === 'undefined' || options.submenu_names[chart.family] === chart.family)) {
  1210. var n = chart.name.split('.')[1];
  1211. if (n.endsWith('_in')) {
  1212. options.submenu_names[chart.family] = n.slice(0, n.lastIndexOf('_in'));
  1213. } else if (n.endsWith('_out')) {
  1214. options.submenu_names[chart.family] = n.slice(0, n.lastIndexOf('_out'));
  1215. } else if (n.startsWith('in_')) {
  1216. options.submenu_names[chart.family] = n.slice(3, n.length);
  1217. } else if (n.startsWith('out_')) {
  1218. options.submenu_names[chart.family] = n.slice(4, n.length);
  1219. } else {
  1220. options.submenu_names[chart.family] = n;
  1221. }
  1222. }
  1223. // increase the priority of IFB devices
  1224. // to have inbound appear before outbound
  1225. if (chart.id.match(/.*-ifb$/)) {
  1226. chart.priority--;
  1227. }
  1228. break;
  1229. default:
  1230. chart.menu = chart.type;
  1231. if (parts.length > 1) {
  1232. chart.menu_pattern = tmp;
  1233. }
  1234. break;
  1235. }
  1236. chart.submenu = chart.family;
  1237. }
  1238. // ----------------------------------------------------------------------------
  1239. function headMain(os, charts, duration) {
  1240. void (os);
  1241. if (urlOptions.mode === 'print') {
  1242. return '';
  1243. }
  1244. var head = '';
  1245. if (typeof charts['system.swap'] !== 'undefined') {
  1246. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.swap"'
  1247. + ' data-dimensions="used"'
  1248. + ' data-append-options="percentage"'
  1249. + ' data-chart-library="easypiechart"'
  1250. + ' data-title="Used Swap"'
  1251. + ' data-units="%"'
  1252. + ' data-easypiechart-max-value="100"'
  1253. + ' data-width="9%"'
  1254. + ' data-before="0"'
  1255. + ' data-after="-' + duration.toString() + '"'
  1256. + ' data-points="' + duration.toString() + '"'
  1257. + ' data-colors="#DD4400"'
  1258. + ' role="application"></div>';
  1259. }
  1260. if (typeof charts['system.io'] !== 'undefined') {
  1261. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.io"'
  1262. + ' data-dimensions="in"'
  1263. + ' data-chart-library="easypiechart"'
  1264. + ' data-title="Disk Read"'
  1265. + ' data-width="11%"'
  1266. + ' data-before="0"'
  1267. + ' data-after="-' + duration.toString() + '"'
  1268. + ' data-points="' + duration.toString() + '"'
  1269. + ' data-common-units="system.io.mainhead"'
  1270. + ' role="application"></div>';
  1271. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.io"'
  1272. + ' data-dimensions="out"'
  1273. + ' data-chart-library="easypiechart"'
  1274. + ' data-title="Disk Write"'
  1275. + ' data-width="11%"'
  1276. + ' data-before="0"'
  1277. + ' data-after="-' + duration.toString() + '"'
  1278. + ' data-points="' + duration.toString() + '"'
  1279. + ' data-common-units="system.io.mainhead"'
  1280. + ' role="application"></div>';
  1281. }
  1282. else if (typeof charts['system.pgpgio'] !== 'undefined') {
  1283. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.pgpgio"'
  1284. + ' data-dimensions="in"'
  1285. + ' data-chart-library="easypiechart"'
  1286. + ' data-title="Disk Read"'
  1287. + ' data-width="11%"'
  1288. + ' data-before="0"'
  1289. + ' data-after="-' + duration.toString() + '"'
  1290. + ' data-points="' + duration.toString() + '"'
  1291. + ' data-common-units="system.pgpgio.mainhead"'
  1292. + ' role="application"></div>';
  1293. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.pgpgio"'
  1294. + ' data-dimensions="out"'
  1295. + ' data-chart-library="easypiechart"'
  1296. + ' data-title="Disk Write"'
  1297. + ' data-width="11%"'
  1298. + ' data-before="0"'
  1299. + ' data-after="-' + duration.toString() + '"'
  1300. + ' data-points="' + duration.toString() + '"'
  1301. + ' data-common-units="system.pgpgio.mainhead"'
  1302. + ' role="application"></div>';
  1303. }
  1304. if (typeof charts['system.cpu'] !== 'undefined') {
  1305. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.cpu"'
  1306. + ' data-chart-library="gauge"'
  1307. + ' data-title="CPU"'
  1308. + ' data-units="%"'
  1309. + ' data-gauge-max-value="100"'
  1310. + ' data-width="20%"'
  1311. + ' data-after="-' + duration.toString() + '"'
  1312. + ' data-points="' + duration.toString() + '"'
  1313. + ' data-colors="' + NETDATA.colors[12] + '"'
  1314. + ' role="application"></div>';
  1315. }
  1316. if (typeof charts['system.net'] !== 'undefined') {
  1317. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.net"'
  1318. + ' data-dimensions="received"'
  1319. + ' data-chart-library="easypiechart"'
  1320. + ' data-title="Net Inbound"'
  1321. + ' data-width="11%"'
  1322. + ' data-before="0"'
  1323. + ' data-after="-' + duration.toString() + '"'
  1324. + ' data-points="' + duration.toString() + '"'
  1325. + ' data-common-units="system.net.mainhead"'
  1326. + ' role="application"></div>';
  1327. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.net"'
  1328. + ' data-dimensions="sent"'
  1329. + ' data-chart-library="easypiechart"'
  1330. + ' data-title="Net Outbound"'
  1331. + ' data-width="11%"'
  1332. + ' data-before="0"'
  1333. + ' data-after="-' + duration.toString() + '"'
  1334. + ' data-points="' + duration.toString() + '"'
  1335. + ' data-common-units="system.net.mainhead"'
  1336. + ' role="application"></div>';
  1337. }
  1338. else if (typeof charts['system.ip'] !== 'undefined') {
  1339. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ip"'
  1340. + ' data-dimensions="received"'
  1341. + ' data-chart-library="easypiechart"'
  1342. + ' data-title="IP Inbound"'
  1343. + ' data-width="11%"'
  1344. + ' data-before="0"'
  1345. + ' data-after="-' + duration.toString() + '"'
  1346. + ' data-points="' + duration.toString() + '"'
  1347. + ' data-common-units="system.ip.mainhead"'
  1348. + ' role="application"></div>';
  1349. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ip"'
  1350. + ' data-dimensions="sent"'
  1351. + ' data-chart-library="easypiechart"'
  1352. + ' data-title="IP Outbound"'
  1353. + ' data-width="11%"'
  1354. + ' data-before="0"'
  1355. + ' data-after="-' + duration.toString() + '"'
  1356. + ' data-points="' + duration.toString() + '"'
  1357. + ' data-common-units="system.ip.mainhead"'
  1358. + ' role="application"></div>';
  1359. }
  1360. else if (typeof charts['system.ipv4'] !== 'undefined') {
  1361. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv4"'
  1362. + ' data-dimensions="received"'
  1363. + ' data-chart-library="easypiechart"'
  1364. + ' data-title="IPv4 Inbound"'
  1365. + ' data-width="11%"'
  1366. + ' data-before="0"'
  1367. + ' data-after="-' + duration.toString() + '"'
  1368. + ' data-points="' + duration.toString() + '"'
  1369. + ' data-common-units="system.ipv4.mainhead"'
  1370. + ' role="application"></div>';
  1371. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv4"'
  1372. + ' data-dimensions="sent"'
  1373. + ' data-chart-library="easypiechart"'
  1374. + ' data-title="IPv4 Outbound"'
  1375. + ' data-width="11%"'
  1376. + ' data-before="0"'
  1377. + ' data-after="-' + duration.toString() + '"'
  1378. + ' data-points="' + duration.toString() + '"'
  1379. + ' data-common-units="system.ipv4.mainhead"'
  1380. + ' role="application"></div>';
  1381. }
  1382. else if (typeof charts['system.ipv6'] !== 'undefined') {
  1383. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv6"'
  1384. + ' data-dimensions="received"'
  1385. + ' data-chart-library="easypiechart"'
  1386. + ' data-title="IPv6 Inbound"'
  1387. + ' data-units="kbps"'
  1388. + ' data-width="11%"'
  1389. + ' data-before="0"'
  1390. + ' data-after="-' + duration.toString() + '"'
  1391. + ' data-points="' + duration.toString() + '"'
  1392. + ' data-common-units="system.ipv6.mainhead"'
  1393. + ' role="application"></div>';
  1394. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ipv6"'
  1395. + ' data-dimensions="sent"'
  1396. + ' data-chart-library="easypiechart"'
  1397. + ' data-title="IPv6 Outbound"'
  1398. + ' data-units="kbps"'
  1399. + ' data-width="11%"'
  1400. + ' data-before="0"'
  1401. + ' data-after="-' + duration.toString() + '"'
  1402. + ' data-points="' + duration.toString() + '"'
  1403. + ' data-common-units="system.ipv6.mainhead"'
  1404. + ' role="application"></div>';
  1405. }
  1406. if (typeof charts['system.ram'] !== 'undefined') {
  1407. head += '<div class="netdata-container" style="margin-right: 10px;" data-netdata="system.ram"'
  1408. + ' data-dimensions="used|buffers|active|wired"' // active and wired are FreeBSD stats
  1409. + ' data-append-options="percentage"'
  1410. + ' data-chart-library="easypiechart"'
  1411. + ' data-title="Used RAM"'
  1412. + ' data-units="%"'
  1413. + ' data-easypiechart-max-value="100"'
  1414. + ' data-width="9%"'
  1415. + ' data-after="-' + duration.toString() + '"'
  1416. + ' data-points="' + duration.toString() + '"'
  1417. + ' data-colors="' + NETDATA.colors[7] + '"'
  1418. + ' role="application"></div>';
  1419. }
  1420. return head;
  1421. }
  1422. function generateHeadCharts(type, chart, duration) {
  1423. if (urlOptions.mode === 'print') {
  1424. return '';
  1425. }
  1426. var head = '';
  1427. var hcharts = netdataDashboard.anyAttribute(netdataDashboard.context, type, chart.context, []);
  1428. if (hcharts.length > 0) {
  1429. var hi = 0, hlen = hcharts.length;
  1430. while (hi < hlen) {
  1431. if (typeof hcharts[hi] === 'function') {
  1432. head += hcharts[hi](netdataDashboard.os, chart.id).replace(/CHART_DURATION/g, duration.toString()).replace(/CHART_UNIQUE_ID/g, chart.id);
  1433. } else {
  1434. head += hcharts[hi].replace(/CHART_DURATION/g, duration.toString()).replace(/CHART_UNIQUE_ID/g, chart.id);
  1435. }
  1436. hi++;
  1437. }
  1438. }
  1439. return head;
  1440. }
  1441. function renderPage(menus, data) {
  1442. var div = document.getElementById('charts_div');
  1443. var pcent_width = Math.floor(100 / chartsPerRow($(div).width()));
  1444. // find the proper duration for per-second updates
  1445. var duration = Math.round(($(div).width() * pcent_width / 100 * data.update_every / 3) / 60) * 60;
  1446. options.duration = duration;
  1447. options.update_every = data.update_every;
  1448. var html = '';
  1449. var sidebar = '<ul class="nav dashboard-sidenav" data-spy="affix" id="sidebar_ul">';
  1450. var mainhead = headMain(netdataDashboard.os, data.charts, duration);
  1451. // sort the menus
  1452. var main = sortObjectByPriority(menus);
  1453. var i = 0, len = main.length;
  1454. while (i < len) {
  1455. var menu = main[i++];
  1456. // generate an entry at the main menu
  1457. var menuid = NETDATA.name2id('menu_' + menu);
  1458. sidebar += '<li class=""><a href="#' + menuid + '" onClick="return scrollToId(\'' + menuid + '\');">' + menus[menu].icon + ' ' + menus[menu].title + '</a><ul class="nav">';
  1459. 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">';
  1460. if (menus[menu].info !== null) {
  1461. html += menus[menu].info;
  1462. }
  1463. // console.log(' >> ' + menu + ' (' + menus[menu].priority + '): ' + menus[menu].title);
  1464. var shtml = '';
  1465. var mhead = '<div class="netdata-chart-row">' + mainhead;
  1466. mainhead = '';
  1467. // sort the submenus of this menu
  1468. var sub = sortObjectByPriority(menus[menu].submenus);
  1469. var si = 0, slen = sub.length;
  1470. while (si < slen) {
  1471. var submenu = sub[si++];
  1472. // generate an entry at the submenu
  1473. var submenuid = NETDATA.name2id('menu_' + menu + '_submenu_' + submenu);
  1474. sidebar += '<li class><a href="#' + submenuid + '" onClick="return scrollToId(\'' + submenuid + '\');">' + menus[menu].submenus[submenu].title + '</a></li>';
  1475. 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>';
  1476. if (menus[menu].submenus[submenu].info !== null) {
  1477. shtml += '<div class="dashboard-submenu-info netdata-chart-alignment" role="document">' + menus[menu].submenus[submenu].info + '</div>';
  1478. }
  1479. var head = '<div class="netdata-chart-row">';
  1480. var chtml = '';
  1481. // console.log(' \------- ' + submenu + ' (' + menus[menu].submenus[submenu].priority + '): ' + menus[menu].submenus[submenu].title);
  1482. // sort the charts in this submenu of this menu
  1483. menus[menu].submenus[submenu].charts.sort(prioritySort);
  1484. var ci = 0, clen = menus[menu].submenus[submenu].charts.length;
  1485. while (ci < clen) {
  1486. var chart = menus[menu].submenus[submenu].charts[ci++];
  1487. // generate the submenu heading charts
  1488. mhead += generateHeadCharts('mainheads', chart, duration);
  1489. head += generateHeadCharts('heads', chart, duration);
  1490. function chartCommonMin(family, context, units) {
  1491. var x = netdataDashboard.anyAttribute(netdataDashboard.context, 'commonMin', context, undefined);
  1492. if (typeof x !== 'undefined') {
  1493. return ' data-common-min="' + family + '/' + context + '/' + units + '"';
  1494. } else {
  1495. return '';
  1496. }
  1497. }
  1498. function chartCommonMax(family, context, units) {
  1499. var x = netdataDashboard.anyAttribute(netdataDashboard.context, 'commonMax', context, undefined);
  1500. if (typeof x !== 'undefined') {
  1501. return ' data-common-max="' + family + '/' + context + '/' + units + '"';
  1502. } else {
  1503. return '';
  1504. }
  1505. }
  1506. // generate the chart
  1507. if (urlOptions.mode === 'print') {
  1508. chtml += '<div role="row" class="dashboard-print-row">';
  1509. }
  1510. 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 + '"'
  1511. + ' data-width="100%"'
  1512. + ' data-height="' + netdataDashboard.contextHeight(chart.context, options.chartsHeight).toString() + 'px"'
  1513. + ' data-dygraph-valuerange="' + netdataDashboard.contextValueRange(chart.context) + '"'
  1514. + ' data-before="0"'
  1515. + ' data-after="-' + duration.toString() + '"'
  1516. + ' data-id="' + NETDATA.name2id(options.hostname + '/' + chart.id) + '"'
  1517. + ' data-colors="' + netdataDashboard.anyAttribute(netdataDashboard.context, 'colors', chart.context, '') + '"'
  1518. + ' data-decimal-digits="' + netdataDashboard.contextDecimalDigits(chart.context, -1) + '"'
  1519. + chartCommonMin(chart.family, chart.context, chart.units)
  1520. + chartCommonMax(chart.family, chart.context, chart.units)
  1521. + ' role="application"></div></div>';
  1522. if (urlOptions.mode === 'print') {
  1523. chtml += '</div>';
  1524. }
  1525. }
  1526. head += '</div>';
  1527. shtml += head + chtml + '</div>';
  1528. }
  1529. mhead += '</div>';
  1530. sidebar += '</ul></li>';
  1531. html += mhead + shtml + '</div></div><hr role="separator"/>';
  1532. }
  1533. const isMemoryModeDbEngine = data.memory_mode === "dbengine";
  1534. 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>';
  1535. 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>';
  1536. sidebar += '<li class="" style="margin:20px;color:#666;"><small>Every ' +
  1537. ((data.update_every === 1) ? 'second' : data.update_every.toString() + ' seconds') + ', ' +
  1538. 'Netdata collects <strong>' + data.dimensions_count.toLocaleString() + '</strong> metrics on ' +
  1539. data.hostname.toString() + ', presents them in <strong>' +
  1540. data.charts_count.toLocaleString() + '</strong> charts' +
  1541. (isMemoryModeDbEngine ? '' : ',') + // oxford comma
  1542. ' and monitors them with <strong>' +
  1543. data.alarms_count.toLocaleString() + '</strong> alarms.';
  1544. if (!isMemoryModeDbEngine) {
  1545. sidebar += '<br />&nbsp;<br />Get more history by ' +
  1546. '<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>';
  1547. }
  1548. sidebar += '<br/>&nbsp;<br/><strong>netdata</strong><br/>' + data.version.toString() + '</small></li>';
  1549. sidebar += '</ul>';
  1550. div.innerHTML = html;
  1551. document.getElementById('sidebar').innerHTML = sidebar;
  1552. if (urlOptions.highlight === true) {
  1553. NETDATA.globalChartUnderlay.init(null
  1554. , urlOptions.highlight_after
  1555. , urlOptions.highlight_before
  1556. , (urlOptions.after > 0) ? urlOptions.after : null
  1557. , (urlOptions.before > 0) ? urlOptions.before : null
  1558. );
  1559. } else {
  1560. NETDATA.globalChartUnderlay.clear();
  1561. }
  1562. if (urlOptions.mode === 'print') {
  1563. printPage();
  1564. } else {
  1565. finalizePage();
  1566. }
  1567. }
  1568. function renderChartsAndMenu(data) {
  1569. options.menus = {};
  1570. options.submenu_names = {};
  1571. var menus = options.menus;
  1572. var charts = data.charts;
  1573. var m, menu_key;
  1574. for (var c in charts) {
  1575. if (!charts.hasOwnProperty(c)) {
  1576. continue;
  1577. }
  1578. var chart = charts[c];
  1579. enrichChartData(chart);
  1580. m = chart.menu;
  1581. // create the menu
  1582. if (typeof menus[m] === 'undefined') {
  1583. menus[m] = {
  1584. menu_pattern: chart.menu_pattern,
  1585. priority: chart.priority,
  1586. submenus: {},
  1587. title: netdataDashboard.menuTitle(chart),
  1588. icon: netdataDashboard.menuIcon(chart),
  1589. info: netdataDashboard.menuInfo(chart),
  1590. height: netdataDashboard.menuHeight(chart) * options.chartsHeight
  1591. };
  1592. } else {
  1593. if (typeof (menus[m].menu_pattern) === 'undefined') {
  1594. menus[m].menu_pattern = chart.menu_pattern;
  1595. }
  1596. if (chart.priority < menus[m].priority) {
  1597. menus[m].priority = chart.priority;
  1598. }
  1599. }
  1600. menu_key = (typeof (menus[m].menu_pattern) !== 'undefined') ? menus[m].menu_pattern : m;
  1601. // create the submenu
  1602. if (typeof menus[m].submenus[chart.submenu] === 'undefined') {
  1603. menus[m].submenus[chart.submenu] = {
  1604. priority: chart.priority,
  1605. charts: [],
  1606. title: null,
  1607. info: netdataDashboard.submenuInfo(menu_key, chart.submenu),
  1608. height: netdataDashboard.submenuHeight(menu_key, chart.submenu, menus[m].height)
  1609. };
  1610. } else {
  1611. if (chart.priority < menus[m].submenus[chart.submenu].priority) {
  1612. menus[m].submenus[chart.submenu].priority = chart.priority;
  1613. }
  1614. }
  1615. // index the chart in the menu/submenu
  1616. menus[m].submenus[chart.submenu].charts.push(chart);
  1617. }
  1618. // propagate the descriptive subname given to QoS
  1619. // to all the other submenus with the same name
  1620. for (var m in menus) {
  1621. if (!menus.hasOwnProperty(m)) {
  1622. continue;
  1623. }
  1624. for (var s in menus[m].submenus) {
  1625. if (!menus[m].submenus.hasOwnProperty(s)) {
  1626. continue;
  1627. }
  1628. // set the family using a name
  1629. if (typeof options.submenu_names[s] !== 'undefined') {
  1630. menus[m].submenus[s].title = s + ' (' + options.submenu_names[s] + ')';
  1631. } else {
  1632. menu_key = (typeof (menus[m].menu_pattern) !== 'undefined') ? menus[m].menu_pattern : m;
  1633. menus[m].submenus[s].title = netdataDashboard.submenuTitle(menu_key, s);
  1634. }
  1635. }
  1636. }
  1637. renderPage(menus, data);
  1638. }
  1639. // ----------------------------------------------------------------------------
  1640. function loadJs(url, callback) {
  1641. $.ajax({
  1642. url: url.startsWith("http") ? url : transformWithOldSuffix(url),
  1643. cache: true,
  1644. dataType: "script",
  1645. xhrFields: { withCredentials: true } // required for the cookie
  1646. })
  1647. .fail(function () {
  1648. alert('Cannot load required JS library: ' + url);
  1649. })
  1650. .always(function () {
  1651. if (typeof callback === 'function') {
  1652. callback();
  1653. }
  1654. })
  1655. }
  1656. var clipboardLoaded = false;
  1657. function loadClipboard(callback) {
  1658. if (clipboardLoaded === false) {
  1659. clipboardLoaded = true;
  1660. loadJs('lib/clipboard-polyfill-be05dad.js', callback);
  1661. } else {
  1662. callback();
  1663. }
  1664. }
  1665. var bootstrapTableLoaded = false;
  1666. function loadBootstrapTable(callback) {
  1667. if (bootstrapTableLoaded === false) {
  1668. bootstrapTableLoaded = true;
  1669. loadJs('lib/bootstrap-table-1.11.0.min.js', function () {
  1670. loadJs('lib/bootstrap-table-export-1.11.0.min.js', function () {
  1671. loadJs('lib/tableExport-1.6.0.min.js', callback);
  1672. })
  1673. });
  1674. } else {
  1675. callback();
  1676. }
  1677. }
  1678. var bootstrapSliderLoaded = false;
  1679. function loadBootstrapSlider(callback) {
  1680. if (bootstrapSliderLoaded === false) {
  1681. bootstrapSliderLoaded = true;
  1682. loadJs('lib/bootstrap-slider-10.0.0.min.js', function () {
  1683. NETDATA._loadCSS(transformWithOldSuffix("css/bootstrap-slider-10.0.0.min.css"));
  1684. callback();
  1685. });
  1686. } else {
  1687. callback();
  1688. }
  1689. }
  1690. var lzStringLoaded = false;
  1691. function loadLzString(callback) {
  1692. if (lzStringLoaded === false) {
  1693. lzStringLoaded = true;
  1694. loadJs('lib/lz-string-1.4.4.min.js', callback);
  1695. } else {
  1696. callback();
  1697. }
  1698. }
  1699. var pakoLoaded = false;
  1700. function loadPako(callback) {
  1701. if (pakoLoaded === false) {
  1702. pakoLoaded = true;
  1703. loadJs('lib/pako-1.0.6.min.js', callback);
  1704. } else {
  1705. callback();
  1706. }
  1707. }
  1708. // ----------------------------------------------------------------------------
  1709. function clipboardCopy(text) {
  1710. clipboard.writeText(text);
  1711. }
  1712. function clipboardCopyBadgeEmbed(url) {
  1713. clipboard.writeText('<embed src="' + url + '" type="image/svg+xml" height="20"/>');
  1714. }
  1715. // ----------------------------------------------------------------------------
  1716. function alarmsUpdateModal() {
  1717. var active = '<h3>Raised Alarms</h3><table class="table">';
  1718. var all = '<h3>All Running Alarms</h3><div class="panel-group" id="alarms_all_accordion" role="tablist" aria-multiselectable="true">';
  1719. 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.';
  1720. loadClipboard(function () {
  1721. });
  1722. NETDATA.alarms.get('all', function (data) {
  1723. options.alarm_families = [];
  1724. alarmsCallback(data);
  1725. if (data === null) {
  1726. document.getElementById('alarms_active').innerHTML =
  1727. document.getElementById('alarms_all').innerHTML =
  1728. document.getElementById('alarms_log').innerHTML =
  1729. 'failed to load alarm data!';
  1730. return;
  1731. }
  1732. function alarmid4human(id) {
  1733. if (id === 0) {
  1734. return '-';
  1735. }
  1736. return id.toString();
  1737. }
  1738. function timestamp4human(timestamp, space) {
  1739. if (timestamp === 0) {
  1740. return '-';
  1741. }
  1742. if (typeof space === 'undefined') {
  1743. space = '&nbsp;';
  1744. }
  1745. var t = new Date(timestamp * 1000);
  1746. var now = new Date();
  1747. if (t.toDateString() === now.toDateString()) {
  1748. return t.toLocaleTimeString();
  1749. }
  1750. return t.toLocaleDateString() + space + t.toLocaleTimeString();
  1751. }
  1752. function alarm_lookup_explain(alarm, chart) {
  1753. var dimensions = ' of all values ';
  1754. if (chart.dimensions.length > 1) {
  1755. dimensions = ' of the sum of all dimensions ';
  1756. }
  1757. if (typeof alarm.lookup_dimensions !== 'undefined') {
  1758. var d = alarm.lookup_dimensions.replace(/|/g, ',');
  1759. var x = d.split(',');
  1760. if (x.length > 1) {
  1761. dimensions = 'of the sum of dimensions <code>' + alarm.lookup_dimensions + '</code> ';
  1762. } else {
  1763. dimensions = 'of all values of dimension <code>' + alarm.lookup_dimensions + '</code> ';
  1764. }
  1765. }
  1766. return '<code>' + alarm.lookup_method + '</code> '
  1767. + dimensions + ', of chart <code>' + alarm.chart + '</code>'
  1768. + ', 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>'
  1769. + ((alarm.lookup_options) ? (', with options <code>' + alarm.lookup_options.replace(/ /g, ',&nbsp;') + '</code>') : '')
  1770. + '.';
  1771. }
  1772. function alarm_to_html(alarm, full) {
  1773. var chart = options.data.charts[alarm.chart];
  1774. if (typeof (chart) === 'undefined') {
  1775. chart = options.data.charts_by_name[alarm.chart];
  1776. if (typeof (chart) === 'undefined') {
  1777. // this means the charts loaded are incomplete
  1778. // probably netdata was restarted and more alarms
  1779. // are now available.
  1780. console.log('Cannot find chart ' + alarm.chart + ', you probably need to refresh the page.');
  1781. return '';
  1782. }
  1783. }
  1784. var has_alarm = (typeof alarm.warn !== 'undefined' || typeof alarm.crit !== 'undefined');
  1785. var badge_url = NETDATA.alarms.server + '/api/v1/badge.svg?chart=' + alarm.chart + '&alarm=' + alarm.name + '&refresh=auto';
  1786. var action_buttons = '<br/>&nbsp;<br/>role: <b>' + alarm.recipient + '</b><br/>&nbsp;<br/>'
  1787. + '<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>'
  1788. + '<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>'
  1789. + '<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>';
  1790. 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>'
  1791. + '<td><table class="table">'
  1792. + ((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>') : '')
  1793. + ((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>') : '');
  1794. if (full === true) {
  1795. var units = chart.units;
  1796. if (units === '%') {
  1797. units = '&#37;';
  1798. }
  1799. 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>') : '')
  1800. + ((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>') : '')
  1801. + ((chart.green !== null) ? ('<tr><td width="10%" style="text-align:right">green&nbsp;threshold</td><td><code>' + chart.green + ' ' + units + '</code></td></tr>') : '')
  1802. + ((chart.red !== null) ? ('<tr><td width="10%" style="text-align:right">red&nbsp;threshold</td><td><code>' + chart.red + ' ' + units + '</code></td></tr>') : '');
  1803. }
  1804. if (alarm.warn_repeat_every > 0) {
  1805. html += '<tr><td width="10%" style="text-align:right">repeat&nbsp;warning</td><td>' + NETDATA.seconds4human(alarm.warn_repeat_every) + '</td></tr>';
  1806. }
  1807. if (alarm.crit_repeat_every > 0) {
  1808. html += '<tr><td width="10%" style="text-align:right">repeat&nbsp;critical</td><td>' + NETDATA.seconds4human(alarm.crit_repeat_every) + '</td></tr>';
  1809. }
  1810. var delay = '';
  1811. if ((alarm.delay_up_duration > 0 || alarm.delay_down_duration > 0) && alarm.delay_multiplier !== 0 && alarm.delay_max_duration > 0) {
  1812. if (alarm.delay_up_duration === alarm.delay_down_duration) {
  1813. delay += '<small><br/>hysteresis ' + NETDATA.seconds4human(alarm.delay_up_duration, {
  1814. space: '&nbsp;',
  1815. negative_suffix: ''
  1816. });
  1817. } else {
  1818. delay = '<small><br/>hysteresis ';
  1819. if (alarm.delay_up_duration > 0) {
  1820. delay += 'on&nbsp;escalation&nbsp;<code>' + NETDATA.seconds4human(alarm.delay_up_duration, {
  1821. space: '&nbsp;',
  1822. negative_suffix: ''
  1823. }) + '</code>, ';
  1824. }
  1825. if (alarm.delay_down_duration > 0) {
  1826. delay += 'on&nbsp;recovery&nbsp;<code>' + NETDATA.seconds4human(alarm.delay_down_duration, {
  1827. space: '&nbsp;',
  1828. negative_suffix: ''
  1829. }) + '</code>, ';
  1830. }
  1831. }
  1832. if (alarm.delay_multiplier !== 1.0) {
  1833. delay += 'multiplied&nbsp;by&nbsp;<code>' + alarm.delay_multiplier.toString() + '</code>';
  1834. delay += ',&nbsp;up&nbsp;to&nbsp;<code>' + NETDATA.seconds4human(alarm.delay_max_duration, {
  1835. space: '&nbsp;',
  1836. negative_suffix: ''
  1837. }) + '</code>';
  1838. }
  1839. delay += '</small>';
  1840. }
  1841. html += '<tr><td width="10%" style="text-align:right">check&nbsp;every</td><td>' + NETDATA.seconds4human(alarm.update_every, {
  1842. space: '&nbsp;',
  1843. negative_suffix: ''
  1844. }) + '</td></tr>'
  1845. + ((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>') : '')
  1846. + '<tr><td width="10%" style="text-align:right">source</td><td><span style="font-family: monospace;">' + alarm.source + '</span></td></tr>'
  1847. + '</table></td></tr>';
  1848. return html;
  1849. }
  1850. function alarm_family_show(id) {
  1851. var html = '<table class="table">';
  1852. var family = options.alarm_families[id];
  1853. var len = family.arr.length;
  1854. while (len--) {
  1855. var alarm = family.arr[len];
  1856. html += alarm_to_html(alarm, true);
  1857. }
  1858. html += '</table>';
  1859. $('#alarm_all_' + id.toString()).html(html);
  1860. enableTooltipsAndPopovers();
  1861. }
  1862. // find the proper family of each alarm
  1863. var x, family, alarm;
  1864. var count_active = 0;
  1865. var count_all = 0;
  1866. var families = {};
  1867. var families_sort = [];
  1868. for (x in data.alarms) {
  1869. if (!data.alarms.hasOwnProperty(x)) {
  1870. continue;
  1871. }
  1872. alarm = data.alarms[x];
  1873. family = alarm.family;
  1874. // find the chart
  1875. var chart = options.data.charts[alarm.chart];
  1876. if (typeof chart === 'undefined') {
  1877. chart = options.data.charts_by_name[alarm.chart];
  1878. }
  1879. // not found - this should never happen!
  1880. if (typeof chart === 'undefined') {
  1881. console.log('WARNING: alarm ' + x + ' is linked to chart ' + alarm.chart + ', which is not found in the list of chart got from the server.');
  1882. chart = { priority: 9999999 };
  1883. }
  1884. else if (typeof chart.menu !== 'undefined' && typeof chart.submenu !== 'undefined')
  1885. // the family based on the chart
  1886. {
  1887. family = chart.menu + ' - ' + chart.submenu;
  1888. }
  1889. if (typeof families[family] === 'undefined') {
  1890. families[family] = {
  1891. name: family,
  1892. arr: [],
  1893. priority: chart.priority
  1894. };
  1895. families_sort.push(families[family]);
  1896. }
  1897. if (chart.priority < families[family].priority) {
  1898. families[family].priority = chart.priority;
  1899. }
  1900. families[family].arr.unshift(alarm);
  1901. }
  1902. // sort the families, like the dashboard menu does
  1903. var families_sorted = families_sort.sort(function (a, b) {
  1904. if (a.priority < b.priority) {
  1905. return -1;
  1906. }
  1907. if (a.priority > b.priority) {
  1908. return 1;
  1909. }
  1910. return naturalSortCompare(a.name, b.name);
  1911. });
  1912. var i = 0;
  1913. var fc = 0;
  1914. var len = families_sorted.length;
  1915. while (len--) {
  1916. family = families_sorted[i++].name;
  1917. var active_family_added = false;
  1918. var expanded = 'true';
  1919. var collapsed = '';
  1920. var cin = 'in';
  1921. if (fc !== 0) {
  1922. all += "</table></div></div></div>";
  1923. expanded = 'false';
  1924. collapsed = 'class="collapsed"';
  1925. cin = '';
  1926. }
  1927. 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() + '">';
  1928. options.alarm_families[fc] = families[family];
  1929. fc++;
  1930. var arr = families[family].arr;
  1931. var c = arr.length;
  1932. while (c--) {
  1933. alarm = arr[c];
  1934. if (alarm.status === 'WARNING' || alarm.status === 'CRITICAL') {
  1935. if (!active_family_added) {
  1936. active_family_added = true;
  1937. active += '<tr><th class="text-center" colspan="2"><h4>' + family + '</h4></th></tr>';
  1938. }
  1939. count_active++;
  1940. active += alarm_to_html(alarm, true);
  1941. }
  1942. count_all++;
  1943. }
  1944. }
  1945. active += "</table>";
  1946. if (families_sorted.length > 0) {
  1947. all += "</div></div></div>";
  1948. }
  1949. all += "</div>";
  1950. if (!count_active) {
  1951. 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>';
  1952. } else {
  1953. active += footer;
  1954. }
  1955. if (!count_all) {
  1956. all += "<h4>No alarms are running in this system.</h4>";
  1957. } else {
  1958. all += footer;
  1959. }
  1960. document.getElementById('alarms_active').innerHTML = active;
  1961. document.getElementById('alarms_all').innerHTML = all;
  1962. enableTooltipsAndPopovers();
  1963. if (families_sorted.length > 0) {
  1964. alarm_family_show(0);
  1965. }
  1966. // register bootstrap events
  1967. var $accordion = $('#alarms_all_accordion');
  1968. $accordion.on('show.bs.collapse', function (d) {
  1969. var target = $(d.target);
  1970. var id = $(target).data('alarm-id');
  1971. alarm_family_show(id);
  1972. });
  1973. $accordion.on('hidden.bs.collapse', function (d) {
  1974. var target = $(d.target);
  1975. var id = $(target).data('alarm-id');
  1976. $('#alarm_all_' + id.toString()).html('');
  1977. });
  1978. document.getElementById('alarms_log').innerHTML = '<h3>Alarm Log</h3><table id="alarms_log_table"></table>';
  1979. loadBootstrapTable(function () {
  1980. $('#alarms_log_table').bootstrapTable({
  1981. url: NETDATA.alarms.server + '/api/v1/alarm_log?all',
  1982. cache: false,
  1983. pagination: true,
  1984. pageSize: 10,
  1985. showPaginationSwitch: false,
  1986. search: true,
  1987. searchTimeOut: 300,
  1988. searchAlign: 'left',
  1989. showColumns: true,
  1990. showExport: true,
  1991. exportDataType: 'basic',
  1992. exportOptions: {
  1993. fileName: 'netdata_alarm_log'
  1994. },
  1995. onClickRow: function (row, $element,field) {
  1996. void (field);
  1997. void ($element);
  1998. let main_url;
  1999. 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'];
  2000. if (NETDATA.registry.isUsingGlobalRegistry() && NETDATA.registry.machine_guid != null) {
  2001. main_url = "https://netdata.cloud/alarms/redirect?agentID=" + NETDATA.registry.machine_guid + common_url;
  2002. } else {
  2003. main_url = NETDATA.registry.server + "/goto-host-from-alarm.html?" + common_url ;
  2004. }
  2005. window.open(main_url,"_blank");
  2006. },
  2007. rowStyle: function (row, index) {
  2008. void (index);
  2009. switch (row.status) {
  2010. case 'CRITICAL':
  2011. return { classes: 'danger' };
  2012. break;
  2013. case 'WARNING':
  2014. return { classes: 'warning' };
  2015. break;
  2016. case 'UNDEFINED':
  2017. return { classes: 'info' };
  2018. break;
  2019. case 'CLEAR':
  2020. return { classes: 'success' };
  2021. break;
  2022. }
  2023. return {};
  2024. },
  2025. showFooter: false,
  2026. showHeader: true,
  2027. showRefresh: true,
  2028. showToggle: false,
  2029. sortable: true,
  2030. silentSort: false,
  2031. columns: [
  2032. {
  2033. field: 'when',
  2034. title: 'Event Date',
  2035. valign: 'middle',
  2036. titleTooltip: 'The date and time the even took place',
  2037. formatter: function (value, row, index) {
  2038. void (row);
  2039. void (index);
  2040. return timestamp4human(value, ' ');
  2041. },
  2042. align: 'center',
  2043. switchable: false,
  2044. sortable: true
  2045. },
  2046. {
  2047. field: 'hostname',
  2048. title: 'Host',
  2049. valign: 'middle',
  2050. titleTooltip: 'The host that generated this event',
  2051. align: 'center',
  2052. visible: false,
  2053. sortable: true
  2054. },
  2055. {
  2056. field: 'unique_id',
  2057. title: 'Unique ID',
  2058. titleTooltip: 'The host unique ID for this event',
  2059. formatter: function (value, row, index) {
  2060. void (row);
  2061. void (index);
  2062. return alarmid4human(value);
  2063. },
  2064. align: 'center',
  2065. valign: 'middle',
  2066. visible: false,
  2067. sortable: true
  2068. },
  2069. {
  2070. field: 'alarm_id',
  2071. title: 'Alarm ID',
  2072. titleTooltip: 'The ID of the alarm that generated this event',
  2073. formatter: function (value, row, index) {
  2074. void (row);
  2075. void (index);
  2076. return alarmid4human(value);
  2077. },
  2078. align: 'center',
  2079. valign: 'middle',
  2080. visible: false,
  2081. sortable: true
  2082. },
  2083. {
  2084. field: 'alarm_event_id',
  2085. title: 'Alarm Event ID',
  2086. titleTooltip: 'The incremental ID of this event for the given alarm',
  2087. formatter: function (value, row, index) {
  2088. void (row);
  2089. void (index);
  2090. return alarmid4human(value);
  2091. },
  2092. align: 'center',
  2093. valign: 'middle',
  2094. visible: false,
  2095. sortable: true
  2096. },
  2097. {
  2098. field: 'chart',
  2099. title: 'Chart',
  2100. titleTooltip: 'The chart the alarm is attached to',
  2101. align: 'center',
  2102. valign: 'middle',
  2103. switchable: false,
  2104. sortable: true
  2105. },
  2106. {
  2107. field: 'family',
  2108. title: 'Family',
  2109. titleTooltip: 'The family of the chart the alarm is attached to',
  2110. align: 'center',
  2111. valign: 'middle',
  2112. visible: false,
  2113. sortable: true
  2114. },
  2115. {
  2116. field: 'name',
  2117. title: 'Alarm',
  2118. titleTooltip: 'The alarm name that generated this event',
  2119. formatter: function (value, row, index) {
  2120. void (row);
  2121. void (index);
  2122. return value.toString().replace(/_/g, ' ');
  2123. },
  2124. align: 'center',
  2125. valign: 'middle',
  2126. switchable: false,
  2127. sortable: true
  2128. },
  2129. {
  2130. field: 'value_string',
  2131. title: 'Friendly Value',
  2132. titleTooltip: 'The value of the alarm, that triggered this event',
  2133. align: 'right',
  2134. valign: 'middle',
  2135. sortable: true
  2136. },
  2137. {
  2138. field: 'old_value_string',
  2139. title: 'Friendly Old Value',
  2140. titleTooltip: 'The value of the alarm, just before this event',
  2141. align: 'right',
  2142. valign: 'middle',
  2143. visible: false,
  2144. sortable: true
  2145. },
  2146. {
  2147. field: 'old_value',
  2148. title: 'Old Value',
  2149. titleTooltip: 'The value of the alarm, just before this event',
  2150. formatter: function (value, row, index) {
  2151. void (row);
  2152. void (index);
  2153. return ((value !== null) ? Math.round(value * 100) / 100 : 'NaN').toString();
  2154. },
  2155. align: 'center',
  2156. valign: 'middle',
  2157. visible: false,
  2158. sortable: true
  2159. },
  2160. {
  2161. field: 'value',
  2162. title: 'Value',
  2163. titleTooltip: 'The value of the alarm, that triggered this event',
  2164. formatter: function (value, row, index) {
  2165. void (row);
  2166. void (index);
  2167. return ((value !== null) ? Math.round(value * 100) / 100 : 'NaN').toString();
  2168. },
  2169. align: 'right',
  2170. valign: 'middle',
  2171. visible: false,
  2172. sortable: true
  2173. },
  2174. {
  2175. field: 'units',
  2176. title: 'Units',
  2177. titleTooltip: 'The units of the value of the alarm',
  2178. align: 'left',
  2179. valign: 'middle',
  2180. visible: false,
  2181. sortable: true
  2182. },
  2183. {
  2184. field: 'old_status',
  2185. title: 'Old Status',
  2186. titleTooltip: 'The status of the alarm, just before this event',
  2187. align: 'center',
  2188. valign: 'middle',
  2189. visible: false,
  2190. sortable: true
  2191. },
  2192. {
  2193. field: 'status',
  2194. title: 'Status',
  2195. titleTooltip: 'The status of the alarm, that was set due to this event',
  2196. align: 'center',
  2197. valign: 'middle',
  2198. switchable: false,
  2199. sortable: true
  2200. },
  2201. {
  2202. field: 'duration',
  2203. title: 'Last Duration',
  2204. titleTooltip: 'The duration the alarm was at its previous state, just before this event',
  2205. formatter: function (value, row, index) {
  2206. void (row);
  2207. void (index);
  2208. return NETDATA.seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
  2209. },
  2210. align: 'center',
  2211. valign: 'middle',
  2212. visible: false,
  2213. sortable: true
  2214. },
  2215. {
  2216. field: 'non_clear_duration',
  2217. title: 'Raised Duration',
  2218. titleTooltip: 'The duration the alarm was raised, just before this event',
  2219. formatter: function (value, row, index) {
  2220. void (row);
  2221. void (index);
  2222. return NETDATA.seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
  2223. },
  2224. align: 'center',
  2225. valign: 'middle',
  2226. visible: false,
  2227. sortable: true
  2228. },
  2229. {
  2230. field: 'recipient',
  2231. title: 'Recipient',
  2232. titleTooltip: 'The recipient of this event',
  2233. align: 'center',
  2234. valign: 'middle',
  2235. visible: false,
  2236. sortable: true
  2237. },
  2238. {
  2239. field: 'processed',
  2240. title: 'Processed Status',
  2241. titleTooltip: 'True when this event is processed',
  2242. formatter: function (value, row, index) {
  2243. void (row);
  2244. void (index);
  2245. if (value === true) {
  2246. return 'DONE';
  2247. } else {
  2248. return 'PENDING';
  2249. }
  2250. },
  2251. align: 'center',
  2252. valign: 'middle',
  2253. visible: false,
  2254. sortable: true
  2255. },
  2256. {
  2257. field: 'updated',
  2258. title: 'Updated Status',
  2259. titleTooltip: 'True when this event has been updated by another event',
  2260. formatter: function (value, row, index) {
  2261. void (row);
  2262. void (index);
  2263. if (value === true) {
  2264. return 'UPDATED';
  2265. } else {
  2266. return 'CURRENT';
  2267. }
  2268. },
  2269. align: 'center',
  2270. valign: 'middle',
  2271. visible: false,
  2272. sortable: true
  2273. },
  2274. {
  2275. field: 'updated_by_id',
  2276. title: 'Updated By ID',
  2277. titleTooltip: 'The unique ID of the event that obsoleted this one',
  2278. formatter: function (value, row, index) {
  2279. void (row);
  2280. void (index);
  2281. return alarmid4human(value);
  2282. },
  2283. align: 'center',
  2284. valign: 'middle',
  2285. visible: false,
  2286. sortable: true
  2287. },
  2288. {
  2289. field: 'updates_id',
  2290. title: 'Updates ID',
  2291. titleTooltip: 'The unique ID of the event obsoleted because of this event',
  2292. formatter: function (value, row, index) {
  2293. void (row);
  2294. void (index);
  2295. return alarmid4human(value);
  2296. },
  2297. align: 'center',
  2298. valign: 'middle',
  2299. visible: false,
  2300. sortable: true
  2301. },
  2302. {
  2303. field: 'exec',
  2304. title: 'Script',
  2305. titleTooltip: 'The script to handle the event notification',
  2306. align: 'center',
  2307. valign: 'middle',
  2308. visible: false,
  2309. sortable: true
  2310. },
  2311. {
  2312. field: 'exec_run',
  2313. title: 'Script Run At',
  2314. titleTooltip: 'The date and time the script has been ran',
  2315. formatter: function (value, row, index) {
  2316. void (row);
  2317. void (index);
  2318. return timestamp4human(value, ' ');
  2319. },
  2320. align: 'center',
  2321. valign: 'middle',
  2322. visible: false,
  2323. sortable: true
  2324. },
  2325. {
  2326. field: 'exec_code',
  2327. title: 'Script Return Value',
  2328. titleTooltip: 'The return code of the script',
  2329. formatter: function (value, row, index) {
  2330. void (row);
  2331. void (index);
  2332. if (value === 0) {
  2333. return 'OK (returned 0)';
  2334. } else {
  2335. return 'FAILED (with code ' + value.toString() + ')';
  2336. }
  2337. },
  2338. align: 'center',
  2339. valign: 'middle',
  2340. visible: false,
  2341. sortable: true
  2342. },
  2343. {
  2344. field: 'delay',
  2345. title: 'Script Delay',
  2346. titleTooltip: 'The hysteresis of the notification',
  2347. formatter: function (value, row, index) {
  2348. void (row);
  2349. void (index);
  2350. return NETDATA.seconds4human(value, { negative_suffix: '', space: ' ', now: 'no time' });
  2351. },
  2352. align: 'center',
  2353. valign: 'middle',
  2354. visible: false,
  2355. sortable: true
  2356. },
  2357. {
  2358. field: 'delay_up_to_timestamp',
  2359. title: 'Script Delay Run At',
  2360. titleTooltip: 'The date and time the script should be run, after hysteresis',
  2361. formatter: function (value, row, index) {
  2362. void (row);
  2363. void (index);
  2364. return timestamp4human(value, ' ');
  2365. },
  2366. align: 'center',
  2367. valign: 'middle',
  2368. visible: false,
  2369. sortable: true
  2370. },
  2371. {
  2372. field: 'info',
  2373. title: 'Description',
  2374. titleTooltip: 'A short description of the alarm',
  2375. align: 'center',
  2376. valign: 'middle',
  2377. visible: false,
  2378. sortable: true
  2379. },
  2380. {
  2381. field: 'source',
  2382. title: 'Alarm Source',
  2383. titleTooltip: 'The source of configuration of the alarm',
  2384. align: 'center',
  2385. valign: 'middle',
  2386. visible: false,
  2387. sortable: true
  2388. }
  2389. ]
  2390. });
  2391. // console.log($('#alarms_log_table').bootstrapTable('getOptions'));
  2392. });
  2393. });
  2394. }
  2395. function alarmsCallback(data) {
  2396. var count = 0, x;
  2397. for (x in data.alarms) {
  2398. if (!data.alarms.hasOwnProperty(x)) {
  2399. continue;
  2400. }
  2401. var alarm = data.alarms[x];
  2402. if (alarm.status === 'WARNING' || alarm.status === 'CRITICAL') {
  2403. count++;
  2404. }
  2405. }
  2406. if (count > 0) {
  2407. document.getElementById('alarms_count_badge').innerHTML = count.toString();
  2408. } else {
  2409. document.getElementById('alarms_count_badge').innerHTML = '';
  2410. }
  2411. }
  2412. function initializeDynamicDashboardWithData(data) {
  2413. if (data !== null) {
  2414. options.hostname = data.hostname;
  2415. options.data = data;
  2416. options.version = data.version;
  2417. options.release_channel = data.release_channel;
  2418. netdataDashboard.os = data.os;
  2419. if (typeof data.hosts !== 'undefined') {
  2420. options.hosts = data.hosts;
  2421. }
  2422. // update the dashboard hostname
  2423. document.getElementById('hostname').innerHTML = '<span id="hostnametext">' + options.hostname + ((netdataSnapshotData !== null) ? ' (snap)' : '').toString() + '</span>&nbsp;&nbsp;<strong class="caret">';
  2424. document.getElementById('hostname').href = NETDATA.serverDefault;
  2425. document.getElementById('netdataVersion').innerHTML = options.version;
  2426. if (netdataSnapshotData !== null) {
  2427. $('#alarmsButton').hide();
  2428. $('#updateButton').hide();
  2429. // $('#loadButton').hide();
  2430. $('#saveButton').hide();
  2431. $('#printButton').hide();
  2432. }
  2433. // update the dashboard title
  2434. document.title = options.hostname + ' netdata dashboard';
  2435. // close the splash screen
  2436. $("#loadOverlay").css("display", "none");
  2437. // create a chart_by_name index
  2438. data.charts_by_name = {};
  2439. var charts = data.charts;
  2440. var x;
  2441. for (x in charts) {
  2442. if (!charts.hasOwnProperty(x)) {
  2443. continue;
  2444. }
  2445. var chart = charts[x];
  2446. data.charts_by_name[chart.name] = chart;
  2447. }
  2448. // render all charts
  2449. renderChartsAndMenu(data);
  2450. // Ensure MyNetdata menu is rendered with latest host info #5370
  2451. renderMyNetdataMenu(isSignedIn() ? cloudAgents : registryAgents);
  2452. }
  2453. }
  2454. // an object to keep initialization configuration
  2455. // needed due to the async nature of the XSS modal
  2456. var initializeConfig = {
  2457. url: null,
  2458. custom_info: true,
  2459. };
  2460. function loadCustomDashboardInfo(url, callback) {
  2461. loadJs(url, function () {
  2462. $.extend(true, netdataDashboard, customDashboard);
  2463. callback();
  2464. });
  2465. }
  2466. function initializeChartsAndCustomInfo() {
  2467. NETDATA.alarms.callback = alarmsCallback;
  2468. // download all the charts the server knows
  2469. NETDATA.chartRegistry.downloadAll(initializeConfig.url, function (data) {
  2470. if (data !== null) {
  2471. if (initializeConfig.custom_info === true && typeof data.custom_info !== 'undefined' && data.custom_info !== "" && netdataSnapshotData === null) {
  2472. //console.log('loading custom dashboard decorations from server ' + initializeConfig.url);
  2473. loadCustomDashboardInfo(NETDATA.serverDefault + data.custom_info, function () {
  2474. initializeDynamicDashboardWithData(data);
  2475. });
  2476. } else {
  2477. //console.log('not loading custom dashboard decorations from server ' + initializeConfig.url);
  2478. initializeDynamicDashboardWithData(data);
  2479. }
  2480. }
  2481. });
  2482. }
  2483. function xssModalDisableXss() {
  2484. //console.log('disabling xss checks');
  2485. NETDATA.xss.enabled = false;
  2486. NETDATA.xss.enabled_for_data = false;
  2487. initializeConfig.custom_info = true;
  2488. initializeChartsAndCustomInfo();
  2489. return false;
  2490. }
  2491. function xssModalKeepXss() {
  2492. //console.log('keeping xss checks');
  2493. NETDATA.xss.enabled = true;
  2494. NETDATA.xss.enabled_for_data = true;
  2495. initializeConfig.custom_info = false;
  2496. initializeChartsAndCustomInfo();
  2497. return false;
  2498. }
  2499. function initializeDynamicDashboard(netdata_url) {
  2500. if (typeof netdata_url === 'undefined' || netdata_url === null) {
  2501. netdata_url = NETDATA.serverDefault;
  2502. }
  2503. initializeConfig.url = netdata_url;
  2504. // initialize clickable alarms
  2505. NETDATA.alarms.chart_div_offset = -50;
  2506. NETDATA.alarms.chart_div_id_prefix = 'chart_';
  2507. NETDATA.alarms.chart_div_animation_duration = 0;
  2508. NETDATA.pause(function () {
  2509. if (typeof netdataCheckXSS !== 'undefined' && netdataCheckXSS === true) {
  2510. //$("#loadOverlay").css("display","none");
  2511. document.getElementById('netdataXssModalServer').innerText = initializeConfig.url;
  2512. $('#xssModal').modal('show');
  2513. } else {
  2514. initializeChartsAndCustomInfo();
  2515. }
  2516. });
  2517. }
  2518. // ----------------------------------------------------------------------------
  2519. function versionLog(msg) {
  2520. document.getElementById('versionCheckLog').innerHTML = msg;
  2521. }
  2522. // New way of checking for updates, based only on versions
  2523. function versionsMatch(v1, v2) {
  2524. if (v1 == v2) {
  2525. return true;
  2526. } else {
  2527. let s1 = v1.split('.');
  2528. let s2 = v2.split('.');
  2529. // Check major version
  2530. let n1 = parseInt(s1[0].substring(1, 2), 10);
  2531. let n2 = parseInt(s2[0].substring(1, 2), 10);
  2532. if (n1 < n2) return false;
  2533. else if (n1 > n2) return true;
  2534. // Check minor version
  2535. n1 = parseInt(s1[1], 10);
  2536. n2 = parseInt(s2[1], 10);
  2537. if (n1 < n2) return false;
  2538. else if (n1 > n2) return true;
  2539. // Split patch: format could be e.g. 0-22-nightly
  2540. s1 = s1[2].split('-');
  2541. s2 = s2[2].split('-');
  2542. n1 = parseInt(s1[0], 10);
  2543. n2 = parseInt(s2[0], 10);
  2544. if (n1 < n2) return false;
  2545. else if (n1 > n2) return true;
  2546. n1 = (s1.length > 1) ? parseInt(s1[1], 10) : 0;
  2547. n2 = (s2.length > 1) ? parseInt(s2[1], 10) : 0;
  2548. if (n1 < n2) return false;
  2549. else return true;
  2550. }
  2551. }
  2552. function getGithubLatestVersion(callback) {
  2553. versionLog('Downloading latest version id from github...');
  2554. $.ajax({
  2555. url: 'https://api.github.com/repos/netdata/netdata/releases/latest',
  2556. async: true,
  2557. cache: false
  2558. })
  2559. .done(function (data) {
  2560. data = data.tag_name.replace(/(\r\n|\n|\r| |\t)/gm, "");
  2561. versionLog('Latest stable version from github is ' + data);
  2562. callback(data);
  2563. })
  2564. .fail(function () {
  2565. versionLog('Failed to download the latest stable version id from github!');
  2566. callback(null);
  2567. });
  2568. }
  2569. function getGCSLatestVersion(callback) {
  2570. versionLog('Downloading latest version id from GCS...');
  2571. $.ajax({
  2572. url: "https://www.googleapis.com/storage/v1/b/netdata-nightlies/o/latest-version.txt",
  2573. async: true,
  2574. cache: false
  2575. })
  2576. .done(function (response) {
  2577. $.ajax({
  2578. url: response.mediaLink,
  2579. async: true,
  2580. cache: false
  2581. })
  2582. .done(function (data) {
  2583. data = data.replace(/(\r\n|\n|\r| |\t)/gm, "");
  2584. versionLog('Latest nightly version from GCS is ' + data);
  2585. callback(data);
  2586. })
  2587. .fail(function (xhr, textStatus, errorThrown) {
  2588. versionLog('Failed to download the latest nightly version id from GCS!');
  2589. callback(null);
  2590. });
  2591. })
  2592. .fail(function (xhr, textStatus, errorThrown) {
  2593. versionLog('Failed to download the latest nightly version from GCS!');
  2594. callback(null);
  2595. });
  2596. }
  2597. function checkForUpdateByVersion(force, callback) {
  2598. if (options.release_channel === 'stable') {
  2599. getGithubLatestVersion(function (sha2) {
  2600. callback(options.version, sha2);
  2601. });
  2602. } else {
  2603. getGCSLatestVersion(function (sha2) {
  2604. callback(options.version, sha2);
  2605. });
  2606. }
  2607. return null;
  2608. }
  2609. function notifyForUpdate(force) {
  2610. versionLog('<p>checking for updates...</p>');
  2611. var now = Date.now();
  2612. if (typeof force === 'undefined' || force !== true) {
  2613. var last = loadLocalStorage('last_update_check');
  2614. if (typeof last === 'string') {
  2615. last = parseInt(last);
  2616. } else {
  2617. last = 0;
  2618. }
  2619. if (now - last < 3600000 * 8) {
  2620. // no need to check it - too soon
  2621. return;
  2622. }
  2623. }
  2624. checkForUpdateByVersion(force, function (sha1, sha2) {
  2625. var save = false;
  2626. if (sha1 === null) {
  2627. save = false;
  2628. 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>');
  2629. } else if (sha2 === null) {
  2630. save = false;
  2631. 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>');
  2632. } else if (versionsMatch(sha1, sha2)) {
  2633. save = true;
  2634. 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>');
  2635. } else {
  2636. save = true;
  2637. var compare = 'https://learn.netdata.cloud/docs/agent/changelog/';
  2638. 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>');
  2639. document.getElementById('update_badge').innerHTML = '!';
  2640. }
  2641. if (save) {
  2642. saveLocalStorage('last_update_check', now.toString());
  2643. }
  2644. });
  2645. }
  2646. // ----------------------------------------------------------------------------
  2647. // printing dashboards
  2648. function showPageFooter() {
  2649. document.getElementById('footer').style.display = 'block';
  2650. }
  2651. function printPreflight() {
  2652. var url = document.location.origin.toString() + document.location.pathname.toString() + document.location.search.toString() + urlOptions.genHash() + ';mode=print';
  2653. var width = 990;
  2654. var height = screen.height * 90 / 100;
  2655. //console.log(url);
  2656. //console.log(document.location);
  2657. 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');
  2658. $('#printPreflightModal').modal('hide');
  2659. }
  2660. function printPage() {
  2661. var print_is_rendering = true;
  2662. $('#printModal').on('hide.bs.modal', function (e) {
  2663. if (print_is_rendering === true) {
  2664. e.preventDefault();
  2665. return false;
  2666. }
  2667. return true;
  2668. });
  2669. $('#printModal').on('show.bs.modal', function () {
  2670. var print_options = {
  2671. stop_updates_when_focus_is_lost: false,
  2672. update_only_visible: false,
  2673. sync_selection: false,
  2674. eliminate_zero_dimensions: false,
  2675. pan_and_zoom_data_padding: false,
  2676. show_help: false,
  2677. legend_toolbox: false,
  2678. resize_charts: false,
  2679. pixels_per_point: 1
  2680. };
  2681. var x;
  2682. for (x in print_options) {
  2683. if (print_options.hasOwnProperty(x)) {
  2684. NETDATA.options.current[x] = print_options[x];
  2685. }
  2686. }
  2687. NETDATA.parseDom();
  2688. showPageFooter();
  2689. NETDATA.globalSelectionSync.stop();
  2690. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], urlOptions.after, urlOptions.before);
  2691. // NETDATA.onresize();
  2692. var el = document.getElementById('printModalProgressBar');
  2693. var eltxt = document.getElementById('printModalProgressBarText');
  2694. function update_chart(idx) {
  2695. var state = NETDATA.options.targets[--idx];
  2696. var pcent = (NETDATA.options.targets.length - idx) * 100 / NETDATA.options.targets.length;
  2697. $(el).css('width', pcent + '%').attr('aria-valuenow', pcent);
  2698. eltxt.innerText = Math.round(pcent).toString() + '%, ' + state.id;
  2699. setTimeout(function () {
  2700. state.updateChart(function () {
  2701. NETDATA.options.targets[idx].resizeForPrint();
  2702. if (idx > 0) {
  2703. update_chart(idx);
  2704. } else {
  2705. print_is_rendering = false;
  2706. $('#printModal').modal('hide');
  2707. window.print();
  2708. window.close();
  2709. }
  2710. })
  2711. }, 0);
  2712. }
  2713. print_is_rendering = true;
  2714. update_chart(NETDATA.options.targets.length);
  2715. });
  2716. $('#printModal').modal('show');
  2717. }
  2718. // --------------------------------------------------------------------
  2719. function jsonStringifyFn(obj) {
  2720. return JSON.stringify(obj, function (key, value) {
  2721. return (typeof value === 'function') ? value.toString() : value;
  2722. });
  2723. }
  2724. function jsonParseFn(str) {
  2725. return JSON.parse(str, function (key, value) {
  2726. if (typeof value != 'string') {
  2727. return value;
  2728. }
  2729. return (value.substring(0, 8) == 'function') ? eval('(' + value + ')') : value;
  2730. });
  2731. }
  2732. // --------------------------------------------------------------------
  2733. var snapshotOptions = {
  2734. bytes_per_chart: 2048,
  2735. compressionDefault: 'pako.deflate.base64',
  2736. compressions: {
  2737. 'none': {
  2738. bytes_per_point_memory: 5.2,
  2739. bytes_per_point_disk: 5.6,
  2740. compress: function (s) {
  2741. return s;
  2742. },
  2743. compressed_length: function (s) {
  2744. return s.length;
  2745. },
  2746. uncompress: function (s) {
  2747. return s;
  2748. }
  2749. },
  2750. 'pako.deflate.base64': {
  2751. bytes_per_point_memory: 1.8,
  2752. bytes_per_point_disk: 1.9,
  2753. compress: function (s) {
  2754. return btoa(pako.deflate(s, { to: 'string' }));
  2755. },
  2756. compressed_length: function (s) {
  2757. return s.length;
  2758. },
  2759. uncompress: function (s) {
  2760. return pako.inflate(atob(s), { to: 'string' });
  2761. }
  2762. },
  2763. 'pako.deflate': {
  2764. bytes_per_point_memory: 1.4,
  2765. bytes_per_point_disk: 3.2,
  2766. compress: function (s) {
  2767. return pako.deflate(s, { to: 'string' });
  2768. },
  2769. compressed_length: function (s) {
  2770. return s.length;
  2771. },
  2772. uncompress: function (s) {
  2773. return pako.inflate(s, { to: 'string' });
  2774. }
  2775. },
  2776. 'lzstring.utf16': {
  2777. bytes_per_point_memory: 1.7,
  2778. bytes_per_point_disk: 2.6,
  2779. compress: function (s) {
  2780. return LZString.compressToUTF16(s);
  2781. },
  2782. compressed_length: function (s) {
  2783. return s.length * 2;
  2784. },
  2785. uncompress: function (s) {
  2786. return LZString.decompressFromUTF16(s);
  2787. }
  2788. },
  2789. 'lzstring.base64': {
  2790. bytes_per_point_memory: 2.1,
  2791. bytes_per_point_disk: 2.3,
  2792. compress: function (s) {
  2793. return LZString.compressToBase64(s);
  2794. },
  2795. compressed_length: function (s) {
  2796. return s.length;
  2797. },
  2798. uncompress: function (s) {
  2799. return LZString.decompressFromBase64(s);
  2800. }
  2801. },
  2802. 'lzstring.uri': {
  2803. bytes_per_point_memory: 2.1,
  2804. bytes_per_point_disk: 2.3,
  2805. compress: function (s) {
  2806. return LZString.compressToEncodedURIComponent(s);
  2807. },
  2808. compressed_length: function (s) {
  2809. return s.length;
  2810. },
  2811. uncompress: function (s) {
  2812. return LZString.decompressFromEncodedURIComponent(s);
  2813. }
  2814. }
  2815. }
  2816. };
  2817. // --------------------------------------------------------------------
  2818. // loading snapshots
  2819. function loadSnapshotModalLog(priority, msg) {
  2820. document.getElementById('loadSnapshotStatus').className = "alert alert-" + priority;
  2821. document.getElementById('loadSnapshotStatus').innerHTML = msg;
  2822. }
  2823. var tmpSnapshotData = null;
  2824. function loadSnapshot() {
  2825. $('#loadSnapshotImport').addClass('disabled');
  2826. if (tmpSnapshotData === null) {
  2827. loadSnapshotPreflightEmpty();
  2828. loadSnapshotModalLog('danger', 'no data have been loaded');
  2829. return;
  2830. }
  2831. loadPako(function () {
  2832. loadLzString(function () {
  2833. loadSnapshotModalLog('info', 'Please wait, activating snapshot...');
  2834. $('#loadSnapshotModal').modal('hide');
  2835. netdataShowAlarms = false;
  2836. netdataRegistry = false;
  2837. netdataServer = tmpSnapshotData.server;
  2838. NETDATA.serverDefault = netdataServer;
  2839. document.getElementById('charts_div').innerHTML = '';
  2840. document.getElementById('sidebar').innerHTML = '';
  2841. NETDATA.globalReset();
  2842. if (typeof tmpSnapshotData.hash !== 'undefined') {
  2843. urlOptions.hash = tmpSnapshotData.hash;
  2844. } else {
  2845. urlOptions.hash = '#';
  2846. }
  2847. if (typeof tmpSnapshotData.info !== 'undefined') {
  2848. var info = jsonParseFn(tmpSnapshotData.info);
  2849. if (typeof info.menu !== 'undefined') {
  2850. netdataDashboard.menu = info.menu;
  2851. }
  2852. if (typeof info.submenu !== 'undefined') {
  2853. netdataDashboard.submenu = info.submenu;
  2854. }
  2855. if (typeof info.context !== 'undefined') {
  2856. netdataDashboard.context = info.context;
  2857. }
  2858. }
  2859. if (typeof tmpSnapshotData.compression !== 'string') {
  2860. tmpSnapshotData.compression = 'none';
  2861. }
  2862. if (typeof snapshotOptions.compressions[tmpSnapshotData.compression] === 'undefined') {
  2863. alert('unknown compression method: ' + tmpSnapshotData.compression);
  2864. tmpSnapshotData.compression = 'none';
  2865. }
  2866. tmpSnapshotData.uncompress = snapshotOptions.compressions[tmpSnapshotData.compression].uncompress;
  2867. netdataSnapshotData = tmpSnapshotData;
  2868. urlOptions.after = tmpSnapshotData.after_ms;
  2869. urlOptions.before = tmpSnapshotData.before_ms;
  2870. if (typeof tmpSnapshotData.highlight_after_ms !== 'undefined'
  2871. && tmpSnapshotData.highlight_after_ms !== null
  2872. && tmpSnapshotData.highlight_after_ms > 0
  2873. && typeof tmpSnapshotData.highlight_before_ms !== 'undefined'
  2874. && tmpSnapshotData.highlight_before_ms !== null
  2875. && tmpSnapshotData.highlight_before_ms > 0
  2876. ) {
  2877. urlOptions.highlight_after = tmpSnapshotData.highlight_after_ms;
  2878. urlOptions.highlight_before = tmpSnapshotData.highlight_before_ms;
  2879. urlOptions.highlight = true;
  2880. } else {
  2881. urlOptions.highlight_after = 0;
  2882. urlOptions.highlight_before = 0;
  2883. urlOptions.highlight = false;
  2884. }
  2885. netdataCheckXSS = false; // disable the modal - this does not affect XSS checks, since dashboard.js is already loaded
  2886. NETDATA.xss.enabled = true; // we should not do any remote requests, but if we do, check them
  2887. NETDATA.xss.enabled_for_data = true; // check also snapshot data - that have been excluded from the initial check, due to compression
  2888. loadSnapshotPreflightEmpty();
  2889. initializeDynamicDashboard();
  2890. });
  2891. });
  2892. };
  2893. function loadSnapshotPreflightFile(file) {
  2894. var filename = NETDATA.xss.string(file.name);
  2895. var fr = new FileReader();
  2896. fr.onload = function (e) {
  2897. document.getElementById('loadSnapshotFilename').innerHTML = filename;
  2898. var result = null;
  2899. try {
  2900. result = NETDATA.xss.checkAlways('snapshot', JSON.parse(e.target.result), /^(snapshot\.info|snapshot\.data)$/);
  2901. //console.log(result);
  2902. var date_after = new Date(result.after_ms);
  2903. var date_before = new Date(result.before_ms);
  2904. if (typeof result.charts_ok === 'undefined') {
  2905. result.charts_ok = 'unknown';
  2906. }
  2907. if (typeof result.charts_failed === 'undefined') {
  2908. result.charts_failed = 0;
  2909. }
  2910. if (typeof result.compression === 'undefined') {
  2911. result.compression = 'none';
  2912. }
  2913. if (typeof result.data_size === 'undefined') {
  2914. result.data_size = 0;
  2915. }
  2916. document.getElementById('loadSnapshotFilename').innerHTML = '<code>' + filename + '</code>';
  2917. document.getElementById('loadSnapshotHostname').innerHTML = '<b>' + result.hostname + '</b>, netdata version: <b>' + result.netdata_version.toString() + '</b>';
  2918. document.getElementById('loadSnapshotURL').innerHTML = result.url;
  2919. 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';
  2920. 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';
  2921. 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>';
  2922. document.getElementById('loadSnapshotComments').innerHTML = ((result.comments) ? result.comments : '').toString();
  2923. loadSnapshotModalLog('success', 'File loaded, click <b>Import</b> to render it!');
  2924. $('#loadSnapshotImport').removeClass('disabled');
  2925. tmpSnapshotData = result;
  2926. }
  2927. catch (e) {
  2928. console.log(e);
  2929. document.getElementById('loadSnapshotStatus').className = "alert alert-danger";
  2930. document.getElementById('loadSnapshotStatus').innerHTML = "Failed to parse this file!";
  2931. $('#loadSnapshotImport').addClass('disabled');
  2932. }
  2933. }
  2934. //console.log(file);
  2935. fr.readAsText(file);
  2936. };
  2937. function loadSnapshotPreflightEmpty() {
  2938. document.getElementById('loadSnapshotFilename').innerHTML = '';
  2939. document.getElementById('loadSnapshotHostname').innerHTML = '';
  2940. document.getElementById('loadSnapshotURL').innerHTML = '';
  2941. document.getElementById('loadSnapshotCharts').innerHTML = '';
  2942. document.getElementById('loadSnapshotInfo').innerHTML = '';
  2943. document.getElementById('loadSnapshotTimeRange').innerHTML = '';
  2944. document.getElementById('loadSnapshotComments').innerHTML = '';
  2945. loadSnapshotModalLog('success', 'Browse for a snapshot file (or drag it and drop it here), then click <b>Import</b> to render it.');
  2946. $('#loadSnapshotImport').addClass('disabled');
  2947. };
  2948. var loadSnapshotDragAndDropInitialized = false;
  2949. function loadSnapshotDragAndDropSetup() {
  2950. if (loadSnapshotDragAndDropInitialized === false) {
  2951. loadSnapshotDragAndDropInitialized = true;
  2952. $('#loadSnapshotDragAndDrop')
  2953. .on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  2954. e.preventDefault();
  2955. e.stopPropagation();
  2956. })
  2957. .on('drop', function (e) {
  2958. if (e.originalEvent.dataTransfer.files.length) {
  2959. loadSnapshotPreflightFile(e.originalEvent.dataTransfer.files.item(0));
  2960. } else {
  2961. loadSnapshotPreflightEmpty();
  2962. loadSnapshotModalLog('danger', 'No file selected');
  2963. }
  2964. });
  2965. }
  2966. };
  2967. function loadSnapshotPreflight() {
  2968. var files = document.getElementById('loadSnapshotSelectFiles').files;
  2969. if (files.length <= 0) {
  2970. loadSnapshotPreflightEmpty();
  2971. loadSnapshotModalLog('danger', 'No file selected');
  2972. return;
  2973. }
  2974. loadSnapshotModalLog('info', 'Loading file...');
  2975. loadSnapshotPreflightFile(files.item(0));
  2976. }
  2977. // --------------------------------------------------------------------
  2978. // saving snapshots
  2979. var saveSnapshotStop = false;
  2980. function saveSnapshotCancel() {
  2981. saveSnapshotStop = true;
  2982. }
  2983. var saveSnapshotModalInitialized = false;
  2984. function saveSnapshotModalSetup() {
  2985. if (saveSnapshotModalInitialized === false) {
  2986. saveSnapshotModalInitialized = true;
  2987. $('#saveSnapshotModal')
  2988. .on('hide.bs.modal', saveSnapshotCancel)
  2989. .on('show.bs.modal', saveSnapshotModalInit)
  2990. .on('shown.bs.modal', function () {
  2991. $('#saveSnapshotResolutionSlider').find(".slider-handle:first").attr("tabindex", 1);
  2992. document.getElementById('saveSnapshotComments').focus();
  2993. });
  2994. }
  2995. };
  2996. function saveSnapshotModalLog(priority, msg) {
  2997. document.getElementById('saveSnapshotStatus').className = "alert alert-" + priority;
  2998. document.getElementById('saveSnapshotStatus').innerHTML = msg;
  2999. }
  3000. function saveSnapshotModalShowExpectedSize() {
  3001. var points = Math.round(saveSnapshotViewDuration / saveSnapshotSelectedSecondsPerPoint);
  3002. var priority = 'info';
  3003. var msg = 'A moderate snapshot.';
  3004. var sizemb = Math.round(
  3005. (options.data.charts_count * snapshotOptions.bytes_per_chart
  3006. + options.data.dimensions_count * points * snapshotOptions.compressions[saveSnapshotCompression].bytes_per_point_disk)
  3007. * 10 / 1024 / 1024) / 10;
  3008. var memmb = Math.round(
  3009. (options.data.charts_count * snapshotOptions.bytes_per_chart
  3010. + options.data.dimensions_count * points * snapshotOptions.compressions[saveSnapshotCompression].bytes_per_point_memory)
  3011. * 10 / 1024 / 1024) / 10;
  3012. if (sizemb < 10) {
  3013. priority = 'success';
  3014. msg = 'A nice small snapshot!';
  3015. }
  3016. if (sizemb > 50) {
  3017. priority = 'warning';
  3018. msg = 'Will stress your browser...';
  3019. }
  3020. if (sizemb > 100) {
  3021. priority = 'danger';
  3022. msg = 'Hm... good luck...';
  3023. }
  3024. saveSnapshotModalLog(priority, 'The snapshot will have ' + points.toString() + ' points per dimension. Expected size on disk ' + sizemb + ' MB, at browser memory ' + memmb + ' MB.<br/>' + msg);
  3025. }
  3026. var saveSnapshotCompression = snapshotOptions.compressionDefault;
  3027. function saveSnapshotSetCompression(name) {
  3028. saveSnapshotCompression = name;
  3029. document.getElementById('saveSnapshotCompressionName').innerHTML = saveSnapshotCompression;
  3030. saveSnapshotModalShowExpectedSize();
  3031. }
  3032. var saveSnapshotSlider = null;
  3033. var saveSnapshotSelectedSecondsPerPoint = 1;
  3034. var saveSnapshotViewDuration = 1;
  3035. function saveSnapshotModalInit() {
  3036. $('#saveSnapshotModalProgressSection').hide();
  3037. $('#saveSnapshotResolutionRadio').show();
  3038. saveSnapshotModalLog('info', 'Select resolution and click <b>Save</b>');
  3039. $('#saveSnapshotExport').removeClass('disabled');
  3040. loadBootstrapSlider(function () {
  3041. saveSnapshotViewDuration = options.duration;
  3042. var start_ms = Math.round(Date.now() - saveSnapshotViewDuration * 1000);
  3043. if (NETDATA.globalPanAndZoom.isActive() === true) {
  3044. saveSnapshotViewDuration = Math.round((NETDATA.globalPanAndZoom.force_before_ms - NETDATA.globalPanAndZoom.force_after_ms) / 1000);
  3045. start_ms = NETDATA.globalPanAndZoom.force_after_ms;
  3046. }
  3047. var start_date = new Date(start_ms);
  3048. 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());
  3049. document.getElementById('saveSnapshotFilename').value = 'netdata-' + options.hostname.toString() + '-' + yyyymmddhhssmm.toString() + '-' + saveSnapshotViewDuration.toString() + '.snapshot';
  3050. saveSnapshotSetCompression(saveSnapshotCompression);
  3051. var min = options.update_every;
  3052. var max = Math.round(saveSnapshotViewDuration / 100);
  3053. if (NETDATA.globalPanAndZoom.isActive() === false) {
  3054. max = Math.round(saveSnapshotViewDuration / 50);
  3055. }
  3056. var view = Math.round(saveSnapshotViewDuration / Math.round($(document.getElementById('charts_div')).width() / 2));
  3057. // console.log('view duration: ' + saveSnapshotViewDuration + ', min: ' + min + ', max: ' + max + ', view: ' + view);
  3058. if (max < 10) {
  3059. max = 10;
  3060. }
  3061. if (max < min) {
  3062. max = min;
  3063. }
  3064. if (view < min) {
  3065. view = min;
  3066. }
  3067. if (view > max) {
  3068. view = max;
  3069. }
  3070. if (saveSnapshotSlider !== null) {
  3071. saveSnapshotSlider.destroy();
  3072. }
  3073. saveSnapshotSlider = new Slider('#saveSnapshotResolutionSlider', {
  3074. ticks: [min, view, max],
  3075. min: min,
  3076. max: max,
  3077. step: options.update_every,
  3078. value: view,
  3079. scale: (max > 100) ? 'logarithmic' : 'linear',
  3080. tooltip: 'always',
  3081. formatter: function (value) {
  3082. if (value < 1) {
  3083. value = 1;
  3084. }
  3085. if (value < options.data.update_every) {
  3086. value = options.data.update_every;
  3087. }
  3088. saveSnapshotSelectedSecondsPerPoint = value;
  3089. saveSnapshotModalShowExpectedSize();
  3090. var seconds = ' seconds ';
  3091. if (value === 1) {
  3092. seconds = ' second ';
  3093. }
  3094. return value + seconds + 'per point' + ((value === options.data.update_every) ? ', server default' : '').toString();
  3095. }
  3096. });
  3097. });
  3098. }
  3099. function saveSnapshot() {
  3100. loadPako(function () {
  3101. loadLzString(function () {
  3102. saveSnapshotStop = false;
  3103. $('#saveSnapshotModalProgressSection').show();
  3104. $('#saveSnapshotResolutionRadio').hide();
  3105. $('#saveSnapshotExport').addClass('disabled');
  3106. var filename = document.getElementById('saveSnapshotFilename').value;
  3107. // console.log(filename);
  3108. saveSnapshotModalLog('info', 'Generating snapshot as <code>' + filename.toString() + '</code>');
  3109. var save_options = {
  3110. stop_updates_when_focus_is_lost: false,
  3111. update_only_visible: false,
  3112. sync_selection: false,
  3113. eliminate_zero_dimensions: true,
  3114. pan_and_zoom_data_padding: false,
  3115. show_help: false,
  3116. legend_toolbox: false,
  3117. resize_charts: false,
  3118. pixels_per_point: 1
  3119. };
  3120. var backedup_options = {};
  3121. var x;
  3122. for (x in save_options) {
  3123. if (save_options.hasOwnProperty(x)) {
  3124. backedup_options[x] = NETDATA.options.current[x];
  3125. NETDATA.options.current[x] = save_options[x];
  3126. }
  3127. }
  3128. var el = document.getElementById('saveSnapshotModalProgressBar');
  3129. var eltxt = document.getElementById('saveSnapshotModalProgressBarText');
  3130. options.data.charts_by_name = null;
  3131. var saveData = {
  3132. hostname: options.hostname,
  3133. server: NETDATA.serverDefault,
  3134. netdata_version: options.data.version,
  3135. snapshot_version: 1,
  3136. after_ms: Date.now() - options.duration * 1000,
  3137. before_ms: Date.now(),
  3138. highlight_after_ms: urlOptions.highlight_after,
  3139. highlight_before_ms: urlOptions.highlight_before,
  3140. duration_ms: options.duration * 1000,
  3141. update_every_ms: options.update_every * 1000,
  3142. data_points: 0,
  3143. url: ((urlOptions.server !== null) ? urlOptions.server : document.location.origin.toString() + document.location.pathname.toString() + document.location.search.toString()).toString(),
  3144. comments: document.getElementById('saveSnapshotComments').value.toString(),
  3145. hash: urlOptions.hash,
  3146. charts: options.data,
  3147. info: jsonStringifyFn({
  3148. menu: netdataDashboard.menu,
  3149. submenu: netdataDashboard.submenu,
  3150. context: netdataDashboard.context
  3151. }),
  3152. charts_ok: 0,
  3153. charts_failed: 0,
  3154. compression: saveSnapshotCompression,
  3155. data_size: 0,
  3156. data: {}
  3157. };
  3158. if (typeof snapshotOptions.compressions[saveData.compression] === 'undefined') {
  3159. alert('unknown compression method: ' + saveData.compression);
  3160. saveData.compression = 'none';
  3161. }
  3162. var compress = snapshotOptions.compressions[saveData.compression].compress;
  3163. var compressed_length = snapshotOptions.compressions[saveData.compression].compressed_length;
  3164. function pack_api1_v1_chart_data(state) {
  3165. if (state.library_name === null || state.data === null) {
  3166. return;
  3167. }
  3168. var data = state.data;
  3169. state.data = null;
  3170. data.state = null;
  3171. var str = JSON.stringify(data);
  3172. if (typeof str === 'string') {
  3173. var cstr = compress(str);
  3174. saveData.data[state.chartDataUniqueID()] = cstr;
  3175. return compressed_length(cstr);
  3176. } else {
  3177. return 0;
  3178. }
  3179. }
  3180. var clearPanAndZoom = false;
  3181. if (NETDATA.globalPanAndZoom.isActive() === false) {
  3182. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], saveData.after_ms, saveData.before_ms);
  3183. clearPanAndZoom = true;
  3184. }
  3185. saveData.after_ms = NETDATA.globalPanAndZoom.force_after_ms;
  3186. saveData.before_ms = NETDATA.globalPanAndZoom.force_before_ms;
  3187. saveData.duration_ms = saveData.before_ms - saveData.after_ms;
  3188. saveData.data_points = Math.round((saveData.before_ms - saveData.after_ms) / (saveSnapshotSelectedSecondsPerPoint * 1000));
  3189. saveSnapshotModalLog('info', 'Generating snapshot with ' + saveData.data_points.toString() + ' data points per dimension...');
  3190. var charts_count = 0;
  3191. var charts_ok = 0;
  3192. var charts_failed = 0;
  3193. function saveSnapshotRestore() {
  3194. $('#saveSnapshotModal').modal('hide');
  3195. // restore the options
  3196. var x;
  3197. for (x in backedup_options) {
  3198. if (backedup_options.hasOwnProperty(x)) {
  3199. NETDATA.options.current[x] = backedup_options[x];
  3200. }
  3201. }
  3202. $(el).css('width', '0%').attr('aria-valuenow', 0);
  3203. eltxt.innerText = '0%';
  3204. if (clearPanAndZoom) {
  3205. NETDATA.globalPanAndZoom.clearMaster();
  3206. }
  3207. NETDATA.options.force_data_points = 0;
  3208. NETDATA.options.fake_chart_rendering = false;
  3209. NETDATA.onscroll_updater_enabled = true;
  3210. NETDATA.onresize();
  3211. NETDATA.unpause();
  3212. $('#saveSnapshotExport').removeClass('disabled');
  3213. }
  3214. NETDATA.globalSelectionSync.stop();
  3215. NETDATA.options.force_data_points = saveData.data_points;
  3216. NETDATA.options.fake_chart_rendering = true;
  3217. NETDATA.onscroll_updater_enabled = false;
  3218. NETDATA.abortAllRefreshes();
  3219. var size = 0;
  3220. var info = ' Resolution: <b>' + saveSnapshotSelectedSecondsPerPoint.toString() + ((saveSnapshotSelectedSecondsPerPoint === 1) ? ' second ' : ' seconds ').toString() + 'per point</b>.';
  3221. function update_chart(idx) {
  3222. if (saveSnapshotStop === true) {
  3223. saveSnapshotModalLog('info', 'Cancelled!');
  3224. saveSnapshotRestore();
  3225. return;
  3226. }
  3227. var state = NETDATA.options.targets[--idx];
  3228. var pcent = (NETDATA.options.targets.length - idx) * 100 / NETDATA.options.targets.length;
  3229. $(el).css('width', pcent + '%').attr('aria-valuenow', pcent);
  3230. eltxt.innerText = Math.round(pcent).toString() + '%, ' + state.id;
  3231. setTimeout(function () {
  3232. charts_count++;
  3233. state.isVisible(true);
  3234. state.current.force_after_ms = saveData.after_ms;
  3235. state.current.force_before_ms = saveData.before_ms;
  3236. state.updateChart(function (status, reason) {
  3237. state.current.force_after_ms = null;
  3238. state.current.force_before_ms = null;
  3239. if (status === true) {
  3240. charts_ok++;
  3241. // state.log('ok');
  3242. size += pack_api1_v1_chart_data(state);
  3243. } else {
  3244. charts_failed++;
  3245. state.log('failed to be updated: ' + reason);
  3246. }
  3247. 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);
  3248. if (idx > 0) {
  3249. update_chart(idx);
  3250. } else {
  3251. saveData.charts_ok = charts_ok;
  3252. saveData.charts_failed = charts_failed;
  3253. saveData.data_size = size;
  3254. // console.log(saveData.compression + ': ' + (size / (options.data.dimensions_count * Math.round(saveSnapshotViewDuration / saveSnapshotSelectedSecondsPerPoint))).toString());
  3255. // save it
  3256. // console.log(saveData);
  3257. saveObjectToClient(saveData, filename);
  3258. if (charts_failed > 0) {
  3259. alert(charts_failed.toString() + ' failed to be downloaded');
  3260. }
  3261. saveSnapshotRestore();
  3262. saveData = null;
  3263. }
  3264. })
  3265. }, 0);
  3266. }
  3267. update_chart(NETDATA.options.targets.length);
  3268. });
  3269. });
  3270. }
  3271. // --------------------------------------------------------------------
  3272. // activate netdata on the page
  3273. function dashboardSettingsSetup() {
  3274. var update_options_modal = function () {
  3275. // console.log('update_options_modal');
  3276. var sync_option = function (option) {
  3277. var self = $('#' + option);
  3278. if (self.prop('checked') !== NETDATA.getOption(option)) {
  3279. // console.log('switching ' + option.toString());
  3280. self.bootstrapToggle(NETDATA.getOption(option) ? 'on' : 'off');
  3281. }
  3282. };
  3283. var theme_sync_option = function (option) {
  3284. var self = $('#' + option);
  3285. self.bootstrapToggle(netdataTheme === 'slate' ? 'on' : 'off');
  3286. };
  3287. var units_sync_option = function (option) {
  3288. var self = $('#' + option);
  3289. if (self.prop('checked') !== (NETDATA.getOption('units') === 'auto')) {
  3290. self.bootstrapToggle(NETDATA.getOption('units') === 'auto' ? 'on' : 'off');
  3291. }
  3292. if (self.prop('checked') === true) {
  3293. $('#settingsLocaleTempRow').show();
  3294. $('#settingsLocaleTimeRow').show();
  3295. } else {
  3296. $('#settingsLocaleTempRow').hide();
  3297. $('#settingsLocaleTimeRow').hide();
  3298. }
  3299. };
  3300. var temp_sync_option = function (option) {
  3301. var self = $('#' + option);
  3302. if (self.prop('checked') !== (NETDATA.getOption('temperature') === 'celsius')) {
  3303. self.bootstrapToggle(NETDATA.getOption('temperature') === 'celsius' ? 'on' : 'off');
  3304. }
  3305. };
  3306. var timezone_sync_option = function (option) {
  3307. var self = $('#' + option);
  3308. document.getElementById('browser_timezone').innerText = NETDATA.options.browser_timezone;
  3309. document.getElementById('server_timezone').innerText = NETDATA.options.server_timezone;
  3310. document.getElementById('current_timezone').innerText = (NETDATA.options.current.timezone === 'default') ? 'unset, using browser default' : NETDATA.options.current.timezone;
  3311. if (self.prop('checked') === NETDATA.dateTime.using_timezone) {
  3312. self.bootstrapToggle(NETDATA.dateTime.using_timezone ? 'off' : 'on');
  3313. }
  3314. };
  3315. sync_option('eliminate_zero_dimensions');
  3316. sync_option('destroy_on_hide');
  3317. sync_option('async_on_scroll');
  3318. sync_option('parallel_refresher');
  3319. sync_option('concurrent_refreshes');
  3320. sync_option('sync_selection');
  3321. sync_option('sync_pan_and_zoom');
  3322. sync_option('stop_updates_when_focus_is_lost');
  3323. sync_option('smooth_plot');
  3324. sync_option('pan_and_zoom_data_padding');
  3325. sync_option('show_help');
  3326. sync_option('seconds_as_time');
  3327. theme_sync_option('netdata_theme_control');
  3328. units_sync_option('units_conversion');
  3329. temp_sync_option('units_temp');
  3330. timezone_sync_option('local_timezone');
  3331. if (NETDATA.getOption('parallel_refresher') === false) {
  3332. $('#concurrent_refreshes_row').hide();
  3333. } else {
  3334. $('#concurrent_refreshes_row').show();
  3335. }
  3336. };
  3337. NETDATA.setOption('setOptionCallback', update_options_modal);
  3338. // handle options changes
  3339. $('#eliminate_zero_dimensions').change(function () {
  3340. NETDATA.setOption('eliminate_zero_dimensions', $(this).prop('checked'));
  3341. });
  3342. $('#destroy_on_hide').change(function () {
  3343. NETDATA.setOption('destroy_on_hide', $(this).prop('checked'));
  3344. });
  3345. $('#async_on_scroll').change(function () {
  3346. NETDATA.setOption('async_on_scroll', $(this).prop('checked'));
  3347. });
  3348. $('#parallel_refresher').change(function () {
  3349. NETDATA.setOption('parallel_refresher', $(this).prop('checked'));
  3350. });
  3351. $('#concurrent_refreshes').change(function () {
  3352. NETDATA.setOption('concurrent_refreshes', $(this).prop('checked'));
  3353. });
  3354. $('#sync_selection').change(function () {
  3355. NETDATA.setOption('sync_selection', $(this).prop('checked'));
  3356. });
  3357. $('#sync_pan_and_zoom').change(function () {
  3358. NETDATA.setOption('sync_pan_and_zoom', $(this).prop('checked'));
  3359. });
  3360. $('#stop_updates_when_focus_is_lost').change(function () {
  3361. urlOptions.update_always = !$(this).prop('checked');
  3362. urlOptions.hashUpdate();
  3363. NETDATA.setOption('stop_updates_when_focus_is_lost', !urlOptions.update_always);
  3364. });
  3365. $('#smooth_plot').change(function () {
  3366. NETDATA.setOption('smooth_plot', $(this).prop('checked'));
  3367. });
  3368. $('#pan_and_zoom_data_padding').change(function () {
  3369. NETDATA.setOption('pan_and_zoom_data_padding', $(this).prop('checked'));
  3370. });
  3371. $('#seconds_as_time').change(function () {
  3372. NETDATA.setOption('seconds_as_time', $(this).prop('checked'));
  3373. });
  3374. $('#local_timezone').change(function () {
  3375. if ($(this).prop('checked')) {
  3376. selected_server_timezone('default', true);
  3377. } else {
  3378. selected_server_timezone('default', false);
  3379. }
  3380. });
  3381. $('#units_conversion').change(function () {
  3382. NETDATA.setOption('units', $(this).prop('checked') ? 'auto' : 'original');
  3383. });
  3384. $('#units_temp').change(function () {
  3385. NETDATA.setOption('temperature', $(this).prop('checked') ? 'celsius' : 'fahrenheit');
  3386. });
  3387. $('#show_help').change(function () {
  3388. urlOptions.help = $(this).prop('checked');
  3389. urlOptions.hashUpdate();
  3390. NETDATA.setOption('show_help', urlOptions.help);
  3391. netdataReload();
  3392. });
  3393. // this has to be the last
  3394. // it reloads the page
  3395. $('#netdata_theme_control').change(function () {
  3396. urlOptions.theme = $(this).prop('checked') ? 'slate' : 'white';
  3397. urlOptions.hashUpdate();
  3398. if (setTheme(urlOptions.theme)) {
  3399. netdataReload();
  3400. }
  3401. });
  3402. }
  3403. function scrollDashboardTo() {
  3404. if (netdataSnapshotData !== null && typeof netdataSnapshotData.hash !== 'undefined') {
  3405. //console.log(netdataSnapshotData.hash);
  3406. scrollToId(netdataSnapshotData.hash.replace('#', ''));
  3407. } else {
  3408. // check if we have to jump to a specific section
  3409. scrollToId(urlOptions.hash.replace('#', ''));
  3410. if (urlOptions.chart !== null) {
  3411. NETDATA.alarms.scrollToChart(urlOptions.chart);
  3412. //urlOptions.hash = '#' + NETDATA.name2id('menu_' + charts[c].menu + '_submenu_' + charts[c].submenu);
  3413. //urlOptions.hash = '#chart_' + NETDATA.name2id(urlOptions.chart);
  3414. //console.log('hash = ' + urlOptions.hash);
  3415. }
  3416. }
  3417. }
  3418. var modalHiddenCallback = null;
  3419. function scrollToChartAfterHidingModal(chart, alarmDate, alarmStatus) {
  3420. modalHiddenCallback = function () {
  3421. NETDATA.alarms.scrollToChart(chart, alarmDate);
  3422. if (['WARNING', 'CRITICAL'].includes(alarmStatus)) {
  3423. const currentChartState = NETDATA.options.targets.find(
  3424. (chartState) => chartState.id === chart,
  3425. )
  3426. const twoMinutes = 2 * 60 * 1000
  3427. NETDATA.globalPanAndZoom.setMaster(
  3428. currentChartState,
  3429. alarmDate - twoMinutes,
  3430. alarmDate + twoMinutes,
  3431. )
  3432. }
  3433. };
  3434. }
  3435. // ----------------------------------------------------------------------------
  3436. function enableTooltipsAndPopovers() {
  3437. $('[data-toggle="tooltip"]').tooltip({
  3438. animated: 'fade',
  3439. trigger: 'hover',
  3440. html: true,
  3441. delay: { show: 500, hide: 0 },
  3442. container: 'body'
  3443. });
  3444. $('[data-toggle="popover"]').popover();
  3445. }
  3446. // ----------------------------------------------------------------------------
  3447. var runOnceOnDashboardLastRun = 0;
  3448. function runOnceOnDashboardWithjQuery() {
  3449. if (runOnceOnDashboardLastRun !== 0) {
  3450. scrollDashboardTo();
  3451. // restore the scrollspy at the proper position
  3452. $(document.body).scrollspy('refresh');
  3453. $(document.body).scrollspy('process');
  3454. return;
  3455. }
  3456. runOnceOnDashboardLastRun = Date.now();
  3457. // ------------------------------------------------------------------------
  3458. // bootstrap modals
  3459. // prevent bootstrap modals from scrolling the page
  3460. // maintains the current scroll position
  3461. // https://stackoverflow.com/a/34754029/4525767
  3462. var scrollPos = 0;
  3463. var modal_depth = 0; // how many modals are currently open
  3464. var modal_shown = false; // set to true, if a modal is shown
  3465. var netdata_paused_on_modal = false; // set to true, if the modal paused netdata
  3466. var scrollspyOffset = $(window).height() / 3; // will be updated below - the offset of scrollspy to select an item
  3467. $('.modal')
  3468. .on('show.bs.modal', function () {
  3469. if (modal_depth === 0) {
  3470. scrollPos = window.scrollY;
  3471. $('body').css({
  3472. overflow: 'hidden',
  3473. position: 'fixed',
  3474. top: -scrollPos
  3475. });
  3476. modal_shown = true;
  3477. if (NETDATA.options.pauseCallback === null) {
  3478. NETDATA.pause(function () {
  3479. });
  3480. netdata_paused_on_modal = true;
  3481. } else {
  3482. netdata_paused_on_modal = false;
  3483. }
  3484. }
  3485. modal_depth++;
  3486. //console.log(urlOptions.after);
  3487. })
  3488. .on('hide.bs.modal', function () {
  3489. modal_depth--;
  3490. if (modal_depth <= 0) {
  3491. modal_depth = 0;
  3492. $('body')
  3493. .css({
  3494. overflow: '',
  3495. position: '',
  3496. top: ''
  3497. });
  3498. // scroll to the position we had open before the modal
  3499. $('html, body')
  3500. .animate({ scrollTop: scrollPos }, 0);
  3501. // unpause netdata, if we paused it
  3502. if (netdata_paused_on_modal === true) {
  3503. NETDATA.unpause();
  3504. netdata_paused_on_modal = false;
  3505. }
  3506. // restore the scrollspy at the proper position
  3507. $(document.body).scrollspy('process');
  3508. }
  3509. //console.log(urlOptions.after);
  3510. })
  3511. .on('hidden.bs.modal', function () {
  3512. if (modal_depth === 0) {
  3513. modal_shown = false;
  3514. }
  3515. if (typeof modalHiddenCallback === 'function') {
  3516. modalHiddenCallback();
  3517. }
  3518. modalHiddenCallback = null;
  3519. //console.log(urlOptions.after);
  3520. });
  3521. // ------------------------------------------------------------------------
  3522. // sidebar / affix
  3523. if (shouldShowSignInBanner()) {
  3524. const el = document.getElementById("sign-in-banner");
  3525. if (el) {
  3526. el.style.display = "initial";
  3527. el.classList.add(`theme-${netdataTheme}`);
  3528. }
  3529. }
  3530. $('#sidebar')
  3531. .affix({
  3532. offset: {
  3533. top: (isdemo()) ? 150 : 0,
  3534. bottom: 0
  3535. }
  3536. })
  3537. .on('affixed.bs.affix', function () {
  3538. // fix scrolling of very long affix lists
  3539. // http://stackoverflow.com/questions/21691585/bootstrap-3-1-0-affix-too-long
  3540. $(this).removeAttr('style');
  3541. })
  3542. .on('affix-top.bs.affix', function () {
  3543. // fix bootstrap affix click bug
  3544. // https://stackoverflow.com/a/37847981/4525767
  3545. if (modal_shown) {
  3546. return false;
  3547. }
  3548. })
  3549. .on('activate.bs.scrollspy', function (e) {
  3550. // change the URL based on the current position of the screen
  3551. if (modal_shown === false) {
  3552. var el = $(e.target);
  3553. var hash = el.find('a').attr('href');
  3554. if (typeof hash === 'string' && hash.substring(0, 1) === '#' && urlOptions.hash.startsWith(hash + '_submenu_') === false) {
  3555. urlOptions.hash = hash;
  3556. urlOptions.hashUpdate();
  3557. }
  3558. }
  3559. });
  3560. Ps.initialize(document.getElementById('sidebar'), {
  3561. wheelSpeed: 0.5,
  3562. wheelPropagation: true,
  3563. swipePropagation: true,
  3564. minScrollbarLength: null,
  3565. maxScrollbarLength: null,
  3566. useBothWheelAxes: false,
  3567. suppressScrollX: true,
  3568. suppressScrollY: false,
  3569. scrollXMarginOffset: 0,
  3570. scrollYMarginOffset: 0,
  3571. theme: 'default'
  3572. });
  3573. // ------------------------------------------------------------------------
  3574. // scrollspy
  3575. if (scrollspyOffset > 250) {
  3576. scrollspyOffset = 250;
  3577. }
  3578. if (scrollspyOffset < 75) {
  3579. scrollspyOffset = 75;
  3580. }
  3581. document.body.setAttribute('data-offset', scrollspyOffset);
  3582. // scroll the dashboard, before activating the scrollspy, so that our
  3583. // hash will not be updated before we got the chance to scroll to it
  3584. scrollDashboardTo();
  3585. $(document.body).scrollspy({
  3586. target: '#sidebar',
  3587. offset: scrollspyOffset // controls the diff of the <hX> element to the top, to select it
  3588. });
  3589. // ------------------------------------------------------------------------
  3590. // my-netdata menu
  3591. Ps.initialize(document.getElementById('my-netdata-dropdown-content'), {
  3592. wheelSpeed: 1,
  3593. wheelPropagation: false,
  3594. swipePropagation: false,
  3595. minScrollbarLength: null,
  3596. maxScrollbarLength: null,
  3597. useBothWheelAxes: false,
  3598. suppressScrollX: true,
  3599. suppressScrollY: false,
  3600. scrollXMarginOffset: 0,
  3601. scrollYMarginOffset: 0,
  3602. theme: 'default'
  3603. });
  3604. $('#myNetdataDropdownParent')
  3605. .on('show.bs.dropdown', function () {
  3606. var hash = urlOptions.genHash();
  3607. $('.registry_link').each(function (idx) {
  3608. this.setAttribute('href', this.getAttribute("href").replace(/#.*$/, hash));
  3609. });
  3610. NETDATA.pause(function () {
  3611. });
  3612. })
  3613. .on('shown.bs.dropdown', function () {
  3614. Ps.update(document.getElementById('my-netdata-dropdown-content'));
  3615. myNetdataMenuDidShow();
  3616. })
  3617. .on('hidden.bs.dropdown', function () {
  3618. NETDATA.unpause();
  3619. });
  3620. $('#deleteRegistryModal')
  3621. .on('hidden.bs.modal', function () {
  3622. deleteRegistryGuid = null;
  3623. });
  3624. // ------------------------------------------------------------------------
  3625. // update modal
  3626. $('#updateModal')
  3627. .on('show.bs.modal', function () {
  3628. versionLog('checking, please wait...');
  3629. })
  3630. .on('shown.bs.modal', function () {
  3631. notifyForUpdate(true);
  3632. });
  3633. // ------------------------------------------------------------------------
  3634. // alarms modal
  3635. $('#alarmsModal')
  3636. .on('shown.bs.modal', function () {
  3637. alarmsUpdateModal();
  3638. })
  3639. .on('hidden.bs.modal', function () {
  3640. document.getElementById('alarms_active').innerHTML =
  3641. document.getElementById('alarms_all').innerHTML =
  3642. document.getElementById('alarms_log').innerHTML =
  3643. 'loading...';
  3644. });
  3645. // ------------------------------------------------------------------------
  3646. dashboardSettingsSetup();
  3647. loadSnapshotDragAndDropSetup();
  3648. saveSnapshotModalSetup();
  3649. showPageFooter();
  3650. // ------------------------------------------------------------------------
  3651. // https://github.com/viralpatel/jquery.shorten/blob/master/src/jquery.shorten.js
  3652. $.fn.shorten = function (settings) {
  3653. "use strict";
  3654. var config = {
  3655. showChars: 750,
  3656. minHideChars: 10,
  3657. ellipsesText: "...",
  3658. moreText: '<i class="fas fa-expand"></i> show more information',
  3659. lessText: '<i class="fas fa-compress"></i> show less information',
  3660. onLess: function () {
  3661. NETDATA.onscroll();
  3662. },
  3663. onMore: function () {
  3664. NETDATA.onscroll();
  3665. },
  3666. errMsg: null,
  3667. force: false
  3668. };
  3669. if (settings) {
  3670. $.extend(config, settings);
  3671. }
  3672. if ($(this).data('jquery.shorten') && !config.force) {
  3673. return false;
  3674. }
  3675. $(this).data('jquery.shorten', true);
  3676. $(document).off("click", '.morelink');
  3677. $(document).on({
  3678. click: function () {
  3679. var $this = $(this);
  3680. if ($this.hasClass('less')) {
  3681. $this.removeClass('less');
  3682. $this.html(config.moreText);
  3683. $this.parent().prev().animate({ 'height': '0' + '%' }, 0, function () {
  3684. $this.parent().prev().prev().show();
  3685. }).hide(0, function () {
  3686. config.onLess();
  3687. });
  3688. } else {
  3689. $this.addClass('less');
  3690. $this.html(config.lessText);
  3691. $this.parent().prev().animate({ 'height': '100' + '%' }, 0, function () {
  3692. $this.parent().prev().prev().hide();
  3693. }).show(0, function () {
  3694. config.onMore();
  3695. });
  3696. }
  3697. return false;
  3698. }
  3699. }, '.morelink');
  3700. return this.each(function () {
  3701. var $this = $(this);
  3702. var content = $this.html();
  3703. var contentlen = $this.text().length;
  3704. if (contentlen > config.showChars + config.minHideChars) {
  3705. var c = content.substr(0, config.showChars);
  3706. if (c.indexOf('<') >= 0) // If there's HTML don't want to cut it
  3707. {
  3708. var inTag = false; // I'm in a tag?
  3709. var bag = ''; // Put the characters to be shown here
  3710. var countChars = 0; // Current bag size
  3711. var openTags = []; // Stack for opened tags, so I can close them later
  3712. var tagName = null;
  3713. for (var i = 0, r = 0; r <= config.showChars; i++) {
  3714. if (content[i] === '<' && !inTag) {
  3715. inTag = true;
  3716. // This could be "tag" or "/tag"
  3717. tagName = content.substring(i + 1, content.indexOf('>', i));
  3718. // If its a closing tag
  3719. if (tagName[0] === '/') {
  3720. if (tagName !== ('/' + openTags[0])) {
  3721. config.errMsg = 'ERROR en HTML: the top of the stack should be the tag that closes';
  3722. } else {
  3723. openTags.shift(); // Pops the last tag from the open tag stack (the tag is closed in the retult HTML!)
  3724. }
  3725. } else {
  3726. // There are some nasty tags that don't have a close tag like <br/>
  3727. if (tagName.toLowerCase() !== 'br') {
  3728. openTags.unshift(tagName); // Add to start the name of the tag that opens
  3729. }
  3730. }
  3731. }
  3732. if (inTag && content[i] === '>') {
  3733. inTag = false;
  3734. }
  3735. if (inTag) {
  3736. bag += content.charAt(i);
  3737. } else {
  3738. // Add tag name chars to the result
  3739. r++;
  3740. if (countChars <= config.showChars) {
  3741. bag += content.charAt(i); // Fix to ie 7 not allowing you to reference string characters using the []
  3742. countChars++;
  3743. } else {
  3744. // Now I have the characters needed
  3745. if (openTags.length > 0) {
  3746. // I have unclosed tags
  3747. //console.log('They were open tags');
  3748. //console.log(openTags);
  3749. for (var j = 0; j < openTags.length; j++) {
  3750. //console.log('Cierro tag ' + openTags[j]);
  3751. bag += '</' + openTags[j] + '>'; // Close all tags that were opened
  3752. // 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
  3753. }
  3754. break;
  3755. }
  3756. }
  3757. }
  3758. }
  3759. c = $('<div/>').html(bag + '<span class="ellip">' + config.ellipsesText + '</span>').html();
  3760. } else {
  3761. c += config.ellipsesText;
  3762. }
  3763. var html = '<div class="shortcontent">' + c +
  3764. '</div><div class="allcontent">' + content +
  3765. '</div><span><a href="javascript://nop/" class="morelink">' + config.moreText + '</a></span>';
  3766. $this.html(html);
  3767. $this.find(".allcontent").hide(); // Hide all text
  3768. $('.shortcontent p:last', $this).css('margin-bottom', 0); //Remove bottom margin on last paragraph as it's likely shortened
  3769. }
  3770. });
  3771. };
  3772. }
  3773. function finalizePage() {
  3774. // resize all charts - without starting the background thread
  3775. // this has to be done while NETDATA is paused
  3776. // if we omit this, the affix menu will be wrong, since all
  3777. // the Dom elements are initially zero-sized
  3778. NETDATA.parseDom();
  3779. // ------------------------------------------------------------------------
  3780. NETDATA.globalPanAndZoom.callback = null;
  3781. NETDATA.globalChartUnderlay.callback = null;
  3782. if (urlOptions.pan_and_zoom === true && NETDATA.options.targets.length > 0) {
  3783. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], urlOptions.after, urlOptions.before);
  3784. }
  3785. // callback for us to track PanAndZoom operations
  3786. NETDATA.globalPanAndZoom.callback = urlOptions.netdataPanAndZoomCallback;
  3787. NETDATA.globalChartUnderlay.callback = urlOptions.netdataHighlightCallback;
  3788. // ------------------------------------------------------------------------
  3789. // let it run (update the charts)
  3790. NETDATA.unpause();
  3791. runOnceOnDashboardWithjQuery();
  3792. $(".shorten").shorten();
  3793. enableTooltipsAndPopovers();
  3794. if (isdemo()) {
  3795. // do not to give errors on netdata demo servers for 60 seconds
  3796. NETDATA.options.current.retries_on_data_failures = 60;
  3797. // google analytics when this is used for the home page of the demo sites
  3798. // this does not run on user's installations
  3799. setTimeout(function () {
  3800. (function (i, s, o, g, r, a, m) {
  3801. i['GoogleAnalyticsObject'] = r;
  3802. i[r] = i[r] || function () {
  3803. (i[r].q = i[r].q || []).push(arguments)
  3804. }, i[r].l = 1 * new Date();
  3805. a = s.createElement(o),
  3806. m = s.getElementsByTagName(o)[0];
  3807. a.async = 1;
  3808. a.src = g;
  3809. m.parentNode.insertBefore(a, m)
  3810. })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
  3811. ga('create', 'UA-64295674-3', 'auto');
  3812. ga('send', 'pageview', '/demosite/' + window.location.host);
  3813. }, 2000);
  3814. } else {
  3815. notifyForUpdate();
  3816. }
  3817. if (urlOptions.show_alarms === true) {
  3818. setTimeout(function () {
  3819. $('#alarmsModal').modal('show');
  3820. }, 1000);
  3821. }
  3822. NETDATA.onresizeCallback = function () {
  3823. Ps.update(document.getElementById('sidebar'));
  3824. Ps.update(document.getElementById('my-netdata-dropdown-content'));
  3825. };
  3826. NETDATA.onresizeCallback();
  3827. if (netdataSnapshotData !== null) {
  3828. NETDATA.globalPanAndZoom.setMaster(NETDATA.options.targets[0], netdataSnapshotData.after_ms, netdataSnapshotData.before_ms);
  3829. }
  3830. //if (urlOptions.nowelcome !== true) {
  3831. // setTimeout(function () {
  3832. // $('#welcomeModal').modal();
  3833. // }, 2000);
  3834. //}
  3835. // var netdataEnded = performance.now();
  3836. // console.log('start up time: ' + (netdataEnded - netdataStarted).toString() + ' ms');
  3837. }
  3838. function resetDashboardOptions() {
  3839. var help = NETDATA.options.current.show_help;
  3840. NETDATA.resetOptions();
  3841. if (setTheme('slate')) {
  3842. netdataReload();
  3843. }
  3844. if (help !== NETDATA.options.current.show_help) {
  3845. netdataReload();
  3846. }
  3847. }
  3848. // callback to add the dashboard info to the
  3849. // parallel javascript downloader in netdata
  3850. var netdataPrepCallback = function () {
  3851. NETDATA.requiredCSS.push({
  3852. url: NETDATA.serverStatic + 'css/bootstrap-toggle-2.2.2.min.css',
  3853. isAlreadyLoaded: function () {
  3854. return false;
  3855. }
  3856. });
  3857. NETDATA.requiredJs.push({
  3858. url: NETDATA.serverStatic + 'lib/bootstrap-toggle-2.2.2.min.js',
  3859. isAlreadyLoaded: function () {
  3860. return false;
  3861. }
  3862. });
  3863. NETDATA.requiredJs.push({
  3864. url: NETDATA.serverStatic + 'dashboard_info.js?v20181019-1',
  3865. async: false,
  3866. isAlreadyLoaded: function () {
  3867. return false;
  3868. }
  3869. });
  3870. if (isdemo()) {
  3871. document.getElementById('masthead').style.display = 'block';
  3872. } else {
  3873. if (urlOptions.update_always === true) {
  3874. NETDATA.setOption('stop_updates_when_focus_is_lost', !urlOptions.update_always);
  3875. }
  3876. }
  3877. };
  3878. var selected_server_timezone = function (timezone, status) {
  3879. //console.log('called with timezone: ' + timezone + ", status: " + ((typeof status === 'undefined')?'undefined':status).toString());
  3880. // clear the error
  3881. document.getElementById('timezone_error_message').innerHTML = '';
  3882. if (typeof status === 'undefined') {
  3883. // the user selected a timezone from the menu
  3884. NETDATA.setOption('user_set_server_timezone', timezone);
  3885. if (NETDATA.dateTime.init(timezone) === false) {
  3886. NETDATA.dateTime.init();
  3887. if (!$('#local_timezone').prop('checked')) {
  3888. $('#local_timezone').bootstrapToggle('on');
  3889. }
  3890. 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.';
  3891. NETDATA.setOption('user_set_server_timezone', NETDATA.options.server_timezone);
  3892. } else {
  3893. if ($('#local_timezone').prop('checked')) {
  3894. $('#local_timezone').bootstrapToggle('off');
  3895. }
  3896. }
  3897. } else if (status === true) {
  3898. // the user wants the browser default timezone to be activated
  3899. NETDATA.dateTime.init();
  3900. } else {
  3901. // the user wants the server default timezone to be activated
  3902. //console.log('found ' + NETDATA.options.current.user_set_server_timezone);
  3903. if (NETDATA.options.current.user_set_server_timezone === 'default') {
  3904. NETDATA.options.current.user_set_server_timezone = NETDATA.options.server_timezone;
  3905. }
  3906. timezone = NETDATA.options.current.user_set_server_timezone;
  3907. if (NETDATA.dateTime.init(timezone) === false) {
  3908. NETDATA.dateTime.init();
  3909. if (!$('#local_timezone').prop('checked')) {
  3910. $('#local_timezone').bootstrapToggle('on');
  3911. }
  3912. document.getElementById('timezone_error_message').innerHTML = 'Sorry. The timezone "' + timezone.toString() + '" is not accepted by your browser. Please select one from the list.';
  3913. NETDATA.setOption('user_set_server_timezone', NETDATA.options.server_timezone);
  3914. }
  3915. }
  3916. document.getElementById('current_timezone').innerText = (NETDATA.options.current.timezone === 'default') ? 'unset, using browser default' : NETDATA.options.current.timezone;
  3917. return false;
  3918. };
  3919. // our entry point
  3920. // var netdataStarted = performance.now();
  3921. var netdataCallback = initializeDynamicDashboard;
  3922. // =================================================================================================
  3923. // netdata.cloud
  3924. let registryAgents = [];
  3925. let cloudAgents = [];
  3926. let myNetdataMenuFilterValue = "";
  3927. let cloudAccountID = null;
  3928. let cloudAccountName = null;
  3929. let cloudToken = null;
  3930. /// Enforces a maximum string length while retaining the prefix and the postfix of
  3931. /// the string.
  3932. function truncateString(str, maxLength) {
  3933. if (str.length <= maxLength) {
  3934. return str;
  3935. }
  3936. const spanLength = Math.floor((maxLength - 3) / 2);
  3937. return `${str.substring(0, spanLength)}...${str.substring(str.length - spanLength)}`;
  3938. }
  3939. // -------------------------------------------------------------------------------------------------
  3940. // netdata.cloud API Client
  3941. // -------------------------------------------------------------------------------------------------
  3942. function isValidAgent(a) {
  3943. return a.urls != null && a.urls.length > 0;
  3944. }
  3945. // https://github.com/netdata/hub/issues/146
  3946. function getCloudAccountAgents() {
  3947. if (!isSignedIn()) {
  3948. return [];
  3949. }
  3950. return fetch(
  3951. `${NETDATA.registry.cloudBaseURL}/api/v1/accounts/${cloudAccountID}/agents`,
  3952. {
  3953. method: "GET",
  3954. mode: "cors",
  3955. headers: {
  3956. "Authorization": `Bearer ${cloudToken}`
  3957. }
  3958. }
  3959. ).then((response) => {
  3960. if (!response.ok) {
  3961. throw Error("Cannot fetch known accounts");
  3962. }
  3963. return response.json();
  3964. }).then((payload) => {
  3965. const agents = payload.result ? payload.result.agents : null;
  3966. if (!agents) {
  3967. return [];
  3968. }
  3969. return agents.filter((a) => isValidAgent(a)).map((a) => {
  3970. return {
  3971. "guid": a.id,
  3972. "name": a.name,
  3973. "url": a.urls[0],
  3974. "alternate_urls": a.urls
  3975. }
  3976. })
  3977. }).catch(function (error) {
  3978. console.log(error);
  3979. return null;
  3980. });
  3981. }
  3982. /** Updates the lastAccessTime and accessCount properties of the agent for the account. */
  3983. function touchAgent() {
  3984. if (!isSignedIn()) {
  3985. return [];
  3986. }
  3987. const touchUrl = `${NETDATA.registry.cloudBaseURL}/api/v1/agents/${NETDATA.registry.machine_guid}/touch?account_id=${cloudAccountID}`;
  3988. return fetch(
  3989. touchUrl,
  3990. {
  3991. method: "post",
  3992. body: "",
  3993. mode: "cors",
  3994. headers: {
  3995. "Authorization": `Bearer ${cloudToken}`
  3996. }
  3997. }
  3998. ).then((response) => {
  3999. if (!response.ok) {
  4000. throw Error("Cannot touch agent" + JSON.stringify(response));
  4001. }
  4002. return response.json();
  4003. }).then((payload) => {
  4004. }).catch(function (error) {
  4005. console.log(error);
  4006. return null;
  4007. });
  4008. }
  4009. // https://github.com/netdata/hub/issues/128
  4010. function postCloudAccountAgents(agentsToSync) {
  4011. if (!isSignedIn()) {
  4012. return [];
  4013. }
  4014. const maskedURL = NETDATA.registry.MASKED_DATA;
  4015. const agents = agentsToSync.map((a) => {
  4016. const urls = a.alternate_urls.filter((url) => url != maskedURL);
  4017. return {
  4018. "id": a.guid,
  4019. "name": a.name,
  4020. "urls": urls
  4021. }
  4022. }).filter((a) => isValidAgent(a))
  4023. const payload = {
  4024. "accountID": cloudAccountID,
  4025. "agents": agents,
  4026. "merge": false,
  4027. };
  4028. return fetch(
  4029. `${NETDATA.registry.cloudBaseURL}/api/v1/accounts/${cloudAccountID}/agents`,
  4030. {
  4031. method: "POST",
  4032. mode: "cors",
  4033. headers: {
  4034. "Content-Type": "application/json; charset=utf-8",
  4035. "Authorization": `Bearer ${cloudToken}`
  4036. },
  4037. body: JSON.stringify(payload)
  4038. }
  4039. ).then((response) => {
  4040. return response.json();
  4041. }).then((payload) => {
  4042. const agents = payload.result ? payload.result.agents : null;
  4043. if (!agents) {
  4044. return [];
  4045. }
  4046. return agents.filter((a) => isValidAgent(a)).map((a) => {
  4047. return {
  4048. "guid": a.id,
  4049. "name": a.name,
  4050. "url": a.urls[0],
  4051. "alternate_urls": a.urls
  4052. }
  4053. })
  4054. });
  4055. }
  4056. function deleteCloudAgentURL(agentID, url) {
  4057. if (!isSignedIn()) {
  4058. return [];
  4059. }
  4060. return fetch(
  4061. `${NETDATA.registry.cloudBaseURL}/api/v1/accounts/${cloudAccountID}/agents/${agentID}/url?value=${encodeURIComponent(url)}`,
  4062. {
  4063. method: "DELETE",
  4064. mode: "cors",
  4065. headers: {
  4066. "Content-Type": "application/json; charset=utf-8",
  4067. "Authorization": `Bearer ${cloudToken}`
  4068. },
  4069. }
  4070. ).then((response) => {
  4071. return response.json();
  4072. }).then((payload) => {
  4073. const count = payload.result ? payload.result.count : 0;
  4074. return count;
  4075. });
  4076. }
  4077. // -------------------------------------------------------------------------------------------------
  4078. function signInDidClick(e) {
  4079. e.preventDefault();
  4080. e.stopPropagation();
  4081. if (!NETDATA.registry.isUsingGlobalRegistry()) {
  4082. // If user is using a private registry, request his consent for
  4083. // synchronizing with cloud.
  4084. showSignInModal();
  4085. return;
  4086. }
  4087. signIn();
  4088. }
  4089. function shouldShowSignInBanner() {
  4090. return false;
  4091. }
  4092. function closeSignInBanner() {
  4093. localStorage.setItem("signInBannerClosed", "true");
  4094. const el = document.getElementById("sign-in-banner");
  4095. if (el) {
  4096. el.style.display = "none";
  4097. }
  4098. }
  4099. function closeSignInBannerDidClick(e) {
  4100. closeSignInBanner();
  4101. }
  4102. function signOutDidClick(e) {
  4103. e.preventDefault();
  4104. e.stopPropagation();
  4105. signOut();
  4106. }
  4107. // -------------------------------------------------------------------------------------------------
  4108. function updateMyNetdataAfterFilterChange() {
  4109. const machinesEl = document.getElementById("my-netdata-menu-machines")
  4110. machinesEl.innerHTML = renderMachines(cloudAgents);
  4111. if (options.hosts.length > 1) {
  4112. const streamedEl = document.getElementById("my-netdata-menu-streamed")
  4113. streamedEl.innerHTML = renderStreamedHosts(options);
  4114. }
  4115. }
  4116. function myNetdataMenuDidShow() {
  4117. const filterEl = document.getElementById("my-netdata-menu-filter-input");
  4118. if (filterEl) {
  4119. filterEl.focus();
  4120. }
  4121. }
  4122. function myNetdataFilterDidChange(e) {
  4123. const inputEl = e.target;
  4124. setTimeout(() => {
  4125. myNetdataMenuFilterValue = inputEl.value;
  4126. updateMyNetdataAfterFilterChange();
  4127. }, 1);
  4128. }
  4129. function myNetdataFilterClearDidClick(e) {
  4130. e.preventDefault();
  4131. e.stopPropagation();
  4132. const inputEl = document.getElementById("my-netdata-menu-filter-input");
  4133. inputEl.value = "";
  4134. myNetdataMenuFilterValue = "";
  4135. updateMyNetdataAfterFilterChange();
  4136. inputEl.focus();
  4137. }
  4138. // -------------------------------------------------------------------------------------------------
  4139. function clearCloudVariables() {
  4140. cloudAccountID = null;
  4141. cloudAccountName = null;
  4142. cloudToken = null;
  4143. }
  4144. function clearCloudLocalStorageItems() {
  4145. localStorage.removeItem("cloud.baseURL");
  4146. localStorage.removeItem("cloud.agentID");
  4147. localStorage.removeItem("cloud.sync");
  4148. }
  4149. function signIn() {
  4150. const url = `${NETDATA.registry.cloudBaseURL}/account/sign-in-agent?id=${NETDATA.registry.machine_guid}&name=${encodeURIComponent(NETDATA.registry.hostname)}&origin=${encodeURIComponent(window.location.origin + "/")}`;
  4151. window.open(url);
  4152. }
  4153. function signOut() {
  4154. cloudSSOSignOut();
  4155. }
  4156. function handleMessage(e) {
  4157. switch (e.data.type) {
  4158. case "sign-in":
  4159. handleSignInMessage(e);
  4160. break;
  4161. case "sign-out":
  4162. handleSignOutMessage(e);
  4163. break;
  4164. default:
  4165. return;
  4166. }
  4167. }
  4168. function handleSignInMessage(e) {
  4169. closeSignInBanner();
  4170. localStorage.setItem("cloud.baseURL", NETDATA.registry.cloudBaseURL);
  4171. cloudAccountID = e.data.accountID;
  4172. cloudAccountName = e.data.accountName;
  4173. cloudToken = e.data.token;
  4174. netdataRegistryCallback(registryAgents);
  4175. if (e.data.redirectURI && !window.location.href.includes(e.data.redirectURI)) {
  4176. // lgtm false-positive - redirectURI does not come from user input, but from iframe callback
  4177. window.location.replace(e.data.redirectURI); // lgtm[js/client-side-unvalidated-url-redirection]
  4178. }
  4179. }
  4180. function handleSignOutMessage(e) {
  4181. clearCloudVariables();
  4182. renderMyNetdataMenu(registryAgents);
  4183. }
  4184. function isSignedIn() {
  4185. return cloudToken != null && cloudAccountID != null;
  4186. }
  4187. function sortedArraysEqual(a, b) {
  4188. if (a.length != b.length) return false;
  4189. for (var i = 0; i < a.length; ++i) {
  4190. if (a[i] !== b[i]) return false;
  4191. }
  4192. return true;
  4193. }
  4194. // If merging is needed returns the merged agents set, otherwise returns null.
  4195. function mergeAgents(cloud, local) {
  4196. let dirty = false;
  4197. const union = new Map();
  4198. for (const cagent of cloud) {
  4199. union.set(cagent.guid, cagent);
  4200. }
  4201. for (const lagent of local) {
  4202. const cagent = union.get(lagent.guid);
  4203. if (cagent) {
  4204. for (const u of lagent.alternate_urls) {
  4205. if (u === NETDATA.registry.MASKED_DATA) { // TODO: temp until registry is updated.
  4206. continue;
  4207. }
  4208. if (!cagent.alternate_urls.includes(u)) {
  4209. dirty = true;
  4210. cagent.alternate_urls.push(u);
  4211. }
  4212. }
  4213. } else {
  4214. dirty = true;
  4215. union.set(lagent.guid, lagent);
  4216. }
  4217. }
  4218. if (dirty) {
  4219. return Array.from(union.values());
  4220. }
  4221. return null;
  4222. }
  4223. function showSignInModal() {
  4224. document.getElementById("sim-registry").innerHTML = NETDATA.registry.server;
  4225. $("#signInModal").modal("show");
  4226. }
  4227. function explicitlySignIn() {
  4228. $("#signInModal").modal("hide");
  4229. signIn();
  4230. }
  4231. function showSyncModal() {
  4232. document.getElementById("sync-registry-modal-registry").innerHTML = NETDATA.registry.server;
  4233. $("#syncRegistryModal").modal("show");
  4234. }
  4235. function explicitlySyncAgents() {
  4236. $("#syncRegistryModal").modal("hide");
  4237. const json = localStorage.getItem("cloud.sync");
  4238. const sync = json ? JSON.parse(json) : {};
  4239. delete sync[cloudAccountID];
  4240. localStorage.setItem("cloud.sync", JSON.stringify(sync));
  4241. NETDATA.registry.init();
  4242. }
  4243. function syncAgents(callback) {
  4244. const json = localStorage.getItem("cloud.sync");
  4245. const sync = json ? JSON.parse(json) : {};
  4246. const currentAgent = {
  4247. guid: NETDATA.registry.machine_guid,
  4248. name: NETDATA.registry.hostname,
  4249. url: NETDATA.serverDefault,
  4250. alternate_urls: [NETDATA.serverDefault],
  4251. }
  4252. const localAgents = sync[cloudAccountID]
  4253. ? [currentAgent]
  4254. : registryAgents.concat([currentAgent]);
  4255. console.log("Checking if sync is needed.", localAgents);
  4256. const agentsToSync = mergeAgents(cloudAgents, localAgents);
  4257. if ((!sync[cloudAccountID]) || agentsToSync) {
  4258. sync[cloudAccountID] = new Date().getTime();
  4259. localStorage.setItem("cloud.sync", JSON.stringify(sync));
  4260. }
  4261. if (agentsToSync) {
  4262. console.log("Synchronizing with netdata.cloud.");
  4263. postCloudAccountAgents(agentsToSync).then((agents) => {
  4264. // TODO: clear syncTime on error!
  4265. cloudAgents = agents;
  4266. callback(cloudAgents);
  4267. });
  4268. return
  4269. }
  4270. callback(cloudAgents);
  4271. }
  4272. let isCloudSSOInitialized = false;
  4273. function cloudSSOInit() {
  4274. const iframeEl = document.getElementById("ssoifrm");
  4275. const url = `${NETDATA.registry.cloudBaseURL}/account/sso-agent?id=${NETDATA.registry.machine_guid}`;
  4276. iframeEl.src = url;
  4277. isCloudSSOInitialized = true;
  4278. }
  4279. function cloudSSOSignOut() {
  4280. const iframe = document.getElementById("ssoifrm");
  4281. const url = `${NETDATA.registry.cloudBaseURL}/account/sign-out-agent`;
  4282. iframe.src = url;
  4283. }
  4284. function initCloud() {
  4285. if (!NETDATA.registry.isCloudEnabled) {
  4286. clearCloudVariables();
  4287. clearCloudLocalStorageItems();
  4288. return;
  4289. }
  4290. if (NETDATA.registry.cloudBaseURL != localStorage.getItem("cloud.baseURL")) {
  4291. clearCloudVariables();
  4292. clearCloudLocalStorageItems();
  4293. if (NETDATA.registry.cloudBaseURL) {
  4294. localStorage.setItem("cloud.baseURL", NETDATA.registry.cloudBaseURL);
  4295. }
  4296. }
  4297. if (!isCloudSSOInitialized) {
  4298. cloudSSOInit();
  4299. }
  4300. touchAgent();
  4301. }
  4302. // This callback is called after NETDATA.registry is initialized.
  4303. function netdataRegistryCallback(machinesArray) {
  4304. localStorage.setItem("cloud.agentID", NETDATA.registry.machine_guid);
  4305. initCloud();
  4306. registryAgents = machinesArray;
  4307. if (isSignedIn()) {
  4308. // We call getCloudAccountAgents() here because it requires that
  4309. // NETDATA.registry is initialized.
  4310. clearMyNetdataMenu();
  4311. getCloudAccountAgents().then((agents) => {
  4312. if (!agents) {
  4313. errorMyNetdataMenu();
  4314. return;
  4315. }
  4316. cloudAgents = agents;
  4317. syncAgents((agents) => {
  4318. const agentsMap = {}
  4319. for (const agent of agents) {
  4320. agentsMap[agent.guid] = agent;
  4321. }
  4322. NETDATA.registry.machines = agentsMap;
  4323. NETDATA.registry.machines_array = agents;
  4324. renderMyNetdataMenu(agents);
  4325. });
  4326. });
  4327. } else {
  4328. renderMyNetdataMenu(machinesArray)
  4329. }
  4330. };
  4331. // If we know the cloudBaseURL and agentID from local storage render (eagerly)
  4332. // the account ui before receiving the definitive response from the web server.
  4333. // This improves the perceived performance.
  4334. function tryFastInitCloud() {
  4335. const baseURL = localStorage.getItem("cloud.baseURL");
  4336. const agentID = localStorage.getItem("cloud.agentID");
  4337. if (baseURL && agentID) {
  4338. NETDATA.registry.cloudBaseURL = baseURL;
  4339. NETDATA.registry.machine_guid = agentID;
  4340. NETDATA.registry.isCloudEnabled = true;
  4341. initCloud();
  4342. }
  4343. }
  4344. function initializeApp() {
  4345. window.addEventListener("message", handleMessage, false);
  4346. // tryFastInitCloud();
  4347. }
  4348. if (document.readyState === "complete") {
  4349. initializeApp();
  4350. } else {
  4351. document.addEventListener("readystatechange", () => {
  4352. if (document.readyState === "complete") {
  4353. initializeApp();
  4354. }
  4355. });
  4356. }