graph.ts 21 KB

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