graph.js 19 KB

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