graph.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'moment',
  5. 'lodash',
  6. 'app/core/utils/kbn',
  7. './graph_tooltip',
  8. './threshold_manager',
  9. 'jquery.flot',
  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. './jquery.flot.events',
  17. ],
  18. function (angular, $, moment, _, kbn, GraphTooltip, thresholdManExports) {
  19. 'use strict';
  20. var module = angular.module('grafana.directives');
  21. var labelWidthCache = {};
  22. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  23. return {
  24. restrict: 'A',
  25. template: '<div> </div>',
  26. link: function(scope, elem) {
  27. var ctrl = scope.ctrl;
  28. var dashboard = ctrl.dashboard;
  29. var panel = ctrl.panel;
  30. var data, annotations;
  31. var sortedSeries;
  32. var legendSideLastValue = null;
  33. var rootScope = scope.$root;
  34. var panelWidth = 0;
  35. var thresholdManager = new thresholdManExports.ThresholdManager(ctrl);
  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. return;
  59. }
  60. annotations = data.annotations || annotations;
  61. render_panel();
  62. });
  63. function getLegendHeight(panelHeight) {
  64. if (!panel.legend.show || panel.legend.rightSide) {
  65. return 0;
  66. }
  67. if (panel.legend.alignAsTable) {
  68. var legendSeries = _.filter(data, function(series) {
  69. return series.hideFromLegend(panel.legend) === false;
  70. });
  71. var total = 23 + (21 * legendSeries.length);
  72. return Math.min(total, Math.floor(panelHeight/2));
  73. } else {
  74. return 26;
  75. }
  76. }
  77. function setElementHeight() {
  78. try {
  79. var height = ctrl.height - getLegendHeight(ctrl.height);
  80. elem.css('height', height + 'px');
  81. return true;
  82. } catch(e) { // IE throws errors sometimes
  83. console.log(e);
  84. return false;
  85. }
  86. }
  87. function shouldAbortRender() {
  88. if (!data) {
  89. return true;
  90. }
  91. if (!setElementHeight()) { return true; }
  92. if (panelWidth === 0) {
  93. return true;
  94. }
  95. }
  96. function getLabelWidth(text, elem) {
  97. var labelWidth = labelWidthCache[text];
  98. if (!labelWidth) {
  99. labelWidth = labelWidthCache[text] = elem.width();
  100. }
  101. return labelWidth;
  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.yaxes[series.yaxis - 1].format];
  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.yaxes[0].label) {
  124. var yaxisLabel = $("<div class='axisLabel left-yaxis-label'></div>")
  125. .text(panel.yaxes[0].label)
  126. .appendTo(elem);
  127. yaxisLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[0].label, yaxisLabel) / 2) + 'px';
  128. }
  129. // add right axis labels
  130. if (panel.yaxes[1].label) {
  131. var rightLabel = $("<div class='axisLabel right-yaxis-label'></div>")
  132. .text(panel.yaxes[1].label)
  133. .appendTo(elem);
  134. rightLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[1].label, rightLabel) / 2) + 'px';
  135. }
  136. thresholdManager.draw(plot);
  137. }
  138. function processOffsetHook(plot, gridMargin) {
  139. var left = panel.yaxes[0];
  140. var right = panel.yaxes[1];
  141. if (left.show && left.label) { gridMargin.left = 20; }
  142. if (right.show && right.label) { gridMargin.right = 20; }
  143. }
  144. // Function for rendering panel
  145. function render_panel() {
  146. panelWidth = elem.width();
  147. if (shouldAbortRender()) {
  148. return;
  149. }
  150. // give space to alert editing
  151. thresholdManager.prepare(elem, data);
  152. var stack = panel.stack ? true : null;
  153. // Populate element
  154. var options = {
  155. hooks: {
  156. draw: [drawHook],
  157. processOffset: [processOffsetHook],
  158. },
  159. legend: { show: false },
  160. series: {
  161. stackpercent: panel.stack ? panel.percentage : false,
  162. stack: panel.percentage ? null : stack,
  163. lines: {
  164. show: panel.lines,
  165. zero: false,
  166. fill: translateFillOption(panel.fill),
  167. lineWidth: panel.linewidth,
  168. steps: panel.steppedLine
  169. },
  170. bars: {
  171. show: panel.bars,
  172. fill: 1,
  173. barWidth: 1,
  174. zero: false,
  175. lineWidth: 0
  176. },
  177. points: {
  178. show: panel.points,
  179. fill: 1,
  180. fillColor: false,
  181. radius: panel.points ? panel.pointradius : 2
  182. },
  183. shadowSize: 0
  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);
  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. thresholdManager.addPlotOptions(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. if (ctrl.renderError) {
  225. delete ctrl.error;
  226. delete ctrl.inspector;
  227. }
  228. } catch (e) {
  229. console.log('flotcharts error', e);
  230. ctrl.error = e.message || "Render Error";
  231. ctrl.renderError = true;
  232. ctrl.inspector = {error: e};
  233. }
  234. if (incrementRenderCounter) {
  235. ctrl.renderingCompleted();
  236. }
  237. }
  238. if (shouldDelayDraw(panel)) {
  239. // temp fix for legends on the side, need to render twice to get dimensions right
  240. callPlot(false);
  241. setTimeout(function() { callPlot(true); }, 50);
  242. legendSideLastValue = panel.legend.rightSide;
  243. }
  244. else {
  245. callPlot(true);
  246. }
  247. }
  248. function translateFillOption(fill) {
  249. return fill === 0 ? 0.001 : fill/10;
  250. }
  251. function shouldDelayDraw(panel) {
  252. if (panel.legend.rightSide) {
  253. return true;
  254. }
  255. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  256. return true;
  257. }
  258. }
  259. function addTimeAxis(options) {
  260. var ticks = panelWidth / 100;
  261. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  262. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  263. options.xaxis = {
  264. timezone: dashboard.getTimezone(),
  265. show: panel.xaxis.show,
  266. mode: "time",
  267. min: min,
  268. max: max,
  269. label: "Datetime",
  270. ticks: ticks,
  271. timeformat: time_format(ticks, min, max),
  272. };
  273. }
  274. function addAnnotations(options) {
  275. if(!annotations || annotations.length === 0) {
  276. return;
  277. }
  278. var types = {};
  279. for (var i = 0; i < annotations.length; i++) {
  280. var item = annotations[i];
  281. if (!types[item.source.name]) {
  282. types[item.source.name] = {
  283. color: item.source.iconColor,
  284. position: 'BOTTOM',
  285. markerSize: 5,
  286. };
  287. }
  288. }
  289. options.events = {
  290. levels: _.keys(types).length + 1,
  291. data: annotations,
  292. types: types,
  293. };
  294. }
  295. //Override min/max to provide more flexible autoscaling
  296. function autoscaleSpanOverride(yaxis, data, options) {
  297. var expr;
  298. if (yaxis.min != null && data != null) {
  299. expr = parseThresholdExpr(yaxis.min);
  300. options.min = autoscaleYAxisMin(expr, data.stats);
  301. }
  302. if (yaxis.max != null && data != null) {
  303. expr = parseThresholdExpr(yaxis.max);
  304. options.max = autoscaleYAxisMax(expr, data.stats);
  305. }
  306. }
  307. function parseThresholdExpr(expr) {
  308. var match, operator, value, precision;
  309. match = expr.match(/\s*([<=>~]*)\W*(\d+(\.\d+)?)/);
  310. if (match) {
  311. operator = match[1];
  312. value = parseFloat(match[2]);
  313. //Precision based on input
  314. precision = match[3] ? match[3].length - 1 : 0;
  315. return {
  316. operator: operator,
  317. value: value,
  318. precision: precision
  319. };
  320. } else {
  321. return undefined;
  322. }
  323. }
  324. function autoscaleYAxisMax(expr, dataStats) {
  325. var operator = expr.operator,
  326. value = expr.value,
  327. precision = expr.precision;
  328. if (operator === ">") {
  329. return dataStats.max < value ? value : null;
  330. } else if (operator === "<") {
  331. return dataStats.max > value ? value : null;
  332. } else if (operator === "~") {
  333. return kbn.roundValue(dataStats.avg + value, precision);
  334. } else if (operator === "=") {
  335. return kbn.roundValue(dataStats.current + value, precision);
  336. } else if (!operator && !isNaN(value)) {
  337. return kbn.roundValue(value, precision);
  338. } else {
  339. return null;
  340. }
  341. }
  342. function autoscaleYAxisMin(expr, dataStats) {
  343. var operator = expr.operator,
  344. value = expr.value,
  345. precision = expr.precision;
  346. if (operator === ">") {
  347. return dataStats.min < value ? value : null;
  348. } else if (operator === "<") {
  349. return dataStats.min > value ? value : null;
  350. } else if (operator === "~") {
  351. return kbn.roundValue(dataStats.avg - value, precision);
  352. } else if (operator === "=") {
  353. return kbn.roundValue(dataStats.current - value, precision);
  354. } else if (!operator && !isNaN(value)) {
  355. return kbn.roundValue(value, precision);
  356. } else {
  357. return null;
  358. }
  359. }
  360. function configureAxisOptions(data, options) {
  361. var defaults = {
  362. position: 'left',
  363. show: panel.yaxes[0].show,
  364. min: panel.yaxes[0].min,
  365. index: 1,
  366. logBase: panel.yaxes[0].logBase || 1,
  367. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  368. };
  369. autoscaleSpanOverride(panel.yaxes[0], data[0], defaults);
  370. options.yaxes.push(defaults);
  371. if (_.find(data, {yaxis: 2})) {
  372. var secondY = _.clone(defaults);
  373. secondY.index = 2,
  374. secondY.show = panel.yaxes[1].show;
  375. secondY.logBase = panel.yaxes[1].logBase || 1,
  376. secondY.position = 'right';
  377. secondY.min = panel.yaxes[1].min;
  378. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  379. autoscaleSpanOverride(panel.yaxes[1], data[1], secondY);
  380. options.yaxes.push(secondY);
  381. applyLogScale(options.yaxes[1], data);
  382. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  383. }
  384. applyLogScale(options.yaxes[0], data);
  385. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  386. }
  387. function applyLogScale(axis, data) {
  388. if (axis.logBase === 1) {
  389. return;
  390. }
  391. var series, i;
  392. var max = axis.max;
  393. if (max === null) {
  394. for (i = 0; i < data.length; i++) {
  395. series = data[i];
  396. if (series.yaxis === axis.index) {
  397. if (max < series.stats.max) {
  398. max = series.stats.max;
  399. }
  400. }
  401. }
  402. if (max === void 0) {
  403. max = Number.MAX_VALUE;
  404. }
  405. }
  406. axis.min = axis.min !== null ? axis.min : 0;
  407. axis.ticks = [0, 1];
  408. var nextTick = 1;
  409. while (true) {
  410. nextTick = nextTick * axis.logBase;
  411. axis.ticks.push(nextTick);
  412. if (nextTick > max) {
  413. break;
  414. }
  415. }
  416. if (axis.logBase === 10) {
  417. axis.transform = function(v) { return Math.log(v+0.1); };
  418. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  419. } else {
  420. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  421. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  422. }
  423. }
  424. function configureAxisMode(axis, format) {
  425. axis.tickFormatter = function(val, axis) {
  426. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  427. };
  428. }
  429. function time_format(ticks, min, max) {
  430. if (min && max && ticks) {
  431. var range = max - min;
  432. var secPerTick = (range/ticks) / 1000;
  433. var oneDay = 86400000;
  434. var oneYear = 31536000000;
  435. if (secPerTick <= 45) {
  436. return "%H:%M:%S";
  437. }
  438. if (secPerTick <= 7200 || range <= oneDay) {
  439. return "%H:%M";
  440. }
  441. if (secPerTick <= 80000) {
  442. return "%m/%d %H:%M";
  443. }
  444. if (secPerTick <= 2419200 || range <= oneYear) {
  445. return "%m/%d";
  446. }
  447. return "%Y-%m";
  448. }
  449. return "%H:%M";
  450. }
  451. new GraphTooltip(elem, dashboard, scope, function() {
  452. return sortedSeries;
  453. });
  454. elem.bind("plotselected", function (event, ranges) {
  455. scope.$apply(function() {
  456. timeSrv.setTime({
  457. from : moment.utc(ranges.xaxis.from),
  458. to : moment.utc(ranges.xaxis.to),
  459. });
  460. });
  461. });
  462. }
  463. };
  464. });
  465. });