graph.js 17 KB

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