graph.ts 21 KB

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