graph.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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, 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 legendSideLastValue = null;
  35. var rootScope = scope.$root;
  36. var panelWidth = 0;
  37. var eventManager = new EventManager(ctrl);
  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. labelMarginX: 0,
  236. },
  237. selection: {
  238. mode: "x",
  239. color: '#666'
  240. },
  241. crosshair: {
  242. mode: 'x'
  243. }
  244. };
  245. for (let i = 0; i < data.length; i++) {
  246. let series = data[i];
  247. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  248. // if hidden remove points and disable stack
  249. if (ctrl.hiddenSeries[series.alias]) {
  250. series.data = [];
  251. series.stack = false;
  252. }
  253. }
  254. switch (panel.xaxis.mode) {
  255. case 'series': {
  256. options.series.bars.barWidth = 0.7;
  257. options.series.bars.align = 'center';
  258. for (let i = 0; i < data.length; i++) {
  259. let series = data[i];
  260. series.data = [[i + 1, series.stats[panel.xaxis.values[0]]]];
  261. }
  262. addXSeriesAxis(options);
  263. break;
  264. }
  265. case 'histogram': {
  266. let bucketSize: number;
  267. let values = getSeriesValues(data);
  268. if (data.length && values.length) {
  269. let histMin = _.min(_.map(data, s => s.stats.min));
  270. let histMax = _.max(_.map(data, s => s.stats.max));
  271. let ticks = panel.xaxis.buckets || panelWidth / 50;
  272. bucketSize = tickStep(histMin, histMax, ticks);
  273. let histogram = convertValuesToHistogram(values, bucketSize);
  274. data[0].data = histogram;
  275. data[0].alias = data[0].label = data[0].id = "count";
  276. data = [data[0]];
  277. options.series.bars.barWidth = bucketSize * 0.8;
  278. } else {
  279. bucketSize = 0;
  280. }
  281. addXHistogramAxis(options, bucketSize);
  282. break;
  283. }
  284. case 'table': {
  285. options.series.bars.barWidth = 0.7;
  286. options.series.bars.align = 'center';
  287. addXTableAxis(options);
  288. break;
  289. }
  290. default: {
  291. options.series.bars.barWidth = getMinTimeStepOfSeries(data) / 1.5;
  292. addTimeAxis(options);
  293. break;
  294. }
  295. }
  296. thresholdManager.addFlotOptions(options, panel);
  297. eventManager.addFlotEvents(annotations, options);
  298. configureAxisOptions(data, options);
  299. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  300. function callPlot(incrementRenderCounter) {
  301. try {
  302. plot = $.plot(elem, sortedSeries, options);
  303. if (ctrl.renderError) {
  304. delete ctrl.error;
  305. delete ctrl.inspector;
  306. }
  307. } catch (e) {
  308. console.log('flotcharts error', e);
  309. ctrl.error = e.message || "Render Error";
  310. ctrl.renderError = true;
  311. ctrl.inspector = {error: e};
  312. }
  313. if (incrementRenderCounter) {
  314. ctrl.renderingCompleted();
  315. }
  316. }
  317. if (shouldDelayDraw(panel)) {
  318. // temp fix for legends on the side, need to render twice to get dimensions right
  319. callPlot(false);
  320. setTimeout(function() { callPlot(true); }, 50);
  321. legendSideLastValue = panel.legend.rightSide;
  322. } else {
  323. callPlot(true);
  324. }
  325. }
  326. function translateFillOption(fill) {
  327. if (panel.percentage && panel.stack) {
  328. return fill === 0 ? 0.001 : fill/10;
  329. } else {
  330. return fill/10;
  331. }
  332. }
  333. function shouldDelayDraw(panel) {
  334. if (panel.legend.rightSide) {
  335. return true;
  336. }
  337. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  338. return true;
  339. }
  340. return false;
  341. }
  342. function addTimeAxis(options) {
  343. var ticks = panelWidth / 100;
  344. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  345. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  346. options.xaxis = {
  347. timezone: dashboard.getTimezone(),
  348. show: panel.xaxis.show,
  349. mode: "time",
  350. min: min,
  351. max: max,
  352. label: "Datetime",
  353. ticks: ticks,
  354. timeformat: time_format(ticks, min, max),
  355. };
  356. }
  357. function addXSeriesAxis(options) {
  358. var ticks = _.map(data, function(series, index) {
  359. return [index + 1, series.alias];
  360. });
  361. options.xaxis = {
  362. timezone: dashboard.getTimezone(),
  363. show: panel.xaxis.show,
  364. mode: null,
  365. min: 0,
  366. max: ticks.length + 1,
  367. label: "Datetime",
  368. ticks: ticks
  369. };
  370. }
  371. function addXHistogramAxis(options, bucketSize) {
  372. let ticks, min, max;
  373. let defaultTicks = panelWidth / 50;
  374. if (data.length && bucketSize) {
  375. ticks = _.map(data[0].data, point => point[0]);
  376. min = _.min(ticks);
  377. max = _.max(ticks);
  378. // Adjust tick step
  379. let tickStep = bucketSize;
  380. let ticks_num = Math.floor((max - min) / tickStep);
  381. while (ticks_num > defaultTicks) {
  382. tickStep = tickStep * 2;
  383. ticks_num = Math.ceil((max - min) / tickStep);
  384. }
  385. // Expand ticks for pretty view
  386. min = Math.floor(min / tickStep) * tickStep;
  387. max = Math.ceil(max / tickStep) * tickStep;
  388. ticks = [];
  389. for (let i = min; i <= max; i += tickStep) {
  390. ticks.push(i);
  391. }
  392. } else {
  393. // Set defaults if no data
  394. ticks = defaultTicks / 2;
  395. min = 0;
  396. max = 1;
  397. }
  398. options.xaxis = {
  399. timezone: dashboard.getTimezone(),
  400. show: panel.xaxis.show,
  401. mode: null,
  402. min: min,
  403. max: max,
  404. label: "Histogram",
  405. ticks: ticks
  406. };
  407. // Use 'short' format for histogram values
  408. configureAxisMode(options.xaxis, 'short');
  409. }
  410. function addXTableAxis(options) {
  411. var ticks = _.map(data, function(series, seriesIndex) {
  412. return _.map(series.datapoints, function(point, pointIndex) {
  413. var tickIndex = seriesIndex * series.datapoints.length + pointIndex;
  414. return [tickIndex + 1, point[1]];
  415. });
  416. });
  417. ticks = _.flatten(ticks, true);
  418. options.xaxis = {
  419. timezone: dashboard.getTimezone(),
  420. show: panel.xaxis.show,
  421. mode: null,
  422. min: 0,
  423. max: ticks.length + 1,
  424. label: "Datetime",
  425. ticks: ticks
  426. };
  427. }
  428. function configureAxisOptions(data, options) {
  429. var defaults = {
  430. position: 'left',
  431. show: panel.yaxes[0].show,
  432. index: 1,
  433. logBase: panel.yaxes[0].logBase || 1,
  434. min: panel.yaxes[0].min ? _.toNumber(panel.yaxes[0].min) : null,
  435. max: panel.yaxes[0].max ? _.toNumber(panel.yaxes[0].max) : null,
  436. tickDecimals: panel.yaxes[0].decimals
  437. };
  438. options.yaxes.push(defaults);
  439. if (_.find(data, {yaxis: 2})) {
  440. var secondY = _.clone(defaults);
  441. secondY.index = 2;
  442. secondY.show = panel.yaxes[1].show;
  443. secondY.logBase = panel.yaxes[1].logBase || 1;
  444. secondY.position = 'right';
  445. secondY.min = panel.yaxes[1].min ? _.toNumber(panel.yaxes[1].min) : null;
  446. secondY.max = panel.yaxes[1].max ? _.toNumber(panel.yaxes[1].max) : null;
  447. secondY.tickDecimals = panel.yaxes[1].decimals !== null ? _.toNumber(panel.yaxes[1].decimals): null;
  448. options.yaxes.push(secondY);
  449. applyLogScale(options.yaxes[1], data);
  450. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  451. }
  452. applyLogScale(options.yaxes[0], data);
  453. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  454. }
  455. function applyLogScale(axis, data) {
  456. if (axis.logBase === 1) {
  457. return;
  458. }
  459. const minSetToZero = axis.min === 0;
  460. if (axis.min < Number.MIN_VALUE) {
  461. axis.min = null;
  462. }
  463. if (axis.max < Number.MIN_VALUE) {
  464. axis.max = null;
  465. }
  466. var series, i;
  467. var max = axis.max, min = axis.min;
  468. for (i = 0; i < data.length; i++) {
  469. series = data[i];
  470. if (series.yaxis === axis.index) {
  471. if (!max || max < series.stats.max) {
  472. max = series.stats.max;
  473. }
  474. if (!min || min > series.stats.logmin) {
  475. min = series.stats.logmin;
  476. }
  477. }
  478. }
  479. axis.transform = function(v) { return (v < Number.MIN_VALUE) ? null : Math.log(v) / Math.log(axis.logBase); };
  480. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  481. if (!max && !min) {
  482. max = axis.inverseTransform(+2);
  483. min = axis.inverseTransform(-2);
  484. } else if (!max) {
  485. max = min*axis.inverseTransform(+4);
  486. } else if (!min) {
  487. min = max*axis.inverseTransform(-4);
  488. }
  489. if (axis.min) {
  490. min = axis.inverseTransform(Math.ceil(axis.transform(axis.min)));
  491. } else {
  492. min = axis.min = axis.inverseTransform(Math.floor(axis.transform(min)));
  493. }
  494. if (axis.max) {
  495. max = axis.inverseTransform(Math.floor(axis.transform(axis.max)));
  496. } else {
  497. max = axis.max = axis.inverseTransform(Math.ceil(axis.transform(max)));
  498. }
  499. if (!min || min < Number.MIN_VALUE || !max || max < Number.MIN_VALUE) {
  500. return;
  501. }
  502. if (Number.isFinite(min) && Number.isFinite(max)) {
  503. if (minSetToZero) {
  504. axis.min = 0.1;
  505. min = 1;
  506. }
  507. axis.ticks = generateTicksForLogScaleYAxis(min, max, axis.logBase);
  508. if (minSetToZero) {
  509. axis.ticks.unshift(0.1);
  510. }
  511. if (axis.ticks[axis.ticks.length - 1] > axis.max) {
  512. axis.max = axis.ticks[axis.ticks.length - 1];
  513. }
  514. } else {
  515. axis.ticks = [1, 2];
  516. delete axis.min;
  517. delete axis.max;
  518. }
  519. }
  520. function generateTicksForLogScaleYAxis(min, max, logBase) {
  521. let ticks = [];
  522. var nextTick;
  523. for (nextTick = min; nextTick <= max; nextTick *= logBase) {
  524. ticks.push(nextTick);
  525. }
  526. const maxNumTicks = Math.ceil(ctrl.height/25);
  527. const numTicks = ticks.length;
  528. if (numTicks > maxNumTicks) {
  529. const factor = Math.ceil(numTicks/maxNumTicks) * logBase;
  530. ticks = [];
  531. for (nextTick = min; nextTick <= (max * factor); nextTick *= factor) {
  532. ticks.push(nextTick);
  533. }
  534. }
  535. return ticks;
  536. }
  537. function configureAxisMode(axis, format) {
  538. axis.tickFormatter = function(val, axis) {
  539. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  540. };
  541. }
  542. function time_format(ticks, min, max) {
  543. if (min && max && ticks) {
  544. var range = max - min;
  545. var secPerTick = (range/ticks) / 1000;
  546. var oneDay = 86400000;
  547. var oneYear = 31536000000;
  548. if (secPerTick <= 45) {
  549. return "%H:%M:%S";
  550. }
  551. if (secPerTick <= 7200 || range <= oneDay) {
  552. return "%H:%M";
  553. }
  554. if (secPerTick <= 80000) {
  555. return "%m/%d %H:%M";
  556. }
  557. if (secPerTick <= 2419200 || range <= oneYear) {
  558. return "%m/%d";
  559. }
  560. return "%Y-%m";
  561. }
  562. return "%H:%M";
  563. }
  564. elem.bind("plotselected", function (event, ranges) {
  565. if ((ranges.ctrlKey || ranges.metaKey) && contextSrv.isEditor) {
  566. setTimeout(() => {
  567. eventManager.updateTime(ranges.xaxis);
  568. }, 100);
  569. } else {
  570. scope.$apply(function() {
  571. timeSrv.setTime({
  572. from : moment.utc(ranges.xaxis.from),
  573. to : moment.utc(ranges.xaxis.to),
  574. });
  575. });
  576. }
  577. });
  578. elem.bind("plotclick", function (event, pos, item) {
  579. if ((pos.ctrlKey || pos.metaKey) && contextSrv.isEditor) {
  580. // Skip if range selected (added in "plotselected" event handler)
  581. let isRangeSelection = pos.x !== pos.x1;
  582. if (!isRangeSelection) {
  583. setTimeout(() => {
  584. eventManager.updateTime({from: pos.x, to: null});
  585. }, 100);
  586. }
  587. }
  588. });
  589. scope.$on('$destroy', function() {
  590. tooltip.destroy();
  591. elem.off();
  592. elem.remove();
  593. });
  594. }
  595. };
  596. }
  597. coreModule.directive('grafanaGraph', graphDirective);