grafanaGraph.js 13 KB

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