graph.ts 20 KB

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