graph.ts 20 KB

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