graph.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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 $ from 'jquery';
  11. import _ from 'lodash';
  12. import moment from 'moment';
  13. import kbn from 'app/core/utils/kbn';
  14. import {tickStep} from 'app/core/utils/ticks';
  15. import {appEvents, coreModule} from 'app/core/core';
  16. import GraphTooltip from './graph_tooltip';
  17. import {ThresholdManager} from './threshold_manager';
  18. import {EventManager} from 'app/features/annotations/all';
  19. import {convertValuesToHistogram, getSeriesValues} from './histogram';
  20. coreModule.directive('grafanaGraph', function($rootScope, timeSrv, popoverSrv) {
  21. return {
  22. restrict: 'A',
  23. template: '',
  24. link: function(scope, elem) {
  25. var ctrl = scope.ctrl;
  26. var dashboard = ctrl.dashboard;
  27. var panel = ctrl.panel;
  28. var annotations = [];
  29. var data;
  30. var plot;
  31. var sortedSeries;
  32. var legendSideLastValue = null;
  33. var rootScope = scope.$root;
  34. var panelWidth = 0;
  35. var eventManager = new EventManager(ctrl, elem, popoverSrv);
  36. var thresholdManager = new ThresholdManager(ctrl);
  37. var tooltip = new GraphTooltip(elem, dashboard, scope, function() {
  38. return sortedSeries;
  39. });
  40. // panel events
  41. ctrl.events.on('panel-teardown', () => {
  42. thresholdManager = null;
  43. if (plot) {
  44. plot.destroy();
  45. plot = null;
  46. }
  47. });
  48. ctrl.events.on('render', function(renderData) {
  49. data = renderData || data;
  50. if (!data) {
  51. return;
  52. }
  53. annotations = ctrl.annotations || [];
  54. render_panel();
  55. });
  56. // global events
  57. appEvents.on('graph-hover', function(evt) {
  58. // ignore other graph hover events if shared tooltip is disabled
  59. if (!dashboard.sharedTooltipModeEnabled()) {
  60. return;
  61. }
  62. // ignore if we are the emitter
  63. if (!plot || evt.panel.id === panel.id || ctrl.otherPanelInFullscreenMode()) {
  64. return;
  65. }
  66. tooltip.show(evt.pos);
  67. }, scope);
  68. appEvents.on('graph-hover-clear', function(event, info) {
  69. if (plot) {
  70. tooltip.clear(plot);
  71. }
  72. }, scope);
  73. function getLegendHeight(panelHeight) {
  74. if (!panel.legend.show || panel.legend.rightSide) {
  75. return 0;
  76. }
  77. if (panel.legend.alignAsTable) {
  78. var legendSeries = _.filter(data, function(series) {
  79. return series.hideFromLegend(panel.legend) === false;
  80. });
  81. var total = 23 + (21 * legendSeries.length);
  82. return Math.min(total, Math.floor(panelHeight/2));
  83. } else {
  84. return 26;
  85. }
  86. }
  87. function setElementHeight() {
  88. try {
  89. var height = ctrl.height - getLegendHeight(ctrl.height);
  90. elem.css('height', height + 'px');
  91. return true;
  92. } catch (e) { // IE throws errors sometimes
  93. console.log(e);
  94. return false;
  95. }
  96. }
  97. function shouldAbortRender() {
  98. if (!data) {
  99. return true;
  100. }
  101. if (!setElementHeight()) { return true; }
  102. if (panelWidth === 0) {
  103. return true;
  104. }
  105. }
  106. function drawHook(plot) {
  107. // Update legend values
  108. var yaxis = plot.getYAxes();
  109. for (var i = 0; i < data.length; i++) {
  110. var series = data[i];
  111. var axis = yaxis[series.yaxis - 1];
  112. var formater = kbn.valueFormats[panel.yaxes[series.yaxis - 1].format];
  113. // decimal override
  114. if (_.isNumber(panel.decimals)) {
  115. series.updateLegendValues(formater, panel.decimals, null);
  116. } else {
  117. // auto decimals
  118. // legend and tooltip gets one more decimal precision
  119. // than graph legend ticks
  120. var tickDecimals = (axis.tickDecimals || -1) + 1;
  121. series.updateLegendValues(formater, tickDecimals, axis.scaledDecimals + 2);
  122. }
  123. if (!rootScope.$$phase) { scope.$digest(); }
  124. }
  125. // add left axis labels
  126. if (panel.yaxes[0].label) {
  127. var yaxisLabel = $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
  128. .text(panel.yaxes[0].label)
  129. .appendTo(elem);
  130. }
  131. // add right axis labels
  132. if (panel.yaxes[1].label) {
  133. var rightLabel = $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
  134. .text(panel.yaxes[1].label)
  135. .appendTo(elem);
  136. }
  137. thresholdManager.draw(plot);
  138. }
  139. function processOffsetHook(plot, gridMargin) {
  140. var left = panel.yaxes[0];
  141. var right = panel.yaxes[1];
  142. if (left.show && left.label) { gridMargin.left = 20; }
  143. if (right.show && right.label) { gridMargin.right = 20; }
  144. // apply y-axis min/max options
  145. var yaxis = plot.getYAxes();
  146. for (var i = 0; i < yaxis.length; i++) {
  147. var axis = yaxis[i];
  148. var panelOptions = panel.yaxes[i];
  149. axis.options.max = panelOptions.max;
  150. axis.options.min = panelOptions.min;
  151. }
  152. }
  153. // Series could have different timeSteps,
  154. // let's find the smallest one so that bars are correctly rendered.
  155. // In addition, only take series which are rendered as bars for this.
  156. function getMinTimeStepOfSeries(data) {
  157. var min = Number.MAX_VALUE;
  158. for (let i = 0; i < data.length; i++) {
  159. if (!data[i].stats.timeStep) {
  160. continue;
  161. }
  162. if (panel.bars) {
  163. if (data[i].bars && data[i].bars.show === false) {
  164. continue;
  165. }
  166. } else {
  167. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  168. continue;
  169. }
  170. }
  171. if (data[i].stats.timeStep < min) {
  172. min = data[i].stats.timeStep;
  173. }
  174. }
  175. return min;
  176. }
  177. // Function for rendering panel
  178. function render_panel() {
  179. panelWidth = elem.width();
  180. if (shouldAbortRender()) {
  181. return;
  182. }
  183. // give space to alert editing
  184. thresholdManager.prepare(elem, data);
  185. var stack = panel.stack ? true : null;
  186. // Populate element
  187. var options: any = {
  188. hooks: {
  189. draw: [drawHook],
  190. processOffset: [processOffsetHook],
  191. },
  192. legend: { show: false },
  193. series: {
  194. stackpercent: panel.stack ? panel.percentage : false,
  195. stack: panel.percentage ? null : stack,
  196. lines: {
  197. show: panel.lines,
  198. zero: false,
  199. fill: translateFillOption(panel.fill),
  200. lineWidth: panel.linewidth,
  201. steps: panel.steppedLine
  202. },
  203. bars: {
  204. show: panel.bars,
  205. fill: 1,
  206. barWidth: 1,
  207. zero: false,
  208. lineWidth: 0
  209. },
  210. points: {
  211. show: panel.points,
  212. fill: 1,
  213. fillColor: false,
  214. radius: panel.points ? panel.pointradius : 2
  215. },
  216. shadowSize: 0
  217. },
  218. yaxes: [],
  219. xaxis: {},
  220. grid: {
  221. minBorderMargin: 0,
  222. markings: [],
  223. backgroundColor: null,
  224. borderWidth: 0,
  225. hoverable: true,
  226. clickable: true,
  227. color: '#c8c8c8',
  228. margin: { left: 0, right: 0 },
  229. },
  230. selection: {
  231. mode: "x",
  232. color: '#666'
  233. },
  234. crosshair: {
  235. mode: 'x'
  236. }
  237. };
  238. for (let i = 0; i < data.length; i++) {
  239. let series = data[i];
  240. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  241. // if hidden remove points and disable stack
  242. if (ctrl.hiddenSeries[series.alias]) {
  243. series.data = [];
  244. series.stack = false;
  245. }
  246. }
  247. switch (panel.xaxis.mode) {
  248. case 'series': {
  249. options.series.bars.barWidth = 0.7;
  250. options.series.bars.align = 'center';
  251. for (let i = 0; i < data.length; i++) {
  252. let series = data[i];
  253. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  254. }
  255. addXSeriesAxis(options);
  256. break;
  257. }
  258. case 'histogram': {
  259. let bucketSize: number;
  260. let values = getSeriesValues(data);
  261. if (data.length && values.length) {
  262. let histMin = _.min(_.map(data, s => s.stats.min));
  263. let histMax = _.max(_.map(data, s => s.stats.max));
  264. let ticks = panel.xaxis.buckets || panelWidth / 50;
  265. bucketSize = tickStep(histMin, histMax, ticks);
  266. let histogram = convertValuesToHistogram(values, bucketSize);
  267. data[0].data = histogram;
  268. data[0].alias = data[0].label = data[0].id = "count";
  269. data = [data[0]];
  270. options.series.bars.barWidth = bucketSize * 0.8;
  271. } else {
  272. bucketSize = 0;
  273. }
  274. addXHistogramAxis(options, bucketSize);
  275. break;
  276. }
  277. case 'table': {
  278. options.series.bars.barWidth = 0.7;
  279. options.series.bars.align = 'center';
  280. addXTableAxis(options);
  281. break;
  282. }
  283. default: {
  284. options.series.bars.barWidth = getMinTimeStepOfSeries(data) / 1.5;
  285. addTimeAxis(options);
  286. break;
  287. }
  288. }
  289. thresholdManager.addFlotOptions(options, panel);
  290. eventManager.addFlotEvents(annotations, options);
  291. configureAxisOptions(data, options);
  292. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  293. function callPlot(incrementRenderCounter) {
  294. try {
  295. plot = $.plot(elem, sortedSeries, options);
  296. if (ctrl.renderError) {
  297. delete ctrl.error;
  298. delete ctrl.inspector;
  299. }
  300. } catch (e) {
  301. console.log('flotcharts error', e);
  302. ctrl.error = e.message || "Render Error";
  303. ctrl.renderError = true;
  304. ctrl.inspector = {error: e};
  305. }
  306. if (incrementRenderCounter) {
  307. ctrl.renderingCompleted();
  308. }
  309. }
  310. if (shouldDelayDraw(panel)) {
  311. // temp fix for legends on the side, need to render twice to get dimensions right
  312. callPlot(false);
  313. setTimeout(function() { callPlot(true); }, 50);
  314. legendSideLastValue = panel.legend.rightSide;
  315. } else {
  316. callPlot(true);
  317. }
  318. }
  319. function translateFillOption(fill) {
  320. return fill === 0 ? 0.001 : fill/10;
  321. }
  322. function shouldDelayDraw(panel) {
  323. if (panel.legend.rightSide) {
  324. return true;
  325. }
  326. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  327. return true;
  328. }
  329. }
  330. function addTimeAxis(options) {
  331. var ticks = panelWidth / 100;
  332. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  333. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  334. options.xaxis = {
  335. timezone: dashboard.getTimezone(),
  336. show: panel.xaxis.show,
  337. mode: "time",
  338. min: min,
  339. max: max,
  340. label: "Datetime",
  341. ticks: ticks,
  342. timeformat: time_format(ticks, min, max),
  343. };
  344. }
  345. function addXSeriesAxis(options) {
  346. var ticks = _.map(data, function(series, index) {
  347. return [index + 1, series.alias];
  348. });
  349. options.xaxis = {
  350. timezone: dashboard.getTimezone(),
  351. show: panel.xaxis.show,
  352. mode: null,
  353. min: 0,
  354. max: ticks.length + 1,
  355. label: "Datetime",
  356. ticks: ticks
  357. };
  358. }
  359. function addXHistogramAxis(options, bucketSize) {
  360. let ticks, min, max;
  361. if (data.length) {
  362. ticks = _.map(data[0].data, point => point[0]);
  363. // Expand ticks for pretty view
  364. min = Math.max(0, _.min(ticks) - bucketSize);
  365. max = _.max(ticks) + bucketSize;
  366. ticks = [];
  367. for (let i = min; i <= max; i += bucketSize) {
  368. ticks.push(i);
  369. }
  370. } else {
  371. // Set defaults if no data
  372. ticks = panelWidth / 100;
  373. min = 0;
  374. max = 1;
  375. }
  376. options.xaxis = {
  377. timezone: dashboard.getTimezone(),
  378. show: panel.xaxis.show,
  379. mode: null,
  380. min: min,
  381. max: max,
  382. label: "Histogram",
  383. ticks: ticks
  384. };
  385. }
  386. function addXTableAxis(options) {
  387. var ticks = _.map(data, function(series, seriesIndex) {
  388. return _.map(series.datapoints, function(point, pointIndex) {
  389. var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  390. return [tickIndex + 1, point[1]];
  391. });
  392. });
  393. ticks = _.flatten(ticks, true);
  394. options.xaxis = {
  395. timezone: dashboard.getTimezone(),
  396. show: panel.xaxis.show,
  397. mode: null,
  398. min: 0,
  399. max: ticks.length + 1,
  400. label: "Datetime",
  401. ticks: ticks
  402. };
  403. }
  404. function configureAxisOptions(data, options) {
  405. var defaults = {
  406. position: 'left',
  407. show: panel.yaxes[0].show,
  408. index: 1,
  409. logBase: panel.yaxes[0].logBase || 1,
  410. min: panel.yaxes[0].min ? _.toNumber(panel.yaxes[0].min) : null,
  411. max: panel.yaxes[0].max ? _.toNumber(panel.yaxes[0].max) : null,
  412. };
  413. options.yaxes.push(defaults);
  414. if (_.find(data, {yaxis: 2})) {
  415. var secondY = _.clone(defaults);
  416. secondY.index = 2;
  417. secondY.show = panel.yaxes[1].show;
  418. secondY.logBase = panel.yaxes[1].logBase || 1;
  419. secondY.position = 'right';
  420. secondY.min = panel.yaxes[1].min ? _.toNumber(panel.yaxes[1].min) : null;
  421. secondY.max = panel.yaxes[1].max ? _.toNumber(panel.yaxes[1].max) : null;
  422. options.yaxes.push(secondY);
  423. applyLogScale(options.yaxes[1], data);
  424. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  425. }
  426. applyLogScale(options.yaxes[0], data);
  427. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  428. }
  429. function applyLogScale(axis, data) {
  430. if (axis.logBase === 1) {
  431. return;
  432. }
  433. if (axis.min < Number.MIN_VALUE) {
  434. axis.min = null;
  435. }
  436. if (axis.max < Number.MIN_VALUE) {
  437. axis.max = null;
  438. }
  439. var series, i;
  440. var max = axis.max, min = axis.min;
  441. for (i = 0; i < data.length; i++) {
  442. series = data[i];
  443. if (series.yaxis === axis.index) {
  444. if (!max || max < series.stats.max) {
  445. max = series.stats.max;
  446. }
  447. if (!min || min > series.stats.logmin) {
  448. min = series.stats.logmin;
  449. }
  450. }
  451. }
  452. axis.transform = function(v) { return (v < Number.MIN_VALUE) ? null : Math.log(v) / Math.log(axis.logBase); };
  453. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  454. if (!max && !min) {
  455. max = axis.inverseTransform(+2);
  456. min = axis.inverseTransform(-2);
  457. } else if (!max) {
  458. max = min*axis.inverseTransform(+4);
  459. } else if (!min) {
  460. min = max*axis.inverseTransform(-4);
  461. }
  462. if (axis.min) {
  463. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  464. } else {
  465. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  466. }
  467. if (axis.max) {
  468. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  469. } else {
  470. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  471. }
  472. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  473. return;
  474. }
  475. axis.ticks = [];
  476. var nextTick;
  477. for (nextTick = min; nextTick <= max; nextTick *= axis.logBase) {
  478. axis.ticks.push(nextTick);
  479. }
  480. axis.tickDecimals = decimalPlaces(min);
  481. }
  482. function decimalPlaces(num) {
  483. if (!num) { return 0; }
  484. return (num.toString().split('.')[1] || []).length;
  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. elem.bind("plotselected", function (event, ranges) {
  514. if (ranges.ctrlKey || ranges.metaKey) {
  515. // scope.$apply(() => {
  516. // eventManager.updateTime(ranges.xaxis);
  517. // });
  518. } else {
  519. scope.$apply(function() {
  520. timeSrv.setTime({
  521. from : moment.utc(ranges.xaxis.from),
  522. to : moment.utc(ranges.xaxis.to),
  523. });
  524. });
  525. }
  526. });
  527. elem.bind("plotclick", function (event, pos, item) {
  528. if (pos.ctrlKey || pos.metaKey || eventManager.event) {
  529. // Skip if range selected (added in "plotselected" event handler)
  530. let isRangeSelection = pos.x !== pos.x1;
  531. if (!isRangeSelection) {
  532. // scope.$apply(() => {
  533. // eventManager.updateTime({from: pos.x, to: null});
  534. // });
  535. }
  536. }
  537. });
  538. scope.$on('$destroy', function() {
  539. tooltip.destroy();
  540. elem.off();
  541. elem.remove();
  542. });
  543. }
  544. };
  545. });