graph.js 17 KB

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