graph.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. import 'vendor/flot/jquery.flot';
  2. import 'vendor/flot/jquery.flot.selection';
  3. import 'vendor/flot/jquery.flot.time';
  4. import 'vendor/flot/jquery.flot.stack';
  5. import 'vendor/flot/jquery.flot.stackpercent';
  6. import 'vendor/flot/jquery.flot.fillbelow';
  7. import 'vendor/flot/jquery.flot.crosshair';
  8. import 'vendor/flot/jquery.flot.dashes';
  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. /** @ngInject **/
  21. function graphDirective(timeSrv, popoverSrv, contextSrv) {
  22. return {
  23. restrict: 'A',
  24. template: '',
  25. link: function(scope, elem) {
  26. var ctrl = scope.ctrl;
  27. var dashboard = ctrl.dashboard;
  28. var panel = ctrl.panel;
  29. var annotations = [];
  30. var data;
  31. var plot;
  32. var sortedSeries;
  33. var panelWidth = 0;
  34. var eventManager = new EventManager(ctrl);
  35. var thresholdManager = new ThresholdManager(ctrl);
  36. var tooltip = new GraphTooltip(elem, dashboard, scope, function() {
  37. return sortedSeries;
  38. });
  39. // panel events
  40. ctrl.events.on('panel-teardown', () => {
  41. thresholdManager = null;
  42. if (plot) {
  43. plot.destroy();
  44. plot = null;
  45. }
  46. });
  47. /**
  48. * Split graph rendering into two parts.
  49. * First, calculate series stats in buildFlotPairs() function. Then legend rendering started
  50. * (see ctrl.events.on('render') in legend.ts).
  51. * When legend is rendered it emits 'legend-rendering-complete' and graph rendered.
  52. */
  53. ctrl.events.on('render', renderData => {
  54. data = renderData || data;
  55. if (!data) {
  56. return;
  57. }
  58. annotations = ctrl.annotations || [];
  59. buildFlotPairs(data);
  60. ctrl.events.emit('render-legend');
  61. });
  62. ctrl.events.on('legend-rendering-complete', () => {
  63. render_panel();
  64. });
  65. // global events
  66. appEvents.on(
  67. 'graph-hover',
  68. evt => {
  69. // ignore other graph hover events if shared tooltip is disabled
  70. if (!dashboard.sharedTooltipModeEnabled()) {
  71. return;
  72. }
  73. // ignore if we are the emitter
  74. if (!plot || evt.panel.id === panel.id || ctrl.otherPanelInFullscreenMode()) {
  75. return;
  76. }
  77. tooltip.show(evt.pos);
  78. },
  79. scope
  80. );
  81. appEvents.on(
  82. 'graph-hover-clear',
  83. (event, info) => {
  84. if (plot) {
  85. tooltip.clear(plot);
  86. }
  87. },
  88. scope
  89. );
  90. function shouldAbortRender() {
  91. if (!data) {
  92. return true;
  93. }
  94. if (panelWidth === 0) {
  95. return true;
  96. }
  97. return false;
  98. }
  99. function drawHook(plot) {
  100. // add left axis labels
  101. if (panel.yaxes[0].label && panel.yaxes[0].show) {
  102. $("<div class='axisLabel left-yaxis-label flot-temp-elem'></div>")
  103. .text(panel.yaxes[0].label)
  104. .appendTo(elem);
  105. }
  106. // add right axis labels
  107. if (panel.yaxes[1].label && panel.yaxes[1].show) {
  108. $("<div class='axisLabel right-yaxis-label flot-temp-elem'></div>")
  109. .text(panel.yaxes[1].label)
  110. .appendTo(elem);
  111. }
  112. if (ctrl.dataWarning) {
  113. $(`<div class="datapoints-warning flot-temp-elem">${ctrl.dataWarning.title}</div>`).appendTo(elem);
  114. }
  115. thresholdManager.draw(plot);
  116. }
  117. function processOffsetHook(plot, gridMargin) {
  118. var left = panel.yaxes[0];
  119. var right = panel.yaxes[1];
  120. if (left.show && left.label) {
  121. gridMargin.left = 20;
  122. }
  123. if (right.show && right.label) {
  124. gridMargin.right = 20;
  125. }
  126. // apply y-axis min/max options
  127. var yaxis = plot.getYAxes();
  128. for (var i = 0; i < yaxis.length; i++) {
  129. var axis = yaxis[i];
  130. var panelOptions = panel.yaxes[i];
  131. axis.options.max = axis.options.max !== null ? axis.options.max : panelOptions.max;
  132. axis.options.min = axis.options.min !== null ? axis.options.min : panelOptions.min;
  133. }
  134. }
  135. // Series could have different timeSteps,
  136. // let's find the smallest one so that bars are correctly rendered.
  137. // In addition, only take series which are rendered as bars for this.
  138. function getMinTimeStepOfSeries(data) {
  139. var min = Number.MAX_VALUE;
  140. for (let i = 0; i < data.length; i++) {
  141. if (!data[i].stats.timeStep) {
  142. continue;
  143. }
  144. if (panel.bars) {
  145. if (data[i].bars && data[i].bars.show === false) {
  146. continue;
  147. }
  148. } else {
  149. if (typeof data[i].bars === 'undefined' || typeof data[i].bars.show === 'undefined' || !data[i].bars.show) {
  150. continue;
  151. }
  152. }
  153. if (data[i].stats.timeStep < min) {
  154. min = data[i].stats.timeStep;
  155. }
  156. }
  157. return min;
  158. }
  159. // Function for rendering panel
  160. function render_panel() {
  161. panelWidth = elem.width();
  162. if (shouldAbortRender()) {
  163. return;
  164. }
  165. // give space to alert editing
  166. thresholdManager.prepare(elem, data);
  167. // un-check dashes if lines are unchecked
  168. panel.dashes = panel.lines ? panel.dashes : false;
  169. // Populate element
  170. let options: any = buildFlotOptions(panel);
  171. prepareXAxis(options, panel);
  172. configureYAxisOptions(data, options);
  173. thresholdManager.addFlotOptions(options, panel);
  174. eventManager.addFlotEvents(annotations, options);
  175. sortedSeries = sortSeries(data, panel);
  176. callPlot(options, true);
  177. }
  178. function buildFlotPairs(data) {
  179. for (let i = 0; i < data.length; i++) {
  180. let series = data[i];
  181. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  182. // if hidden remove points and disable stack
  183. if (ctrl.hiddenSeries[series.alias]) {
  184. series.data = [];
  185. series.stack = false;
  186. }
  187. }
  188. }
  189. function prepareXAxis(options, panel) {
  190. switch (panel.xaxis.mode) {
  191. case 'series': {
  192. options.series.bars.barWidth = 0.7;
  193. options.series.bars.align = 'center';
  194. for (let i = 0; i < data.length; i++) {
  195. let series = data[i];
  196. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  197. }
  198. addXSeriesAxis(options);
  199. break;
  200. }
  201. case 'histogram': {
  202. let bucketSize: number;
  203. let values = getSeriesValues(data);
  204. if (data.length && values.length) {
  205. let histMin = _.min(_.map(data, s => s.stats.min));
  206. let histMax = _.max(_.map(data, s => s.stats.max));
  207. let ticks = panel.xaxis.buckets || panelWidth / 50;
  208. bucketSize = tickStep(histMin, histMax, ticks);
  209. let histogram = convertValuesToHistogram(values, bucketSize);
  210. data[0].data = histogram;
  211. options.series.bars.barWidth = bucketSize * 0.8;
  212. } else {
  213. bucketSize = 0;
  214. }
  215. addXHistogramAxis(options, bucketSize);
  216. break;
  217. }
  218. case 'table': {
  219. options.series.bars.barWidth = 0.7;
  220. options.series.bars.align = 'center';
  221. addXTableAxis(options);
  222. break;
  223. }
  224. default: {
  225. options.series.bars.barWidth = getMinTimeStepOfSeries(data) / 1.5;
  226. addTimeAxis(options);
  227. break;
  228. }
  229. }
  230. }
  231. function callPlot(options, incrementRenderCounter) {
  232. try {
  233. plot = $.plot(elem, sortedSeries, options);
  234. if (ctrl.renderError) {
  235. delete ctrl.error;
  236. delete ctrl.inspector;
  237. }
  238. } catch (e) {
  239. console.log('flotcharts error', e);
  240. ctrl.error = e.message || 'Render Error';
  241. ctrl.renderError = true;
  242. ctrl.inspector = { error: e };
  243. }
  244. if (incrementRenderCounter) {
  245. ctrl.renderingCompleted();
  246. }
  247. }
  248. function buildFlotOptions(panel) {
  249. const stack = panel.stack ? true : null;
  250. let options = {
  251. hooks: {
  252. draw: [drawHook],
  253. processOffset: [processOffsetHook],
  254. },
  255. legend: { show: false },
  256. series: {
  257. stackpercent: panel.stack ? panel.percentage : false,
  258. stack: panel.percentage ? null : stack,
  259. lines: {
  260. show: panel.lines,
  261. zero: false,
  262. fill: translateFillOption(panel.fill),
  263. lineWidth: panel.dashes ? 0 : panel.linewidth,
  264. steps: panel.steppedLine,
  265. },
  266. dashes: {
  267. show: panel.dashes,
  268. lineWidth: panel.linewidth,
  269. dashLength: [panel.dashLength, panel.spaceLength],
  270. },
  271. bars: {
  272. show: panel.bars,
  273. fill: 1,
  274. barWidth: 1,
  275. zero: false,
  276. lineWidth: 0,
  277. },
  278. points: {
  279. show: panel.points,
  280. fill: 1,
  281. fillColor: false,
  282. radius: panel.points ? panel.pointradius : 2,
  283. },
  284. shadowSize: 0,
  285. },
  286. yaxes: [],
  287. xaxis: {},
  288. grid: {
  289. minBorderMargin: 0,
  290. markings: [],
  291. backgroundColor: null,
  292. borderWidth: 0,
  293. hoverable: true,
  294. clickable: true,
  295. color: '#c8c8c8',
  296. margin: { left: 0, right: 0 },
  297. labelMarginX: 0,
  298. },
  299. selection: {
  300. mode: 'x',
  301. color: '#666',
  302. },
  303. crosshair: {
  304. mode: 'x',
  305. },
  306. };
  307. return options;
  308. }
  309. function sortSeries(series, panel) {
  310. var sortBy = panel.legend.sort;
  311. var sortOrder = panel.legend.sortDesc;
  312. var haveSortBy = sortBy !== null || sortBy !== undefined;
  313. var haveSortOrder = sortOrder !== null || sortOrder !== undefined;
  314. var shouldSortBy = panel.stack && haveSortBy && haveSortOrder;
  315. var sortDesc = panel.legend.sortDesc === true ? -1 : 1;
  316. series.sort((x, y) => {
  317. if (x.zindex > y.zindex) {
  318. return 1;
  319. }
  320. if (x.zindex < y.zindex) {
  321. return -1;
  322. }
  323. if (shouldSortBy) {
  324. if (x.stats[sortBy] > y.stats[sortBy]) {
  325. return 1 * sortDesc;
  326. }
  327. if (x.stats[sortBy] < y.stats[sortBy]) {
  328. return -1 * sortDesc;
  329. }
  330. }
  331. return 0;
  332. });
  333. return series;
  334. }
  335. function translateFillOption(fill) {
  336. if (panel.percentage && panel.stack) {
  337. return fill === 0 ? 0.001 : fill / 10;
  338. } else {
  339. return fill / 10;
  340. }
  341. }
  342. function addTimeAxis(options) {
  343. var ticks = panelWidth / 100;
  344. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  345. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  346. options.xaxis = {
  347. timezone: dashboard.getTimezone(),
  348. show: panel.xaxis.show,
  349. mode: 'time',
  350. min: min,
  351. max: max,
  352. label: 'Datetime',
  353. ticks: ticks,
  354. timeformat: time_format(ticks, min, max),
  355. };
  356. }
  357. function addXSeriesAxis(options) {
  358. var ticks = _.map(data, function(series, index) {
  359. return [index + 1, series.alias];
  360. });
  361. options.xaxis = {
  362. timezone: dashboard.getTimezone(),
  363. show: panel.xaxis.show,
  364. mode: null,
  365. min: 0,
  366. max: ticks.length + 1,
  367. label: 'Datetime',
  368. ticks: ticks,
  369. };
  370. }
  371. function addXHistogramAxis(options, bucketSize) {
  372. let ticks, min, max;
  373. let defaultTicks = panelWidth / 50;
  374. if (data.length && bucketSize) {
  375. ticks = _.map(data[0].data, point => point[0]);
  376. min = _.min(ticks);
  377. max = _.max(ticks);
  378. // Adjust tick step
  379. let tickStep = bucketSize;
  380. let ticks_num = Math.floor((max - min) / tickStep);
  381. while (ticks_num > defaultTicks) {
  382. tickStep = tickStep * 2;
  383. ticks_num = Math.ceil((max - min) / tickStep);
  384. }
  385. // Expand ticks for pretty view
  386. min = Math.floor(min / tickStep) * tickStep;
  387. max = Math.ceil(max / tickStep) * tickStep;
  388. ticks = [];
  389. for (let i = min; i <= max; i += tickStep) {
  390. ticks.push(i);
  391. }
  392. } else {
  393. // Set defaults if no data
  394. ticks = defaultTicks / 2;
  395. min = 0;
  396. max = 1;
  397. }
  398. options.xaxis = {
  399. timezone: dashboard.getTimezone(),
  400. show: panel.xaxis.show,
  401. mode: null,
  402. min: min,
  403. max: max,
  404. label: 'Histogram',
  405. ticks: ticks,
  406. };
  407. // Use 'short' format for histogram values
  408. configureAxisMode(options.xaxis, 'short');
  409. }
  410. function addXTableAxis(options) {
  411. var ticks = _.map(data, function(series, seriesIndex) {
  412. return _.map(series.datapoints, function(point, pointIndex) {
  413. var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  414. return [tickIndex + 1, point[1]];
  415. });
  416. });
  417. ticks = _.flatten(ticks, true);
  418. options.xaxis = {
  419. timezone: dashboard.getTimezone(),
  420. show: panel.xaxis.show,
  421. mode: null,
  422. min: 0,
  423. max: ticks.length + 1,
  424. label: 'Datetime',
  425. ticks: ticks,
  426. };
  427. }
  428. function configureYAxisOptions(data, options) {
  429. var defaults = {
  430. position: 'left',
  431. show: panel.yaxes[0].show,
  432. index: 1,
  433. logBase: panel.yaxes[0].logBase || 1,
  434. min: parseNumber(panel.yaxes[0].min),
  435. max: parseNumber(panel.yaxes[0].max),
  436. tickDecimals: panel.yaxes[0].decimals,
  437. };
  438. options.yaxes.push(defaults);
  439. if (_.find(data, { yaxis: 2 })) {
  440. var secondY = _.clone(defaults);
  441. secondY.index = 2;
  442. secondY.show = panel.yaxes[1].show;
  443. secondY.logBase = panel.yaxes[1].logBase || 1;
  444. secondY.position = 'right';
  445. secondY.min = parseNumber(panel.yaxes[1].min);
  446. secondY.max = parseNumber(panel.yaxes[1].max);
  447. secondY.tickDecimals = panel.yaxes[1].decimals;
  448. options.yaxes.push(secondY);
  449. applyLogScale(options.yaxes[1], data);
  450. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? 'percent' : panel.yaxes[1].format);
  451. }
  452. applyLogScale(options.yaxes[0], data);
  453. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? 'percent' : panel.yaxes[0].format);
  454. }
  455. function parseNumber(value: any) {
  456. if (value === null || typeof value === 'undefined') {
  457. return null;
  458. }
  459. return _.toNumber(value);
  460. }
  461. function applyLogScale(axis, data) {
  462. if (axis.logBase === 1) {
  463. return;
  464. }
  465. const minSetToZero = axis.min === 0;
  466. if (axis.min < Number.MIN_VALUE) {
  467. axis.min = null;
  468. }
  469. if (axis.max < Number.MIN_VALUE) {
  470. axis.max = null;
  471. }
  472. var series, i;
  473. var max = axis.max,
  474. min = axis.min;
  475. for (i = 0; i < data.length; i++) {
  476. series = data[i];
  477. if (series.yaxis === axis.index) {
  478. if (!max || max < series.stats.max) {
  479. max = series.stats.max;
  480. }
  481. if (!min || min > series.stats.logmin) {
  482. min = series.stats.logmin;
  483. }
  484. }
  485. }
  486. axis.transform = function(v) {
  487. return v < Number.MIN_VALUE ? null : Math.log(v) / Math.log(axis.logBase);
  488. };
  489. axis.inverseTransform = function(v) {
  490. return Math.pow(axis.logBase, v);
  491. };
  492. if (!max && !min) {
  493. max = axis.inverseTransform(+2);
  494. min = axis.inverseTransform(-2);
  495. } else if (!max) {
  496. max = min * axis.inverseTransform(+4);
  497. } else if (!min) {
  498. min = max * axis.inverseTransform(-4);
  499. }
  500. if (axis.min) {
  501. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  502. } else {
  503. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  504. }
  505. if (axis.max) {
  506. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  507. } else {
  508. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  509. }
  510. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  511. return;
  512. }
  513. if (Number.isFinite(min) && Number.isFinite(max)) {
  514. if (minSetToZero) {
  515. axis.min = 0.1;
  516. min = 1;
  517. }
  518. axis.ticks = generateTicksForLogScaleYAxis(min, max, axis.logBase);
  519. if (minSetToZero) {
  520. axis.ticks.unshift(0.1);
  521. }
  522. if (axis.ticks[axis.ticks.length - 1] > axis.max) {
  523. axis.max = axis.ticks[axis.ticks.length - 1];
  524. }
  525. } else {
  526. axis.ticks = [1, 2];
  527. delete axis.min;
  528. delete axis.max;
  529. }
  530. }
  531. function generateTicksForLogScaleYAxis(min, max, logBase) {
  532. let ticks = [];
  533. var nextTick;
  534. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  535. ticks.push(nextTick);
  536. }
  537. const maxNumTicks = Math.ceil(ctrl.height / 25);
  538. const numTicks = ticks.length;
  539. if (numTicks > maxNumTicks) {
  540. const factor = Math.ceil(numTicks / maxNumTicks) * logBase;
  541. ticks = [];
  542. for (nextTick = min; nextTick <= max * factor; nextTick *= factor) {
  543. ticks.push(nextTick);
  544. }
  545. }
  546. return ticks;
  547. }
  548. function configureAxisMode(axis, format) {
  549. axis.tickFormatter = function(val, axis) {
  550. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  551. };
  552. }
  553. function time_format(ticks, min, max) {
  554. if (min && max && ticks) {
  555. var range = max - min;
  556. var secPerTick = range / ticks / 1000;
  557. var oneDay = 86400000;
  558. var oneYear = 31536000000;
  559. if (secPerTick <= 45) {
  560. return '%H:%M:%S';
  561. }
  562. if (secPerTick <= 7200 || range <= oneDay) {
  563. return '%H:%M';
  564. }
  565. if (secPerTick <= 80000) {
  566. return '%m/%d %H:%M';
  567. }
  568. if (secPerTick <= 2419200 || range <= oneYear) {
  569. return '%m/%d';
  570. }
  571. return '%Y-%m';
  572. }
  573. return '%H:%M';
  574. }
  575. elem.bind('plotselected', function(event, ranges) {
  576. if (panel.xaxis.mode !== 'time') {
  577. // Skip if panel in histogram or series mode
  578. plot.clearSelection();
  579. return;
  580. }
  581. if ((ranges.ctrlKey || ranges.metaKey) && contextSrv.isEditor) {
  582. // Add annotation
  583. setTimeout(() => {
  584. eventManager.updateTime(ranges.xaxis);
  585. }, 100);
  586. } else {
  587. scope.$apply(function() {
  588. timeSrv.setTime({
  589. from: moment.utc(ranges.xaxis.from),
  590. to: moment.utc(ranges.xaxis.to),
  591. });
  592. });
  593. }
  594. });
  595. elem.bind('plotclick', function(event, pos, item) {
  596. if (panel.xaxis.mode !== 'time') {
  597. // Skip if panel in histogram or series mode
  598. return;
  599. }
  600. if ((pos.ctrlKey || pos.metaKey) && contextSrv.isEditor) {
  601. // Skip if range selected (added in "plotselected" event handler)
  602. let isRangeSelection = pos.x !== pos.x1;
  603. if (!isRangeSelection) {
  604. setTimeout(() => {
  605. eventManager.updateTime({ from: pos.x, to: null });
  606. }, 100);
  607. }
  608. }
  609. });
  610. scope.$on('$destroy', function() {
  611. tooltip.destroy();
  612. elem.off();
  613. elem.remove();
  614. });
  615. },
  616. };
  617. }
  618. coreModule.directive('grafanaGraph', graphDirective);