graph.ts 21 KB

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