graph.ts 21 KB

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