graph.js 16 KB

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