grafanaGraph.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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 (scope.otherPanelInFullscreenMode()) { return; }
  20. scope.get_data();
  21. });
  22. scope.$on('toggleLegend', function(e, alias) {
  23. if (hiddenData[alias]) {
  24. data.push(hiddenData[alias]);
  25. delete hiddenData[alias];
  26. }
  27. render_panel();
  28. });
  29. // Receive render events
  30. scope.$on('render',function(event, d) {
  31. data = d || data;
  32. render_panel();
  33. });
  34. // Re-render if the window is resized
  35. angular.element(window).bind('resize', function() {
  36. render_panel();
  37. });
  38. function setElementHeight() {
  39. try {
  40. elem.css({ height: scope.height || scope.panel.height || scope.row.height });
  41. return true;
  42. } catch(e) { // IE throws errors sometimes
  43. return false;
  44. }
  45. }
  46. // Function for rendering panel
  47. function render_panel() {
  48. if (!data) { return; }
  49. if (scope.otherPanelInFullscreenMode()) { return; }
  50. if (!setElementHeight()) { return; }
  51. if (_.isString(data)) {
  52. render_panel_as_graphite_png(data);
  53. return;
  54. }
  55. var panel = scope.panel;
  56. _.each(_.keys(scope.hiddenSeries), function(seriesAlias) {
  57. var dataSeries = _.find(data, function(series) {
  58. return series.info.alias === seriesAlias;
  59. });
  60. if (dataSeries) {
  61. hiddenData[dataSeries.info.alias] = dataSeries;
  62. data = _.without(data, dataSeries);
  63. }
  64. });
  65. var stack = panel.stack ? true : null;
  66. // Populate element
  67. var options = {
  68. legend: { show: false },
  69. series: {
  70. stackpercent: panel.stack ? panel.percentage : false,
  71. stack: panel.percentage ? null : stack,
  72. lines: {
  73. show: panel.lines,
  74. zero: false,
  75. fill: panel.fill === 0 ? 0.001 : panel.fill/10,
  76. lineWidth: panel.linewidth,
  77. steps: panel.steppedLine
  78. },
  79. bars: {
  80. show: panel.bars,
  81. fill: 1,
  82. barWidth: 1,
  83. zero: false,
  84. lineWidth: 0
  85. },
  86. points: {
  87. show: panel.points,
  88. fill: 1,
  89. fillColor: false,
  90. radius: panel.pointradius
  91. },
  92. shadowSize: 1
  93. },
  94. yaxes: [],
  95. xaxis: {},
  96. grid: {
  97. markings: [],
  98. backgroundColor: null,
  99. borderWidth: 0,
  100. hoverable: true,
  101. color: '#c8c8c8'
  102. },
  103. selection: {
  104. mode: "x",
  105. color: '#666'
  106. }
  107. };
  108. for (var i = 0; i < data.length; i++) {
  109. var _d = data[i].getFlotPairs(panel.nullPointMode, panel.y_formats);
  110. data[i].data = _d;
  111. }
  112. if (panel.bars && data.length && data[0].info.timeStep) {
  113. options.series.bars.barWidth = data[0].info.timeStep / 1.5;
  114. }
  115. addTimeAxis(options);
  116. addGridThresholds(options, panel);
  117. addAnnotations(options);
  118. configureAxisOptions(data, options);
  119. plot = $.plot(elem, data, options);
  120. addAxisLabels();
  121. }
  122. function addTimeAxis(options) {
  123. var ticks = elem.width() / 100;
  124. var min = _.isUndefined(scope.range.from) ? null : scope.range.from.getTime();
  125. var max = _.isUndefined(scope.range.to) ? null : scope.range.to.getTime();
  126. options.xaxis = {
  127. timezone: dashboard.current.timezone,
  128. show: scope.panel['x-axis'],
  129. mode: "time",
  130. min: min,
  131. max: max,
  132. label: "Datetime",
  133. ticks: ticks,
  134. timeformat: time_format(scope.interval, ticks, min, max),
  135. };
  136. }
  137. function addGridThresholds(options, panel) {
  138. if (panel.grid.threshold1) {
  139. var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null);
  140. options.grid.markings.push({
  141. yaxis: { from: panel.grid.threshold1, to: limit1 },
  142. color: panel.grid.threshold1Color
  143. });
  144. if (panel.grid.threshold2) {
  145. var limit2;
  146. if (panel.grid.thresholdLine) {
  147. limit2 = panel.grid.threshold2;
  148. } else {
  149. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  150. }
  151. options.grid.markings.push({
  152. yaxis: { from: panel.grid.threshold2, to: limit2 },
  153. color: panel.grid.threshold2Color
  154. });
  155. }
  156. }
  157. }
  158. function addAnnotations(options) {
  159. if(!data.annotations || data.annotations.length === 0) {
  160. return;
  161. }
  162. var types = {};
  163. _.each(data.annotations, function(event) {
  164. if (!types[event.annotation.name]) {
  165. types[event.annotation.name] = {
  166. level: _.keys(types).length + 1,
  167. icon: {
  168. icon: "icon-chevron-down",
  169. size: event.annotation.iconSize,
  170. color: event.annotation.iconColor,
  171. }
  172. };
  173. }
  174. if (event.annotation.showLine) {
  175. options.grid.markings.push({
  176. color: event.annotation.lineColor,
  177. lineWidth: 1,
  178. xaxis: { from: event.min, to: event.max }
  179. });
  180. }
  181. });
  182. options.events = {
  183. levels: _.keys(types).length + 1,
  184. data: data.annotations,
  185. types: types
  186. };
  187. }
  188. function addAxisLabels() {
  189. if (scope.panel.leftYAxisLabel) {
  190. elem.css('margin-left', '10px');
  191. var yaxisLabel = $("<div class='axisLabel yaxisLabel'></div>")
  192. .text(scope.panel.leftYAxisLabel)
  193. .appendTo(elem);
  194. yaxisLabel.css("margin-top", yaxisLabel.width() / 2 - 20);
  195. } else if (elem.css('margin-left')) {
  196. elem.css('margin-left', '');
  197. }
  198. }
  199. function configureAxisOptions(data, options) {
  200. var defaults = {
  201. position: 'left',
  202. show: scope.panel['y-axis'],
  203. min: scope.panel.grid.min,
  204. max: scope.panel.percentage && scope.panel.stack ? 100 : scope.panel.grid.max,
  205. };
  206. options.yaxes.push(defaults);
  207. if (_.findWhere(data, {yaxis: 2})) {
  208. var secondY = _.clone(defaults);
  209. secondY.position = 'right';
  210. options.yaxes.push(secondY);
  211. configureAxisMode(options.yaxes[1], scope.panel.y_formats[1]);
  212. }
  213. configureAxisMode(options.yaxes[0], scope.panel.y_formats[0]);
  214. }
  215. function configureAxisMode(axis, format) {
  216. if (format === 'bytes') {
  217. axis.mode = 'byte';
  218. }
  219. else if (format !== 'none') {
  220. axis.tickFormatter = kbn.getFormatFunction(format, 1);
  221. }
  222. }
  223. function time_format(interval, ticks, min, max) {
  224. if (min && max && ticks) {
  225. var secPerTick = ((max - min) / ticks) / 1000;
  226. if (secPerTick <= 45) {
  227. return "%H:%M:%S";
  228. }
  229. if (secPerTick <= 3600) {
  230. return "%H:%M";
  231. }
  232. if (secPerTick <= 80000) {
  233. return "%m/%d %H:%M";
  234. }
  235. if (secPerTick <= 2419200) {
  236. return "%m/%d";
  237. }
  238. return "%Y-%m";
  239. }
  240. return "%H:%M";
  241. }
  242. var $tooltip = $('<div>');
  243. elem.bind("plothover", function (event, pos, item) {
  244. var group, value, timestamp, seriesInfo, format;
  245. if (item) {
  246. seriesInfo = item.series.info;
  247. format = scope.panel.y_formats[seriesInfo.yaxis - 1];
  248. if (seriesInfo.alias) {
  249. group = '<small style="font-size:0.9em;">' +
  250. '<i class="icon-circle" style="color:'+item.series.color+';"></i>' + ' ' +
  251. (seriesInfo.alias || seriesInfo.query)+
  252. '</small><br>';
  253. } else {
  254. group = kbn.query_color_dot(item.series.color, 15) + ' ';
  255. }
  256. if (scope.panel.stack && scope.panel.tooltip.value_type === 'individual') {
  257. value = item.datapoint[1] - item.datapoint[2];
  258. }
  259. else {
  260. value = item.datapoint[1];
  261. }
  262. value = kbn.getFormatFunction(format, 2)(value);
  263. timestamp = dashboard.current.timezone === 'browser' ?
  264. moment(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss') :
  265. moment.utc(item.datapoint[0]).format('YYYY-MM-DD HH:mm:ss');
  266. $tooltip
  267. .html(
  268. group + value + " @ " + timestamp
  269. )
  270. .place_tt(pos.pageX, pos.pageY);
  271. } else {
  272. $tooltip.detach();
  273. }
  274. });
  275. function render_panel_as_graphite_png(url) {
  276. url += '&width=' + elem.width();
  277. url += '&height=' + elem.css('height').replace('px', '');
  278. url += '&bgcolor=1f1f1f'; // @grayDarker & @kibanaPanelBackground
  279. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  280. url += scope.panel.stack ? '&areaMode=stacked' : '';
  281. url += scope.panel.fill !== 0 ? ('&areaAlpha=' + (scope.panel.fill/10).toFixed(1)) : '';
  282. url += scope.panel.linewidth !== 0 ? '&lineWidth=' + scope.panel.linewidth : '';
  283. url += scope.panel.legend ? '' : '&hideLegend=true';
  284. url += scope.panel.grid.min !== null ? '&yMin=' + scope.panel.grid.min : '';
  285. url += scope.panel.grid.max !== null ? '&yMax=' + scope.panel.grid.max : '';
  286. url += scope.panel['x-axis'] ? '' : '&hideAxes=true';
  287. url += scope.panel['y-axis'] ? '' : '&hideYAxis=true';
  288. switch(scope.panel.y_formats[0]) {
  289. case 'bytes':
  290. url += '&yUnitSystem=binary';
  291. break;
  292. case 'short':
  293. url += '&yUnitSystem=si';
  294. break;
  295. case 'none':
  296. url += '&yUnitSystem=none';
  297. break;
  298. }
  299. switch(scope.panel.nullPointMode) {
  300. case 'connected':
  301. url += '&lineMode=connected';
  302. break;
  303. case 'null':
  304. break; // graphite default lineMode
  305. case 'null as zero':
  306. url += "&drawNullAsZero=true";
  307. break;
  308. }
  309. url += scope.panel.steppedLine ? '&lineMode=staircase' : '';
  310. elem.html('<img src="' + url + '"></img>');
  311. }
  312. elem.bind("plotselected", function (event, ranges) {
  313. filterSrv.setTime({
  314. from : moment.utc(ranges.xaxis.from).toDate(),
  315. to : moment.utc(ranges.xaxis.to).toDate(),
  316. });
  317. });
  318. }
  319. };
  320. });
  321. });