graph.ts 17 KB

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