grafanaGraph.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'kbn',
  5. 'moment',
  6. 'underscore'
  7. ],
  8. function (angular, $, kbn, moment, _) {
  9. 'use strict';
  10. var module = angular.module('kibana.directives');
  11. module.directive('grafanaGraph', function(filterSrv, $rootScope, dashboard) {
  12. return {
  13. restrict: 'A',
  14. template: '<div> </div>',
  15. link: function(scope, elem) {
  16. var data, plot;
  17. var hiddenData = {};
  18. scope.$on('refresh',function() {
  19. if ($rootScope.fullscreen && !scope.fullscreen) {
  20. return;
  21. }
  22. scope.get_data();
  23. });
  24. scope.$on('toggleLegend', function(e, alias) {
  25. if (hiddenData[alias]) {
  26. data.push(hiddenData[alias]);
  27. delete hiddenData[alias];
  28. }
  29. render_panel();
  30. });
  31. // Receive render events
  32. scope.$on('render',function(event, d) {
  33. data = d || data;
  34. render_panel();
  35. });
  36. // Re-render if the window is resized
  37. angular.element(window).bind('resize', function() {
  38. render_panel();
  39. });
  40. function setElementHeight() {
  41. try {
  42. elem.css({ height: scope.height || scope.panel.height || scope.row.height });
  43. return true;
  44. } catch(e) { // IE throws errors sometimes
  45. return false;
  46. }
  47. }
  48. // Function for rendering panel
  49. function render_panel() {
  50. if (!data) { return; }
  51. if (!setElementHeight()) { return; }
  52. if (_.isString(data)) {
  53. render_panel_as_graphite_png(data);
  54. return;
  55. }
  56. _.each(data, function(series) {
  57. series.label = series.info.alias;
  58. series.color = series.info.color;
  59. });
  60. _.each(_.keys(scope.hiddenSeries), function(seriesAlias) {
  61. var dataSeries = _.find(data, function(series) {
  62. return series.info.alias === seriesAlias;
  63. });
  64. if (dataSeries) {
  65. hiddenData[dataSeries.info.alias] = dataSeries;
  66. data = _.without(data, dataSeries);
  67. }
  68. });
  69. // Set barwidth based on specified interval
  70. var barwidth = kbn.interval_to_ms(scope.panel.interval);
  71. var stack = scope.panel.stack ? true : null;
  72. // Populate element
  73. var options = {
  74. legend: { show: false },
  75. series: {
  76. stackpercent: scope.panel.stack ? scope.panel.percentage : false,
  77. stack: scope.panel.percentage ? null : stack,
  78. lines: {
  79. show: scope.panel.lines,
  80. // Silly, but fixes bug in stacked percentages
  81. fill: scope.panel.fill === 0 ? 0.001 : scope.panel.fill/10,
  82. lineWidth: scope.panel.linewidth,
  83. steps: scope.panel.steppedLine
  84. },
  85. bars: {
  86. show: scope.panel.bars,
  87. fill: 1,
  88. barWidth: barwidth/1.5,
  89. zero: false,
  90. lineWidth: 0
  91. },
  92. points: {
  93. show: scope.panel.points,
  94. fill: 1,
  95. fillColor: false,
  96. radius: scope.panel.pointradius
  97. },
  98. shadowSize: 1
  99. },
  100. yaxes: [],
  101. xaxis: {
  102. timezone: dashboard.current.timezone,
  103. show: scope.panel['x-axis'],
  104. mode: "time",
  105. min: _.isUndefined(scope.range.from) ? null : scope.range.from.getTime(),
  106. max: _.isUndefined(scope.range.to) ? null : scope.range.to.getTime(),
  107. timeformat: time_format(scope.panel.interval),
  108. label: "Datetime",
  109. ticks: elem.width()/100
  110. },
  111. grid: {
  112. backgroundColor: null,
  113. borderWidth: 0,
  114. hoverable: true,
  115. color: '#c8c8c8'
  116. },
  117. selection: {
  118. mode: "x",
  119. color: '#666'
  120. }
  121. };
  122. addAnnotations(options);
  123. // when rendering stacked bars, we need to ensure each point that has data is zero-filled
  124. // so that the stacking happens in the proper order
  125. var required_times = [];
  126. if (data.length > 1) {
  127. required_times = Array.prototype.concat.apply([], _.map(data, function (query) {
  128. return query.time_series.getOrderedTimes();
  129. }));
  130. required_times = _.uniq(required_times.sort(function (a, b) {
  131. // decending numeric sort
  132. return a-b;
  133. }), true);
  134. }
  135. for (var i = 0; i < data.length; i++) {
  136. var _d = data[i].time_series.getFlotPairs(required_times, scope.panel.nullPointMode);
  137. data[i].yaxis = data[i].info.yaxis;
  138. data[i].data = _d;
  139. data[i].info.y_format = data[i].yaxis === 1 ? scope.panel.y_format : scope.panel.y2_format;
  140. }
  141. configureAxisOptions(data, options);
  142. plot = $.plot(elem, data, options);
  143. addAxisLabels();
  144. }
  145. function render_panel_as_graphite_png(url) {
  146. url += '&width=' + elem.width();
  147. url += '&height=' + elem.css('height').replace('px', '');
  148. url += '&bgcolor=1f1f1f'; // @grayDarker & @kibanaPanelBackground
  149. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  150. url += scope.panel.stack ? '&areaMode=stacked' : '';
  151. url += scope.panel.fill !== 0 ? ('&areaAlpha=' + (scope.panel.fill/10).toFixed(1)) : '';
  152. url += scope.panel.linewidth !== 0 ? '&lineWidth=' + scope.panel.linewidth : '';
  153. url += scope.panel.legend ? '' : '&hideLegend=true';
  154. url += scope.panel.grid.min ? '&yMin=' + scope.panel.grid.min : '';
  155. url += scope.panel.grid.max ? '&yMax=' + scope.panel.grid.max : '';
  156. url += scope.panel['x-axis'] ? '' : '&hideAxes=true';
  157. url += scope.panel['y-axis'] ? '' : '&hideYAxis=true';
  158. switch(scope.panel.y_format) {
  159. case 'bytes':
  160. url += '&yUnitSystem=binary';
  161. break;
  162. case 'short':
  163. url += '&yUnitSystem=si';
  164. break;
  165. case 'none':
  166. url += '&yUnitSystem=none';
  167. break;
  168. }
  169. switch(scope.panel.nullPointMode) {
  170. case 'connected':
  171. url += '&lineMode=connected';
  172. break;
  173. case 'null':
  174. break; // graphite default lineMode
  175. case 'null as zero':
  176. url += "&drawNullAsZero=true";
  177. break;
  178. }
  179. url += scope.panel.steppedLine ? '&lineMode=staircase' : '';
  180. elem.html('<img src="' + url + '"></img>');
  181. }
  182. function addAnnotations(options) {
  183. if(scope.panel.annotate.enable) {
  184. options.events = {
  185. levels: 1,
  186. data: scope.annotations,
  187. types: {
  188. 'annotation': {
  189. level: 1,
  190. icon: {
  191. icon: "icon-tag icon-flip-vertical",
  192. size: 20,
  193. color: "#222",
  194. outline: "#bbb"
  195. }
  196. }
  197. }
  198. };
  199. }
  200. }
  201. function addAxisLabels() {
  202. if (scope.panel.leftYAxisLabel) {
  203. elem.css('margin-left', '10px');
  204. var yaxisLabel = $("<div class='axisLabel yaxisLabel'></div>")
  205. .text(scope.panel.leftYAxisLabel)
  206. .appendTo(elem);
  207. yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
  208. } else if (elem.css('margin-left')) {
  209. elem.css('margin-left', '');
  210. }
  211. }
  212. function configureAxisOptions(data, options) {
  213. var defaults = {
  214. position: 'left',
  215. show: scope.panel['y-axis'],
  216. min: scope.panel.grid.min,
  217. max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.max,
  218. };
  219. options.yaxes.push(defaults);
  220. if (_.findWhere(data, {yaxis: 2})) {
  221. var secondY = _.clone(defaults);
  222. secondY.position = 'right';
  223. options.yaxes.push(secondY);
  224. configureAxisMode(options.yaxes[1], scope.panel.y2_format);
  225. }
  226. configureAxisMode(options.yaxes[0], scope.panel.y_format);
  227. }
  228. function configureAxisMode(axis, format) {
  229. if (format === 'bytes') {
  230. axis.mode = "byte";
  231. }
  232. if (format === 'short') {
  233. axis.tickFormatter = function(val) {
  234. return kbn.shortFormat(val,0);
  235. };
  236. }
  237. if (format === 'ms') {
  238. axis.tickFormatter = kbn.msFormat;
  239. }
  240. }
  241. function time_format(interval) {
  242. var _int = kbn.interval_to_seconds(interval);
  243. if(_int >= 2628000) {
  244. return "%Y-%m";
  245. }
  246. if(_int >= 10000) {
  247. return "%Y-%m-%d";
  248. }
  249. if(_int >= 60) {
  250. return "%H:%M<br>%m-%d";
  251. }
  252. return "%H:%M:%S";
  253. }
  254. var $tooltip = $('<div>');
  255. elem.bind("plothover", function (event, pos, item) {
  256. var group, value, timestamp;
  257. if (item) {
  258. if (item.series.info.alias || scope.panel.tooltip.query_as_alias) {
  259. group = '<small style="font-size:0.9em;">' +
  260. '<i class="icon-circle" style="color:'+item.series.color+';"></i>' + ' ' +
  261. (item.series.info.alias || item.series.info.query)+
  262. '</small><br>';
  263. } else {
  264. group = kbn.query_color_dot(item.series.color, 15) + ' ';
  265. }
  266. value = (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') ?
  267. item.datapoint[1] - item.datapoint[2] :
  268. item.datapoint[1];
  269. if(item.series.info.y_format === 'bytes') {
  270. value = kbn.byteFormat(value,2);
  271. }
  272. if(item.series.info.y_format === 'short') {
  273. value = kbn.shortFormat(value,2);
  274. }
  275. if(item.series.info.y_format === 'ms') {
  276. value = kbn.msFormat(value);
  277. }
  278. timestamp = dashboard.current.timezone === 'browser' ?
  279. moment(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss') :
  280. moment.utc(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss');
  281. $tooltip
  282. .html(
  283. group + value + " @ " + timestamp
  284. )
  285. .place_tt(pos.pageX, pos.pageY);
  286. } else {
  287. $tooltip.detach();
  288. }
  289. });
  290. elem.bind("plotselected", function (event, ranges) {
  291. filterSrv.setTime({
  292. from : moment.utc(ranges.xaxis.from).toDate(),
  293. to : moment.utc(ranges.xaxis.to).toDate(),
  294. });
  295. });
  296. }
  297. };
  298. });
  299. });