graph.ts 19 KB

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