graph.js 17 KB

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