graph.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'moment',
  5. 'lodash',
  6. 'app/core/utils/kbn',
  7. './graph_tooltip',
  8. 'jquery.flot',
  9. 'jquery.flot.selection',
  10. 'jquery.flot.time',
  11. 'jquery.flot.stack',
  12. 'jquery.flot.stackpercent',
  13. 'jquery.flot.fillbelow',
  14. 'jquery.flot.crosshair',
  15. './jquery.flot.events',
  16. ],
  17. function (angular, $, moment, _, kbn, GraphTooltip) {
  18. 'use strict';
  19. var module = angular.module('grafana.directives');
  20. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  21. return {
  22. restrict: 'A',
  23. template: '<div> </div>',
  24. link: function(scope, elem) {
  25. var ctrl = scope.ctrl;
  26. var dashboard = ctrl.dashboard;
  27. var panel = ctrl.panel;
  28. var data, annotations;
  29. var sortedSeries;
  30. var legendSideLastValue = null;
  31. var rootScope = scope.$root;
  32. var panelWidth = 0;
  33. rootScope.onAppEvent('setCrosshair', function(event, info) {
  34. // do not need to to this if event is from this panel
  35. if (info.scope === scope) {
  36. return;
  37. }
  38. if(dashboard.sharedCrosshair) {
  39. var plot = elem.data().plot;
  40. if (plot) {
  41. plot.setCrosshair({ x: info.pos.x, y: info.pos.y });
  42. }
  43. }
  44. }, scope);
  45. rootScope.onAppEvent('clearCrosshair', function() {
  46. var plot = elem.data().plot;
  47. if (plot) {
  48. plot.clearCrosshair();
  49. }
  50. }, scope);
  51. // Receive render events
  52. ctrl.events.on('render', function(renderData) {
  53. data = renderData || data;
  54. if (!data) {
  55. ctrl.refresh();
  56. return;
  57. }
  58. annotations = data.annotations || annotations;
  59. render_panel();
  60. });
  61. function getLegendHeight(panelHeight) {
  62. if (!panel.legend.show || panel.legend.rightSide) {
  63. return 0;
  64. }
  65. if (panel.legend.alignAsTable) {
  66. var legendSeries = _.filter(data, function(series) {
  67. return series.hideFromLegend(panel.legend) === false;
  68. });
  69. var total = 23 + (21 * legendSeries.length);
  70. return Math.min(total, Math.floor(panelHeight/2));
  71. } else {
  72. return 26;
  73. }
  74. }
  75. function setElementHeight() {
  76. try {
  77. var height = ctrl.height - getLegendHeight(ctrl.height);
  78. elem.css('height', height + 'px');
  79. return true;
  80. } catch(e) { // IE throws errors sometimes
  81. console.log(e);
  82. return false;
  83. }
  84. }
  85. function shouldAbortRender() {
  86. if (!data) {
  87. return true;
  88. }
  89. if (!setElementHeight()) { return true; }
  90. if(_.isString(data)) {
  91. render_panel_as_graphite_png(data);
  92. return true;
  93. }
  94. if (panelWidth === 0) {
  95. return true;
  96. }
  97. }
  98. function getLabelWidth(type, text, elem) {
  99. var labelWidth = 0;
  100. if (!rootScope.labelWidthCache) {
  101. rootScope.labelWidthCache = {};
  102. }
  103. if (!rootScope.labelWidthCache[type]) {
  104. rootScope.labelWidthCache[type] = {};
  105. }
  106. if (rootScope.labelWidthCache[type][text]) {
  107. labelWidth = rootScope.labelWidthCache[type][text];
  108. } else {
  109. labelWidth = elem.width();
  110. rootScope.labelWidthCache[type][text] = labelWidth;
  111. }
  112. return labelWidth;
  113. }
  114. function drawHook(plot) {
  115. // Update legend values
  116. var yaxis = plot.getYAxes();
  117. for (var i = 0; i < data.length; i++) {
  118. var series = data[i];
  119. var axis = yaxis[series.yaxis - 1];
  120. var formater = kbn.valueFormats[panel.yaxes[series.yaxis - 1].format];
  121. // decimal override
  122. if (_.isNumber(panel.decimals)) {
  123. series.updateLegendValues(formater, panel.decimals, null);
  124. } else {
  125. // auto decimals
  126. // legend and tooltip gets one more decimal precision
  127. // than graph legend ticks
  128. var tickDecimals = (axis.tickDecimals || -1) + 1;
  129. series.updateLegendValues(formater, tickDecimals, axis.scaledDecimals + 2);
  130. }
  131. if(!rootScope.$$phase) { scope.$digest(); }
  132. }
  133. // add left axis labels
  134. if (panel.yaxes[0].label) {
  135. var yaxisLabel = $("<div class='axisLabel left-yaxis-label'></div>")
  136. .text(panel.yaxes[0].label)
  137. .appendTo(elem);
  138. yaxisLabel[0].style.marginTop = (getLabelWidth('left', panel.yaxes[0].label, yaxisLabel) / 2) + 'px';
  139. }
  140. // add right axis labels
  141. if (panel.yaxes[1].label) {
  142. var rightLabel = $("<div class='axisLabel right-yaxis-label'></div>")
  143. .text(panel.yaxes[1].label)
  144. .appendTo(elem);
  145. rightLabel[0].style.marginTop = (getLabelWidth('right', panel.yaxes[1].label, rightLabel) / 2) + 'px';
  146. }
  147. }
  148. function processOffsetHook(plot, gridMargin) {
  149. var left = panel.yaxes[0];
  150. var right = panel.yaxes[1];
  151. if (left.show && left.label) { gridMargin.left = 20; }
  152. if (right.show && right.label) { gridMargin.right = 20; }
  153. }
  154. // Function for rendering panel
  155. function render_panel() {
  156. if (!rootScope.panelWidthCache) {
  157. rootScope.panelWidthCache = {};
  158. }
  159. if (rootScope.panelWidthCache[panel.span]) {
  160. panelWidth = rootScope.panelWidthCache[panel.span];
  161. } else {
  162. panelWidth = elem.width();
  163. rootScope.panelWidthCache[panel.span] = panelWidth;
  164. }
  165. if (shouldAbortRender()) {
  166. return;
  167. }
  168. var stack = panel.stack ? true : null;
  169. // Populate element
  170. var options = {
  171. hooks: {
  172. draw: [drawHook],
  173. processOffset: [processOffsetHook],
  174. },
  175. legend: { show: false },
  176. series: {
  177. stackpercent: panel.stack ? panel.percentage : false,
  178. stack: panel.percentage ? null : stack,
  179. lines: {
  180. show: panel.lines,
  181. zero: false,
  182. fill: translateFillOption(panel.fill),
  183. lineWidth: panel.linewidth,
  184. steps: panel.steppedLine
  185. },
  186. bars: {
  187. show: panel.bars,
  188. fill: 1,
  189. barWidth: 1,
  190. zero: false,
  191. lineWidth: 0
  192. },
  193. points: {
  194. show: panel.points,
  195. fill: 1,
  196. fillColor: false,
  197. radius: panel.points ? panel.pointradius : 2
  198. },
  199. shadowSize: 0
  200. },
  201. yaxes: [],
  202. xaxis: {},
  203. grid: {
  204. minBorderMargin: 0,
  205. markings: [],
  206. backgroundColor: null,
  207. borderWidth: 0,
  208. hoverable: true,
  209. color: '#c8c8c8',
  210. margin: { left: 0, right: 0 },
  211. },
  212. selection: {
  213. mode: "x",
  214. color: '#666'
  215. },
  216. crosshair: {
  217. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  218. }
  219. };
  220. for (var i = 0; i < data.length; i++) {
  221. var series = data[i];
  222. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  223. // if hidden remove points and disable stack
  224. if (ctrl.hiddenSeries[series.alias]) {
  225. series.data = [];
  226. series.stack = false;
  227. }
  228. }
  229. if (data.length && data[0].stats.timeStep) {
  230. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  231. }
  232. addTimeAxis(options);
  233. addGridThresholds(options, panel);
  234. addAnnotations(options);
  235. configureAxisOptions(data, options);
  236. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  237. function callPlot(incrementRenderCounter) {
  238. try {
  239. $.plot(elem, sortedSeries, options);
  240. } catch (e) {
  241. console.log('flotcharts error', e);
  242. }
  243. if (incrementRenderCounter) {
  244. ctrl.renderingCompleted();
  245. }
  246. }
  247. if (shouldDelayDraw(panel)) {
  248. // temp fix for legends on the side, need to render twice to get dimensions right
  249. callPlot(false);
  250. setTimeout(function() { callPlot(true); }, 50);
  251. legendSideLastValue = panel.legend.rightSide;
  252. }
  253. else {
  254. callPlot(true);
  255. }
  256. }
  257. function translateFillOption(fill) {
  258. return fill === 0 ? 0.001 : fill/10;
  259. }
  260. function shouldDelayDraw(panel) {
  261. if (panel.legend.rightSide) {
  262. return true;
  263. }
  264. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  265. return true;
  266. }
  267. }
  268. function addTimeAxis(options) {
  269. var ticks = panelWidth / 100;
  270. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  271. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  272. options.xaxis = {
  273. timezone: dashboard.getTimezone(),
  274. show: panel.xaxis.show,
  275. mode: "time",
  276. min: min,
  277. max: max,
  278. label: "Datetime",
  279. ticks: ticks,
  280. timeformat: time_format(ticks, min, max),
  281. };
  282. }
  283. function addGridThresholds(options, panel) {
  284. if (_.isNumber(panel.grid.threshold1)) {
  285. var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null);
  286. options.grid.markings.push({
  287. yaxis: { from: panel.grid.threshold1, to: limit1 },
  288. color: panel.grid.threshold1Color
  289. });
  290. if (_.isNumber(panel.grid.threshold2)) {
  291. var limit2;
  292. if (panel.grid.thresholdLine) {
  293. limit2 = panel.grid.threshold2;
  294. } else {
  295. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  296. }
  297. options.grid.markings.push({
  298. yaxis: { from: panel.grid.threshold2, to: limit2 },
  299. color: panel.grid.threshold2Color
  300. });
  301. }
  302. }
  303. }
  304. function addAnnotations(options) {
  305. if(!annotations || annotations.length === 0) {
  306. return;
  307. }
  308. var types = {};
  309. _.each(annotations, function(event) {
  310. if (!types[event.annotation.name]) {
  311. types[event.annotation.name] = {
  312. color: event.annotation.iconColor,
  313. position: 'BOTTOM',
  314. markerSize: 5,
  315. };
  316. }
  317. });
  318. options.events = {
  319. levels: _.keys(types).length + 1,
  320. data: annotations,
  321. types: types,
  322. };
  323. }
  324. function configureAxisOptions(data, options) {
  325. var defaults = {
  326. position: 'left',
  327. show: panel.yaxes[0].show,
  328. min: panel.yaxes[0].min,
  329. index: 1,
  330. logBase: panel.yaxes[0].logBase || 1,
  331. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  332. };
  333. options.yaxes.push(defaults);
  334. if (_.findWhere(data, {yaxis: 2})) {
  335. var secondY = _.clone(defaults);
  336. secondY.index = 2,
  337. secondY.show = panel.yaxes[1].show;
  338. secondY.logBase = panel.yaxes[1].logBase || 1,
  339. secondY.position = 'right';
  340. secondY.min = panel.yaxes[1].min;
  341. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  342. options.yaxes.push(secondY);
  343. applyLogScale(options.yaxes[1], data);
  344. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  345. }
  346. applyLogScale(options.yaxes[0], data);
  347. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  348. }
  349. function applyLogScale(axis, data) {
  350. if (axis.logBase === 1) {
  351. return;
  352. }
  353. var series, i;
  354. var max = axis.max;
  355. if (max === null) {
  356. for (i = 0; i < data.length; i++) {
  357. series = data[i];
  358. if (series.yaxis === axis.index) {
  359. if (max < series.stats.max) {
  360. max = series.stats.max;
  361. }
  362. }
  363. }
  364. if (max === void 0) {
  365. max = Number.MAX_VALUE;
  366. }
  367. }
  368. axis.min = axis.min !== null ? axis.min : 0;
  369. axis.ticks = [0, 1];
  370. var nextTick = 1;
  371. while (true) {
  372. nextTick = nextTick * axis.logBase;
  373. axis.ticks.push(nextTick);
  374. if (nextTick > max) {
  375. break;
  376. }
  377. }
  378. if (axis.logBase === 10) {
  379. axis.transform = function(v) { return Math.log(v+0.1); };
  380. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  381. } else {
  382. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  383. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  384. }
  385. }
  386. function configureAxisMode(axis, format) {
  387. axis.tickFormatter = function(val, axis) {
  388. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  389. };
  390. }
  391. function time_format(ticks, min, max) {
  392. if (min && max && ticks) {
  393. var range = max - min;
  394. var secPerTick = (range/ticks) / 1000;
  395. var oneDay = 86400000;
  396. var oneYear = 31536000000;
  397. if (secPerTick <= 45) {
  398. return "%H:%M:%S";
  399. }
  400. if (secPerTick <= 7200 || range <= oneDay) {
  401. return "%H:%M";
  402. }
  403. if (secPerTick <= 80000) {
  404. return "%m/%d %H:%M";
  405. }
  406. if (secPerTick <= 2419200 || range <= oneYear) {
  407. return "%m/%d";
  408. }
  409. return "%Y-%m";
  410. }
  411. return "%H:%M";
  412. }
  413. function render_panel_as_graphite_png(url) {
  414. url += '&width=' + panelWidth;
  415. url += '&height=' + elem.css('height').replace('px', '');
  416. url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground
  417. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  418. url += panel.stack ? '&areaMode=stacked' : '';
  419. url += panel.fill !== 0 ? ('&areaAlpha=' + (panel.fill/10).toFixed(1)) : '';
  420. url += panel.linewidth !== 0 ? '&lineWidth=' + panel.linewidth : '';
  421. url += panel.legend.show ? '&hideLegend=false' : '&hideLegend=true';
  422. if (panel.yaxes && panel.yaxes.length > 0) {
  423. var showYaxis = false;
  424. for(var i = 0; panel.yaxes.length > i; i++) {
  425. if (panel.yaxes[i].show) {
  426. url += (panel.yaxes[i].min !== null && panel.yaxes[i].min !== undefined) ? '&yMin=' + panel.yaxes[i].min : '';
  427. url += (panel.yaxes[i].max !== null && panel.yaxes[i].max !== undefined) ? '&yMax=' + panel.yaxes[i].max : '';
  428. showYaxis = true;
  429. break;
  430. }
  431. }
  432. url += showYaxis ? '' : '&hideYAxis=true';
  433. }
  434. url += panel.xaxis.show ? '' : '&hideAxes=true';
  435. switch(panel.yaxes[0].format) {
  436. case 'bytes':
  437. url += '&yUnitSystem=binary';
  438. break;
  439. case 'bits':
  440. url += '&yUnitSystem=binary';
  441. break;
  442. case 'bps':
  443. url += '&yUnitSystem=si';
  444. break;
  445. case 'pps':
  446. url += '&yUnitSystem=si';
  447. break;
  448. case 'Bps':
  449. url += '&yUnitSystem=si';
  450. break;
  451. case 'short':
  452. url += '&yUnitSystem=si';
  453. break;
  454. case 'joule':
  455. url += '&yUnitSystem=si';
  456. break;
  457. case 'watt':
  458. url += '&yUnitSystem=si';
  459. break;
  460. case 'ev':
  461. url += '&yUnitSystem=si';
  462. break;
  463. case 'none':
  464. url += '&yUnitSystem=none';
  465. break;
  466. }
  467. switch(panel.nullPointMode) {
  468. case 'connected':
  469. url += '&lineMode=connected';
  470. break;
  471. case 'null':
  472. break; // graphite default lineMode
  473. case 'null as zero':
  474. url += "&drawNullAsZero=true";
  475. break;
  476. }
  477. url += panel.steppedLine ? '&lineMode=staircase' : '';
  478. elem.html('<img src="' + url + '"></img>');
  479. }
  480. new GraphTooltip(elem, dashboard, scope, function() {
  481. return sortedSeries;
  482. });
  483. elem.bind("plotselected", function (event, ranges) {
  484. scope.$apply(function() {
  485. timeSrv.setTime({
  486. from : moment.utc(ranges.xaxis.from),
  487. to : moment.utc(ranges.xaxis.to),
  488. });
  489. });
  490. });
  491. }
  492. };
  493. });
  494. });