graph.ts 20 KB

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