grafanaGraph.js 13 KB

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