graph.js 16 KB

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