graph.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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(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;
  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(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() {
  217. try {
  218. $.plot(elem, sortedSeries, options);
  219. } catch (e) {
  220. console.log('flotcharts error', e);
  221. }
  222. }
  223. if (shouldDelayDraw(panel)) {
  224. // temp fix for legends on the side, need to render twice to get dimensions right
  225. callPlot();
  226. setTimeout(callPlot, 50);
  227. legendSideLastValue = panel.legend.rightSide;
  228. }
  229. else {
  230. callPlot();
  231. }
  232. }
  233. function translateFillOption(fill) {
  234. return fill === 0 ? 0.001 : fill/10;
  235. }
  236. function shouldDelayDraw(panel) {
  237. if (panel.legend.rightSide) {
  238. return true;
  239. }
  240. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  241. return true;
  242. }
  243. return false;
  244. }
  245. function addTimeAxis(options) {
  246. var ticks = elem.width() / 100;
  247. var min = _.isUndefined(scope.range.from) ? null : scope.range.from.getTime();
  248. var max = _.isUndefined(scope.range.to) ? null : scope.range.to.getTime();
  249. options.xaxis = {
  250. timezone: dashboard.timezone,
  251. show: scope.panel['x-axis'],
  252. mode: "time",
  253. min: min,
  254. max: max,
  255. label: "Datetime",
  256. ticks: ticks,
  257. timeformat: time_format(scope.interval, ticks, min, max),
  258. };
  259. }
  260. function addGridThresholds(options, panel) {
  261. if (_.isNumber(panel.grid.threshold1)) {
  262. var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null);
  263. options.grid.markings.push({
  264. yaxis: { from: panel.grid.threshold1, to: limit1 },
  265. color: panel.grid.threshold1Color
  266. });
  267. if (_.isNumber(panel.grid.threshold2)) {
  268. var limit2;
  269. if (panel.grid.thresholdLine) {
  270. limit2 = panel.grid.threshold2;
  271. } else {
  272. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  273. }
  274. options.grid.markings.push({
  275. yaxis: { from: panel.grid.threshold2, to: limit2 },
  276. color: panel.grid.threshold2Color
  277. });
  278. }
  279. }
  280. }
  281. function addAnnotations(options) {
  282. if(!annotations || annotations.length === 0) {
  283. return;
  284. }
  285. var types = {};
  286. _.each(annotations, function(event) {
  287. if (!types[event.annotation.name]) {
  288. types[event.annotation.name] = {
  289. level: _.keys(types).length + 1,
  290. icon: {
  291. icon: "fa fa-chevron-down",
  292. size: event.annotation.iconSize,
  293. color: event.annotation.iconColor,
  294. }
  295. };
  296. }
  297. if (event.annotation.showLine) {
  298. options.grid.markings.push({
  299. color: event.annotation.lineColor,
  300. lineWidth: 1,
  301. xaxis: { from: event.min, to: event.max }
  302. });
  303. }
  304. });
  305. options.events = {
  306. levels: _.keys(types).length + 1,
  307. data: annotations,
  308. types: types
  309. };
  310. }
  311. function configureAxisOptions(data, options) {
  312. var defaults = {
  313. position: 'left',
  314. show: scope.panel['y-axis'],
  315. min: scope.panel.grid.leftMin,
  316. index: 1,
  317. logBase: scope.panel.grid.leftLogBase || 1,
  318. max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.leftMax,
  319. };
  320. options.yaxes.push(defaults);
  321. if (_.findWhere(data, {yaxis: 2})) {
  322. var secondY = _.clone(defaults);
  323. secondY.index = 2,
  324. secondY.logBase = scope.panel.grid.rightLogBase || 2,
  325. secondY.position = 'right';
  326. secondY.min = scope.panel.grid.rightMin;
  327. secondY.max = scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.rightMax;
  328. options.yaxes.push(secondY);
  329. applyLogScale(options.yaxes[1], data);
  330. configureAxisMode(options.yaxes[1], scope.panel.y_formats[1]);
  331. }
  332. applyLogScale(options.yaxes[0], data);
  333. configureAxisMode(options.yaxes[0], scope.panel.y_formats[0]);
  334. }
  335. function applyLogScale(axis, data) {
  336. if (axis.logBase === 1) {
  337. return;
  338. }
  339. var series, i;
  340. var max = axis.max;
  341. if (max === null) {
  342. for (i = 0; i < data.length; i++) {
  343. series = data[i];
  344. if (series.yaxis === axis.index) {
  345. if (max < series.stats.max) {
  346. max = series.stats.max;
  347. }
  348. }
  349. }
  350. if (max === void 0) {
  351. max = Number.MAX_VALUE;
  352. }
  353. }
  354. axis.min = axis.min !== null ? axis.min : 0;
  355. axis.ticks = [0, 1];
  356. var nextTick = 1;
  357. while (true) {
  358. nextTick = nextTick * axis.logBase;
  359. axis.ticks.push(nextTick);
  360. if (nextTick > max) {
  361. break;
  362. }
  363. }
  364. if (axis.logBase === 10) {
  365. axis.transform = function(v) { return Math.log(v+0.1); };
  366. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  367. } else {
  368. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  369. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  370. }
  371. }
  372. function configureAxisMode(axis, format) {
  373. axis.tickFormatter = function(val, axis) {
  374. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  375. };
  376. }
  377. function time_format(interval, ticks, min, max) {
  378. if (min && max && ticks) {
  379. var secPerTick = ((max - min) / ticks) / 1000;
  380. if (secPerTick <= 45) {
  381. return "%H:%M:%S";
  382. }
  383. if (secPerTick <= 7200) {
  384. return "%H:%M";
  385. }
  386. if (secPerTick <= 80000) {
  387. return "%m/%d %H:%M";
  388. }
  389. if (secPerTick <= 2419200) {
  390. return "%m/%d";
  391. }
  392. return "%Y-%m";
  393. }
  394. return "%H:%M";
  395. }
  396. function render_panel_as_graphite_png(url) {
  397. url += '&width=' + elem.width();
  398. url += '&height=' + elem.css('height').replace('px', '');
  399. url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground
  400. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  401. url += scope.panel.stack ? '&areaMode=stacked' : '';
  402. url += scope.panel.fill !== 0 ? ('&areaAlpha=' + (scope.panel.fill/10).toFixed(1)) : '';
  403. url += scope.panel.linewidth !== 0 ? '&lineWidth=' + scope.panel.linewidth : '';
  404. url += scope.panel.legend.show ? '&hideLegend=false' : '&hideLegend=true';
  405. url += scope.panel.grid.leftMin !== null ? '&yMin=' + scope.panel.grid.leftMin : '';
  406. url += scope.panel.grid.leftMax !== null ? '&yMax=' + scope.panel.grid.leftMax : '';
  407. url += scope.panel.grid.rightMin !== null ? '&yMin=' + scope.panel.grid.rightMin : '';
  408. url += scope.panel.grid.rightMax !== null ? '&yMax=' + scope.panel.grid.rightMax : '';
  409. url += scope.panel['x-axis'] ? '' : '&hideAxes=true';
  410. url += scope.panel['y-axis'] ? '' : '&hideYAxis=true';
  411. switch(scope.panel.y_formats[0]) {
  412. case 'bytes':
  413. url += '&yUnitSystem=binary';
  414. break;
  415. case 'bits':
  416. url += '&yUnitSystem=binary';
  417. break;
  418. case 'bps':
  419. url += '&yUnitSystem=si';
  420. break;
  421. case 'Bps':
  422. url += '&yUnitSystem=si';
  423. break;
  424. case 'short':
  425. url += '&yUnitSystem=si';
  426. break;
  427. case 'joule':
  428. url += '&yUnitSystem=si';
  429. break;
  430. case 'watt':
  431. url += '&yUnitSystem=si';
  432. break;
  433. case 'ev':
  434. url += '&yUnitSystem=si';
  435. break;
  436. case 'none':
  437. url += '&yUnitSystem=none';
  438. break;
  439. }
  440. switch(scope.panel.nullPointMode) {
  441. case 'connected':
  442. url += '&lineMode=connected';
  443. break;
  444. case 'null':
  445. break; // graphite default lineMode
  446. case 'null as zero':
  447. url += "&drawNullAsZero=true";
  448. break;
  449. }
  450. url += scope.panel.steppedLine ? '&lineMode=staircase' : '';
  451. elem.html('<img src="' + url + '"></img>');
  452. }
  453. new GraphTooltip(elem, dashboard, scope, function() {
  454. return sortedSeries;
  455. });
  456. elem.bind("plotselected", function (event, ranges) {
  457. scope.$apply(function() {
  458. timeSrv.setTime({
  459. from : moment.utc(ranges.xaxis.from).toDate(),
  460. to : moment.utc(ranges.xaxis.to).toDate(),
  461. });
  462. });
  463. });
  464. }
  465. };
  466. });
  467. });