grafanaGraph.js 12 KB

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