graph.ts 20 KB

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