graph.ts 20 KB

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