graph.js 17 KB

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