graph.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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.editingThresholds) {
  157. if (!thresholdControls) {
  158. var thresholdMargin = panel.thresholds.length > 1 ? '220px' : '110px';
  159. elem.css('margin-right', thresholdMargin);
  160. thresholdControls = new ThresholdControls(ctrl);
  161. }
  162. } else if (thresholdControls) {
  163. elem.css('margin-right', '0');
  164. thresholdControls.cleanUp();
  165. thresholdControls = null;
  166. }
  167. var stack = panel.stack ? true : null;
  168. // Populate element
  169. var options = {
  170. hooks: {
  171. draw: [drawHook],
  172. processOffset: [processOffsetHook],
  173. },
  174. legend: { show: false },
  175. series: {
  176. stackpercent: panel.stack ? panel.percentage : false,
  177. stack: panel.percentage ? null : stack,
  178. lines: {
  179. show: panel.lines,
  180. zero: false,
  181. fill: translateFillOption(panel.fill),
  182. lineWidth: panel.linewidth,
  183. steps: panel.steppedLine
  184. },
  185. bars: {
  186. show: panel.bars,
  187. fill: 1,
  188. barWidth: 1,
  189. zero: false,
  190. lineWidth: 0
  191. },
  192. points: {
  193. show: panel.points,
  194. fill: 1,
  195. fillColor: false,
  196. radius: panel.points ? panel.pointradius : 2
  197. },
  198. shadowSize: 0
  199. },
  200. yaxes: [],
  201. xaxis: {},
  202. grid: {
  203. minBorderMargin: 0,
  204. markings: [],
  205. backgroundColor: null,
  206. borderWidth: 0,
  207. hoverable: true,
  208. color: '#c8c8c8',
  209. margin: { left: 0, right: 0 },
  210. },
  211. selection: {
  212. mode: "x",
  213. color: '#666'
  214. },
  215. crosshair: {
  216. mode: panel.tooltip.shared || dashboard.sharedCrosshair ? "x" : null
  217. }
  218. };
  219. for (var i = 0; i < data.length; i++) {
  220. var series = data[i];
  221. series.data = series.getFlotPairs(series.nullPointMode || panel.nullPointMode);
  222. // if hidden remove points and disable stack
  223. if (ctrl.hiddenSeries[series.alias]) {
  224. series.data = [];
  225. series.stack = false;
  226. }
  227. }
  228. if (data.length && data[0].stats.timeStep) {
  229. options.series.bars.barWidth = data[0].stats.timeStep / 1.5;
  230. }
  231. addTimeAxis(options);
  232. addGridThresholds(options, panel);
  233. addAnnotations(options);
  234. configureAxisOptions(data, options);
  235. sortedSeries = _.sortBy(data, function(series) { return series.zindex; });
  236. function callPlot(incrementRenderCounter) {
  237. try {
  238. $.plot(elem, sortedSeries, options);
  239. delete ctrl.error;
  240. delete ctrl.inspector;
  241. } catch (e) {
  242. console.log('flotcharts error', e);
  243. ctrl.error = e.message || "Render Error";
  244. ctrl.inspector = {error: ctrl.error};
  245. }
  246. if (incrementRenderCounter) {
  247. ctrl.renderingCompleted();
  248. }
  249. }
  250. if (shouldDelayDraw(panel)) {
  251. // temp fix for legends on the side, need to render twice to get dimensions right
  252. callPlot(false);
  253. setTimeout(function() { callPlot(true); }, 50);
  254. legendSideLastValue = panel.legend.rightSide;
  255. }
  256. else {
  257. callPlot(true);
  258. }
  259. }
  260. function translateFillOption(fill) {
  261. return fill === 0 ? 0.001 : fill/10;
  262. }
  263. function shouldDelayDraw(panel) {
  264. if (panel.legend.rightSide) {
  265. return true;
  266. }
  267. if (legendSideLastValue !== null && panel.legend.rightSide !== legendSideLastValue) {
  268. return true;
  269. }
  270. }
  271. function addTimeAxis(options) {
  272. var ticks = panelWidth / 100;
  273. var min = _.isUndefined(ctrl.range.from) ? null : ctrl.range.from.valueOf();
  274. var max = _.isUndefined(ctrl.range.to) ? null : ctrl.range.to.valueOf();
  275. options.xaxis = {
  276. timezone: dashboard.getTimezone(),
  277. show: panel.xaxis.show,
  278. mode: "time",
  279. min: min,
  280. max: max,
  281. label: "Datetime",
  282. ticks: ticks,
  283. timeformat: time_format(ticks, min, max),
  284. };
  285. }
  286. function addGridThresholds(options, panel) {
  287. if (!panel.thresholds || panel.thresholds.length === 0) {
  288. return;
  289. }
  290. var gtLimit = Infinity;
  291. var ltLimit = -Infinity;
  292. for (var i = 0; i < panel.thresholds.length; i++) {
  293. var threshold = panel.thresholds[i];
  294. if (!_.isNumber(threshold.value)) {
  295. continue;
  296. }
  297. var limit;
  298. switch(threshold.op) {
  299. case 'gt': {
  300. limit = gtLimit;
  301. gtLimit = threshold.value;
  302. break;
  303. }
  304. case 'lt': {
  305. limit = ltLimit;
  306. ltLimit = threshold.value;
  307. break;
  308. }
  309. }
  310. switch(threshold.colorMode) {
  311. case 'critical': {
  312. threshold.fillColor = 'rgba(234, 112, 112, 0.12)';
  313. threshold.lineColor = 'rgba(237, 46, 24, 0.60)';
  314. break;
  315. }
  316. case 'warning': {
  317. threshold.fillColor = 'rgba(235, 138, 14, 0.12)';
  318. threshold.lineColor = 'rgba(247, 149, 32, 0.60)';
  319. break;
  320. }
  321. case 'ok': {
  322. threshold.fillColor = 'rgba(11, 237, 50, 0.090)';
  323. threshold.lineColor = 'rgba(6,163,69, 0.60)';
  324. break;
  325. }
  326. case 'custom': {
  327. threshold.fillColor = threshold.fillColor;
  328. threshold.lineColor = threshold.lineColor;
  329. break;
  330. }
  331. }
  332. // fill
  333. if (threshold.fill) {
  334. options.grid.markings.push({yaxis: {from: threshold.value, to: limit}, color: threshold.fillColor});
  335. }
  336. if (threshold.line) {
  337. options.grid.markings.push({yaxis: {from: threshold.value, to: threshold.value}, color: threshold.lineColor});
  338. }
  339. }
  340. }
  341. function addAnnotations(options) {
  342. if(!annotations || annotations.length === 0) {
  343. return;
  344. }
  345. var types = {};
  346. _.each(annotations, function(event) {
  347. if (!types[event.annotation.name]) {
  348. types[event.annotation.name] = {
  349. color: event.annotation.iconColor,
  350. position: 'BOTTOM',
  351. markerSize: 5,
  352. };
  353. }
  354. });
  355. options.events = {
  356. levels: _.keys(types).length + 1,
  357. data: annotations,
  358. types: types,
  359. };
  360. }
  361. function configureAxisOptions(data, options) {
  362. var defaults = {
  363. position: 'left',
  364. show: panel.yaxes[0].show,
  365. min: panel.yaxes[0].min,
  366. index: 1,
  367. logBase: panel.yaxes[0].logBase || 1,
  368. max: panel.percentage && panel.stack ? 100 : panel.yaxes[0].max,
  369. };
  370. options.yaxes.push(defaults);
  371. if (_.findWhere(data, {yaxis: 2})) {
  372. var secondY = _.clone(defaults);
  373. secondY.index = 2,
  374. secondY.show = panel.yaxes[1].show;
  375. secondY.logBase = panel.yaxes[1].logBase || 1,
  376. secondY.position = 'right';
  377. secondY.min = panel.yaxes[1].min;
  378. secondY.max = panel.percentage && panel.stack ? 100 : panel.yaxes[1].max;
  379. options.yaxes.push(secondY);
  380. applyLogScale(options.yaxes[1], data);
  381. configureAxisMode(options.yaxes[1], panel.percentage && panel.stack ? "percent" : panel.yaxes[1].format);
  382. }
  383. applyLogScale(options.yaxes[0], data);
  384. configureAxisMode(options.yaxes[0], panel.percentage && panel.stack ? "percent" : panel.yaxes[0].format);
  385. }
  386. function applyLogScale(axis, data) {
  387. if (axis.logBase === 1) {
  388. return;
  389. }
  390. var series, i;
  391. var max = axis.max;
  392. if (max === null) {
  393. for (i = 0; i < data.length; i++) {
  394. series = data[i];
  395. if (series.yaxis === axis.index) {
  396. if (max < series.stats.max) {
  397. max = series.stats.max;
  398. }
  399. }
  400. }
  401. if (max === void 0) {
  402. max = Number.MAX_VALUE;
  403. }
  404. }
  405. axis.min = axis.min !== null ? axis.min : 0;
  406. axis.ticks = [0, 1];
  407. var nextTick = 1;
  408. while (true) {
  409. nextTick = nextTick * axis.logBase;
  410. axis.ticks.push(nextTick);
  411. if (nextTick > max) {
  412. break;
  413. }
  414. }
  415. if (axis.logBase === 10) {
  416. axis.transform = function(v) { return Math.log(v+0.1); };
  417. axis.inverseTransform = function (v) { return Math.pow(10,v); };
  418. } else {
  419. axis.transform = function(v) { return Math.log(v+0.1) / Math.log(axis.logBase); };
  420. axis.inverseTransform = function (v) { return Math.pow(axis.logBase,v); };
  421. }
  422. }
  423. function configureAxisMode(axis, format) {
  424. axis.tickFormatter = function(val, axis) {
  425. return kbn.valueFormats[format](val, axis.tickDecimals, axis.scaledDecimals);
  426. };
  427. }
  428. function time_format(ticks, min, max) {
  429. if (min && max && ticks) {
  430. var range = max - min;
  431. var secPerTick = (range/ticks) / 1000;
  432. var oneDay = 86400000;
  433. var oneYear = 31536000000;
  434. if (secPerTick <= 45) {
  435. return "%H:%M:%S";
  436. }
  437. if (secPerTick <= 7200 || range <= oneDay) {
  438. return "%H:%M";
  439. }
  440. if (secPerTick <= 80000) {
  441. return "%m/%d %H:%M";
  442. }
  443. if (secPerTick <= 2419200 || range <= oneYear) {
  444. return "%m/%d";
  445. }
  446. return "%Y-%m";
  447. }
  448. return "%H:%M";
  449. }
  450. new GraphTooltip(elem, dashboard, scope, function() {
  451. return sortedSeries;
  452. });
  453. elem.bind("plotselected", function (event, ranges) {
  454. scope.$apply(function() {
  455. timeSrv.setTime({
  456. from : moment.utc(ranges.xaxis.from),
  457. to : moment.utc(ranges.xaxis.to),
  458. });
  459. });
  460. });
  461. }
  462. };
  463. });
  464. });