grafanaGraph.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'kbn',
  5. 'moment',
  6. 'lodash',
  7. './grafanaGraph.tooltip'
  8. ],
  9. function (angular, $, kbn, moment, _, GraphTooltip) {
  10. 'use strict';
  11. var module = angular.module('grafana.directives');
  12. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  13. return {
  14. restrict: 'A',
  15. template: '<div> </div>',
  16. link: function(scope, elem) {
  17. var dashboard = scope.dashboard;
  18. var data, annotations;
  19. var legendSideLastValue = null;
  20. scope.crosshairEmiter = false;
  21. scope.onAppEvent('setCrosshair', function(event, info) {
  22. // do not need to to this if event is from this panel
  23. if (info.scope === scope) {
  24. return;
  25. }
  26. if(dashboard.sharedCrosshair) {
  27. var plot = elem.data().plot;
  28. if (plot) {
  29. plot.setCrosshair({ x: info.pos.x, y: info.pos.y });
  30. }
  31. }
  32. });
  33. scope.onAppEvent('clearCrosshair', function() {
  34. var plot = elem.data().plot;
  35. if (plot) {
  36. plot.clearCrosshair();
  37. }
  38. });
  39. scope.$on('refresh', function() {
  40. scope.get_data();
  41. });
  42. // Receive render events
  43. scope.$on('render',function(event, renderData) {
  44. data = renderData || data;
  45. if (!data) {
  46. scope.get_data();
  47. return;
  48. }
  49. annotations = data.annotations || annotations;
  50. render_panel();
  51. });
  52. function setElementHeight() {
  53. try {
  54. var height = scope.height || scope.panel.height || scope.row.height;
  55. if (_.isString(height)) {
  56. height = parseInt(height.replace('px', ''), 10);
  57. }
  58. height -= scope.panel.title ? 24 : 9; // subtract panel title bar
  59. if (scope.panel.legend.show && !scope.panel.legend.rightSide) {
  60. height = height - 21; // subtract one line legend
  61. }
  62. elem.css('height', height + 'px');
  63. return true;
  64. } catch(e) { // IE throws errors sometimes
  65. return false;
  66. }
  67. }
  68. function shouldAbortRender() {
  69. if (!data) {
  70. return true;
  71. }
  72. if ($rootScope.fullscreen && !scope.fullscreen) {
  73. return true;
  74. }
  75. if (!setElementHeight()) { return true; }
  76. if (_.isString(data)) {
  77. render_panel_as_graphite_png(data);
  78. return true;
  79. }
  80. if (elem.width() === 0) {
  81. return;
  82. }
  83. }
  84. function updateLegendValues(plot) {
  85. var yaxis = plot.getYAxes();
  86. for (var i = 0; i < data.length; i++) {
  87. var series = data[i];
  88. var axis = yaxis[series.yaxis - 1];
  89. var formater = kbn.valueFormats[scope.panel.y_formats[series.yaxis - 1]];
  90. series.updateLegendValues(formater, axis.tickDecimals, axis.scaledDecimals+ 2);
  91. if(!scope.$$phase) { scope.$digest(); }
  92. }
  93. }
  94. // Function for rendering panel
  95. function render_panel() {
  96. if (shouldAbortRender()) {
  97. return;
  98. }
  99. var panel = scope.panel;
  100. var stack = panel.stack ? true : null;
  101. // Populate element
  102. var options = {
  103. hooks: { draw: [updateLegendValues] },
  104. legend: { show: false },
  105. series: {
  106. stackpercent: panel.stack ? panel.percentage : false,
  107. stack: panel.percentage ? null : stack,
  108. lines: {
  109. show: panel.lines,
  110. zero: false,
  111. fill: translateFillOption(panel.fill),
  112. lineWidth: panel.linewidth,
  113. steps: panel.steppedLine
  114. },
  115. bars: {
  116. show: panel.bars,
  117. fill: 1,
  118. barWidth: 1,
  119. zero: false,
  120. lineWidth: 0
  121. },
  122. points: {
  123. show: panel.points,
  124. fill: 1,
  125. fillColor: false,
  126. radius: panel.points ? panel.pointradius : 2
  127. // little points when highlight points
  128. },
  129. shadowSize: 1
  130. },
  131. yaxes: [],
  132. xaxis: {},
  133. grid: {
  134. minBorderMargin: 0,
  135. markings: [],
  136. backgroundColor: null,
  137. borderWidth: 0,
  138. hoverable: true,
  139. color: '#c8c8c8'
  140. },
  141. selection: {
  142. mode: "x",
  143. color: '#666'
  144. },
  145. crosshair: {
  146. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  147. }
  148. };
  149. for (var i = 0; i < data.length; i++) {
  150. var series = data[i];
  151. series.applySeriesOverrides(panel.seriesOverrides);
  152. series.data = series.getFlotPairs(panel.nullPointMode, panel.y_formats);
  153. // if hidden remove points and disable stack
  154. if (scope.hiddenSeries[series.alias]) {
  155. series.data = [];
  156. series.stack = false;
  157. }
  158. }
  159. if (data.length && data[0].stats.timeStep) {
  160. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  161. }
  162. addTimeAxis(options);
  163. addGridThresholds(options, panel);
  164. addAnnotations(options);
  165. configureAxisOptions(data, options);
  166. var sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  167. function callPlot() {
  168. try {
  169. $.plot(elem, sortedSeries, options);
  170. } catch (e) {
  171. console.log('flotcharts error', e);
  172. }
  173. addAxisLabels();
  174. }
  175. if (shouldDelayDraw(panel)) {
  176. // temp fix for legends on the side, need to render twice to get dimensions right
  177. callPlot();
  178. setTimeout(callPlot, 50);
  179. legendSideLastValue = panel.legend.rightSide;
  180. }
  181. else {
  182. callPlot();
  183. }
  184. }
  185. function translateFillOption(fill) {
  186. return fill === 0 ? 0.001 : fill/10;
  187. }
  188. function shouldDelayDraw(panel) {
  189. if (panel.legend.rightSide) {
  190. return true;
  191. }
  192. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  193. return true;
  194. }
  195. return false;
  196. }
  197. function addTimeAxis(options) {
  198. var ticks = elem.width() / 100;
  199. var min = _.isUndefined(scope.range.from) ? null : scope.range.from.getTime();
  200. var max = _.isUndefined(scope.range.to) ? null : scope.range.to.getTime();
  201. options.xaxis = {
  202. timezone: dashboard.timezone,
  203. show: scope.panel['x-axis'],
  204. mode: "time",
  205. min: min,
  206. max: max,
  207. label: "Datetime",
  208. ticks: ticks,
  209. timeformat: time_format(scope.interval, ticks, min, max),
  210. };
  211. }
  212. function addGridThresholds(options, panel) {
  213. if (panel.grid.threshold1) {
  214. var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null);
  215. options.grid.markings.push({
  216. yaxis: { from: panel.grid.threshold1, to: limit1 },
  217. color: panel.grid.threshold1Color
  218. });
  219. if (panel.grid.threshold2) {
  220. var limit2;
  221. if (panel.grid.thresholdLine) {
  222. limit2 = panel.grid.threshold2;
  223. } else {
  224. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  225. }
  226. options.grid.markings.push({
  227. yaxis: { from: panel.grid.threshold2, to: limit2 },
  228. color: panel.grid.threshold2Color
  229. });
  230. }
  231. }
  232. }
  233. function addAnnotations(options) {
  234. if(!annotations || annotations.length === 0) {
  235. return;
  236. }
  237. var types = {};
  238. _.each(annotations, function(event) {
  239. if (!types[event.annotation.name]) {
  240. types[event.annotation.name] = {
  241. level: _.keys(types).length + 1,
  242. icon: {
  243. icon: "icon-chevron-down",
  244. size: event.annotation.iconSize,
  245. color: event.annotation.iconColor,
  246. }
  247. };
  248. }
  249. if (event.annotation.showLine) {
  250. options.grid.markings.push({
  251. color: event.annotation.lineColor,
  252. lineWidth: 1,
  253. xaxis: { from: event.min, to: event.max }
  254. });
  255. }
  256. });
  257. options.events = {
  258. levels: _.keys(types).length + 1,
  259. data: annotations,
  260. types: types
  261. };
  262. }
  263. function addAxisLabels() {
  264. if (scope.panel.leftYAxisLabel) {
  265. elem.css('margin-left', '10px');
  266. var yaxisLabel = $("<div class='axisLabel yaxisLabel'></div>")
  267. .text(scope.panel.leftYAxisLabel)
  268. .appendTo(elem);
  269. yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
  270. } else if (elem.css('margin-left')) {
  271. elem.css('margin-left', '');
  272. }
  273. }
  274. function configureAxisOptions(data, options) {
  275. var defaults = {
  276. position: 'left',
  277. show: scope.panel['y-axis'],
  278. min: scope.panel.grid.leftMin,
  279. max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.leftMax,
  280. };
  281. options.yaxes.push(defaults);
  282. if (_.findWhere(data, {yaxis: 2})) {
  283. var secondY = _.clone(defaults);
  284. secondY.position = 'right';
  285. secondY.min = scope.panel.grid.rightMin;
  286. secondY.max = scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.rightMax;
  287. options.yaxes.push(secondY);
  288. configureAxisMode(options.yaxes[1], scope.panel.y_formats[1]);
  289. }
  290. configureAxisMode(options.yaxes[0], scope.panel.y_formats[0]);
  291. }
  292. function configureAxisMode(axis, format) {
  293. axis.tickFormatter = function(val, axis) {
  294. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  295. };
  296. }
  297. function time_format(interval, ticks, min, max) {
  298. if (min && max && ticks) {
  299. var secPerTick = ((max - min) / ticks) / 1000;
  300. if (secPerTick <= 45) {
  301. return "%H:%M:%S";
  302. }
  303. if (secPerTick <= 3600) {
  304. return "%H:%M";
  305. }
  306. if (secPerTick <= 80000) {
  307. return "%m/%d %H:%M";
  308. }
  309. if (secPerTick <= 2419200) {
  310. return "%m/%d";
  311. }
  312. return "%Y-%m";
  313. }
  314. return "%H:%M";
  315. }
  316. function render_panel_as_graphite_png(url) {
  317. url += '&width=' + elem.width();
  318. url += '&height=' + elem.css('height').replace('px', '');
  319. url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground
  320. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  321. url += scope.panel.stack ? '&areaMode=stacked' : '';
  322. url += scope.panel.fill !== 0 ? ('&areaAlpha=' + (scope.panel.fill/10).toFixed(1)) : '';
  323. url += scope.panel.linewidth !== 0 ? '&lineWidth=' + scope.panel.linewidth : '';
  324. url += scope.panel.legend.show ? '&hideLegend=false' : '&hideLegend=true';
  325. url += scope.panel.grid.leftMin !== null ? '&yMin=' + scope.panel.grid.leftMin : '';
  326. url += scope.panel.grid.leftMax !== null ? '&yMax=' + scope.panel.grid.leftMax : '';
  327. url += scope.panel.grid.rightMin !== null ? '&yMin=' + scope.panel.grid.rightMin : '';
  328. url += scope.panel.grid.rightMax !== null ? '&yMax=' + scope.panel.grid.rightMax : '';
  329. url += scope.panel['x-axis'] ? '' : '&hideAxes=true';
  330. url += scope.panel['y-axis'] ? '' : '&hideYAxis=true';
  331. switch(scope.panel.y_formats[0]) {
  332. case 'bytes':
  333. url += '&yUnitSystem=binary';
  334. break;
  335. case 'bits':
  336. url += '&yUnitSystem=binary';
  337. break;
  338. case 'bps':
  339. url += '&yUnitSystem=si';
  340. break;
  341. case 'short':
  342. url += '&yUnitSystem=si';
  343. break;
  344. case 'none':
  345. url += '&yUnitSystem=none';
  346. break;
  347. }
  348. switch(scope.panel.nullPointMode) {
  349. case 'connected':
  350. url += '&lineMode=connected';
  351. break;
  352. case 'null':
  353. break; // graphite default lineMode
  354. case 'null as zero':
  355. url += "&drawNullAsZero=true";
  356. break;
  357. }
  358. url += scope.panel.steppedLine ? '&lineMode=staircase' : '';
  359. elem.html('<img src="' + url + '"></img>');
  360. }
  361. new GraphTooltip(elem, dashboard, scope, function() {
  362. return data;
  363. });
  364. elem.bind("plotselected", function (event, ranges) {
  365. scope.$apply(function() {
  366. timeSrv.setTime({
  367. from : moment.utc(ranges.xaxis.from).toDate(),
  368. to : moment.utc(ranges.xaxis.to).toDate(),
  369. });
  370. });
  371. });
  372. }
  373. };
  374. });
  375. });