graph.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. ///<reference path="../../../headers/common.d.ts" />
  2. import 'jquery.flot';
  3. import 'jquery.flot.selection';
  4. import 'jquery.flot.time';
  5. import 'jquery.flot.stack';
  6. import 'jquery.flot.stackpercent';
  7. import 'jquery.flot.fillbelow';
  8. import 'jquery.flot.crosshair';
  9. import './jquery.flot.events';
  10. import angular from 'angular';
  11. import $ from 'jquery';
  12. import moment from 'moment';
  13. import _ from 'lodash';
  14. import kbn from 'app/core/utils/kbn';
  15. import GraphTooltip from './graph_tooltip';
  16. import {ThresholdManager} from './threshold_manager';
  17. var module = angular.module('grafana.directives');
  18. var labelWidthCache = {};
  19. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  20. return {
  21. restrict: 'A',
  22. template: '<div> </div>',
  23. link: function(scope, elem) {
  24. var ctrl = scope.ctrl;
  25. var dashboard = ctrl.dashboard;
  26. var panel = ctrl.panel;
  27. var data, annotations;
  28. var sortedSeries;
  29. var legendSideLastValue = null;
  30. var rootScope = scope.$root;
  31. var panelWidth = 0;
  32. var thresholdManager = new ThresholdManager(ctrl);
  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. ctrl.events.on('render', function(renderData) {
  53. data = renderData || data;
  54. if (!data) {
  55. return;
  56. }
  57. annotations = data.annotations || annotations;
  58. render_panel();
  59. });
  60. function getLegendHeight(panelHeight) {
  61. if (!panel.legend.show || panel.legend.rightSide) {
  62. return 0;
  63. }
  64. if (panel.legend.alignAsTable) {
  65. var legendSeries = _.filter(data, function(series) {
  66. return series.hideFromLegend(panel.legend) === false;
  67. });
  68. var total = 23 + (21 * legendSeries.length);
  69. return Math.min(total, Math.floor(panelHeight/2));
  70. } else {
  71. return 26;
  72. }
  73. }
  74. function setElementHeight() {
  75. try {
  76. var height = ctrl.height - getLegendHeight(ctrl.height);
  77. elem.css('height', height + 'px');
  78. return true;
  79. } catch (e) { // IE throws errors sometimes
  80. console.log(e);
  81. return false;
  82. }
  83. }
  84. function shouldAbortRender() {
  85. if (!data) {
  86. return true;
  87. }
  88. if (!setElementHeight()) { return true; }
  89. if (panelWidth === 0) {
  90. return true;
  91. }
  92. }
  93. function getLabelWidth(text, elem) {
  94. var labelWidth = labelWidthCache[text];
  95. if (!labelWidth) {
  96. labelWidth = labelWidthCache[text] = elem.width();
  97. }
  98. return labelWidth;
  99. }
  100. function drawHook(plot) {
  101. // Update legend values
  102. var yaxis = plot.getYAxes();
  103. for (var i = 0; i < data.length; i++) {
  104. var series = data[i];
  105. var axis = yaxis[series.yaxis - 1];
  106. var formater = kbn.valueFormats[panel.yaxes[series.yaxis - 1].format];
  107. // decimal override
  108. if (_.isNumber(panel.decimals)) {
  109. series.updateLegendValues(formater, panel.decimals, null);
  110. } else {
  111. // auto decimals
  112. // legend and tooltip gets one more decimal precision
  113. // than graph legend ticks
  114. var tickDecimals = (axis.tickDecimals || -1) + 1;
  115. series.updateLegendValues(formater, tickDecimals, axis.scaledDecimals + 2);
  116. }
  117. if (!rootScope.$$phase) { scope.$digest(); }
  118. }
  119. // add left axis labels
  120. if (panel.yaxes[0].label) {
  121. var yaxisLabel = $("<div class='axisLabel left-yaxis-label'></div>")
  122. .text(panel.yaxes[0].label)
  123. .appendTo(elem);
  124. yaxisLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[0].label, yaxisLabel) / 2) + 'px';
  125. }
  126. // add right axis labels
  127. if (panel.yaxes[1].label) {
  128. var rightLabel = $("<div class='axisLabel right-yaxis-label'></div>")
  129. .text(panel.yaxes[1].label)
  130. .appendTo(elem);
  131. rightLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[1].label, rightLabel) / 2) + 'px';
  132. }
  133. thresholdManager.draw(plot);
  134. }
  135. function processOffsetHook(plot, gridMargin) {
  136. var left = panel.yaxes[0];
  137. var right = panel.yaxes[1];
  138. if (left.show && left.label) { gridMargin.left = 20; }
  139. if (right.show && right.label) { gridMargin.right = 20; }
  140. }
  141. function processDatapoints(plot) {
  142. console.log('processDatapoints');
  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: any = {
  155. hooks: {
  156. draw: [drawHook],
  157. processOffset: [processOffsetHook],
  158. processDatapoints: [processDatapoints],
  159. },
  160. legend: { show: false },
  161. series: {
  162. stackpercent: panel.stack ? panel.percentage : false,
  163. stack: panel.percentage ? null : stack,
  164. lines: {
  165. show: panel.lines,
  166. zero: false,
  167. fill: translateFillOption(panel.fill),
  168. lineWidth: panel.linewidth,
  169. steps: panel.steppedLine
  170. },
  171. bars: {
  172. show: panel.bars,
  173. fill: 1,
  174. barWidth: 1,
  175. zero: false,
  176. lineWidth: 0
  177. },
  178. points: {
  179. show: panel.points,
  180. fill: 1,
  181. fillColor: false,
  182. radius: panel.points ? panel.pointradius : 2
  183. },
  184. shadowSize: 0
  185. },
  186. yaxes: [],
  187. xaxis: {},
  188. grid: {
  189. minBorderMargin: 0,
  190. markings: [],
  191. backgroundColor: null,
  192. borderWidth: 0,
  193. hoverable: true,
  194. color: '#c8c8c8',
  195. margin: { left: 0, right: 0 },
  196. },
  197. selection: {
  198. mode: "x",
  199. color: '#666'
  200. },
  201. crosshair: {
  202. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  203. }
  204. };
  205. for (let i = 0; i < data.length; i++) {
  206. var series = data[i];
  207. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  208. // if hidden remove points and disable stack
  209. if (ctrl.hiddenSeries[series.alias]) {
  210. series.data = [];
  211. series.stack = false;
  212. }
  213. }
  214. switch (panel.xaxis.mode) {
  215. case 'series': {
  216. options.series.bars.barWidth = 0.7;
  217. options.series.bars.align = 'center';
  218. for (let i = 0; i < data.length; i++) {
  219. var series = data[i];
  220. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  221. }
  222. addXSeriesAxis(options);
  223. break;
  224. }
  225. case 'table': {
  226. options.series.bars.barWidth = 0.7;
  227. options.series.bars.align = 'center';
  228. addXTableAxis(options);
  229. break;
  230. }
  231. default: {
  232. if (data.length && data[0].stats.timeStep) {
  233. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  234. }
  235. addTimeAxis(options);
  236. break;
  237. }
  238. }
  239. thresholdManager.addPlotOptions(options, panel);
  240. addAnnotations(options);
  241. configureAxisOptions(data, options);
  242. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  243. function callPlot(incrementRenderCounter) {
  244. try {
  245. $.plot(elem, sortedSeries, options);
  246. if (ctrl.renderError) {
  247. delete ctrl.error;
  248. delete ctrl.inspector;
  249. }
  250. } catch (e) {
  251. console.log('flotcharts error', e);
  252. ctrl.error = e.message || "Render Error";
  253. ctrl.renderError = true;
  254. ctrl.inspector = {error: e};
  255. }
  256. if (incrementRenderCounter) {
  257. ctrl.renderingCompleted();
  258. }
  259. }
  260. if (shouldDelayDraw(panel)) {
  261. // temp fix for legends on the side, need to render twice to get dimensions right
  262. callPlot(false);
  263. setTimeout(function() { callPlot(true); }, 50);
  264. legendSideLastValue = panel.legend.rightSide;
  265. } else {
  266. callPlot(true);
  267. }
  268. }
  269. function translateFillOption(fill) {
  270. return fill === 0 ? 0.001 : fill/10;
  271. }
  272. function shouldDelayDraw(panel) {
  273. if (panel.legend.rightSide) {
  274. return true;
  275. }
  276. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  277. return true;
  278. }
  279. }
  280. function addTimeAxis(options) {
  281. var ticks = panelWidth / 100;
  282. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  283. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  284. options.xaxis = {
  285. timezone: dashboard.getTimezone(),
  286. show: panel.xaxis.show,
  287. mode: "time",
  288. min: min,
  289. max: max,
  290. label: "Datetime",
  291. ticks: ticks,
  292. timeformat: time_format(ticks, min, max),
  293. };
  294. }
  295. function addXSeriesAxis(options) {
  296. var ticks = _.map(data, function(series, index) {
  297. return [index + 1, series.alias];
  298. });
  299. options.xaxis = {
  300. timezone: dashboard.getTimezone(),
  301. show: panel.xaxis.show,
  302. mode: null,
  303. min: 0,
  304. max: ticks.length + 1,
  305. label: "Datetime",
  306. ticks: ticks
  307. };
  308. }
  309. function addXTableAxis(options) {
  310. var ticks = _.map(data, function(series, seriesIndex) {
  311. return _.map(series.datapoints, function(point, pointIndex) {
  312. var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  313. return [tickIndex + 1, point[1]];
  314. });
  315. });
  316. ticks = _.flatten(ticks, true);
  317. options.xaxis = {
  318. timezone: dashboard.getTimezone(),
  319. show: panel.xaxis.show,
  320. mode: null,
  321. min: 0,
  322. max: ticks.length + 1,
  323. label: "Datetime",
  324. ticks: ticks
  325. };
  326. }
  327. function addAnnotations(options) {
  328. if (!annotations || annotations.length === 0) {
  329. return;
  330. }
  331. var types = {};
  332. for (var i = 0; i < annotations.length; i++) {
  333. var item = annotations[i];
  334. if (!types[item.source.name]) {
  335. types[item.source.name] = {
  336. color: item.source.iconColor,
  337. position: 'BOTTOM',
  338. markerSize: 5,
  339. };
  340. }
  341. }
  342. options.events = {
  343. levels: _.keys(types).length + 1,
  344. data: annotations,
  345. types: types,
  346. };
  347. }
  348. //Override min/max to provide more flexible autoscaling
  349. function autoscaleSpanOverride(yaxis, data, options) {
  350. var expr;
  351. if (yaxis.min != null && data != null) {
  352. expr = parseThresholdExpr(yaxis.min);
  353. options.min = autoscaleYAxisMin(expr, data.stats);
  354. }
  355. if (yaxis.max != null && data != null) {
  356. expr = parseThresholdExpr(yaxis.max);
  357. options.max = autoscaleYAxisMax(expr, data.stats);
  358. }
  359. }
  360. function parseThresholdExpr(expr) {
  361. var match, operator, value, precision;
  362. expr = String(expr);
  363. match = expr.match(/\s*([<=>~]*)\s*(\-?\d+(\.\d+)?)/);
  364. if (match) {
  365. operator = match[1];
  366. value = parseFloat(match[2]);
  367. //Precision based on input
  368. precision = match[3] ? match[3].length - 1 : 0;
  369. return {
  370. operator: operator,
  371. value: value,
  372. precision: precision
  373. };
  374. } else {
  375. return undefined;
  376. }
  377. }
  378. function autoscaleYAxisMax(expr, dataStats) {
  379. var operator = expr.operator,
  380. value = expr.value,
  381. precision = expr.precision;
  382. if (operator === ">") {
  383. return dataStats.max < value ? value : null;
  384. } else if (operator === "<") {
  385. return dataStats.max > value ? value : null;
  386. } else if (operator === "~") {
  387. return kbn.roundValue(dataStats.avg + value, precision);
  388. } else if (operator === "=") {
  389. return kbn.roundValue(dataStats.current + value, precision);
  390. } else if (!operator && !isNaN(value)) {
  391. return kbn.roundValue(value, precision);
  392. } else {
  393. return null;
  394. }
  395. }
  396. function autoscaleYAxisMin(expr, dataStats) {
  397. var operator = expr.operator,
  398. value = expr.value,
  399. precision = expr.precision;
  400. if (operator === ">") {
  401. return dataStats.min < value ? value : null;
  402. } else if (operator === "<") {
  403. return dataStats.min > value ? value : null;
  404. } else if (operator === "~") {
  405. return kbn.roundValue(dataStats.avg - value, precision);
  406. } else if (operator === "=") {
  407. return kbn.roundValue(dataStats.current - value, precision);
  408. } else if (!operator && !isNaN(value)) {
  409. return kbn.roundValue(value, precision);
  410. } else {
  411. return null;
  412. }
  413. }
  414. function configureAxisOptions(data, options) {
  415. var defaults = {
  416. position: 'left',
  417. show: panel.yaxes[0].show,
  418. min: panel.yaxes[0].min,
  419. index: 1,
  420. logBase: panel.yaxes[0].logBase || 1,
  421. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  422. };
  423. // autoscaleSpanOverride(panel.yaxes[0], data[0], defaults);
  424. options.yaxes.push(defaults);
  425. if (_.find(data, {yaxis: 2})) {
  426. var secondY = _.clone(defaults);
  427. secondY.index = 2;
  428. secondY.show = panel.yaxes[1].show;
  429. secondY.logBase = panel.yaxes[1].logBase || 1;
  430. secondY.position = 'right';
  431. secondY.min = panel.yaxes[1].min;
  432. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  433. // autoscaleSpanOverride(panel.yaxes[1], data[1], secondY);
  434. options.yaxes.push(secondY);
  435. applyLogScale(options.yaxes[1], data);
  436. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  437. }
  438. applyLogScale(options.yaxes[0], data);
  439. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  440. }
  441. function applyLogScale(axis, data) {
  442. if (axis.logBase === 1) {
  443. return;
  444. }
  445. var series, i;
  446. var max = axis.max;
  447. if (max === null) {
  448. for (i = 0; i < data.length; i++) {
  449. series = data[i];
  450. if (series.yaxis === axis.index) {
  451. if (max < series.stats.max) {
  452. max = series.stats.max;
  453. }
  454. }
  455. }
  456. if (max === void 0) {
  457. max = Number.MAX_VALUE;
  458. }
  459. }
  460. axis.min = axis.min !== null ? axis.min : 0;
  461. axis.ticks = [0, 1];
  462. var nextTick = 1;
  463. while (true) {
  464. nextTick = nextTick * axis.logBase;
  465. axis.ticks.push(nextTick);
  466. if (nextTick > max) {
  467. break;
  468. }
  469. }
  470. if (axis.logBase === 10) {
  471. axis.transform = function(v) { return Math.log(v+0.1); };
  472. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  473. } else {
  474. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  475. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  476. }
  477. }
  478. function configureAxisMode(axis, format) {
  479. axis.tickFormatter = function(val, axis) {
  480. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  481. };
  482. }
  483. function time_format(ticks, min, max) {
  484. if (min && max && ticks) {
  485. var range = max - min;
  486. var secPerTick = (range/ticks) / 1000;
  487. var oneDay = 86400000;
  488. var oneYear = 31536000000;
  489. if (secPerTick <= 45) {
  490. return "%H:%M:%S";
  491. }
  492. if (secPerTick <= 7200 || range <= oneDay) {
  493. return "%H:%M";
  494. }
  495. if (secPerTick <= 80000) {
  496. return "%m/%d %H:%M";
  497. }
  498. if (secPerTick <= 2419200 || range <= oneYear) {
  499. return "%m/%d";
  500. }
  501. return "%Y-%m";
  502. }
  503. return "%H:%M";
  504. }
  505. new GraphTooltip(elem, dashboard, scope, function() {
  506. return sortedSeries;
  507. });
  508. elem.bind("plotselected", function (event, ranges) {
  509. scope.$apply(function() {
  510. timeSrv.setTime({
  511. from : moment.utc(ranges.xaxis.from),
  512. to : moment.utc(ranges.xaxis.to),
  513. });
  514. });
  515. });
  516. }
  517. };
  518. });