graph.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'moment',
  5. 'lodash',
  6. 'app/core/utils/kbn',
  7. './graph_tooltip',
  8. 'jquery.flot',
  9. 'jquery.flot.selection',
  10. 'jquery.flot.time',
  11. 'jquery.flot.stack',
  12. 'jquery.flot.stackpercent',
  13. 'jquery.flot.fillbelow',
  14. 'jquery.flot.crosshair',
  15. './jquery.flot.events',
  16. ],
  17. function (angular, $, moment, _, kbn, GraphTooltip) {
  18. 'use strict';
  19. var module = angular.module('grafana.directives');
  20. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  21. return {
  22. restrict: 'A',
  23. template: '<div> </div>',
  24. link: function(scope, elem) {
  25. var ctrl = scope.ctrl;
  26. var dashboard = ctrl.dashboard;
  27. var panel = ctrl.panel;
  28. var data, annotations;
  29. var sortedSeries;
  30. var graphHeight;
  31. var legendSideLastValue = null;
  32. var rootScope = scope.$root;
  33. rootScope.onAppEvent('setCrosshair', function(event, info) {
  34. // do not need to to this if event is from this panel
  35. if (info.scope === scope) {
  36. return;
  37. }
  38. if(dashboard.sharedCrosshair) {
  39. var plot = elem.data().plot;
  40. if (plot) {
  41. plot.setCrosshair({ x: info.pos.x, y: info.pos.y });
  42. }
  43. }
  44. }, scope);
  45. rootScope.onAppEvent('clearCrosshair', function() {
  46. var plot = elem.data().plot;
  47. if (plot) {
  48. plot.clearCrosshair();
  49. }
  50. }, scope);
  51. // Receive render events
  52. scope.$on('render',function(event, renderData) {
  53. data = renderData || data;
  54. if (!data) {
  55. ctrl.refresh();
  56. return;
  57. }
  58. annotations = data.annotations || annotations;
  59. render_panel();
  60. });
  61. function getLegendHeight(panelHeight) {
  62. if (!panel.legend.show || panel.legend.rightSide) {
  63. return 0;
  64. }
  65. if (panel.legend.alignAsTable) {
  66. var legendSeries = _.filter(data, function(series) {
  67. return series.hideFromLegend(panel.legend) === false;
  68. });
  69. console.log(legendSeries.length);
  70. var total = 23 + (22 * legendSeries.length);
  71. return Math.min(total, Math.floor(panelHeight/2));
  72. } else {
  73. return 26;
  74. }
  75. }
  76. function setElementHeight() {
  77. try {
  78. graphHeight = ctrl.height || panel.height || ctrl.row.height;
  79. if (_.isString(graphHeight)) {
  80. graphHeight = parseInt(graphHeight.replace('px', ''), 10);
  81. }
  82. graphHeight -= 5; // padding
  83. graphHeight -= panel.title ? 25 : 5; // subtract panel title bar
  84. graphHeight = graphHeight - getLegendHeight(graphHeight); // subtract one line legend
  85. elem.css('height', graphHeight + 'px');
  86. return true;
  87. } catch(e) { // IE throws errors sometimes
  88. console.log(e);
  89. return false;
  90. }
  91. }
  92. function shouldAbortRender() {
  93. if (!data) {
  94. return true;
  95. }
  96. if (ctrl.otherPanelInFullscreenMode()) {
  97. return true;
  98. }
  99. if (!setElementHeight()) { return true; }
  100. if(_.isString(data)) {
  101. render_panel_as_graphite_png(data);
  102. return true;
  103. }
  104. if (elem.width() === 0) {
  105. return true;
  106. }
  107. }
  108. function drawHook(plot) {
  109. // Update legend values
  110. var yaxis = plot.getYAxes();
  111. for (var i = 0; i < data.length; i++) {
  112. var series = data[i];
  113. var axis = yaxis[series.yaxis - 1];
  114. var formater = kbn.valueFormats[panel.y_formats[series.yaxis - 1]];
  115. // decimal override
  116. if (_.isNumber(panel.decimals)) {
  117. series.updateLegendValues(formater, panel.decimals, null);
  118. } else {
  119. // auto decimals
  120. // legend and tooltip gets one more decimal precision
  121. // than graph legend ticks
  122. var tickDecimals = (axis.tickDecimals || -1) + 1;
  123. series.updateLegendValues(formater, tickDecimals, axis.scaledDecimals + 2);
  124. }
  125. if(!rootScope.$$phase) { scope.$digest(); }
  126. }
  127. // add left axis labels
  128. if (panel.leftYAxisLabel) {
  129. var yaxisLabel = $("<div class='axisLabel left-yaxis-label'></div>")
  130. .text(panel.leftYAxisLabel)
  131. .appendTo(elem);
  132. yaxisLabel.css("margin-top", yaxisLabel.width() / 2);
  133. }
  134. // add right axis labels
  135. if (panel.rightYAxisLabel) {
  136. var rightLabel = $("<div class='axisLabel right-yaxis-label'></div>")
  137. .text(panel.rightYAxisLabel)
  138. .appendTo(elem);
  139. rightLabel.css("margin-top", rightLabel.width() / 2);
  140. }
  141. }
  142. function processOffsetHook(plot, gridMargin) {
  143. if (panel.leftYAxisLabel) { gridMargin.left = 20; }
  144. if (panel.rightYAxisLabel) { gridMargin.right = 20; }
  145. }
  146. // Function for rendering panel
  147. function render_panel() {
  148. if (shouldAbortRender()) {
  149. return;
  150. }
  151. var stack = panel.stack ? true : null;
  152. // Populate element
  153. var options = {
  154. hooks: {
  155. draw: [drawHook],
  156. processOffset: [processOffsetHook],
  157. },
  158. legend: { show: false },
  159. series: {
  160. stackpercent: panel.stack ? panel.percentage : false,
  161. stack: panel.percentage ? null : stack,
  162. lines: {
  163. show: panel.lines,
  164. zero: false,
  165. fill: translateFillOption(panel.fill),
  166. lineWidth: panel.linewidth,
  167. steps: panel.steppedLine
  168. },
  169. bars: {
  170. show: panel.bars,
  171. fill: 1,
  172. barWidth: 1,
  173. zero: false,
  174. lineWidth: 0
  175. },
  176. points: {
  177. show: panel.points,
  178. fill: 1,
  179. fillColor: false,
  180. radius: panel.points ? panel.pointradius : 2
  181. // little points when highlight points
  182. },
  183. shadowSize: 1
  184. },
  185. yaxes: [],
  186. xaxis: {},
  187. grid: {
  188. minBorderMargin: 0,
  189. markings: [],
  190. backgroundColor: null,
  191. borderWidth: 0,
  192. hoverable: true,
  193. color: '#c8c8c8',
  194. margin: { left: 0, right: 0 },
  195. },
  196. selection: {
  197. mode: "x",
  198. color: '#666'
  199. },
  200. crosshair: {
  201. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  202. }
  203. };
  204. for (var i = 0; i < data.length; i++) {
  205. var series = data[i];
  206. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode, panel.y_formats);
  207. // if hidden remove points and disable stack
  208. if (ctrl.hiddenSeries[series.alias]) {
  209. series.data = [];
  210. series.stack = false;
  211. }
  212. }
  213. if (data.length && data[0].stats.timeStep) {
  214. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  215. }
  216. addTimeAxis(options);
  217. addGridThresholds(options, panel);
  218. addAnnotations(options);
  219. configureAxisOptions(data, options);
  220. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  221. function callPlot(incrementRenderCounter) {
  222. try {
  223. $.plot(elem, sortedSeries, options);
  224. } catch (e) {
  225. console.log('flotcharts error', e);
  226. }
  227. if (incrementRenderCounter) {
  228. ctrl.renderingCompleted();
  229. }
  230. }
  231. if (shouldDelayDraw(panel)) {
  232. // temp fix for legends on the side, need to render twice to get dimensions right
  233. callPlot(false);
  234. setTimeout(function() { callPlot(true); }, 50);
  235. legendSideLastValue = panel.legend.rightSide;
  236. }
  237. else {
  238. callPlot(true);
  239. }
  240. }
  241. function translateFillOption(fill) {
  242. return fill === 0 ? 0.001 : fill/10;
  243. }
  244. function shouldDelayDraw(panel) {
  245. if (panel.legend.rightSide) {
  246. return true;
  247. }
  248. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  249. return true;
  250. }
  251. }
  252. function addTimeAxis(options) {
  253. var ticks = elem.width() / 100;
  254. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  255. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  256. options.xaxis = {
  257. timezone: dashboard.timezone,
  258. show: panel['x-axis'],
  259. mode: "time",
  260. min: min,
  261. max: max,
  262. label: "Datetime",
  263. ticks: ticks,
  264. timeformat: time_format(ticks, min, max),
  265. };
  266. }
  267. function addGridThresholds(options, panel) {
  268. if (_.isNumber(panel.grid.threshold1)) {
  269. var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null);
  270. options.grid.markings.push({
  271. yaxis: { from: panel.grid.threshold1, to: limit1 },
  272. color: panel.grid.threshold1Color
  273. });
  274. if (_.isNumber(panel.grid.threshold2)) {
  275. var limit2;
  276. if (panel.grid.thresholdLine) {
  277. limit2 = panel.grid.threshold2;
  278. } else {
  279. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  280. }
  281. options.grid.markings.push({
  282. yaxis: { from: panel.grid.threshold2, to: limit2 },
  283. color: panel.grid.threshold2Color
  284. });
  285. }
  286. }
  287. }
  288. function addAnnotations(options) {
  289. if(!annotations || annotations.length === 0) {
  290. return;
  291. }
  292. var types = {};
  293. _.each(annotations, function(event) {
  294. if (!types[event.annotation.name]) {
  295. types[event.annotation.name] = {
  296. color: event.annotation.iconColor,
  297. position: 'BOTTOM',
  298. markerSize: 5,
  299. };
  300. }
  301. });
  302. options.events = {
  303. levels: _.keys(types).length + 1,
  304. data: annotations,
  305. types: types,
  306. };
  307. }
  308. function configureAxisOptions(data, options) {
  309. var defaults = {
  310. position: 'left',
  311. show: panel['y-axis'],
  312. min: panel.grid.leftMin,
  313. index: 1,
  314. logBase: panel.grid.leftLogBase || 1,
  315. max: panel.percentage && panel.stack ? 100 : panel.grid.leftMax,
  316. };
  317. options.yaxes.push(defaults);
  318. if (_.findWhere(data, {yaxis: 2})) {
  319. var secondY = _.clone(defaults);
  320. secondY.index = 2,
  321. secondY.logBase = panel.grid.rightLogBase || 1,
  322. secondY.position = 'right';
  323. secondY.min = panel.grid.rightMin;
  324. secondY.max = panel.percentage && panel.stack ? 100 : panel.grid.rightMax;
  325. options.yaxes.push(secondY);
  326. applyLogScale(options.yaxes[1], data);
  327. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.y_formats[1]);
  328. }
  329. applyLogScale(options.yaxes[0], data);
  330. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.y_formats[0]);
  331. }
  332. function applyLogScale(axis, data) {
  333. if (axis.logBase === 1) {
  334. return;
  335. }
  336. var series, i;
  337. var max = axis.max;
  338. if (max === null) {
  339. for (i = 0; i < data.length; i++) {
  340. series = data[i];
  341. if (series.yaxis === axis.index) {
  342. if (max < series.stats.max) {
  343. max = series.stats.max;
  344. }
  345. }
  346. }
  347. if (max === void 0) {
  348. max = Number.MAX_VALUE;
  349. }
  350. }
  351. axis.min = axis.min !== null ? axis.min : 0;
  352. axis.ticks = [0, 1];
  353. var nextTick = 1;
  354. while (true) {
  355. nextTick = nextTick * axis.logBase;
  356. axis.ticks.push(nextTick);
  357. if (nextTick > max) {
  358. break;
  359. }
  360. }
  361. if (axis.logBase === 10) {
  362. axis.transform = function(v) { return Math.log(v+0.1); };
  363. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  364. } else {
  365. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  366. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  367. }
  368. }
  369. function configureAxisMode(axis, format) {
  370. axis.tickFormatter = function(val, axis) {
  371. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  372. };
  373. }
  374. function time_format(ticks, min, max) {
  375. if (min && max && ticks) {
  376. var range = max - min;
  377. var secPerTick = (range/ticks) / 1000;
  378. var oneDay = 86400000;
  379. var oneYear = 31536000000;
  380. if (secPerTick <= 45) {
  381. return "%H:%M:%S";
  382. }
  383. if (secPerTick <= 7200 || range <= oneDay) {
  384. return "%H:%M";
  385. }
  386. if (secPerTick <= 80000) {
  387. return "%m/%d %H:%M";
  388. }
  389. if (secPerTick <= 2419200 || range <= oneYear) {
  390. return "%m/%d";
  391. }
  392. return "%Y-%m";
  393. }
  394. return "%H:%M";
  395. }
  396. function render_panel_as_graphite_png(url) {
  397. url += '&width=' + elem.width();
  398. url += '&height=' + elem.css('height').replace('px', '');
  399. url += '&bgcolor=1f1f1f'; // @grayDarker & @grafanaPanelBackground
  400. url += '&fgcolor=BBBFC2'; // @textColor & @grayLighter
  401. url += panel.stack ? '&areaMode=stacked' : '';
  402. url += panel.fill !== 0 ? ('&areaAlpha=' + (panel.fill/10).toFixed(1)) : '';
  403. url += panel.linewidth !== 0 ? '&lineWidth=' + panel.linewidth : '';
  404. url += panel.legend.show ? '&hideLegend=false' : '&hideLegend=true';
  405. url += panel.grid.leftMin !== null ? '&yMin=' + panel.grid.leftMin : '';
  406. url += panel.grid.leftMax !== null ? '&yMax=' + panel.grid.leftMax : '';
  407. url += panel.grid.rightMin !== null ? '&yMin=' + panel.grid.rightMin : '';
  408. url += panel.grid.rightMax !== null ? '&yMax=' + panel.grid.rightMax : '';
  409. url += panel['x-axis'] ? '' : '&hideAxes=true';
  410. url += panel['y-axis'] ? '' : '&hideYAxis=true';
  411. switch(panel.y_formats[0]) {
  412. case 'bytes':
  413. url += '&yUnitSystem=binary';
  414. break;
  415. case 'bits':
  416. url += '&yUnitSystem=binary';
  417. break;
  418. case 'bps':
  419. url += '&yUnitSystem=si';
  420. break;
  421. case 'pps':
  422. url += '&yUnitSystem=si';
  423. break;
  424. case 'Bps':
  425. url += '&yUnitSystem=si';
  426. break;
  427. case 'short':
  428. url += '&yUnitSystem=si';
  429. break;
  430. case 'joule':
  431. url += '&yUnitSystem=si';
  432. break;
  433. case 'watt':
  434. url += '&yUnitSystem=si';
  435. break;
  436. case 'ev':
  437. url += '&yUnitSystem=si';
  438. break;
  439. case 'none':
  440. url += '&yUnitSystem=none';
  441. break;
  442. }
  443. switch(panel.nullPointMode) {
  444. case 'connected':
  445. url += '&lineMode=connected';
  446. break;
  447. case 'null':
  448. break; // graphite default lineMode
  449. case 'null as zero':
  450. url += "&drawNullAsZero=true";
  451. break;
  452. }
  453. url += panel.steppedLine ? '&lineMode=staircase' : '';
  454. elem.html('<img src="' + url + '"></img>');
  455. }
  456. new GraphTooltip(elem, dashboard, scope, function() {
  457. return sortedSeries;
  458. });
  459. elem.bind("plotselected", function (event, ranges) {
  460. scope.$apply(function() {
  461. timeSrv.setTime({
  462. from : moment.utc(ranges.xaxis.from),
  463. to : moment.utc(ranges.xaxis.to),
  464. });
  465. });
  466. });
  467. }
  468. };
  469. });
  470. });