graph.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. './jquery.flot.alerts',
  17. ],
  18. function (angular, $, moment, _, kbn, GraphTooltip) {
  19. 'use strict';
  20. var module = angular.module('grafana.directives');
  21. var labelWidthCache = {};
  22. var panelWidthCache = {};
  23. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  24. return {
  25. restrict: 'A',
  26. template: '<div> </div>',
  27. link: function(scope, elem) {
  28. var ctrl = scope.ctrl;
  29. var dashboard = ctrl.dashboard;
  30. var panel = ctrl.panel;
  31. var data, annotations;
  32. var sortedSeries;
  33. var legendSideLastValue = null;
  34. var rootScope = scope.$root;
  35. var panelWidth = 0;
  36. rootScope.onAppEvent('setCrosshair', function(event, info) {
  37. // do not need to to this if event is from this panel
  38. if (info.scope === scope) {
  39. return;
  40. }
  41. if(dashboard.sharedCrosshair) {
  42. var plot = elem.data().plot;
  43. if (plot) {
  44. plot.setCrosshair({ x: info.pos.x, y: info.pos.y });
  45. }
  46. }
  47. }, scope);
  48. rootScope.onAppEvent('clearCrosshair', function() {
  49. var plot = elem.data().plot;
  50. if (plot) {
  51. plot.clearCrosshair();
  52. }
  53. }, scope);
  54. // Receive render events
  55. ctrl.events.on('render', function(renderData) {
  56. data = renderData || data;
  57. if (!data) {
  58. ctrl.refresh();
  59. return;
  60. }
  61. annotations = data.annotations || annotations;
  62. render_panel();
  63. });
  64. function getLegendHeight(panelHeight) {
  65. if (!panel.legend.show || panel.legend.rightSide) {
  66. return 0;
  67. }
  68. if (panel.legend.alignAsTable) {
  69. var legendSeries = _.filter(data, function(series) {
  70. return series.hideFromLegend(panel.legend) === false;
  71. });
  72. var total = 23 + (21 * legendSeries.length);
  73. return Math.min(total, Math.floor(panelHeight/2));
  74. } else {
  75. return 26;
  76. }
  77. }
  78. function setElementHeight() {
  79. try {
  80. var height = ctrl.height - getLegendHeight(ctrl.height);
  81. elem.css('height', height + 'px');
  82. return true;
  83. } catch(e) { // IE throws errors sometimes
  84. console.log(e);
  85. return false;
  86. }
  87. }
  88. function shouldAbortRender() {
  89. if (!data) {
  90. return true;
  91. }
  92. if (!setElementHeight()) { return true; }
  93. if(_.isString(data)) {
  94. render_panel_as_graphite_png(data);
  95. return true;
  96. }
  97. if (panelWidth === 0) {
  98. return true;
  99. }
  100. }
  101. function getLabelWidth(text, elem) {
  102. var labelWidth = labelWidthCache[text];
  103. if (!labelWidth) {
  104. labelWidth = labelWidthCache[text] = elem.width();
  105. }
  106. return labelWidth;
  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.yaxes[series.yaxis - 1].format];
  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.yaxes[0].label) {
  129. var yaxisLabel = $("<div class='axisLabel left-yaxis-label'></div>")
  130. .text(panel.yaxes[0].label)
  131. .appendTo(elem);
  132. yaxisLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[0].label, yaxisLabel) / 2) + 'px';
  133. }
  134. // add right axis labels
  135. if (panel.yaxes[1].label) {
  136. var rightLabel = $("<div class='axisLabel right-yaxis-label'></div>")
  137. .text(panel.yaxes[1].label)
  138. .appendTo(elem);
  139. rightLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[1].label, rightLabel) / 2) + 'px';
  140. }
  141. }
  142. function processOffsetHook(plot, gridMargin) {
  143. var left = panel.yaxes[0];
  144. var right = panel.yaxes[1];
  145. if (left.show && left.label) { gridMargin.left = 20; }
  146. if (right.show && right.label) { gridMargin.right = 20; }
  147. }
  148. // Function for rendering panel
  149. function render_panel() {
  150. panelWidth = panelWidthCache[panel.span];
  151. if (!panelWidth) {
  152. panelWidth = panelWidthCache[panel.span] = elem.width();
  153. }
  154. if (shouldAbortRender()) {
  155. return;
  156. }
  157. var stack = panel.stack ? true : null;
  158. // Populate element
  159. var options = {
  160. hooks: {
  161. draw: [drawHook],
  162. processOffset: [processOffsetHook],
  163. },
  164. legend: { show: false },
  165. series: {
  166. stackpercent: panel.stack ? panel.percentage : false,
  167. stack: panel.percentage ? null : stack,
  168. lines: {
  169. show: panel.lines,
  170. zero: false,
  171. fill: translateFillOption(panel.fill),
  172. lineWidth: panel.linewidth,
  173. steps: panel.steppedLine
  174. },
  175. bars: {
  176. show: panel.bars,
  177. fill: 1,
  178. barWidth: 1,
  179. zero: false,
  180. lineWidth: 0
  181. },
  182. points: {
  183. show: panel.points,
  184. fill: 1,
  185. fillColor: false,
  186. radius: panel.points ? panel.pointradius : 2
  187. },
  188. shadowSize: 0
  189. },
  190. yaxes: [],
  191. xaxis: {},
  192. grid: {
  193. minBorderMargin: 0,
  194. markings: [],
  195. backgroundColor: null,
  196. borderWidth: 0,
  197. hoverable: true,
  198. color: '#c8c8c8',
  199. margin: { left: 0, right: 0 },
  200. },
  201. selection: {
  202. mode: "x",
  203. color: '#666'
  204. },
  205. crosshair: {
  206. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  207. }
  208. };
  209. for (var i = 0; i < data.length; i++) {
  210. var series = data[i];
  211. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  212. // if hidden remove points and disable stack
  213. if (ctrl.hiddenSeries[series.alias]) {
  214. series.data = [];
  215. series.stack = false;
  216. }
  217. }
  218. if (data.length && data[0].stats.timeStep) {
  219. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  220. }
  221. addTimeAxis(options);
  222. addGridThresholds(options, panel);
  223. addAnnotations(options);
  224. configureAxisOptions(data, options);
  225. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  226. function callPlot(incrementRenderCounter) {
  227. try {
  228. $.plot(elem, sortedSeries, options);
  229. } catch (e) {
  230. console.log('flotcharts error', e);
  231. }
  232. if (incrementRenderCounter) {
  233. ctrl.renderingCompleted();
  234. }
  235. }
  236. if (shouldDelayDraw(panel)) {
  237. // temp fix for legends on the side, need to render twice to get dimensions right
  238. callPlot(false);
  239. setTimeout(function() { callPlot(true); }, 50);
  240. legendSideLastValue = panel.legend.rightSide;
  241. }
  242. else {
  243. callPlot(true);
  244. }
  245. }
  246. function translateFillOption(fill) {
  247. return fill === 0 ? 0.001 : fill/10;
  248. }
  249. function shouldDelayDraw(panel) {
  250. if (panel.legend.rightSide) {
  251. return true;
  252. }
  253. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  254. return true;
  255. }
  256. }
  257. function addTimeAxis(options) {
  258. var ticks = panelWidth / 100;
  259. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  260. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  261. options.xaxis = {
  262. timezone: dashboard.getTimezone(),
  263. show: panel.xaxis.show,
  264. mode: "time",
  265. min: min,
  266. max: max,
  267. label: "Datetime",
  268. ticks: ticks,
  269. timeformat: time_format(ticks, min, max),
  270. };
  271. }
  272. function addGridThresholds(options, panel) {
  273. if (_.isNumber(panel.grid.threshold1)) {
  274. var limit1 = panel.grid.thresholdLine ? panel.grid.threshold1 : (panel.grid.threshold2 || null);
  275. options.grid.markings.push({
  276. yaxis: { from: panel.grid.threshold1, to: limit1 },
  277. color: panel.grid.threshold1Color
  278. });
  279. if (_.isNumber(panel.grid.threshold2)) {
  280. var limit2;
  281. if (panel.grid.thresholdLine) {
  282. limit2 = panel.grid.threshold2;
  283. } else {
  284. limit2 = panel.grid.threshold1 > panel.grid.threshold2 ? -Infinity : +Infinity;
  285. }
  286. options.grid.markings.push({
  287. yaxis: { from: panel.grid.threshold2, to: limit2 },
  288. color: panel.grid.threshold2Color
  289. });
  290. }
  291. }
  292. }
  293. function addAnnotations(options) {
  294. if(!annotations || annotations.length === 0) {
  295. return;
  296. }
  297. var types = {};
  298. _.each(annotations, function(event) {
  299. if (!types[event.annotation.name]) {
  300. types[event.annotation.name] = {
  301. color: event.annotation.iconColor,
  302. position: 'BOTTOM',
  303. markerSize: 5,
  304. };
  305. }
  306. });
  307. options.events = {
  308. levels: _.keys(types).length + 1,
  309. data: annotations,
  310. types: types,
  311. };
  312. }
  313. function configureAxisOptions(data, options) {
  314. var defaults = {
  315. position: 'left',
  316. show: panel.yaxes[0].show,
  317. min: panel.yaxes[0].min,
  318. index: 1,
  319. logBase: panel.yaxes[0].logBase || 1,
  320. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  321. };
  322. options.yaxes.push(defaults);
  323. if (_.findWhere(data, {yaxis: 2})) {
  324. var secondY = _.clone(defaults);
  325. secondY.index = 2,
  326. secondY.show = panel.yaxes[1].show;
  327. secondY.logBase = panel.yaxes[1].logBase || 1,
  328. secondY.position = 'right';
  329. secondY.min = panel.yaxes[1].min;
  330. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  331. options.yaxes.push(secondY);
  332. applyLogScale(options.yaxes[1], data);
  333. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  334. }
  335. applyLogScale(options.yaxes[0], data);
  336. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  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=' + panelWidth;
  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. if (panel.yaxes && panel.yaxes.length > 0) {
  412. var showYaxis = false;
  413. for(var i = 0; panel.yaxes.length > i; i++) {
  414. if (panel.yaxes[i].show) {
  415. url += (panel.yaxes[i].min !== null && panel.yaxes[i].min !== undefined) ? '&yMin=' + panel.yaxes[i].min : '';
  416. url += (panel.yaxes[i].max !== null && panel.yaxes[i].max !== undefined) ? '&yMax=' + panel.yaxes[i].max : '';
  417. showYaxis = true;
  418. break;
  419. }
  420. }
  421. url += showYaxis ? '' : '&hideYAxis=true';
  422. }
  423. url += panel.xaxis.show ? '' : '&hideAxes=true';
  424. switch(panel.yaxes[0].format) {
  425. case 'bytes':
  426. url += '&yUnitSystem=binary';
  427. break;
  428. case 'bits':
  429. url += '&yUnitSystem=binary';
  430. break;
  431. case 'bps':
  432. url += '&yUnitSystem=si';
  433. break;
  434. case 'pps':
  435. url += '&yUnitSystem=si';
  436. break;
  437. case 'Bps':
  438. url += '&yUnitSystem=si';
  439. break;
  440. case 'short':
  441. url += '&yUnitSystem=si';
  442. break;
  443. case 'joule':
  444. url += '&yUnitSystem=si';
  445. break;
  446. case 'watt':
  447. url += '&yUnitSystem=si';
  448. break;
  449. case 'ev':
  450. url += '&yUnitSystem=si';
  451. break;
  452. case 'none':
  453. url += '&yUnitSystem=none';
  454. break;
  455. }
  456. switch(panel.nullPointMode) {
  457. case 'connected':
  458. url += '&lineMode=connected';
  459. break;
  460. case 'null':
  461. break; // graphite default lineMode
  462. case 'null as zero':
  463. url += "&drawNullAsZero=true";
  464. break;
  465. }
  466. url += panel.steppedLine ? '&lineMode=staircase' : '';
  467. elem.html('<img src="' + url + '"></img>');
  468. }
  469. new GraphTooltip(elem, dashboard, scope, function() {
  470. return sortedSeries;
  471. });
  472. elem.bind("plotselected", function (event, ranges) {
  473. scope.$apply(function() {
  474. timeSrv.setTime({
  475. from : moment.utc(ranges.xaxis.from),
  476. to : moment.utc(ranges.xaxis.to),
  477. });
  478. });
  479. });
  480. }
  481. };
  482. });
  483. });