graph.ts 21 KB

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