graph.ts 20 KB

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