graph.js 17 KB

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