graph.js 17 KB

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