graph.ts 21 KB

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