graph.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. if (ctrl.renderError) {
  226. delete ctrl.error;
  227. delete ctrl.inspector;
  228. }
  229. } catch (e) {
  230. console.log('flotcharts error', e);
  231. ctrl.error = e.message || "Render Error";
  232. ctrl.renderError = true;
  233. ctrl.inspector = {error: ctrl.error};
  234. }
  235. if (incrementRenderCounter) {
  236. ctrl.renderingCompleted();
  237. }
  238. }
  239. if (shouldDelayDraw(panel)) {
  240. // temp fix for legends on the side, need to render twice to get dimensions right
  241. callPlot(false);
  242. setTimeout(function() { callPlot(true); }, 50);
  243. legendSideLastValue = panel.legend.rightSide;
  244. }
  245. else {
  246. callPlot(true);
  247. }
  248. }
  249. function translateFillOption(fill) {
  250. return fill === 0 ? 0.001 : fill/10;
  251. }
  252. function shouldDelayDraw(panel) {
  253. if (panel.legend.rightSide) {
  254. return true;
  255. }
  256. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  257. return true;
  258. }
  259. }
  260. function addTimeAxis(options) {
  261. var ticks = panelWidth / 100;
  262. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  263. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  264. options.xaxis = {
  265. timezone: dashboard.getTimezone(),
  266. show: panel.xaxis.show,
  267. mode: "time",
  268. min: min,
  269. max: max,
  270. label: "Datetime",
  271. ticks: ticks,
  272. timeformat: time_format(ticks, min, max),
  273. };
  274. }
  275. function addAnnotations(options) {
  276. if(!annotations || annotations.length === 0) {
  277. return;
  278. }
  279. var types = {};
  280. _.each(annotations, function(event) {
  281. if (!types[event.annotation.name]) {
  282. types[event.annotation.name] = {
  283. color: event.annotation.iconColor,
  284. position: 'BOTTOM',
  285. markerSize: 5,
  286. };
  287. }
  288. });
  289. options.events = {
  290. levels: _.keys(types).length + 1,
  291. data: annotations,
  292. types: types,
  293. };
  294. }
  295. function configureAxisOptions(data, options) {
  296. var defaults = {
  297. position: 'left',
  298. show: panel.yaxes[0].show,
  299. min: panel.yaxes[0].min,
  300. index: 1,
  301. logBase: panel.yaxes[0].logBase || 1,
  302. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  303. };
  304. options.yaxes.push(defaults);
  305. if (_.findWhere(data, {yaxis: 2})) {
  306. var secondY = _.clone(defaults);
  307. secondY.index = 2,
  308. secondY.show = panel.yaxes[1].show;
  309. secondY.logBase = panel.yaxes[1].logBase || 1,
  310. secondY.position = 'right';
  311. secondY.min = panel.yaxes[1].min;
  312. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  313. options.yaxes.push(secondY);
  314. applyLogScale(options.yaxes[1], data);
  315. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  316. }
  317. applyLogScale(options.yaxes[0], data);
  318. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  319. }
  320. function applyLogScale(axis, data) {
  321. if (axis.logBase === 1) {
  322. return;
  323. }
  324. var series, i;
  325. var max = axis.max;
  326. if (max === null) {
  327. for (i = 0; i < data.length; i++) {
  328. series = data[i];
  329. if (series.yaxis === axis.index) {
  330. if (max < series.stats.max) {
  331. max = series.stats.max;
  332. }
  333. }
  334. }
  335. if (max === void 0) {
  336. max = Number.MAX_VALUE;
  337. }
  338. }
  339. axis.min = axis.min !== null ? axis.min : 0;
  340. axis.ticks = [0, 1];
  341. var nextTick = 1;
  342. while (true) {
  343. nextTick = nextTick * axis.logBase;
  344. axis.ticks.push(nextTick);
  345. if (nextTick > max) {
  346. break;
  347. }
  348. }
  349. if (axis.logBase === 10) {
  350. axis.transform = function(v) { return Math.log(v+0.1); };
  351. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  352. } else {
  353. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  354. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  355. }
  356. }
  357. function configureAxisMode(axis, format) {
  358. axis.tickFormatter = function(val, axis) {
  359. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  360. };
  361. }
  362. function time_format(ticks, min, max) {
  363. if (min && max && ticks) {
  364. var range = max - min;
  365. var secPerTick = (range/ticks) / 1000;
  366. var oneDay = 86400000;
  367. var oneYear = 31536000000;
  368. if (secPerTick <= 45) {
  369. return "%H:%M:%S";
  370. }
  371. if (secPerTick <= 7200 || range <= oneDay) {
  372. return "%H:%M";
  373. }
  374. if (secPerTick <= 80000) {
  375. return "%m/%d %H:%M";
  376. }
  377. if (secPerTick <= 2419200 || range <= oneYear) {
  378. return "%m/%d";
  379. }
  380. return "%Y-%m";
  381. }
  382. return "%H:%M";
  383. }
  384. new GraphTooltip(elem, dashboard, scope, function() {
  385. return sortedSeries;
  386. });
  387. elem.bind("plotselected", function (event, ranges) {
  388. scope.$apply(function() {
  389. timeSrv.setTime({
  390. from : moment.utc(ranges.xaxis.from),
  391. to : moment.utc(ranges.xaxis.to),
  392. });
  393. });
  394. });
  395. }
  396. };
  397. });
  398. });