graph.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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 (panel.xaxis.mode === 'series') {
  208. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  209. } else if (panel.xaxis.mode === 'table' ||
  210. panel.xaxis.mode === 'elastic') {
  211. series.data = [];
  212. for (var j = 0; j < series.datapoints.length; j++) {
  213. var dataIndex = i * series.datapoints.length + j;
  214. series.datapoints[j];
  215. series.data.push([
  216. dataIndex + 1,
  217. series.datapoints[j][0]
  218. ]);
  219. }
  220. }
  221. // if hidden remove points and disable stack
  222. if (ctrl.hiddenSeries[series.alias]) {
  223. series.data = [];
  224. series.stack = false;
  225. }
  226. }
  227. if (panel.xaxis.mode === 'series') {
  228. if (data.length) {
  229. options.series.bars.barWidth = 0.7;
  230. options.series.bars.align = 'center';
  231. }
  232. addXSeriesAxis(options);
  233. } else if (panel.xaxis.mode === 'table' ||
  234. panel.xaxis.mode === 'elastic') {
  235. if (data.length) {
  236. options.series.bars.barWidth = 0.7;
  237. options.series.bars.align = 'center';
  238. }
  239. addXTableAxis(options);
  240. } else {
  241. if (data.length && data[0].stats.timeStep) {
  242. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  243. }
  244. addTimeAxis(options);
  245. }
  246. thresholdManager.addPlotOptions(options, panel);
  247. addAnnotations(options);
  248. configureAxisOptions(data, options);
  249. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  250. function callPlot(incrementRenderCounter) {
  251. try {
  252. $.plot(elem, sortedSeries, options);
  253. if (ctrl.renderError) {
  254. delete ctrl.error;
  255. delete ctrl.inspector;
  256. }
  257. } catch (e) {
  258. console.log('flotcharts error', e);
  259. ctrl.error = e.message || "Render Error";
  260. ctrl.renderError = true;
  261. ctrl.inspector = {error: e};
  262. }
  263. if (incrementRenderCounter) {
  264. ctrl.renderingCompleted();
  265. }
  266. }
  267. if (shouldDelayDraw(panel)) {
  268. // temp fix for legends on the side, need to render twice to get dimensions right
  269. callPlot(false);
  270. setTimeout(function() { callPlot(true); }, 50);
  271. legendSideLastValue = panel.legend.rightSide;
  272. }
  273. else {
  274. callPlot(true);
  275. }
  276. }
  277. function translateFillOption(fill) {
  278. return fill === 0 ? 0.001 : fill/10;
  279. }
  280. function shouldDelayDraw(panel) {
  281. if (panel.legend.rightSide) {
  282. return true;
  283. }
  284. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  285. return true;
  286. }
  287. }
  288. function addTimeAxis(options) {
  289. var ticks = panelWidth / 100;
  290. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  291. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  292. options.xaxis = {
  293. timezone: dashboard.getTimezone(),
  294. show: panel.xaxis.show,
  295. mode: "time",
  296. min: min,
  297. max: max,
  298. label: "Datetime",
  299. ticks: ticks,
  300. timeformat: time_format(ticks, min, max),
  301. };
  302. }
  303. function addXSeriesAxis(options) {
  304. var ticks = _.map(data, function(series, index) {
  305. return [index + 1, series.alias];
  306. });
  307. options.xaxis = {
  308. timezone: dashboard.getTimezone(),
  309. show: panel.xaxis.show,
  310. mode: null,
  311. min: 0,
  312. max: ticks.length + 1,
  313. label: "Datetime",
  314. ticks: ticks
  315. };
  316. }
  317. function addXTableAxis(options) {
  318. var ticks = _.map(data, function(series, seriesIndex) {
  319. return _.map(series.datapoints, function(point, pointIndex) {
  320. var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  321. return [tickIndex + 1, point[1]];
  322. });
  323. });
  324. ticks = _.flatten(ticks, true);
  325. options.xaxis = {
  326. timezone: dashboard.getTimezone(),
  327. show: panel.xaxis.show,
  328. mode: null,
  329. min: 0,
  330. max: ticks.length + 1,
  331. label: "Datetime",
  332. ticks: ticks
  333. };
  334. }
  335. function addAnnotations(options) {
  336. if(!annotations || annotations.length === 0) {
  337. return;
  338. }
  339. var types = {};
  340. for (var i = 0; i < annotations.length; i++) {
  341. var item = annotations[i];
  342. if (!types[item.source.name]) {
  343. types[item.source.name] = {
  344. color: item.source.iconColor,
  345. position: 'BOTTOM',
  346. markerSize: 5,
  347. };
  348. }
  349. }
  350. options.events = {
  351. levels: _.keys(types).length + 1,
  352. data: annotations,
  353. types: types,
  354. };
  355. }
  356. //Override min/max to provide more flexible autoscaling
  357. function autoscaleSpanOverride(yaxis, data, options) {
  358. var expr;
  359. if (yaxis.min != null && data != null) {
  360. expr = parseThresholdExpr(yaxis.min);
  361. options.min = autoscaleYAxisMin(expr, data.stats);
  362. }
  363. if (yaxis.max != null && data != null) {
  364. expr = parseThresholdExpr(yaxis.max);
  365. options.max = autoscaleYAxisMax(expr, data.stats);
  366. }
  367. }
  368. function parseThresholdExpr(expr) {
  369. var match, operator, value, precision;
  370. expr = String(expr);
  371. match = expr.match(/\s*([<=>~]*)\s*(\-?\d+(\.\d+)?)/);
  372. if (match) {
  373. operator = match[1];
  374. value = parseFloat(match[2]);
  375. //Precision based on input
  376. precision = match[3] ? match[3].length - 1 : 0;
  377. return {
  378. operator: operator,
  379. value: value,
  380. precision: precision
  381. };
  382. } else {
  383. return undefined;
  384. }
  385. }
  386. function autoscaleYAxisMax(expr, dataStats) {
  387. var operator = expr.operator,
  388. value = expr.value,
  389. precision = expr.precision;
  390. if (operator === ">") {
  391. return dataStats.max < value ? value : null;
  392. } else if (operator === "<") {
  393. return dataStats.max > value ? value : null;
  394. } else if (operator === "~") {
  395. return kbn.roundValue(dataStats.avg + value, precision);
  396. } else if (operator === "=") {
  397. return kbn.roundValue(dataStats.current + value, precision);
  398. } else if (!operator && !isNaN(value)) {
  399. return kbn.roundValue(value, precision);
  400. } else {
  401. return null;
  402. }
  403. }
  404. function autoscaleYAxisMin(expr, dataStats) {
  405. var operator = expr.operator,
  406. value = expr.value,
  407. precision = expr.precision;
  408. if (operator === ">") {
  409. return dataStats.min < value ? value : null;
  410. } else if (operator === "<") {
  411. return dataStats.min > value ? value : null;
  412. } else if (operator === "~") {
  413. return kbn.roundValue(dataStats.avg - value, precision);
  414. } else if (operator === "=") {
  415. return kbn.roundValue(dataStats.current - value, precision);
  416. } else if (!operator && !isNaN(value)) {
  417. return kbn.roundValue(value, precision);
  418. } else {
  419. return null;
  420. }
  421. }
  422. function configureAxisOptions(data, options) {
  423. var defaults = {
  424. position: 'left',
  425. show: panel.yaxes[0].show,
  426. min: panel.yaxes[0].min,
  427. index: 1,
  428. logBase: panel.yaxes[0].logBase || 1,
  429. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  430. };
  431. autoscaleSpanOverride(panel.yaxes[0], data[0], defaults);
  432. options.yaxes.push(defaults);
  433. if (_.find(data, {yaxis: 2})) {
  434. var secondY = _.clone(defaults);
  435. secondY.index = 2,
  436. secondY.show = panel.yaxes[1].show;
  437. secondY.logBase = panel.yaxes[1].logBase || 1,
  438. secondY.position = 'right';
  439. secondY.min = panel.yaxes[1].min;
  440. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  441. autoscaleSpanOverride(panel.yaxes[1], data[1], secondY);
  442. options.yaxes.push(secondY);
  443. applyLogScale(options.yaxes[1], data);
  444. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  445. }
  446. applyLogScale(options.yaxes[0], data);
  447. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  448. }
  449. function applyLogScale(axis, data) {
  450. if (axis.logBase === 1) {
  451. return;
  452. }
  453. var series, i;
  454. var max = axis.max;
  455. if (max === null) {
  456. for (i = 0; i < data.length; i++) {
  457. series = data[i];
  458. if (series.yaxis === axis.index) {
  459. if (max < series.stats.max) {
  460. max = series.stats.max;
  461. }
  462. }
  463. }
  464. if (max === void 0) {
  465. max = Number.MAX_VALUE;
  466. }
  467. }
  468. axis.min = axis.min !== null ? axis.min : 0;
  469. axis.ticks = [0, 1];
  470. var nextTick = 1;
  471. while (true) {
  472. nextTick = nextTick * axis.logBase;
  473. axis.ticks.push(nextTick);
  474. if (nextTick > max) {
  475. break;
  476. }
  477. }
  478. if (axis.logBase === 10) {
  479. axis.transform = function(v) { return Math.log(v+0.1); };
  480. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  481. } else {
  482. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  483. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  484. }
  485. }
  486. function configureAxisMode(axis, format) {
  487. axis.tickFormatter = function(val, axis) {
  488. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  489. };
  490. }
  491. function time_format(ticks, min, max) {
  492. if (min && max && ticks) {
  493. var range = max - min;
  494. var secPerTick = (range/ticks) / 1000;
  495. var oneDay = 86400000;
  496. var oneYear = 31536000000;
  497. if (secPerTick <= 45) {
  498. return "%H:%M:%S";
  499. }
  500. if (secPerTick <= 7200 || range <= oneDay) {
  501. return "%H:%M";
  502. }
  503. if (secPerTick <= 80000) {
  504. return "%m/%d %H:%M";
  505. }
  506. if (secPerTick <= 2419200 || range <= oneYear) {
  507. return "%m/%d";
  508. }
  509. return "%Y-%m";
  510. }
  511. return "%H:%M";
  512. }
  513. new GraphTooltip(elem, dashboard, scope, function() {
  514. return sortedSeries;
  515. });
  516. elem.bind("plotselected", function (event, ranges) {
  517. scope.$apply(function() {
  518. timeSrv.setTime({
  519. from : moment.utc(ranges.xaxis.from),
  520. to : moment.utc(ranges.xaxis.to),
  521. });
  522. });
  523. });
  524. }
  525. };
  526. });
  527. });