graph.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. define([
  2. 'angular',
  3. 'jquery',
  4. 'moment',
  5. 'lodash',
  6. 'app/core/utils/kbn',
  7. './graph_tooltip',
  8. './threshold_manager',
  9. 'jquery.flot',
  10. 'jquery.flot.selection',
  11. 'jquery.flot.time',
  12. 'jquery.flot.stack',
  13. 'jquery.flot.stackpercent',
  14. 'jquery.flot.fillbelow',
  15. 'jquery.flot.crosshair',
  16. './jquery.flot.events',
  17. ],
  18. function (angular, $, moment, _, kbn, GraphTooltip, thresholdManExports) {
  19. 'use strict';
  20. var module = angular.module('grafana.directives');
  21. var labelWidthCache = {};
  22. module.directive('grafanaGraph', function($rootScope, timeSrv) {
  23. return {
  24. restrict: 'A',
  25. template: '<div> </div>',
  26. link: function(scope, elem) {
  27. var ctrl = scope.ctrl;
  28. var dashboard = ctrl.dashboard;
  29. var panel = ctrl.panel;
  30. var data, annotations;
  31. var sortedSeries;
  32. var legendSideLastValue = null;
  33. var rootScope = scope.$root;
  34. var panelWidth = 0;
  35. var thresholdManager = new thresholdManExports.ThresholdManager(ctrl);
  36. rootScope.onAppEvent('setCrosshair', function(event, info) {
  37. // do not need to to this if event is from this panel
  38. if (info.scope === scope) {
  39. return;
  40. }
  41. if(dashboard.sharedCrosshair) {
  42. var plot = elem.data().plot;
  43. if (plot) {
  44. plot.setCrosshair({ x: info.pos.x, y: info.pos.y });
  45. }
  46. }
  47. }, scope);
  48. rootScope.onAppEvent('clearCrosshair', function() {
  49. var plot = elem.data().plot;
  50. if (plot) {
  51. plot.clearCrosshair();
  52. }
  53. }, scope);
  54. // Receive render events
  55. ctrl.events.on('render', function(renderData) {
  56. data = renderData || data;
  57. if (!data) {
  58. ctrl.refresh();
  59. return;
  60. }
  61. annotations = data.annotations || annotations;
  62. render_panel();
  63. });
  64. function getLegendHeight(panelHeight) {
  65. if (!panel.legend.show || panel.legend.rightSide) {
  66. return 0;
  67. }
  68. if (panel.legend.alignAsTable) {
  69. var legendSeries = _.filter(data, function(series) {
  70. return series.hideFromLegend(panel.legend) === false;
  71. });
  72. var total = 23 + (21 * legendSeries.length);
  73. return Math.min(total, Math.floor(panelHeight/2));
  74. } else {
  75. return 26;
  76. }
  77. }
  78. function setElementHeight() {
  79. try {
  80. var height = ctrl.height - getLegendHeight(ctrl.height);
  81. elem.css('height', height + 'px');
  82. return true;
  83. } catch(e) { // IE throws errors sometimes
  84. console.log(e);
  85. return false;
  86. }
  87. }
  88. function shouldAbortRender() {
  89. if (!data) {
  90. return true;
  91. }
  92. if (!setElementHeight()) { return true; }
  93. if (panelWidth === 0) {
  94. return true;
  95. }
  96. }
  97. function getLabelWidth(text, elem) {
  98. var labelWidth = labelWidthCache[text];
  99. if (!labelWidth) {
  100. labelWidth = labelWidthCache[text] = elem.width();
  101. }
  102. return labelWidth;
  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'></div>")
  126. .text(panel.yaxes[0].label)
  127. .appendTo(elem);
  128. yaxisLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[0].label, yaxisLabel) / 2) + 'px';
  129. }
  130. // add right axis labels
  131. if (panel.yaxes[1].label) {
  132. var rightLabel = $("<div class='axisLabel right-yaxis-label'></div>")
  133. .text(panel.yaxes[1].label)
  134. .appendTo(elem);
  135. rightLabel[0].style.marginTop = (getLabelWidth(panel.yaxes[1].label, rightLabel) / 2) + 'px';
  136. }
  137. thresholdManager.draw(plot);
  138. }
  139. function processOffsetHook(plot, gridMargin) {
  140. var left = panel.yaxes[0];
  141. var right = panel.yaxes[1];
  142. if (left.show && left.label) { gridMargin.left = 20; }
  143. if (right.show && right.label) { gridMargin.right = 20; }
  144. }
  145. // Function for rendering panel
  146. function render_panel() {
  147. panelWidth = elem.width();
  148. if (shouldAbortRender()) {
  149. return;
  150. }
  151. // give space to alert editing
  152. thresholdManager.prepare(elem, data);
  153. var stack = panel.stack ? true : null;
  154. // Populate element
  155. var options = {
  156. hooks: {
  157. draw: [drawHook],
  158. processOffset: [processOffsetHook],
  159. },
  160. legend: { show: false },
  161. series: {
  162. stackpercent: panel.stack ? panel.percentage : false,
  163. stack: panel.percentage ? null : stack,
  164. lines: {
  165. show: panel.lines,
  166. zero: false,
  167. fill: translateFillOption(panel.fill),
  168. lineWidth: panel.linewidth,
  169. steps: panel.steppedLine
  170. },
  171. bars: {
  172. show: panel.bars,
  173. fill: 1,
  174. barWidth: 1,
  175. zero: false,
  176. lineWidth: 0
  177. },
  178. points: {
  179. show: panel.points,
  180. fill: 1,
  181. fillColor: false,
  182. radius: panel.points ? panel.pointradius : 2
  183. },
  184. shadowSize: 0
  185. },
  186. yaxes: [],
  187. xaxis: {},
  188. grid: {
  189. minBorderMargin: 0,
  190. markings: [],
  191. backgroundColor: null,
  192. borderWidth: 0,
  193. hoverable: true,
  194. color: '#c8c8c8',
  195. margin: { left: 0, right: 0 },
  196. },
  197. selection: {
  198. mode: "x",
  199. color: '#666'
  200. },
  201. crosshair: {
  202. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  203. }
  204. };
  205. for (var i = 0; i < data.length; i++) {
  206. var series = data[i];
  207. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  208. // if hidden remove points and disable stack
  209. if (ctrl.hiddenSeries[series.alias]) {
  210. series.data = [];
  211. series.stack = false;
  212. }
  213. }
  214. if (data.length && data[0].stats.timeStep) {
  215. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  216. }
  217. addTimeAxis(options);
  218. thresholdManager.addPlotOptions(options, panel);
  219. addAnnotations(options);
  220. configureAxisOptions(data, options);
  221. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  222. function callPlot(incrementRenderCounter) {
  223. try {
  224. $.plot(elem, sortedSeries, options);
  225. delete ctrl.error;
  226. delete ctrl.inspector;
  227. } catch (e) {
  228. console.log('flotcharts error', e);
  229. ctrl.error = e.message || "Render Error";
  230. ctrl.inspector = {error: ctrl.error};
  231. }
  232. if (incrementRenderCounter) {
  233. ctrl.renderingCompleted();
  234. }
  235. }
  236. if (shouldDelayDraw(panel)) {
  237. // temp fix for legends on the side, need to render twice to get dimensions right
  238. callPlot(false);
  239. setTimeout(function() { callPlot(true); }, 50);
  240. legendSideLastValue = panel.legend.rightSide;
  241. }
  242. else {
  243. callPlot(true);
  244. }
  245. }
  246. function translateFillOption(fill) {
  247. return fill === 0 ? 0.001 : fill/10;
  248. }
  249. function shouldDelayDraw(panel) {
  250. if (panel.legend.rightSide) {
  251. return true;
  252. }
  253. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  254. return true;
  255. }
  256. }
  257. function addTimeAxis(options) {
  258. var ticks = panelWidth / 100;
  259. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  260. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  261. options.xaxis = {
  262. timezone: dashboard.getTimezone(),
  263. show: panel.xaxis.show,
  264. mode: "time",
  265. min: min,
  266. max: max,
  267. label: "Datetime",
  268. ticks: ticks,
  269. timeformat: time_format(ticks, min, max),
  270. };
  271. }
  272. function addAnnotations(options) {
  273. if(!annotations || annotations.length === 0) {
  274. return;
  275. }
  276. var types = {};
  277. _.each(annotations, function(event) {
  278. if (!types[event.annotation.name]) {
  279. types[event.annotation.name] = {
  280. color: event.annotation.iconColor,
  281. position: 'BOTTOM',
  282. markerSize: 5,
  283. };
  284. }
  285. });
  286. options.events = {
  287. levels: _.keys(types).length + 1,
  288. data: annotations,
  289. types: types,
  290. };
  291. }
  292. function configureAxisOptions(data, options) {
  293. var defaults = {
  294. position: 'left',
  295. show: panel.yaxes[0].show,
  296. min: panel.yaxes[0].min,
  297. index: 1,
  298. logBase: panel.yaxes[0].logBase || 1,
  299. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  300. };
  301. options.yaxes.push(defaults);
  302. if (_.findWhere(data, {yaxis: 2})) {
  303. var secondY = _.clone(defaults);
  304. secondY.index = 2,
  305. secondY.show = panel.yaxes[1].show;
  306. secondY.logBase = panel.yaxes[1].logBase || 1,
  307. secondY.position = 'right';
  308. secondY.min = panel.yaxes[1].min;
  309. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  310. options.yaxes.push(secondY);
  311. applyLogScale(options.yaxes[1], data);
  312. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  313. }
  314. applyLogScale(options.yaxes[0], data);
  315. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  316. }
  317. function applyLogScale(axis, data) {
  318. if (axis.logBase === 1) {
  319. return;
  320. }
  321. var series, i;
  322. var max = axis.max;
  323. if (max === null) {
  324. for (i = 0; i < data.length; i++) {
  325. series = data[i];
  326. if (series.yaxis === axis.index) {
  327. if (max < series.stats.max) {
  328. max = series.stats.max;
  329. }
  330. }
  331. }
  332. if (max === void 0) {
  333. max = Number.MAX_VALUE;
  334. }
  335. }
  336. axis.min = axis.min !== null ? axis.min : 0;
  337. axis.ticks = [0, 1];
  338. var nextTick = 1;
  339. while (true) {
  340. nextTick = nextTick * axis.logBase;
  341. axis.ticks.push(nextTick);
  342. if (nextTick > max) {
  343. break;
  344. }
  345. }
  346. if (axis.logBase === 10) {
  347. axis.transform = function(v) { return Math.log(v+0.1); };
  348. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  349. } else {
  350. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  351. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  352. }
  353. }
  354. function configureAxisMode(axis, format) {
  355. axis.tickFormatter = function(val, axis) {
  356. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  357. };
  358. }
  359. function time_format(ticks, min, max) {
  360. if (min && max && ticks) {
  361. var range = max - min;
  362. var secPerTick = (range/ticks) / 1000;
  363. var oneDay = 86400000;
  364. var oneYear = 31536000000;
  365. if (secPerTick <= 45) {
  366. return "%H:%M:%S";
  367. }
  368. if (secPerTick <= 7200 || range <= oneDay) {
  369. return "%H:%M";
  370. }
  371. if (secPerTick <= 80000) {
  372. return "%m/%d %H:%M";
  373. }
  374. if (secPerTick <= 2419200 || range <= oneYear) {
  375. return "%m/%d";
  376. }
  377. return "%Y-%m";
  378. }
  379. return "%H:%M";
  380. }
  381. new GraphTooltip(elem, dashboard, scope, function() {
  382. return sortedSeries;
  383. });
  384. elem.bind("plotselected", function (event, ranges) {
  385. scope.$apply(function() {
  386. timeSrv.setTime({
  387. from : moment.utc(ranges.xaxis.from),
  388. to : moment.utc(ranges.xaxis.to),
  389. });
  390. });
  391. });
  392. }
  393. };
  394. });
  395. });